Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

refactor: simplify concepts and tighten user-facing copy

Lakr73ec3fef31db
diff --git a/Makefile b/Makefile
index 7159de5d..0375b71a 100644
--- a/Makefile
+++ b/Makefile
@@ -18,8 +18,15 @@ BACKUPS_DIR ?= vm.backups
NAME ?=
BACKUP_INCLUDE_IPSW ?= 0
FORCE ?= 0
-RESTORE_UDID ?= # UDID for restore operations
-RESTORE_ECID ?= # ECID for restore operations
+# UDID and ECID for restore operations
+RESTORE_UDID ?=
+RESTORE_ECID ?=
+
+# Truth test for the boolean flags above and on the command line. One place
+# owns the accepted spellings; use as $(call truthy,$(FLAG)) — it expands to
+# non-empty when the flag is on. NB: this is not an emptiness test, so it is
+# not a substitute for $(if $(RESTORE_UDID),…) and friends.
+truthy = $(filter 1 true yes YES TRUE,$(1))
# ─── Build info ──────────────────────────────────────────────────
GIT_HASH := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
@@ -53,17 +60,17 @@ help:
@echo " Options: JB=1 Jailbreak firmware/CFW path"
@echo " DEV=1 Dev firmware/CFW path (dev TXM + cfw_install_dev)"
@echo " EXP=1 Experimental firmware/CFW path (JB + EXP-only patches:"
- @echo " kernel hv_vmm rename, DSC byte-5 mangle, watchdogd surgical,"
+ @echo " kernel hv_vmm rename, DSC byte-5 mangle, surgical watchdogd patch,"
@echo " DT identity properties, post-restore DT rewrite, opt-in build spoof)"
@echo " LESS=1 Build, keeping iOS security mitigations enabled."
@echo " SKIP_PROJECT_SETUP=1 Skip setup_tools/build"
@echo " INTERACTIVE=1 Prompt at first-boot stages (default: non-interactive)"
@echo " SUDO_PASSWORD=... Preload sudo credential for setup flow"
- @echo " NO_BINPACK=1 Excludes the SSH, VNC, ... binaries from being installed (patchless-only, currently)"
- @echo " NO_VPHONED=1 Excludes vphoned from being installed (patchless-only, currently)"
+ @echo " NO_BINPACK=1 Skip installing the SSH, VNC and other bundled binaries (patchless only)"
+ @echo " NO_VPHONED=1 Skip installing vphoned (patchless only)"
@echo " SPOOF_BUILD=<id> (EXP only) Rewrite ProductBuildVersion in SystemVersion.plist to <id>"
- @echo " e.g. SPOOF_BUILD=23F77 makes Settings -> About show that build."
- @echo " Omitted/empty -> EXP-JB-7 skipped, build version stays at the IPSW value."
+ @echo " e.g. SPOOF_BUILD=23F77 makes Settings → About show that build."
+ @echo " Unset or empty keeps the build version that ships in the IPSW."
@echo ""
@echo "Setup (one-time):"
@echo " make setup_tools Install all tools (brew, trustcache, insert_dylib, venv+pymobiledevice3)"
@@ -85,13 +92,13 @@ help:
@echo " make vm_restore NAME=<name> Restore a named backup into vm/"
@echo " make vm_switch NAME=<name> Save current + restore target (one step)"
@echo " make vm_list List available backups"
- @echo " Options: BACKUP_INCLUDE_IPSW=1 Include *_Restore* IPSW dirs in backup"
+ @echo " Options: BACKUP_INCLUDE_IPSW=1 Include *_Restore* IPSW directories in the backup"
@echo " FORCE=1 Skip overwrite prompt on restore"
@echo " make amfidont_allow_vphone Start amfidont for the signed vphone-cli binary"
@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"
- @echo " Options: NO_VPHONED=1 Excludes vphoned from being installed"
+ @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:"
@@ -107,8 +114,8 @@ help:
@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 Excludes the SSH, VNC, ... binaries from being installed"
- @echo " NO_VPHONED=1 Excludes vphoned from being installed"
+ @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)"
@@ -121,14 +128,14 @@ help:
@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 on any skipped sub-patch (broad drift gate)"
+ @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"
@echo " make restore Restore to device (pymobiledevice3 backend)"
- @echo " make restore_offline Restore offline — decrypts AEA images in place, uses cached .shsh blob"
+ @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"
@@ -147,12 +154,12 @@ help:
setup_machine:
@if count=0; \
- [ -n "$(filter 1 true yes YES TRUE,$(JB))" ] && count=$$((count+1)); \
- [ -n "$(filter 1 true yes YES TRUE,$(DEV))" ] && count=$$((count+1)); \
- [ -n "$(filter 1 true yes YES TRUE,$(EXP))" ] && count=$$((count+1)); \
- [ -n "$(filter 1 true yes YES TRUE,$(LESS))" ] && count=$$((count+1)); \
+ [ -n "$(call truthy,$(JB))" ] && count=$$((count+1)); \
+ [ -n "$(call truthy,$(DEV))" ] && count=$$((count+1)); \
+ [ -n "$(call truthy,$(EXP))" ] && count=$$((count+1)); \
+ [ -n "$(call truthy,$(LESS))" ] && count=$$((count+1)); \
[ $$count -gt 1 ]; then \
- echo "Error: JB=1, DEV=1, EXP=1, and LESS=1 are mutually exclusive"; \
+ echo "Error: use only one of JB=1, DEV=1, EXP=1 or LESS=1."; \
exit 1; \
fi
SUDO_PASSWORD="$(SUDO_PASSWORD)" \
@@ -161,11 +168,11 @@ setup_machine:
NO_VPHONED="$(NO_VPHONED)" \
SPOOF_BUILD="$(SPOOF_BUILD)" \
zsh $(SCRIPTS)/setup_machine.sh \
- $(if $(filter 1 true yes YES TRUE,$(JB)),--jb,) \
- $(if $(filter 1 true yes YES TRUE,$(DEV)),--dev,) \
- $(if $(filter 1 true yes YES TRUE,$(EXP)),--exp,) \
- $(if $(filter 1 true yes YES TRUE,$(LESS)),--less,) \
- $(if $(filter 1 true yes YES TRUE,$(SKIP_PROJECT_SETUP)),--skip-project-setup,)
+ $(if $(call truthy,$(JB)),--jb,) \
+ $(if $(call truthy,$(DEV)),--dev,) \
+ $(if $(call truthy,$(EXP)),--exp,) \
+ $(if $(call truthy,$(LESS)),--less,) \
+ $(if $(call truthy,$(SKIP_PROJECT_SETUP)),--skip-project-setup,)
setup_tools:
VARIANT=$(VARIANT) zsh $(SCRIPTS)/setup_tools.sh
@@ -179,24 +186,22 @@ setup_tools:
clean:
@set -e; \
echo "=== Cleaning build/tooling artifacts ==="; \
- echo "Removing: .build .swiftpm .vphoned.signed $(VENV) $(TOOLS_PREFIX)"; \
+ echo "Removing: .build .swiftpm $(VENV) $(TOOLS_PREFIX)"; \
if [ "$(CLEAN_VM)" = "1" ] || [ "$(CLEAN_IPSW)" = "1" ]; then \
echo ""; \
echo "WARNING: destructive clean requested."; \
[ "$(CLEAN_VM)" = "1" ] && echo " VM directory: $(VM_DIR)/"; \
[ "$(CLEAN_IPSW)" = "1" ] && echo " IPSW cache: ipsws/"; \
- printf "Also remove destructive targets above? [y/N] "; \
+ printf "Also permanently delete the data listed above? [y/N] "; \
read answer; \
case "$$answer" in y|Y|yes|YES) ;; *) \
echo "[-] Destructive clean cancelled; no files removed."; \
exit 0; \
esac; \
fi; \
- rm -rf .build .swiftpm .vphoned.signed "$(VENV)" "$(TOOLS_PREFIX)"; \
- if [ "$(CLEAN_VM)" = "1" ] || [ "$(CLEAN_IPSW)" = "1" ]; then \
- if [ "$(CLEAN_VM)" = "1" ]; then rm -rf "$(VM_DIR)"; fi; \
- if [ "$(CLEAN_IPSW)" = "1" ]; then rm -rf ipsws; fi; \
- fi
+ rm -rf .build .swiftpm "$(VENV)" "$(TOOLS_PREFIX)"; \
+ if [ "$(CLEAN_VM)" = "1" ]; then rm -rf "$(VM_DIR)"; fi; \
+ if [ "$(CLEAN_IPSW)" = "1" ]; then rm -rf ipsws; fi
# ═══════════════════════════════════════════════════════════════════
# Build
@@ -208,16 +213,21 @@ build: $(BINARY)
patcher_build: $(PATCHER_BINARY)
-$(PATCHER_BINARY): $(SWIFT_SOURCES) Package.swift
- @echo "=== Building vphone-cli patcher ($(GIT_HASH)) ==="
+# Stamp the current commit into $(BUILD_INFO). Both build recipes use this, so
+# the generated file's shape has one owner.
+define WRITE_BUILD_INFO
@echo '// Auto-generated — do not edit' > $(BUILD_INFO)
@echo 'enum VPhoneBuildInfo { static let commitHash = "$(GIT_HASH)" }' >> $(BUILD_INFO)
+endef
+
+$(PATCHER_BINARY): $(SWIFT_SOURCES) Package.swift
+ @echo "=== Building vphone-cli patcher ($(GIT_HASH)) ==="
+ $(WRITE_BUILD_INFO)
@set -o pipefail; swift build 2>&1 | tail -5
$(BINARY): $(SWIFT_SOURCES) Package.swift $(ENTITLEMENTS)
@echo "=== Building vphone-cli ($(GIT_HASH)) ==="
- @echo '// Auto-generated — do not edit' > $(BUILD_INFO)
- @echo 'enum VPhoneBuildInfo { static let commitHash = "$(GIT_HASH)" }' >> $(BUILD_INFO)
+ $(WRITE_BUILD_INFO)
@set -o pipefail; swift build -c release 2>&1 | tail -5
@echo ""
@echo "=== Signing with entitlements ==="
@@ -253,7 +263,7 @@ vphoned:
# VM management
# ═══════════════════════════════════════════════════════════════════
-.PHONY: vm_new vm_backup vm_restore vm_switch vm_list amfidont_allow_vphone boot_host_preflight boot boot_less boot_dfu boot_binary_check
+.PHONY: vm_new vm_backup vm_restore vm_switch vm_list amfidont_allow_vphone boot_host_preflight boot boot_less boot_dfu boot_binary_check boot_binary_check_less
vm_new:
CPU="$(CPU)" MEMORY="$(MEMORY)" \
@@ -272,10 +282,10 @@ vm_switch:
zsh $(SCRIPTS)/vm_switch.sh
vm_list:
- @if [ -d "$(BACKUPS_DIR)" ]; then \
+ @found=0; \
+ if [ -d "$(BACKUPS_DIR)" ]; then \
current=""; \
[ -f "$(VM_DIR)/.vm_name" ] && current="$$(cat "$(VM_DIR)/.vm_name")"; \
- found=0; \
for d in "$(BACKUPS_DIR)"/*/; do \
[ -f "$${d}config.plist" ] || continue; \
name="$$(basename "$$d")"; \
@@ -287,10 +297,8 @@ vm_list:
fi; \
found=1; \
done; \
- if [ "$$found" = "0" ]; then echo " (no backups yet — run: make vm_backup NAME=<name>)"; fi; \
- else \
- echo " (no backups yet — run: make vm_backup NAME=<name>)"; \
- fi
+ fi; \
+ if [ "$$found" = "0" ]; then echo " (no backups yet — run: make vm_backup NAME=<name>)"; fi
amfidont_allow_vphone: bundle
zsh $(SCRIPTS)/start_amfidont_for_vphone.sh
@@ -308,7 +316,7 @@ define BOOT_BINARY_CHECK
if [ $$rc -ne 0 ]; then \
echo "Error: signed vphone-cli failed to launch (exit $$rc)." >&2; \
echo "Check private virtualization entitlement support and ensure SIP/AMFI are disabled on the host." >&2; \
- echo "Repo workaround: start the AMFI bypass helper with 'make amfidont_allow_vphone' and retry." >&2; \
+ echo "Alternatively, start the AMFI bypass helper with 'make amfidont_allow_vphone', then try again." >&2; \
if [ -s "$$tmp_log" ]; then \
echo "--- vphone-cli preflight log ---" >&2; \
tail -n 40 "$$tmp_log" >&2; \
@@ -333,7 +341,7 @@ boot_less: bundle boot_binary_check_less
cd "$(VM_DIR)" && "$(CURDIR)/$(BUNDLE_BIN)" \
--config ./config.plist \
--variant less \
- $(if $(filter 1 true yes YES TRUE,$(NO_VPHONED)),--no-vphoned,)
+ $(if $(call truthy,$(NO_VPHONED)),--no-vphoned,)
boot_dfu: build boot_binary_check
cd "$(VM_DIR)" && "$(CURDIR)/$(BINARY)" \
@@ -344,25 +352,25 @@ boot_dfu: build boot_binary_check
# Firmware pipeline
# ═══════════════════════════════════════════════════════════════════
-.PHONY: fw_prepare fw_patch fw_patch_less fw_patch_dev fw_patch_jb
+.PHONY: fw_prepare fw_patch fw_patch_less fw_patch_dev fw_patch_jb fw_patch_exp
fw_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 $(filter 1 true yes YES TRUE,$(FORCE_EXC_GUARD)),--force-exc-guard,)
+ $(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 $(filter 1 true yes YES TRUE,$(NO_BINPACK)),--no-binpack,)
- $(if $(filter 1 true yes YES TRUE,$(NO_VPHONED)),--no-vphoned,)
+ $(if $(call truthy,$(NO_BINPACK)),--no-binpack,)
+ $(if $(call truthy,$(NO_VPHONED)),--no-vphoned,)
else
fw_patch_less:
- @echo "fw_patch_less must be run via sudo"
+ @echo "Error: fw_patch_less needs root. Run: sudo make fw_patch_less"
@exit 1
endif
@@ -371,13 +379,13 @@ fw_patch_dev: patcher_build
fw_patch_jb: patcher_build
"$(CURDIR)/$(PATCHER_BINARY)" patch-firmware --vm-directory "$(VM_DIR_ABS)" --variant jb \
- $(if $(filter 1 true yes YES TRUE,$(FORCE_EXC_GUARD)),--force-exc-guard,) \
- $(if $(filter 1 true yes YES TRUE,$(FRIDA)),--frida,)
+ $(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 $(filter 1 true yes YES TRUE,$(FORCE_EXC_GUARD)),--force-exc-guard,) \
- $(if $(filter 1 true yes YES TRUE,$(FRIDA)),--frida,)
+ $(if $(call truthy,$(FORCE_EXC_GUARD)),--force-exc-guard,) \
+ $(if $(call truthy,$(FRIDA)),--frida,)
.PHONY: test_jb_patches
@@ -387,7 +395,7 @@ fw_patch_exp: patcher_build
# 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 $(filter 1 true yes YES TRUE,$(QUICK)),--quick,)
+ $(if $(call truthy,$(QUICK)),--quick,)
.PHONY: test_fw_patches
@@ -400,7 +408,7 @@ test_jb_patches: patcher_build
# VARIANTS="exp" Limit to specific variants (default: jb exp)
test_fw_patches: patcher_build
zsh "$(CURDIR)/tests/test_firmware_patches.sh" --no-build \
- $(if $(filter 1 true yes YES TRUE,$(QUICK)),--quick,)
+ $(if $(call truthy,$(QUICK)),--quick,)
# ═══════════════════════════════════════════════════════════════════
# Restore
@@ -447,21 +455,21 @@ restore_offline:
echo "[-] No iPhone*_Restore directory in $(VM_DIR)/"; \
exit 1; \
fi; \
- echo "[+] Decrypting AEA images in place..."; \
+ echo "[+] Decrypting AEA images in place…"; \
for aea in "$$RESTORE_SRC"/*.dmg.aea; do \
[ -f "$$aea" ] || continue; \
[ "$$(xxd -l 4 -p "$$aea")" = "41454131" ] || continue; \
base=$$(basename "$$aea"); \
if ! ipsw fw aea -o "$$RESTORE_SRC" "$$aea"; then \
- echo "[-] ipsw fw aea failed for $$base — aborting"; \
+ echo "[-] Could not decrypt $$base with ipsw — restore stopped."; \
exit 1; \
fi; \
if ! mv -f "$$RESTORE_SRC/$${base%.aea}" "$$aea"; then \
- echo "[-] mv failed for $$base — aborting (decrypted file missing?)"; \
+ echo "[-] Could not replace $$base with its decrypted image — restore stopped."; \
exit 1; \
fi; \
if [ "$$(xxd -l 4 -p "$$aea")" = "41454131" ]; then \
- echo "[-] $$base still AEA1-encrypted after decrypt — aborting"; \
+ echo "[-] $$base is still encrypted after decryption — restore stopped."; \
exit 1; \
fi; \
done; \
@@ -494,4 +502,4 @@ cfw_install_exp:
# 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 $(filter 1 true yes YES TRUE,$(FRIDA)),VPHONE_FRIDA=1) zsh "$(CURDIR)/$(SCRIPTS)/cfw_install_host.sh" --variant $(if $(VARIANT),$(VARIANT),exp) "$(VM_DIR_ABS)"
+ $(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)"
diff --git a/research/VPhoneVirtualMachineRefactored.swift b/research/VPhoneVirtualMachineRefactored.swift
index f85f69cf..28a6941d 100644
--- a/research/VPhoneVirtualMachineRefactored.swift
+++ b/research/VPhoneVirtualMachineRefactored.swift
@@ -54,36 +54,29 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
}
init(options: Configuration) throws {
- // Create hardware model
let hardwareModel = try VPhoneHardware.createModel()
print("[vphone] PV=3 hardware model: isSupported = true")
- // Configure platform
let platform = try configurePlatform(
machineIDURL: options.machineIDURL,
nvramURL: options.nvramURL,
hardwareModel: hardwareModel
)
- // Resolve device identity
if let machineIdentifier = platform.machineIdentifier {
ecidHex = Self.resolveDeviceIdentity(machineIdentifier: machineIdentifier)?.ecidHex
} else {
ecidHex = nil
}
- // Create bootloader
let bootloader = createBootloader(romURL: options.romURL)
- // Build VM configuration
let config = buildConfiguration(
options: options,
- hardwareModel: hardwareModel,
platform: platform,
bootloader: bootloader
)
- // Validate configuration
try config.validate()
print("[vphone] Configuration validated")
@@ -91,7 +84,6 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
super.init()
virtualMachine.delegate = self
- // Setup serial output forwarding
if let readHandle = serialOutputReadHandle {
readHandle.readabilityHandler = { handle in
let data = handle.availableData
@@ -111,11 +103,9 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
let platform = VZMacPlatformConfiguration()
platform.hardwareModel = hardwareModel
- // Load or create machine identifier
let machineIdentifier = loadOrCreateMachineIdentifier(at: machineIDURL)
platform.machineIdentifier = machineIdentifier
- // Create auxiliary storage (NVRAM)
let auxiliaryStorage = try VZMacAuxiliaryStorage(
creatingStorageAt: nvramURL,
hardwareModel: hardwareModel,
@@ -123,7 +113,6 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
)
platform.auxiliaryStorage = auxiliaryStorage
- // Configure boot args for serial output
setBootArgsSerialOutput(auxiliaryStorage)
return platform
@@ -168,7 +157,6 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
private func buildConfiguration(
options: Configuration,
- hardwareModel _: VZMacHardwareModel,
platform: VZMacPlatformConfiguration,
bootloader: VZMacOSBootLoader
) -> VZVirtualMachineConfiguration {
@@ -178,22 +166,21 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
config.cpuCount = max(options.cpuCount, VZVirtualMachineConfiguration.minimumAllowedCPUCount)
config.memorySize = max(options.memorySize, VZVirtualMachineConfiguration.minimumAllowedMemorySize)
- // Configure each subsystem
- configureDisplay(&config, screen: options.screenConfiguration)
- configureAudio(&config)
- configureStorage(&config, diskURL: options.diskURL)
- configureNetwork(&config)
- configureSerialPort(&config)
- configureInputDevices(&config)
- configureSocketDevice(&config)
- configureBattery(&config)
- configureDebugStub(&config, port: options.kernelDebugPort)
- configureSEP(&config, options: options)
+ configureDisplay(config, screen: options.screenConfiguration)
+ configureAudio(config)
+ configureStorage(config, diskURL: options.diskURL)
+ configureNetwork(config)
+ configureSerialPort(config)
+ configureInputDevices(config)
+ configureSocketDevice(config)
+ configureBattery(config)
+ configureDebugStub(config, port: options.kernelDebugPort)
+ configureSEP(config, options: options)
return config
}
- private func configureDisplay(_ config: inout VZVirtualMachineConfiguration, screen: ScreenConfiguration) {
+ private func configureDisplay(_ config: VZVirtualMachineConfiguration, screen: ScreenConfiguration) {
let graphicsConfiguration = VZMacGraphicsDeviceConfiguration()
let displayConfiguration = VZMacGraphicsDisplayConfiguration(
widthInPixels: screen.width,
@@ -204,7 +191,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
config.graphicsDevices = [graphicsConfiguration]
}
- private func configureAudio(_ config: inout VZVirtualMachineConfiguration) {
+ private func configureAudio(_ config: VZVirtualMachineConfiguration) {
let soundDevice = VZVirtioSoundDeviceConfiguration()
let inputStream = VZVirtioSoundDeviceInputStreamConfiguration()
inputStream.source = VZHostAudioInputStreamSource()
@@ -216,7 +203,7 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
config.audioDevices = [soundDevice]
}
- private func configureStorage(_ config: inout VZVirtualMachineConfiguration, diskURL: URL) {
+ private func configureStorage(_ config: VZVirtualMachineConfiguration, diskURL: URL) {
guard FileManager.default.fileExists(atPath: diskURL.path) else {
print("[vphone] Warning: Disk image not found at \(diskURL.path)")
return
@@ -227,13 +214,13 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
config.storageDevices = [storageDevice]
}
- private func configureNetwork(_ config: inout VZVirtualMachineConfiguration) {
+ private func configureNetwork(_ config: VZVirtualMachineConfiguration) {
let networkDevice = VZVirtioNetworkDeviceConfiguration()
networkDevice.attachment = VZNATNetworkDeviceAttachment()
config.networkDevices = [networkDevice]
}
- private func configureSerialPort(_ config: inout VZVirtualMachineConfiguration) {
+ private func configureSerialPort(_ config: VZVirtualMachineConfiguration) {
guard let serialPort = Dynamic._VZPL011SerialPortConfiguration().asObject as? VZSerialPortConfiguration else {
return
}
@@ -246,7 +233,6 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
fileHandleForWriting: outputPipe.fileHandleForWriting
)
- // Forward host stdin → VM serial input
forwardStandardInput(to: inputPipe.fileHandleForWriting)
serialOutputReadHandle = outputPipe.fileHandleForReading
@@ -266,62 +252,62 @@ class VPhoneVirtualMachineRefactored: NSObject, VZVirtualMachineDelegate {
}
}
- private func configureInputDevices(_ config: inout VZVirtualMachineConfiguration) {
- // Multi-touch screen
+ private func configureInputDevices(_ config: VZVirtualMachineConfiguration) {
if let touchScreen = Dynamic._VZUSBTouchScreenConfiguration().asObject {
Dynamic(config)._setMultiTouchDevices([touchScreen])
print("[vphone] USB touch screen configured")
}
- // Keyboard
config.keyboards = [VZUSBKeyboardConfiguration()]
}
- private func configureSocketDevice(_ config: inout VZVirtualMachineConfiguration) {
+ private func configureSocketDevice(_ config: VZVirtualMachineConfiguration) {
config.socketDevices = [VZVirtioSocketDeviceConfiguration()]
}
- private func configureBattery(_ config: inout VZVirtualMachineConfiguration) {
- let batterySource = Dynamic._VZMacSyntheticBatterySource()
- batterySource.setCharge(100.0)
- batterySource.setConnectivity(BatteryConnectivity.charging)
+ private func configureBattery(_ config: VZVirtualMachineConfiguration) {
+ let syntheticBatterySource = Dynamic._VZMacSyntheticBatterySource()
+ syntheticBatterySource.setCharge(100.0)
+ syntheticBatterySource.setConnectivity(BatteryConnectivity.charging)
let batteryConfiguration = Dynamic._VZMacBatteryPowerSourceDeviceConfiguration()
- batteryConfiguration.setSource(batterySource.asObject)
+ batteryConfiguration.setSource(syntheticBatterySource.asObject)
guard let batteryObject = batteryConfiguration.asObject else { return }
Dynamic(config)._setPowerSourceDevices([batteryObject])
- self.batterySource = batterySource.asObject as AnyObject?
+ self.batterySource = syntheticBatterySource.asObject as AnyObject?
print("[vphone] Synthetic battery configured (100%, charging)")
}
- private func configureDebugStub(_ config: inout VZVirtualMachineConfiguration, port: Int?) {
- if let port {
- guard (6000 ... 65535).contains(port) else {
- print("[vphone] Warning: Invalid kernel debug port \(port), using system-assigned")
- configureDefaultDebugStub(&config)
- return
- }
+ private func configureDebugStub(_ config: VZVirtualMachineConfiguration, port: Int?) {
+ guard let port else {
+ configureDefaultDebugStub(config)
+ return
+ }
- if let debugStub = Dynamic._VZGDBDebugStubConfiguration(port: port).asObject {
- Dynamic(config)._setDebugStub(debugStub)
- print("[vphone] Kernel GDB debug stub: tcp://127.0.0.1:\(port)")
- } else {
- configureDefaultDebugStub(&config)
- }
- } else {
- configureDefaultDebugStub(&config)
+ guard (6000 ... 65535).contains(port) else {
+ print("[vphone] Warning: Invalid kernel debug port \(port), using system-assigned")
+ configureDefaultDebugStub(config)
+ return
+ }
+
+ guard let debugStub = Dynamic._VZGDBDebugStubConfiguration(port: port).asObject else {
+ configureDefaultDebugStub(config)
+ return
}
+
+ Dynamic(config)._setDebugStub(debugStub)
+ print("[vphone] Kernel GDB debug stub: tcp://127.0.0.1:\(port)")
}
- private func configureDefaultDebugStub(_ config: inout VZVirtualMachineConfiguration) {
+ private func configureDefaultDebugStub(_ config: VZVirtualMachineConfiguration) {
let debugStub = Dynamic._VZGDBDebugStubConfiguration().asObject
Dynamic(config)._setDebugStub(debugStub)
print("[vphone] Kernel GDB debug stub enabled (system-assigned port)")
}
- private func configureSEP(_ config: inout VZVirtualMachineConfiguration, options: Configuration) {
+ private func configureSEP(_ config: VZVirtualMachineConfiguration, options: Configuration) {
let sepConfiguration = Dynamic._VZSEPCoprocessorConfiguration(storageURL: options.sepStorageURL)
sepConfiguration.setRomBinaryURL(options.sepRomURL)
sepConfiguration.setDebugStub(Dynamic._VZGDBDebugStubConfiguration().asObject)
diff --git a/research/manifest_and_refactoring_summary.md b/research/manifest_and_refactoring_summary.md
index dd70d4a2..062edc80 100644
--- a/research/manifest_and_refactoring_summary.md
+++ b/research/manifest_and_refactoring_summary.md
@@ -12,7 +12,7 @@
### Files Created
-- `sources/vphone-cli/VPhoneVirtualMachineManifest.swift` - Manifest structure (compatible with security-pcc)
+- `sources/VPhoneCore/VPhoneVirtualMachineManifest.swift` - Manifest structure (compatible with security-pcc)
- `scripts/vm_manifest.py` - Python script to generate config.plist
### Changes Made
@@ -111,14 +111,14 @@
#### Refactored Version Created
-`sources/vphone-cli/VPhoneVirtualMachineRefactored.swift` demonstrates:
+`research/VPhoneVirtualMachineRefactored.swift` demonstrates:
1. **Extracted configuration methods**:
```swift
private func configurePlatform(...)
- private func configureDisplay(_ config: inout VZVirtualMachineConfiguration, screen: ScreenConfiguration)
- private func configureAudio(_ config: inout VZVirtualMachineConfiguration)
+ private func configureDisplay(_ config: VZVirtualMachineConfiguration, screen: ScreenConfiguration)
+ private func configureAudio(_ config: VZVirtualMachineConfiguration)
// ... etc
```
diff --git a/scripts/boot_host_preflight.sh b/scripts/boot_host_preflight.sh
index 26c35382..75cb18db 100755
--- a/scripts/boot_host_preflight.sh
+++ b/scripts/boot_host_preflight.sh
@@ -9,7 +9,6 @@ PROJECT_ROOT="${SCRIPT_DIR:h}"
ASSERT_BOOTABLE=0
QUIET=0
-LESS=0
while [[ $# -gt 0 ]]; do
case "$1" in
@@ -22,7 +21,8 @@ while [[ $# -gt 0 ]]; do
shift
;;
--less)
- LESS=1
+ # Accepted for `make boot_binary_check_less` (Makefile), which passes it
+ # alongside --assert-bootable; this script's checks do not differ.
shift
;;
*)
@@ -145,13 +145,11 @@ if [[ -f "$RELEASE_BIN" ]]; then
fi
print_section "Unsigned Debug Binary"
-DEBUG_HELP_RC=0
if [[ ! -f "$DEBUG_BIN" ]]; then
echo "(skipped — debug binary not built; run 'make patcher_build' to include)"
else
set +e
run_capture "debug_help" "$DEBUG_BIN" --help
- DEBUG_HELP_RC=$?
set -e
fi
@@ -166,7 +164,6 @@ RELEASE_HELP_RC=$?
set -e
print_section "Signed Debug Control"
-SIGNED_DEBUG_HELP_RC=0
if [[ ! -f "$DEBUG_BIN" ]]; then
echo "(skipped — debug binary not built)"
else
@@ -174,7 +171,6 @@ else
codesign --force --sign - --entitlements "$ENTITLEMENTS" "$TMP_SIGNED_DEBUG" >/dev/null
set +e
run_capture "signed_debug_help" "$TMP_SIGNED_DEBUG" --help
- SIGNED_DEBUG_HELP_RC=$?
set -e
fi
diff --git a/scripts/camfix/libcamfix.m b/scripts/camfix/libcamfix.m
index b07727c2..c2b73700 100644
--- a/scripts/camfix/libcamfix.m
+++ b/scripts/camfix/libcamfix.m
@@ -1,31 +1,51 @@
/*
* libcamfix — substrate-injected into Camera.app (com.apple.camera).
*
- * 1. Suppress the -[AVCaptureFigVideoDevice _setActiveFormat:...] crash
+ * Our virtual camera has no daemon-side still or preview pipeline behind it,
+ * so AVFoundation's own paths crash, throw, or render black. The hooks
+ * installed by cfx_install_all_hooks substitute our own:
+ *
+ * 1. -[AVCaptureFigVideoDevice _setActiveFormat:...]: suppress the crash
* when the device is our virtual camera and the format argument is nil.
* Camera.app's session-preset → format lookup returns nil for our synth
* because no preset matches our published formats exactly. Substitute
* the device's first supported format instead.
*
- * 2. Same -[AVCapturePhotoOutput capturePhotoWithSettings:delegate:] swizzle
- * as libcameratest: when the photo output is bound to our virtual camera,
- * read /var/jb/var/mobile/Library/vphone-vcam-frame.shm, build a
- * CMSampleBuffer, and async-fire the deprecated delegate method with the
- * sample buffer. JPEG-encoded delivery happens client-side via ImageIO.
+ * 2. -[AVCapturePhotoOutput capturePhotoWithSettings:delegate:]: when the
+ * photo output is bound to our virtual camera, read
+ * /var/jb/var/mobile/Library/vphone-vcam-frame.shm and fire the modern
+ * didFinishProcessingPhoto:error: delegate with an AVCapturePhoto built
+ * from that frame; JPEG encoding happens client-side via ImageIO. The
+ * deprecated CMSampleBuffer delegate is the fallback, taken only for a
+ * client that implements nothing else. If this hook fails, the capture
+ * path falls back to the original AVF code path (which would re-throw /
+ * error out).
+ *
+ * 3. The moment-capture trio (begin / commit / cancelMomentCapture):
+ * Camera.app's shutter path. For our virtual camera the original is
+ * deliberately never called — it throws — so AVF's state stays clean and
+ * subsequent shutter taps don't compound corruption.
+ *
+ * 4. AVCaptureSession's _setRunning: / _setInterrupted: guards and its
+ * isRunning / isInterrupted getters: keep a vcam-bound session live
+ * although no sample buffers ever flow through it.
+ *
+ * 5. The AVCaptureVideoPreviewLayer pump and its scan timer: push CGImage
+ * frames into CALayer.contents, since nothing feeds the layer otherwise.
*
- * Failure mode if either hook fails: capture path falls back to the original
- * AVF code path (which would re-throw / error out). All logging goes to
- * /var/mobile/Library/Logs/CrashReporter/camfix.log via NSLog (Camera.app
- * has Apple's TCC access to that area).
+ * 6. AVCapturePhoto's -fileDataRepresentation / -CGImageRepresentation: hand
+ * back the bytes stamped onto the photos we synthesized.
+ *
+ * 7. CAMStillImageCaptureRequest stubs for the accessors Camera.app's
+ * capture engine reads off a request.
+ *
+ * All logging goes to /tmp/camfix.log, written by cfxlog.
*/
#import <AVFoundation/AVFoundation.h>
-#import <CoreImage/CoreImage.h>
#import <Foundation/Foundation.h>
#import <ImageIO/ImageIO.h>
-#import <MobileCoreServices/MobileCoreServices.h>
#import <IOSurface/IOSurfaceRef.h>
-#import <Photos/Photos.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
@@ -93,6 +113,27 @@ static BOOL cfx_shm_open(void) {
return YES;
}
+// One owner for "map the frame and check it is usable": opens the shm,
+// rejects a zeroed header, and rejects a pixel plane that runs past the
+// mapping. On success returns the header — the pixels start
+// CFX_SHM_HEADER_SIZE bytes after cfx_shm_base — and writes the pixel-plane
+// length to *outLen. Returns NULL when the frame cannot be read.
+static const cfx_shm_header_t *cfx_shm_frame(size_t *outLen) {
+ if (!cfx_shm_open()) return NULL;
+ const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;
+ if (!hdr->width || !hdr->height || !hdr->bytes_per_row) {
+ cfxlog(@"shm header zeros");
+ return NULL;
+ }
+ size_t len = (size_t)hdr->bytes_per_row * hdr->height;
+ if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) {
+ cfxlog(@"shm: pixel range exceeds mapping");
+ return NULL;
+ }
+ *outLen = len;
+ return hdr;
+}
+
static void cfx_release_bytes(void *refcon, const void *base) {
(void)refcon;
free((void *)base);
@@ -104,14 +145,10 @@ static void cfx_cg_release_data(void *info, const void *data, size_t size) {
}
static CMSampleBufferRef cfx_build_cmsb(void) {
- if (!cfx_shm_open()) return NULL;
- const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;
+ size_t len = 0;
+ const cfx_shm_header_t *hdr = cfx_shm_frame(&len);
+ if (!hdr) return NULL;
uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;
- if (!w || !h || !bpr) { cfxlog(@"shm header zeros"); return NULL; }
- size_t len = (size_t)bpr * h;
- if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) {
- cfxlog(@"shm: pixel range exceeds mapping"); return NULL;
- }
void *pixels = malloc(len);
if (!pixels) return NULL;
memcpy(pixels, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);
@@ -190,11 +227,12 @@ static IMP cfx_orig_capturePhoto = NULL;
// Forward decls: helpers defined further down — shared with the
// moment-capture (Camera.app) delivery path.
static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED;
-static CGImageRef cfx_build_cgimage_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED;
-static NSData *cfx_build_jpeg_from_shm(uint32_t *outW, uint32_t *outH);
+static CGImageRef cfx_build_cgimage_from_shm(void) CF_RETURNS_RETAINED;
+static NSData *cfx_build_jpeg_from_shm(void);
static id cfx_build_avcapturephoto_with_request(IOSurfaceRef surf,
uint32_t w, uint32_t h,
id captureRequest);
+static BOOL cfx_output_is_for_vcam(id self);
// Associated-object keys (used by fileDataRepresentation /
// CGImageRepresentation hooks to recognize "our" photos). Defined here
@@ -203,7 +241,24 @@ static id cfx_build_avcapturephoto_with_request(IOSurfaceRef surf,
static const void *CFX_ASSOC_JPEG_KEY = &CFX_ASSOC_JPEG_KEY;
static const void *CFX_ASSOC_CGIMG_KEY = &CFX_ASSOC_CGIMG_KEY;
-static void cfx_deliver_capturePhoto(id output, id delegate, id settings) {
+// Tag a synthesized photo with our JPEG + CGImage so fileDataRepresentation
+// / CGImageRepresentation return our bytes. Returns the JPEG so the caller
+// can log its size.
+static NSData *cfx_stamp_photo(id photo) {
+ NSData *jpeg = cfx_build_jpeg_from_shm();
+ CGImageRef cgImg = cfx_build_cgimage_from_shm();
+ if (jpeg) objc_setAssociatedObject(photo, CFX_ASSOC_JPEG_KEY, jpeg,
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ if (cgImg) {
+ objc_setAssociatedObject(photo, CFX_ASSOC_CGIMG_KEY,
+ (__bridge id)cgImg,
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ CGImageRelease(cgImg);
+ }
+ return jpeg;
+}
+
+static void cfx_deliver_capturePhoto(id output, id delegate) {
// Modern path used by any AVF client: build a real AVCapturePhoto from
// the shm frame, tag it with our JPEG + CGImage so fileDataRepresentation
// / CGImageRepresentation return our bytes, fire the modern delegate
@@ -240,16 +295,7 @@ static void cfx_deliver_capturePhoto(id output, id delegate, id settings) {
CFRelease(surf);
if (!photo) { cfxlog(@"[capturePhoto] no AVCapturePhoto"); return; }
- NSData *jpeg = cfx_build_jpeg_from_shm(NULL, NULL);
- CGImageRef cgImg = cfx_build_cgimage_from_shm(NULL, NULL);
- if (jpeg) objc_setAssociatedObject(photo, CFX_ASSOC_JPEG_KEY, jpeg,
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- if (cgImg) {
- objc_setAssociatedObject(photo, CFX_ASSOC_CGIMG_KEY,
- (__bridge id)cgImg,
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- CGImageRelease(cgImg);
- }
+ NSData *jpeg = cfx_stamp_photo(photo);
cfxlog(@"[capturePhoto] firing didFinishProcessingPhoto: with vcam photo (%lu bytes jpeg)",
(unsigned long)jpeg.length);
((void (*)(id, SEL, id, id, id))objc_msgSend)(delegate, S5, output, photo, nil);
@@ -258,22 +304,7 @@ static void cfx_deliver_capturePhoto(id output, id delegate, id settings) {
static void cfx_capturePhoto_hook(id self, SEL _cmd, id settings, id delegate) {
cfxlog(@"[capturePhoto] self=%p settings=%@ delegate=%@",
self, settings, delegate);
- BOOL forVcam = NO;
- @try {
- NSArray *conns = [self valueForKey:@"connections"];
- for (AVCaptureConnection *conn in conns) {
- for (AVCaptureInputPort *port in conn.inputPorts) {
- id input = port.input;
- if ([input isKindOfClass:[AVCaptureDeviceInput class]]) {
- AVCaptureDevice *d = ((AVCaptureDeviceInput *)input).device;
- if ([d.uniqueID isEqualToString:VCAM_UID]) { forVcam = YES; break; }
- }
- }
- if (forVcam) break;
- }
- } @catch (NSException *e) {
- cfxlog(@"connection probe exception: %@", e);
- }
+ BOOL forVcam = cfx_output_is_for_vcam(self);
cfxlog(@"forVcam=%d", forVcam);
if (!forVcam) {
@@ -283,10 +314,9 @@ static void cfx_capturePhoto_hook(id self, SEL _cmd, id settings, id delegate) {
}
__strong id retainedSelf = self;
__strong id retainedDelegate = delegate;
- __strong id retainedSettings = settings;
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
@autoreleasepool {
- cfx_deliver_capturePhoto(retainedSelf, retainedDelegate, retainedSettings);
+ cfx_deliver_capturePhoto(retainedSelf, retainedDelegate);
}
});
}
@@ -318,34 +348,9 @@ static dispatch_source_t cfx_preview_timer = NULL;
static IMP cfx_orig_pv_initWithSession = NULL;
static IMP cfx_orig_pv_initWithSessionMakeConnection = NULL;
-static CGImageRef cfx_make_cgimage_from_shm(void) CF_RETURNS_RETAINED;
-static CGImageRef cfx_make_cgimage_from_shm(void) {
- if (!cfx_shm_open()) return NULL;
- const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;
- uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;
- if (!w || !h || !bpr) return NULL;
- size_t len = (size_t)bpr * h;
- if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) return NULL;
- CFDataRef data = CFDataCreate(kCFAllocatorDefault,
- cfx_shm_base + CFX_SHM_HEADER_SIZE, len);
- if (!data) return NULL;
- CGDataProviderRef prov = CGDataProviderCreateWithCFData(data);
- CFRelease(data);
- if (!prov) return NULL;
- CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
- // BGRA byte order = kCGImageAlphaPremultipliedFirst + kCGBitmapByteOrder32Little
- CGImageRef img = CGImageCreate(
- w, h, 8, 32, bpr, cs,
- kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little,
- prov, NULL, false, kCGRenderingIntentDefault);
- CGColorSpaceRelease(cs);
- CGDataProviderRelease(prov);
- return img;
-}
-
static void cfx_pump_preview_once(void) {
if (!cfx_preview_layers || cfx_preview_layers.count == 0) return;
- CGImageRef img = cfx_make_cgimage_from_shm();
+ CGImageRef img = cfx_build_cgimage_from_shm();
if (!img) return;
dispatch_async(dispatch_get_main_queue(), ^{
for (CALayer *layer in cfx_preview_layers) {
@@ -370,6 +375,12 @@ static void cfx_preview_start_timer(void) {
cfxlog(@"preview pump armed (30 Hz)");
}
+static void cfx_adopt_preview_layer(id layer) {
+ if (!cfx_preview_layers) cfx_preview_layers = [NSHashTable weakObjectsHashTable];
+ [cfx_preview_layers addObject:layer];
+ cfx_preview_start_timer();
+}
+
static BOOL cfx_session_is_for_vcam(AVCaptureSession *session) {
@try {
for (AVCaptureInput *inp in session.inputs) {
@@ -389,11 +400,7 @@ static id cfx_pv_initWithSession_hook(id self, SEL _cmd, AVCaptureSession *sessi
BOOL forVcam = (session != nil) && cfx_session_is_for_vcam(session);
cfxlog(@"[PVLayer initWithSession:%p] ret=%p forVcam=%d cls=%@",
session, ret, forVcam, NSStringFromClass([ret class]));
- if (ret && forVcam) {
- if (!cfx_preview_layers) cfx_preview_layers = [NSHashTable weakObjectsHashTable];
- [cfx_preview_layers addObject:ret];
- cfx_preview_start_timer();
- }
+ if (ret && forVcam) cfx_adopt_preview_layer(ret);
return ret;
}
@@ -407,11 +414,7 @@ static id cfx_pv_initWithSessionMakeConnection_hook(id self, SEL _cmd,
BOOL forVcam = (session != nil) && cfx_session_is_for_vcam(session);
cfxlog(@"[PVLayer _initWithSession:%p makeConnection:%d] ret=%p forVcam=%d cls=%@",
session, makeConnection, ret, forVcam, NSStringFromClass([ret class]));
- if (ret && forVcam) {
- if (!cfx_preview_layers) cfx_preview_layers = [NSHashTable weakObjectsHashTable];
- [cfx_preview_layers addObject:ret];
- cfx_preview_start_timer();
- }
+ if (ret && forVcam) cfx_adopt_preview_layer(ret);
return ret;
}
@@ -422,11 +425,7 @@ static void cfx_pv_setSession_hook(id self, SEL _cmd, AVCaptureSession *session)
BOOL forVcam = (session != nil) && cfx_session_is_for_vcam(session);
cfxlog(@"[PVLayer setSession:%p] self=%p forVcam=%d cls=%@",
session, self, forVcam, NSStringFromClass([self class]));
- if (session && forVcam) {
- if (!cfx_preview_layers) cfx_preview_layers = [NSHashTable weakObjectsHashTable];
- [cfx_preview_layers addObject:self];
- cfx_preview_start_timer();
- }
+ if (session && forVcam) cfx_adopt_preview_layer(self);
}
// Diagnostic: every CALayer subclass that has setSession: should fire here.
@@ -659,37 +658,19 @@ static BOOL cfx_output_is_for_vcam(id self) {
}
}
}
- } @catch (NSException *e) {}
- return NO;
-}
-
-static void cfx_deliver_photo_to_delegate(id output, id delegate) {
- if (!delegate) return;
- CMSampleBufferRef sbuf = cfx_build_cmsb();
- if (!sbuf) { cfxlog(@"deliver: no shm sample"); return; }
- SEL oldSel = NSSelectorFromString(
- @"captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:");
- if ([delegate respondsToSelector:oldSel]) {
- cfxlog(@"deliver: firing deprecated delegate");
- ((void (*)(id, SEL, id, CMSampleBufferRef, CMSampleBufferRef, id, id, id))objc_msgSend)(
- delegate, oldSel, output, sbuf, NULL, (id)nil, (id)nil, (id)nil);
- } else {
- cfxlog(@"deliver: no deprecated delegate; AVCapturePhoto path needs 27-arg init we don't synthesize");
+ } @catch (NSException *e) {
+ cfxlog(@"connection probe exception: %@", e);
}
- CFRelease(sbuf);
+ return NO;
}
// MARK: - JPEG + IOSurface builders
-typedef struct { int32_t width, height; } cfx_video_dims_t;
-
-static NSData *cfx_build_jpeg_from_shm(uint32_t *outW, uint32_t *outH) {
- if (!cfx_shm_open()) return nil;
- const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;
+static NSData *cfx_build_jpeg_from_shm(void) {
+ size_t len = 0;
+ const cfx_shm_header_t *hdr = cfx_shm_frame(&len);
+ if (!hdr) return nil;
uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;
- if (!w || !h || !bpr) return nil;
- size_t len = (size_t)bpr * h;
- if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) return nil;
void *copy = malloc(len);
if (!copy) return nil;
@@ -715,18 +696,14 @@ static NSData *cfx_build_jpeg_from_shm(uint32_t *outW, uint32_t *outH) {
CFRelease(dest);
CGImageRelease(img);
if (!ok) return nil;
- if (outW) *outW = w;
- if (outH) *outH = h;
return data;
}
-static CGImageRef cfx_build_cgimage_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED {
- if (!cfx_shm_open()) return NULL;
- const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;
+static CGImageRef cfx_build_cgimage_from_shm(void) CF_RETURNS_RETAINED {
+ size_t len = 0;
+ const cfx_shm_header_t *hdr = cfx_shm_frame(&len);
+ if (!hdr) return NULL;
uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;
- if (!w || !h || !bpr) return NULL;
- size_t len = (size_t)bpr * h;
- if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) return NULL;
void *copy = malloc(len);
if (!copy) return NULL;
memcpy(copy, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);
@@ -739,18 +716,14 @@ static CGImageRef cfx_build_cgimage_from_shm(uint32_t *outW, uint32_t *outH) CF_
dp, NULL, false, kCGRenderingIntentDefault);
CGDataProviderRelease(dp);
CGColorSpaceRelease(cs);
- if (outW) *outW = w;
- if (outH) *outH = h;
return img;
}
static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED {
- if (!cfx_shm_open()) return NULL;
- const cfx_shm_header_t *hdr = (const cfx_shm_header_t *)cfx_shm_base;
+ size_t len = 0;
+ const cfx_shm_header_t *hdr = cfx_shm_frame(&len);
+ if (!hdr) return NULL;
uint32_t w = hdr->width, h = hdr->height, bpr = hdr->bytes_per_row;
- if (!w || !h || !bpr) return NULL;
- size_t len = (size_t)bpr * h;
- if ((size_t)CFX_SHM_HEADER_SIZE + len > cfx_shm_size) return NULL;
NSDictionary *props = @{
(NSString *)kIOSurfaceWidth: @(w),
(NSString *)kIOSurfaceHeight: @(h),
@@ -887,34 +860,6 @@ static id cfx_invoke_with_labeled_args(id target, SEL selector,
// MARK: - AVCapturePhoto / Resolved settings synthesis
-static id cfx_build_resolved_settings(int64_t uniqueID, int32_t w, int32_t h) {
- Class cls = NSClassFromString(@"AVCaptureResolvedPhotoSettings");
- if (!cls) return nil;
- SEL sel = cfx_find_selector_by_prefix(cls, @"resolvedSettingsWithUniqueID:",
- /*classMethod*/YES);
- if (!sel) { cfxlog(@"resolved: no factory selector found"); return nil; }
-
- cfx_video_dims_t photoDim = {w, h};
- cfx_video_dims_t previewDim = {w / 4, h / 4};
- id result = cfx_invoke_with_labeled_args(
- cls, sel,
- ^(NSString *label, const char *typeEnc, void *out) {
- if ([label isEqualToString:@"uniqueID"]) {
- *(int64_t *)out = uniqueID;
- } else if ([label isEqualToString:@"photoDimensions"]) {
- *(cfx_video_dims_t *)out = photoDim;
- } else if ([label isEqualToString:@"previewDimensions"]) {
- *(cfx_video_dims_t *)out = previewDim;
- }
- // All other labels (rawPhotoDimensions, livePhotoMovieEnabled,
- // photoManifest, etc.) stay zeroed/nil — the factory tolerates
- // it on builds where this whole path even works at all
- // (26.5 trips on nil photoManifest, hence the fallback below).
- });
- if (result) cfxlog(@"resolved settings built: %p uid=%lld", result, uniqueID);
- return result;
-}
-
static id cfx_build_avcapturephoto_with_request(IOSurfaceRef surf,
uint32_t w, uint32_t h,
id captureRequest) {
@@ -970,10 +915,6 @@ static id cfx_build_avcapturephoto_with_request(IOSurfaceRef surf,
return result;
}
-static id cfx_build_avcapturephoto(IOSurfaceRef surf, uint32_t w, uint32_t h) {
- return cfx_build_avcapturephoto_with_request(surf, w, h, nil);
-}
-
// MARK: - fileDataRepresentation / CGImageRepresentation hooks
//
// We tag synthesized photos via objc_setAssociatedObject so the hook
@@ -1067,7 +1008,7 @@ static void cfx_drive_capture(id output, id delegate, id settings) {
if (!surf || !w || !h) {
cfxlog(@"[drive] no IOSurface — falling back to error finish");
NSError *err = [NSError errorWithDomain:AVFoundationErrorDomain code:-11800
- userInfo:@{NSLocalizedDescriptionKey:@"vcam no shm"}];
+ userInfo:@{NSLocalizedDescriptionKey:@"Unable to take the photo. Try again."}];
SEL finishSel = @selector(captureOutput:didFinishCaptureForResolvedSettings:error:);
if ([delegate respondsToSelector:finishSel]) {
((void (*)(id, SEL, id, id, id))objc_msgSend)(delegate, finishSel, output, nil, err);
@@ -1086,16 +1027,7 @@ static void cfx_drive_capture(id output, id delegate, id settings) {
}
// Stamp it with our JPEG so fileDataRepresentation returns our bytes.
- NSData *jpeg = cfx_build_jpeg_from_shm(NULL, NULL);
- CGImageRef cgImg = cfx_build_cgimage_from_shm(NULL, NULL);
- if (jpeg) objc_setAssociatedObject(photo, CFX_ASSOC_JPEG_KEY, jpeg,
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- if (cgImg) {
- objc_setAssociatedObject(photo, CFX_ASSOC_CGIMG_KEY,
- (__bridge id)cgImg,
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- CGImageRelease(cgImg);
- }
+ NSData *jpeg = cfx_stamp_photo(photo);
cfxlog(@"[drive] photo stamped jpeg=%lu bytes", (unsigned long)jpeg.length);
// Fire the FULL standard delegate sequence. CAMCaptureEngine tracks
@@ -1268,21 +1200,8 @@ static void cfx_install_moment_capture_hooks(void) {
static IMP cfx_orig_setRunning = NULL;
static IMP cfx_orig_setInterrupted = NULL;
-static BOOL cfx_session_uses_vcam(id session) {
- @try {
- NSArray *inputs = [session valueForKey:@"inputs"];
- for (id inp in inputs) {
- if ([inp isKindOfClass:[AVCaptureDeviceInput class]]) {
- AVCaptureDevice *d = ((AVCaptureDeviceInput *)inp).device;
- if ([d.uniqueID isEqualToString:VCAM_UID]) return YES;
- }
- }
- } @catch (NSException *e) {}
- return NO;
-}
-
static void cfx_session_setRunning_hook(id self, SEL _cmd, BOOL running) {
- if (!running && cfx_session_uses_vcam(self)) {
+ if (!running && cfx_session_is_for_vcam(self)) {
cfxlog(@"[session _setRunning:NO] suppressed for vcam session %p", self);
return;
}
@@ -1294,7 +1213,7 @@ static void cfx_session_setInterrupted_hook(id self, SEL _cmd,
BOOL interrupted,
long reason,
id interruptor) {
- if (interrupted && cfx_session_uses_vcam(self)) {
+ if (interrupted && cfx_session_is_for_vcam(self)) {
cfxlog(@"[session _setInterrupted:YES reason=%ld] suppressed for vcam session %p",
reason, self);
return;
@@ -1338,7 +1257,7 @@ static int cfx_isInterrupted_logged = 0;
static BOOL cfx_session_isRunning_hook(id self, SEL _cmd) {
typedef BOOL (*Fn)(id, SEL);
BOOL real = ((Fn)cfx_orig_isRunning)(self, _cmd);
- if (cfx_session_uses_vcam(self)) {
+ if (cfx_session_is_for_vcam(self)) {
if (cfx_isRunning_logged < 3) {
cfxlog(@"[isRunning] real=%d -> forcing YES (session=%p)", real, self);
cfx_isRunning_logged++;
@@ -1351,7 +1270,7 @@ static BOOL cfx_session_isRunning_hook(id self, SEL _cmd) {
static BOOL cfx_session_isInterrupted_hook(id self, SEL _cmd) {
typedef BOOL (*Fn)(id, SEL);
BOOL real = ((Fn)cfx_orig_isInterrupted)(self, _cmd);
- if (cfx_session_uses_vcam(self) && real) {
+ if (cfx_session_is_for_vcam(self) && real) {
if (cfx_isInterrupted_logged < 3) {
cfxlog(@"[isInterrupted] real=%d -> forcing NO (session=%p)", real, self);
cfx_isInterrupted_logged++;
diff --git a/scripts/cfw_install.sh b/scripts/cfw_install.sh
index 83a94a0e..aecae494 100755
--- a/scripts/cfw_install.sh
+++ b/scripts/cfw_install.sh
@@ -14,7 +14,7 @@
# - VM restored (make restore) and powered off
# - `ipsw` tool installed (brew install blacktop/tap/ipsw)
# - `aea` tool available (macOS 12+)
-# - Python: make setup_venv && source .venv/bin/activate
+# - Python: make setup_tools && source .venv/bin/activate
# - cfw_input/ or resources/cfw_input.tar.zst present
#
# Usage: make cfw_install
@@ -60,7 +60,7 @@ die() {
exit 1
}
-check_prerequisites() {
+require_signing_tools() {
local missing=()
command -v ldid &>/dev/null || missing+=("ldid (brew install ldid-procursus)")
if ((${#missing[@]} > 0)); then
@@ -146,14 +146,14 @@ setup_cfw_input() {
}
# ── Check prerequisites ────────────────────────────────────────
-check_prereqs() {
+require_firmware_tools() {
command -v ipsw >/dev/null 2>&1 || die "'ipsw' not found. Install: brew install blacktop/tap/ipsw"
command -v aea >/dev/null 2>&1 || die "'aea' not found (requires macOS 12+)"
- [[ -x "$PYTHON3" ]] || die "python3 not found (tried: $PYTHON3). Run: make setup_venv"
+ [[ -x "$PYTHON3" ]] || die "python3 not found (tried: $PYTHON3). Run: make setup_tools"
echo "[*] Python: $PYTHON3 ($("$PYTHON3" --version 2>&1))"
local py_err
py_err="$("$PYTHON3" -c "import capstone, keystone" 2>&1)" || {
- die "Missing Python deps (using $PYTHON3).\n Error: ${py_err}\n Fix: source ${SCRIPT_DIR:h}/.venv/bin/activate && pip install capstone keystone-engine\n Or: make setup_venv"
+ die "Missing Python dependencies (using $PYTHON3).\n Error: ${py_err}\n Fix: source ${SCRIPT_DIR:h}/.venv/bin/activate && pip install capstone keystone-engine\n Or: make setup_tools"
}
}
@@ -188,7 +188,7 @@ mount_vol() { # mount_vol <slice, e.g. s1> <mountpoint> [opts]
# ════════════════════════════════════════════════════════════════
echo "[*] cfw_install.sh — Installing CFW on vphone..."
-check_prereqs
+require_firmware_tools
RESTORE_DIR=$(find_restore_dir)
echo "[+] Restore directory: $RESTORE_DIR"
@@ -196,7 +196,7 @@ echo "[+] Restore directory: $RESTORE_DIR"
setup_cfw_input
INPUT_DIR="$VM_DIR/$CFW_INPUT"
echo "[+] Input resources: $INPUT_DIR"
-check_prerequisites
+require_signing_tools
mkdir -p "$TEMP_DIR"
@@ -324,16 +324,12 @@ fi
# kernel patches that make the userclient accept 27's native 0x6e0 struct.
IOS_VERSION=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
-IOMFB_TARGET=""
-case "$IOS_VERSION" in
- 26.0*|18.*) IOMFB_TARGET=0x560 ;;
-esac
-if [[ -n "$IOMFB_TARGET" ]]; then
- echo " [*] Patching IOMobileFramebuffer SwapEnd payload size (iOS $IOS_VERSION -> $IOMFB_TARGET)..."
- [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
- "$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-iomfb-swapend "$DSC_DIR" --target-size "$IOMFB_TARGET"
-fi
case "$IOS_VERSION" in
+ 26.0*|18.*)
+ echo " [*] Patching IOMobileFramebuffer SwapEnd payload size (iOS $IOS_VERSION -> 0x560)..."
+ [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
+ "$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-iomfb-swapend "$DSC_DIR" --target-size 0x560
+ ;;
27.*)
echo " [*] Forcing IOMobileFramebuffer present onto the kern (method-5) path (iOS $IOS_VERSION)..."
[[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
@@ -360,7 +356,6 @@ esac
# bluetoothd/...). Absent on 26.x/18.x libxpc (self-gating patcher no-ops there).
# FORCE_DSC_MAXSLIDE=1 (default 0): opt in to zeroing maxSlide on non-27 bases,
# whose caches fit and would otherwise self-gate to a no-op (--force bypasses that).
-DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
FORCE_DSC_MAXSLIDE="${FORCE_DSC_MAXSLIDE:-0}"
case "$IOS_VERSION" in
27.*)
diff --git a/scripts/cfw_install_dev.sh b/scripts/cfw_install_dev.sh
index fc898abb..14e00761 100755
--- a/scripts/cfw_install_dev.sh
+++ b/scripts/cfw_install_dev.sh
@@ -14,7 +14,7 @@
# - VM restored (make restore) and powered off
# - `ipsw` tool installed (brew install blacktop/tap/ipsw)
# - `aea` tool available (macOS 12+)
-# - Python: make setup_venv && source .venv/bin/activate
+# - Python: make setup_tools && source .venv/bin/activate
# - cfw_input/ or resources/cfw_input.tar.zst + resources/cfw_dev/rpcserver_ios present
#
# Usage: make cfw_install_dev
@@ -55,7 +55,7 @@ die() {
exit 1
}
-check_prerequisites() {
+require_signing_tools() {
local missing=()
command -v ldid &>/dev/null || missing+=("ldid (brew install ldid-procursus)")
if ((${#missing[@]} > 0)); then
@@ -141,14 +141,14 @@ apply_dev_overlay() {
}
# ── Check prerequisites ────────────────────────────────────────
-check_prereqs() {
+require_firmware_tools() {
command -v ipsw >/dev/null 2>&1 || die "'ipsw' not found. Install: brew install blacktop/tap/ipsw"
command -v aea >/dev/null 2>&1 || die "'aea' not found (requires macOS 12+)"
- [[ -x "$PYTHON3" ]] || die "python3 not found (tried: $PYTHON3). Run: make setup_venv"
+ [[ -x "$PYTHON3" ]] || die "python3 not found (tried: $PYTHON3). Run: make setup_tools"
echo "[*] Python: $PYTHON3 ($("$PYTHON3" --version 2>&1))"
local py_err
py_err="$("$PYTHON3" -c "import capstone, keystone" 2>&1)" || {
- die "Missing Python deps (using $PYTHON3).\n Error: ${py_err}\n Fix: source ${SCRIPT_DIR:h}/.venv/bin/activate && pip install capstone keystone-engine\n Or: make setup_venv"
+ die "Missing Python dependencies (using $PYTHON3).\n Error: ${py_err}\n Fix: source ${SCRIPT_DIR:h}/.venv/bin/activate && pip install capstone keystone-engine\n Or: make setup_tools"
}
}
@@ -183,7 +183,7 @@ mount_vol() { # mount_vol <slice, e.g. s1> <mountpoint> [opts]
# ════════════════════════════════════════════════════════════════
echo "[*] cfw_install.sh — Installing CFW on vphone..."
-check_prereqs
+require_firmware_tools
RESTORE_DIR=$(find_restore_dir)
echo "[+] Restore directory: $RESTORE_DIR"
@@ -192,7 +192,7 @@ setup_cfw_input
apply_dev_overlay
INPUT_DIR="$VM_DIR/$CFW_INPUT"
echo "[+] Input resources: $INPUT_DIR"
-check_prerequisites
+require_signing_tools
mkdir -p "$TEMP_DIR"
@@ -327,16 +327,14 @@ echo " [+] Cryptex installed"
# accept iOS 27's native 0x6e0 struct (variable-size dispatch), so 27 must send
# its native size — leave it unpatched here.
IOS_VERSION=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
-IOMFB_TARGET=""
case "$IOS_VERSION" in
- 26.0*|18.*) IOMFB_TARGET=0x560 ;;
+ 26.0*|18.*)
+ echo " [*] Patching IOMobileFramebuffer SwapEnd payload size (iOS $IOS_VERSION -> 0x560)..."
+ DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
+ [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
+ "$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-iomfb-swapend "$DSC_DIR" --target-size 0x560
+ ;;
esac
-if [[ -n "$IOMFB_TARGET" ]]; then
- echo " [*] Patching IOMobileFramebuffer SwapEnd payload size (iOS $IOS_VERSION -> $IOMFB_TARGET)..."
- DSC_DIR="$MNT1/System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
- [[ -d "$DSC_DIR" ]] || die "dyld cache dir missing: $DSC_DIR"
- "$PYTHON3" "$SCRIPT_DIR/patchers/cfw.py" patch-iomfb-swapend "$DSC_DIR" --target-size "$IOMFB_TARGET"
-fi
# ═══════════ 2/7 PATCH SEPUTIL ════════════════════════════════
echo ""
diff --git a/scripts/cfw_install_exp.sh b/scripts/cfw_install_exp.sh
index 95d3561d..9544e0a7 100755
--- a/scripts/cfw_install_exp.sh
+++ b/scripts/cfw_install_exp.sh
@@ -31,7 +31,7 @@ set -euo pipefail
# ── Restore caller's PATH — Nix /etc/zshenv resets PATH on zsh startup ─
[[ -n "${_VPHONE_PATH:-}" ]] && export PATH="$_VPHONE_PATH"
-VM_DIR="${1:-.}"
+VM_DIR="$(cd "${1:-.}" && pwd)"
SCRIPT_DIR="${0:a:h}"
# ── Python resolver — prefer project venv over whatever is in PATH ─
@@ -69,15 +69,14 @@ echo ""
# is the EXP variant's device-like user-mode patching, kept out of
# the JB install path so JB remains unaffected.
# ────────────────────────────────────────────────────────────────────
-VM_DIR_ABS="$(cd "${VM_DIR:-.}" && pwd)"
-JB_TEMP_DIR="$VM_DIR_ABS/.cfw_temp"
+JB_TEMP_DIR="$VM_DIR/.cfw_temp"
JB_SYSOS_DMG="$JB_TEMP_DIR/CryptexSystemOS.dmg"
JB_MNT_SYSOS="$JB_TEMP_DIR/mnt_sysos_hv_vmm"
mkdir -p "$JB_TEMP_DIR"
# Find the restore directory (same logic as cfw_install.sh)
JB_RESTORE_DIR=""
-for d in "$VM_DIR_ABS"/iPhone*_Restore; do
+for d in "$VM_DIR"/iPhone*_Restore; do
[[ -d "$d" ]] && { JB_RESTORE_DIR="$d"; break; }
done
@@ -145,9 +144,6 @@ zsh "$SCRIPT_DIR/cfw_install.sh" "$VM_DIR"
# Step 2: JB-specific phases
# ════════════════════════════════════════════════════════════════
-# Resolve absolute paths (same as base script)
-VM_DIR="$(cd "${VM_DIR}" && pwd)"
-
# ── Configuration ───────────────────────────────────────────────
CFW_INPUT="cfw_input"
CFW_JB_INPUT="cfw_jb_input"
@@ -454,12 +450,12 @@ echo " [+] debugserver entitlements patched"
# Grant Campo the backboard/frontboard mach-lookups the 26.4 temporary-sandbox denies (see 0_binary_patch_comparison.md #14).
# 27-gated on the mounted rootfs SystemVersion.plist: 26.x userlands don't need it and Campo.app exists there too.
CAMPO_BIN="$MNT1/Applications/Campo.app/Campo"
-CAMPO_BASE_IOS=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
-case "$CAMPO_BASE_IOS" in
+BASE_IOS=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
+case "$BASE_IOS" in
27.*)
if [[ -f "$CAMPO_BIN" ]]; then
echo ""
- echo "[JB-3b] Granting Campo backboard/frontboard mach-lookup exceptions (iOS $CAMPO_BASE_IOS)..."
+ echo "[JB-3b] Granting Campo backboard/frontboard mach-lookup exceptions (iOS $BASE_IOS)..."
cp "$CAMPO_BIN" "$TEMP_DIR/Campo"
ldid -e "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true
if [[ -s "$TEMP_DIR/Campo.entitlements" ]]; then
@@ -476,7 +472,7 @@ case "$CAMPO_BASE_IOS" in
fi
;;
*)
- echo "[JB-3b] skip Campo sandbox fix (base iOS ${CAMPO_BASE_IOS:-unknown} — 27-only)"
+ echo "[JB-3b] skip Campo sandbox fix (base iOS ${BASE_IOS:-unknown} — 27-only)"
;;
esac
@@ -683,18 +679,17 @@ fi
# script must NOT version-check on guest sw_vers — the hybrid guest does not reliably
# report the 27 userland version at first boot). Version read from the mounted rootfs
# SystemVersion.plist, the same source cfw_install.sh gates its 27 patches on.
-JB_BASE_IOS=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
-case "$JB_BASE_IOS" in
+case "$BASE_IOS" in
27.*)
VPREGISTER="$(build_vpregister)"
if [[ -f "$VPREGISTER" ]]; then
cp -R "$VPREGISTER" "$MNT1/cores/vpregister"
/bin/chmod 0755 $MNT1/cores/vpregister
- echo " [+] vpregister -> /cores/ (iOS $JB_BASE_IOS)"
+ echo " [+] vpregister -> /cores/ (iOS $BASE_IOS)"
fi
;;
*)
- echo " [skip] vpregister (base iOS ${JB_BASE_IOS:-unknown} — 27-only; uicache registers apps on older bases)"
+ echo " [skip] vpregister (base iOS ${BASE_IOS:-unknown} — 27-only; uicache registers apps on older bases)"
;;
esac
if [[ -f "$SETUP_PLIST" ]]; then
diff --git a/scripts/cfw_install_jb.sh b/scripts/cfw_install_jb.sh
index 56a8d1f3..672a9b18 100755
--- a/scripts/cfw_install_jb.sh
+++ b/scripts/cfw_install_jb.sh
@@ -285,12 +285,12 @@ echo " [+] debugserver entitlements patched"
# Grant Campo the backboard/frontboard mach-lookups the 26.4 temporary-sandbox denies (see 0_binary_patch_comparison.md #14).
# 27-gated on the mounted rootfs SystemVersion.plist (same source as vpregister/DSC gates): 26.x userlands don't need it and Campo.app exists there too.
CAMPO_BIN="$MNT1/Applications/Campo.app/Campo"
-CAMPO_BASE_IOS=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
-case "$CAMPO_BASE_IOS" in
+BASE_IOS=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
+case "$BASE_IOS" in
27.*)
if [[ -f "$CAMPO_BIN" ]]; then
echo ""
- echo "[JB-3b] Granting Campo backboard/frontboard mach-lookup exceptions (iOS $CAMPO_BASE_IOS)..."
+ echo "[JB-3b] Granting Campo backboard/frontboard mach-lookup exceptions (iOS $BASE_IOS)..."
cp "$CAMPO_BIN" "$TEMP_DIR/Campo"
ldid -e "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true
if [[ -s "$TEMP_DIR/Campo.entitlements" ]]; then
@@ -307,7 +307,7 @@ case "$CAMPO_BASE_IOS" in
fi
;;
*)
- echo "[JB-3b] skip Campo sandbox fix (base iOS ${CAMPO_BASE_IOS:-unknown} — 27-only)"
+ echo "[JB-3b] skip Campo sandbox fix (base iOS ${BASE_IOS:-unknown} — 27-only)"
;;
esac
@@ -437,18 +437,17 @@ fi
# script must NOT version-check on guest sw_vers — the hybrid guest does not reliably
# report the 27 userland version at first boot). Version read from the mounted rootfs
# SystemVersion.plist, the same source cfw_install.sh gates its 27 patches on.
-JB_BASE_IOS=$(/usr/bin/plutil -extract ProductVersion raw -o - "$MNT1/System/Library/CoreServices/SystemVersion.plist" 2>/dev/null || true)
-case "$JB_BASE_IOS" in
+case "$BASE_IOS" in
27.*)
VPREGISTER="$(build_vpregister)"
if [[ -f "$VPREGISTER" ]]; then
cp -R "$VPREGISTER" "$MNT1/cores/vpregister"
/bin/chmod 0755 $MNT1/cores/vpregister
- echo " [+] vpregister -> /cores/ (iOS $JB_BASE_IOS)"
+ echo " [+] vpregister -> /cores/ (iOS $BASE_IOS)"
fi
;;
*)
- echo " [skip] vpregister (base iOS ${JB_BASE_IOS:-unknown} — 27-only; uicache registers apps on older bases)"
+ echo " [skip] vpregister (base iOS ${BASE_IOS:-unknown} — 27-only; uicache registers apps on older bases)"
;;
esac
if [[ -f "$SETUP_PLIST" ]]; then
diff --git a/scripts/patchers/campo_mach_lookup_exceptions.py b/scripts/patchers/campo_mach_lookup_exceptions.py
index bd2053b4..d44ef6a3 100644
--- a/scripts/patchers/campo_mach_lookup_exceptions.py
+++ b/scripts/patchers/campo_mach_lookup_exceptions.py
@@ -48,7 +48,7 @@ def merge(path):
def main(argv):
if len(argv) != 2:
- print("usage: campo_mach_lookup_exceptions.py <entitlements.plist>",
+ print("Usage: campo_mach_lookup_exceptions.py <entitlements.plist>",
file=sys.stderr)
return 2
merge(argv[1])
diff --git a/scripts/patchers/cfw.py b/scripts/patchers/cfw.py
index a9c076f9..2a4c147b 100755
--- a/scripts/patchers/cfw.py
+++ b/scripts/patchers/cfw.py
@@ -59,7 +59,6 @@ Commands:
installs. Self-gating (no-op on pre-iOS-27 userlands where the method is absent).
patch-xpc-lwcr <chunks_dir> [--dry-run]
- patch-lockdown-mode <chunks_dir> [--dry-run]
Stop libxpc's Lightweight Code Requirement self-check (_xpc_token_satisfies_lwcr)
from brk-aborting on our JB. iOS 27's LWCR matcher returns the contradictory
(matched=0, error_code=MATCH) pair under our code-signing environment; the
@@ -68,6 +67,15 @@ Commands:
from error_code + drops the abort (cset w0,eq; nop; nop) and re-attests the page.
Self-gating (no-op on pre-iOS-27 userlands where the symbol is absent).
+ patch-lockdown-mode <chunks_dir> [--dry-run]
+ Stop libSystem's os_lockdown_mode_enabled() from aborting when the
+ Lockdown Mode sysctl is missing. iOS 27 crashes on a -1 return from
+ security.mac.lockdown_mode_state_public, which the vphone600 26.x kernel
+ does not implement, so launchd is the first caller to abort and the
+ kernel panics at boot. NOPs the error branch so the query reads 0 and
+ boot continues, then re-attests the page. Self-gating (no-op on
+ pre-iOS-27 userlands where the symbol is absent).
+
patch-camera-dsc <chunks_dir> <dsc_header> [--dry-run] [--force]
Apply the 10-patch set to the DSC chunks that makes Camera.app
launch-survivable on a vphone VM: synthesises a single
@@ -107,7 +115,8 @@ Commands:
Dependencies:
pip install capstone keystone-engine
- ipsw CLI in $PATH (only required for patch-hv-vmm-dsc, experimental variant only)
+ ipsw CLI in $PATH (required for patch-camera-dsc, patch-iomfb-swapend and
+ patch-iomfb-force-kern)
"""
import os
@@ -160,7 +169,7 @@ def main():
if cmd == "cryptex-paths":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py cryptex-paths <BuildManifest.plist>")
+ print("Usage: cfw.py cryptex-paths <BuildManifest.plist>")
sys.exit(1)
sysos, appos = parse_cryptex_paths(sys.argv[2])
print(sysos)
@@ -168,43 +177,43 @@ def main():
elif cmd == "patch-seputil":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-seputil <binary>")
+ print("Usage: cfw.py patch-seputil <binary>")
sys.exit(1)
if not patch_seputil(sys.argv[2]):
sys.exit(1)
elif cmd == "patch-launchd-cache-loader":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-launchd-cache-loader <binary>")
+ print("Usage: cfw.py patch-launchd-cache-loader <binary>")
sys.exit(1)
if not patch_launchd_cache_loader(sys.argv[2]):
sys.exit(1)
elif cmd == "patch-mobileactivationd":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-mobileactivationd <binary>")
+ print("Usage: cfw.py patch-mobileactivationd <binary>")
sys.exit(1)
if not patch_mobileactivationd(sys.argv[2]):
sys.exit(1)
elif cmd == "patch-launchd-jetsam":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-launchd-jetsam <binary>")
+ print("Usage: cfw.py patch-launchd-jetsam <binary>")
sys.exit(1)
if not patch_launchd_jetsam(sys.argv[2]):
sys.exit(1)
elif cmd == "patch-hv-vmm-dsc":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-hv-vmm-dsc <chunks_dir> [--dry-run]")
+ print("Usage: cfw.py patch-hv-vmm-dsc <chunks_dir> [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
- results = patch_hv_vmm_in_dsc(sys.argv[2], dry_run=dry_run)
+ patch_hv_vmm_in_dsc(sys.argv[2], dry_run=dry_run)
sys.exit(0)
elif cmd == "patch-iomfb-swapend":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-iomfb-swapend <chunks_dir> "
+ print("Usage: cfw.py patch-iomfb-swapend <chunks_dir> "
"[--target-size <hex|int>] [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
@@ -221,7 +230,7 @@ def main():
elif cmd == "patch-iomfb-force-kern":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-iomfb-force-kern <chunks_dir> [--dry-run]")
+ print("Usage: cfw.py patch-iomfb-force-kern <chunks_dir> [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
try:
@@ -233,7 +242,7 @@ def main():
elif cmd == "patch-dsc-maxslide":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-dsc-maxslide <chunks_dir> [--dry-run] [--force]")
+ print("Usage: cfw.py patch-dsc-maxslide <chunks_dir> [--dry-run] [--force]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
force = "--force" in sys.argv[3:]
@@ -242,7 +251,7 @@ def main():
elif cmd == "patch-lsd-embedded-reg":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-lsd-embedded-reg <chunks_dir> [--dry-run]")
+ print("Usage: cfw.py patch-lsd-embedded-reg <chunks_dir> [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
patch_lsd_embedded_reg(sys.argv[2], dry_run=dry_run)
@@ -250,14 +259,14 @@ def main():
elif cmd == "patch-xpc-lwcr":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-xpc-lwcr <chunks_dir> [--dry-run]")
+ print("Usage: cfw.py patch-xpc-lwcr <chunks_dir> [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
patch_xpc_lwcr(sys.argv[2], dry_run=dry_run)
elif cmd == "patch-lockdown-mode":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-lockdown-mode <chunks_dir> [--dry-run]")
+ print("Usage: cfw.py patch-lockdown-mode <chunks_dir> [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
patch_lockdown_mode(sys.argv[2], dry_run=dry_run)
@@ -265,7 +274,7 @@ def main():
elif cmd == "patch-camera-dsc":
if len(sys.argv) < 4:
- print("Usage: patch_cfw.py patch-camera-dsc <chunks_dir> <dsc_header> [--dry-run] [--force]")
+ print("Usage: cfw.py patch-camera-dsc <chunks_dir> <dsc_header> [--dry-run] [--force]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[4:]
force = "--force" in sys.argv[4:]
@@ -274,11 +283,11 @@ def main():
elif cmd == "patch-watchdogd":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-watchdogd <binary> [--dry-run]")
+ print("Usage: cfw.py patch-watchdogd <binary> [--dry-run]")
sys.exit(1)
dry_run = "--dry-run" in sys.argv[3:]
try:
- n = patch_watchdogd(sys.argv[2], dry_run=dry_run)
+ patch_watchdogd(sys.argv[2], dry_run=dry_run)
except ValueError as e:
print(f"[-] {e}")
sys.exit(1)
@@ -289,26 +298,26 @@ def main():
elif cmd == "patch-diskimagesiod":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-diskimagesiod <binary>")
+ print("Usage: cfw.py patch-diskimagesiod <binary>")
sys.exit(1)
if not patch_diskimagesiod(sys.argv[2]):
sys.exit(1)
elif cmd == "inject-daemons":
if len(sys.argv) < 4:
- print("Usage: patch_cfw.py inject-daemons <launchd.plist> <daemon_dir>")
+ print("Usage: cfw.py inject-daemons <launchd.plist> <daemon_dir>")
sys.exit(1)
inject_daemons(sys.argv[2], sys.argv[3])
elif cmd == "patch-dropbear-plist":
if len(sys.argv) < 3:
- print("Usage: patch_cfw.py patch-dropbear-plist <dropbear.plist>")
+ print("Usage: cfw.py patch-dropbear-plist <dropbear.plist>")
sys.exit(1)
patch_dropbear_plist(sys.argv[2])
elif cmd == "inject-dylib":
if len(sys.argv) < 4:
- print("Usage: patch_cfw.py inject-dylib <binary> <dylib_path>")
+ print("Usage: cfw.py inject-dylib <binary> <dylib_path>")
sys.exit(1)
import subprocess, shutil
insert_dylib_bin = shutil.which("insert_dylib")
diff --git a/scripts/patchers/cfw_asm.py b/scripts/patchers/cfw_asm.py
index 56f348f3..068df1e3 100644
--- a/scripts/patchers/cfw_asm.py
+++ b/scripts/patchers/cfw_asm.py
@@ -1,48 +1,9 @@
"""Shared helpers for CFW patch modules."""
-#!/usr/bin/env python3
-"""
-patch_cfw.py — Dynamic binary patching for CFW installation on vphone600.
-Uses capstone for disassembly-based anchoring and keystone for instruction
-assembly, producing reliable, upgrade-proof patches.
-
-Called by install_cfw.sh during CFW installation.
-
-Commands:
- cryptex-paths <BuildManifest.plist>
- Print SystemOS and AppOS DMG paths from BuildManifest.
-
- patch-seputil <binary>
- Patch seputil gigalocker UUID to "AA".
-
- patch-launchd-cache-loader <binary>
- NOP the cache validation check in launchd_cache_loader.
-
- patch-mobileactivationd <binary>
- Patch -[DeviceType should_hactivate] to always return true.
-
- patch-launchd-jetsam <binary>
- Patch launchd jetsam panic guard to avoid initproc crash loop.
-
- inject-daemons <launchd.plist> <daemon_dir>
- Inject bash/dropbear/trollvnc into launchd.plist.
-
- inject-dylib <binary> <dylib_path>
- Inject LC_LOAD_DYLIB into Mach-O binary (thin or universal).
- Equivalent to: optool install -c load -p <dylib_path> -t <binary>
-
-Dependencies:
- pip install capstone keystone-engine
-"""
-
-import os
-import plistlib
import struct
-import subprocess
-import sys
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN
-from capstone.arm64_const import ARM64_OP_IMM
+from capstone.arm64_const import ARM64_OP_REG, ARM64_OP_IMM
from keystone import Ks, KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN as KS_MODE_LE
# ══════════════════════════════════════════════════════════════════
@@ -94,6 +55,16 @@ def _log_asm(data, offset, count=5, marker_off=-1):
print(f" {tag} 0x{insn.address:08X}: {insn.mnemonic:8s} {insn.op_str}")
+def _mov_reg_imm(insn):
+ """If `insn` is `mov <reg>, #<imm>`, return (reg_name, imm); else None."""
+ if insn.mnemonic != "mov":
+ return None
+ ops = insn.operands
+ if len(ops) != 2 or ops[0].type != ARM64_OP_REG or ops[1].type != ARM64_OP_IMM:
+ return None
+ return insn.reg_name(ops[0].reg), ops[1].imm
+
+
# ══════════════════════════════════════════════════════════════════
# Mach-O helpers
# ══════════════════════════════════════════════════════════════════
@@ -199,9 +170,3 @@ def find_symbol_va(data, name_fragment):
return n_value
return -1
-
-
-# ══════════════════════════════════════════════════════════════════
-# 1. seputil — Gigalocker UUID patch
-# ══════════════════════════════════════════════════════════════════
-
diff --git a/scripts/patchers/cfw_daemons.py b/scripts/patchers/cfw_daemons.py
index 62a8afd7..8dbc2ccf 100644
--- a/scripts/patchers/cfw_daemons.py
+++ b/scripts/patchers/cfw_daemons.py
@@ -1,8 +1,9 @@
"""Daemon injection and cryptex path helpers."""
-from .cfw_asm import *
import os
import plistlib
+import subprocess
+import sys
DROPBEAR_KEY_ARGS = [
@@ -102,8 +103,3 @@ def patch_dropbear_plist(plist_path):
patch_dropbear_daemon(daemon)
with open(plist_path, "wb") as f:
plistlib.dump(daemon, f, sort_keys=False)
-
-
-# ══════════════════════════════════════════════════════════════════
-# CLI
-# ══════════════════════════════════════════════════════════════════
diff --git a/scripts/patchers/cfw_dsc_chunks.py b/scripts/patchers/cfw_dsc_chunks.py
index 8ba10547..d015bd33 100644
--- a/scripts/patchers/cfw_dsc_chunks.py
+++ b/scripts/patchers/cfw_dsc_chunks.py
@@ -48,15 +48,11 @@ Reference: dyld project, dyld_cache_format.h.
import os
import struct
import re
-import glob
-
-CHUNK_GLOB_NAMES = (
- "dyld_shared_cache_arm64e",
- "dyld_shared_cache_arm64e.[0-9]",
- "dyld_shared_cache_arm64e.[0-9][0-9]",
- "dyld_shared_cache_arm64e.symbols",
-)
+try:
+ from .cfw_asm import _cs
+except ImportError: # direct self-test / standalone execution
+ from cfw_asm import _cs
def _enumerate_chunks(chunks_dir):
@@ -123,6 +119,45 @@ def _parse_chunk_mappings(path):
return out
+def resolve_local_symbol(chunks_dir, name):
+ """Resolve a symbol (including an ObjC method symbol) to its vmaddr via the
+ DSC's own `.symbols` local-symbol table (in-image; no repo-exported dumps).
+ ipsw `symaddr -a` times out on this cache, so parse the table directly."""
+ sym = os.path.join(chunks_dir, "dyld_shared_cache_arm64e.symbols")
+ with open(sym, "rb") as f:
+ hdr = f.read(0x100)
+ if hdr[:15] != b"dyld_v1 arm64e":
+ raise RuntimeError(f"unexpected .symbols magic in {sym}")
+ local_off = struct.unpack_from("<Q", hdr, 72)[0]
+ f.seek(local_off)
+ nlist_off, nlist_cnt, str_off, str_sz, _eo, _ec = struct.unpack("<IIIIII", f.read(24))
+ f.seek(local_off + str_off)
+ strings = f.read(str_sz)
+ f.seek(local_off + nlist_off)
+ nl = f.read(nlist_cnt * 16)
+ want = name.encode()
+ for i in range(nlist_cnt):
+ n_strx, _t, _s, _d, n_value = struct.unpack_from("<IBBHQ", nl, i * 16)
+ if n_strx >= len(strings):
+ continue
+ end = strings.find(b"\x00", n_strx)
+ if strings[n_strx:end] == want:
+ return n_value
+ raise RuntimeError(f"could not resolve {name!r} in .symbols")
+
+
+def _disasm_function(chunks, vma, max_insns):
+ """Disassemble from `vma` up to the first ret/retab (function end) or
+ `max_insns`, whichever comes first. `chunks` is a DSCChunks."""
+ buf = chunks.bytes_at_vma(vma, max_insns * 4)
+ insns = []
+ for insn in _cs.disasm(buf, vma):
+ insns.append(insn)
+ if insn.mnemonic in ("ret", "retab"):
+ break
+ return insns
+
+
class DSCChunks:
"""Lazy random-access byte view over a chunked dyld shared cache."""
@@ -243,22 +278,6 @@ class DSCChunks:
i = p + 1
return out
- def iter_executable_mapping_bytes(self):
- """Yield (chunk_path, file_offset, vmaddr_start, mapping_bytes) for
- every mapping whose `initProt` includes VM_PROT_EXECUTE.
-
- Non-executable mappings (LINKEDIT, __DATA, __DATA_CONST) are
- skipped so we never try to disassemble them.
- """
- for addr_start, addr_end, file_off, init_prot, cp in self._ranges:
- if not (init_prot & self.VM_PROT_EXECUTE):
- continue
- size = addr_end - addr_start
- with open(cp, "rb") as f:
- f.seek(file_off)
- buf = f.read(size)
- yield cp, file_off, addr_start, buf
-
def read_at_vma(self, vma, length, *, allow_short=False):
"""Read `length` bytes starting at `vma`, contained in a single
mapping. With `allow_short=True`, returns whatever is available
diff --git a/scripts/patchers/cfw_patch_build_version.py b/scripts/patchers/cfw_patch_build_version.py
index f61e7c9a..d831fdb1 100644
--- a/scripts/patchers/cfw_patch_build_version.py
+++ b/scripts/patchers/cfw_patch_build_version.py
@@ -48,19 +48,19 @@ def patch_plist(path: str, target: str, *, dry_run: bool = False) -> bool:
try:
plist = plistlib.loads(data)
except Exception as e:
- raise ValueError(f"{path}: cannot parse as plist: {e}")
+ raise ValueError(f"cannot parse as plist: {e}")
if not isinstance(plist, dict):
raise ValueError(
- f"{path}: top-level plist is {type(plist).__name__}, expected dict"
+ f"top-level plist is {type(plist).__name__}, expected dict"
)
current = plist.get(KEY)
if current is None:
- raise ValueError(f"{path}: no {KEY!r} key present")
+ raise ValueError(f"no {KEY!r} key present")
if not isinstance(current, str):
raise ValueError(
- f"{path}: {KEY!r} is {type(current).__name__}, expected str"
+ f"{KEY!r} is {type(current).__name__}, expected str"
)
if current == target:
@@ -92,7 +92,7 @@ def _main(argv):
try:
patch_plist(path, target, dry_run=dry_run)
except Exception as e:
- print(f"[-] {type(e).__name__}: {e}", file=sys.stderr)
+ print(f"[-] {type(e).__name__}: Unable to patch {path}: {e}", file=sys.stderr)
return 1
return 0
diff --git a/scripts/patchers/cfw_patch_cache_loader.py b/scripts/patchers/cfw_patch_cache_loader.py
index e52584ec..eaeca782 100644
--- a/scripts/patchers/cfw_patch_cache_loader.py
+++ b/scripts/patchers/cfw_patch_cache_loader.py
@@ -1,11 +1,8 @@
"""launchd cache loader patch module."""
from .cfw_asm import *
-from .cfw_asm import _log_asm
-from capstone import Cs, CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN
+from .cfw_asm import _log_asm, _cs
-_adrp_cs = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)
-_adrp_cs.detail = True
def patch_launchd_cache_loader(filepath):
"""NOP the cache validation check in launchd_cache_loader.
@@ -31,7 +28,6 @@ def patch_launchd_cache_loader(filepath):
# Strategy 1: Search for anchor strings in __cstring
# Code always references the START of a C string, so after finding a
# substring match, back-scan to the enclosing string's first byte.
- cstring_sec = find_section(sections, "__TEXT,__cstring")
anchor_strings = [
b"unsecure_cache",
b"unsecure",
@@ -135,7 +131,7 @@ def _find_adrp_add_ref(code, base_va, target_va):
adrp_cache = {}
for off in range(0, len(code) - 4, 4):
- insns = list(_adrp_cs.disasm(code[off : off + 4], base_va + off))
+ insns = list(_cs.disasm(code[off : off + 4], base_va + off))
if not insns:
continue
insn = insns[0]
@@ -212,8 +208,3 @@ def _find_nearby_branch(data, ref_foff, text_foff, text_size):
return check_foff
return -1
-
-
-# ══════════════════════════════════════════════════════════════════
-# 3. mobileactivationd — Hackivation bypass
-# ══════════════════════════════════════════════════════════════════
diff --git a/scripts/patchers/cfw_patch_camera_dsc.py b/scripts/patchers/cfw_patch_camera_dsc.py
index a1300f67..8e710641 100644
--- a/scripts/patchers/cfw_patch_camera_dsc.py
+++ b/scripts/patchers/cfw_patch_camera_dsc.py
@@ -199,18 +199,11 @@ def apply_avf_auth_only(chunks_dir, dsc_path, *, dry_run=False, force=False):
return 1
-def patch_camera_in_dsc(chunks_dir, dsc_path=None):
- """Entry point used by `cfw.py patch-camera-dsc`."""
- if not dsc_path:
- raise RuntimeError("dsc_path is required (pass --dsc-header on the CLI)")
- return apply_all_camera_patches(chunks_dir, dsc_path)
-
-
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser(description="Camera DSC patcher")
- ap.add_argument("chunks_dir", help="directory containing dyld_shared_cache_arm64e.* files")
- ap.add_argument("dsc_header", help="path to the dyld_shared_cache_arm64e header (no suffix)")
+ ap.add_argument("chunks_dir", help="Directory containing dyld_shared_cache_arm64e.* files")
+ ap.add_argument("dsc_header", help="Path to the dyld_shared_cache_arm64e header (no suffix)")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--force", action="store_true")
ap.add_argument("--avf-only", action="store_true",
diff --git a/scripts/patchers/cfw_patch_iomfb_swapend.py b/scripts/patchers/cfw_patch_iomfb_swapend.py
index 37e7d08b..bf9025c9 100644
--- a/scripts/patchers/cfw_patch_iomfb_swapend.py
+++ b/scripts/patchers/cfw_patch_iomfb_swapend.py
@@ -43,15 +43,13 @@ import re
import shutil
import subprocess
-from capstone.arm64_const import ARM64_OP_REG, ARM64_OP_IMM
-
try:
- from .cfw_asm import asm, _cs
- from .cfw_dsc_chunks import DSCChunks
+ from .cfw_asm import asm, _cs, _mov_reg_imm
+ from .cfw_dsc_chunks import DSCChunks, _disasm_function
from .cfw_dsc_codesign import reattest_modified_pages
except ImportError: # direct self-test execution
- from cfw_asm import asm, _cs
- from cfw_dsc_chunks import DSCChunks
+ from cfw_asm import asm, _cs, _mov_reg_imm
+ from cfw_dsc_chunks import DSCChunks, _disasm_function
from cfw_dsc_codesign import reattest_modified_pages
@@ -84,28 +82,6 @@ def _resolve_symbol(dsc_path, image, symbol):
raise RuntimeError(f"could not resolve {symbol} in {image}")
-def _mov_reg_imm(insn):
- """If `insn` is `mov <reg>, #<imm>`, return (reg_name, imm); else None."""
- if insn.mnemonic != "mov":
- return None
- ops = insn.operands
- if len(ops) != 2 or ops[0].type != ARM64_OP_REG or ops[1].type != ARM64_OP_IMM:
- return None
- return insn.reg_name(ops[0].reg), ops[1].imm
-
-
-def _disasm_function(chunks, vma, max_insns=64):
- """Disassemble from `vma` up to the first ret/retab (function end) or
- `max_insns`, whichever comes first."""
- buf = chunks.bytes_at_vma(vma, max_insns * 4)
- insns = []
- for insn in _cs.disasm(buf, vma):
- insns.append(insn)
- if insn.mnemonic in ("ret", "retab"):
- break
- return insns
-
-
def _find_swap_size_insn(insns):
"""Locate the `mov w3,#imm` that sets the SwapEnd input-state size.
@@ -141,7 +117,7 @@ def patch_iomfb_swapend(chunks_dir, *, dsc_path=None, target_size=TARGET_SIZE,
fn_vma = _resolve_symbol(dsc_path, IOMFB, SWAPEND_SYMBOL)
print(f" [.] {SWAPEND_SYMBOL} @ 0x{fn_vma:X}")
- insns = _disasm_function(chunks, fn_vma)
+ insns = _disasm_function(chunks, fn_vma, 64)
target = _find_swap_size_insn(insns)
if target is None:
raise ValueError(
diff --git a/scripts/patchers/cfw_patch_lockdown_mode.py b/scripts/patchers/cfw_patch_lockdown_mode.py
index 4531da6d..bb5b4f7f 100644
--- a/scripts/patchers/cfw_patch_lockdown_mode.py
+++ b/scripts/patchers/cfw_patch_lockdown_mode.py
@@ -26,15 +26,13 @@ is re-attested (`cfw_dsc_codesign.py`).
from capstone.arm64_const import ARM64_OP_IMM
try:
- from .cfw_asm import asm, _cs
- from .cfw_dsc_chunks import DSCChunks
+ from .cfw_asm import asm
+ from .cfw_dsc_chunks import DSCChunks, resolve_local_symbol, _disasm_function
from .cfw_dsc_codesign import reattest_modified_pages
- from .cfw_patch_xpc_lwcr import _resolve_local_symbol
except ImportError:
- from cfw_asm import asm, _cs
- from cfw_dsc_chunks import DSCChunks
+ from cfw_asm import asm
+ from cfw_dsc_chunks import DSCChunks, resolve_local_symbol, _disasm_function
from cfw_dsc_codesign import reattest_modified_pages
- from cfw_patch_xpc_lwcr import _resolve_local_symbol
SYMBOL_CANDIDATES = (
"___os_lockdown_mode_enabled_block_invoke",
@@ -47,16 +45,6 @@ def _imm(insn, idx):
return ops[idx].imm if idx < len(ops) and ops[idx].type == ARM64_OP_IMM else None
-def _disasm(chunks, vma, n=60):
- buf = chunks.bytes_at_vma(vma, n * 4)
- out = []
- for insn in _cs.disasm(buf, vma):
- out.append(insn)
- if insn.mnemonic in ("ret", "retab"):
- break
- return out
-
-
def _find_error_gate(insns):
"""The `cmn wR, #1; b.eq` sysctl-error idiom, preceded by a bl."""
saw_bl = False
@@ -79,7 +67,7 @@ def patch_lockdown_mode(chunks_dir, *, dry_run=False):
fn_vma = None
for name in SYMBOL_CANDIDATES:
try:
- fn_vma = _resolve_local_symbol(chunks_dir, name)
+ fn_vma = resolve_local_symbol(chunks_dir, name)
break
except RuntimeError:
continue
@@ -88,7 +76,7 @@ def patch_lockdown_mode(chunks_dir, *, dry_run=False):
return 0
print(f" [.] {name} @ 0x{fn_vma:X}")
- gate = _find_error_gate(_disasm(chunks, fn_vma))
+ gate = _find_error_gate(_disasm_function(chunks, fn_vma, 60))
if gate is None:
raise ValueError("lockdown_mode: `cmn wR,#1; b.eq <crash>` sysctl-error gate not found")
print(f" [.] gate @ 0x{gate.address:X}: {gate.mnemonic} {gate.op_str}")
diff --git a/scripts/patchers/cfw_patch_lsd_embedded_reg.py b/scripts/patchers/cfw_patch_lsd_embedded_reg.py
index 32cfde43..cd3bd6a9 100644
--- a/scripts/patchers/cfw_patch_lsd_embedded_reg.py
+++ b/scripts/patchers/cfw_patch_lsd_embedded_reg.py
@@ -40,17 +40,15 @@ re-attested (TXM enforces per-page); the resulting CDHash change is accepted by
the JB's always-true AMFI cdhash-trust patch.
"""
-import struct
-
-from capstone.arm64_const import ARM64_OP_REG, ARM64_OP_IMM
+from capstone.arm64_const import ARM64_OP_REG
try:
- from .cfw_asm import asm, _cs
- from .cfw_dsc_chunks import DSCChunks
+ from .cfw_asm import asm, _mov_reg_imm
+ from .cfw_dsc_chunks import DSCChunks, resolve_local_symbol, _disasm_function
from .cfw_dsc_codesign import reattest_modified_pages
except ImportError: # direct self-test / standalone execution
- from cfw_asm import asm, _cs
- from cfw_dsc_chunks import DSCChunks
+ from cfw_asm import asm, _mov_reg_imm
+ from cfw_dsc_chunks import DSCChunks, resolve_local_symbol, _disasm_function
from cfw_dsc_codesign import reattest_modified_pages
@@ -58,53 +56,6 @@ LAUNCHSERVICES = "/System/Library/Frameworks/CoreServices.framework/CoreServices
METHOD = "-[_LSDModifyClient clientIsEntitledForEmbeddedRegistrationOperations]"
-def _resolve_local_symbol(chunks_dir, name):
- """Resolve an ObjC method symbol to its vmaddr via the DSC's own
- `.symbols` local-symbol table (in-image; no repo-exported dumps). ipsw
- `symaddr -a` times out on this cache, so parse the table directly."""
- import os
- sym = os.path.join(chunks_dir, "dyld_shared_cache_arm64e.symbols")
- with open(sym, "rb") as f:
- hdr = f.read(0x100)
- if hdr[:15] != b"dyld_v1 arm64e":
- raise RuntimeError(f"unexpected .symbols magic in {sym}")
- local_off = struct.unpack_from("<Q", hdr, 72)[0]
- f.seek(local_off)
- nlist_off, nlist_cnt, str_off, str_sz, _eo, _ec = struct.unpack("<IIIIII", f.read(24))
- f.seek(local_off + str_off)
- strings = f.read(str_sz)
- f.seek(local_off + nlist_off)
- nl = f.read(nlist_cnt * 16)
- want = name.encode()
- for i in range(nlist_cnt):
- n_strx, _t, _s, _d, n_value = struct.unpack_from("<IBBHQ", nl, i * 16)
- if n_strx >= len(strings):
- continue
- end = strings.find(b"\x00", n_strx)
- if strings[n_strx:end] == want:
- return n_value
- raise RuntimeError(f"could not resolve {name!r} in .symbols")
-
-
-def _mov_reg_imm(insn):
- if insn.mnemonic != "mov":
- return None
- ops = insn.operands
- if len(ops) != 2 or ops[0].type != ARM64_OP_REG or ops[1].type != ARM64_OP_IMM:
- return None
- return insn.reg_name(ops[0].reg), ops[1].imm
-
-
-def _disasm_function(chunks, vma, max_insns=96):
- buf = chunks.bytes_at_vma(vma, max_insns * 4)
- insns = []
- for insn in _cs.disasm(buf, vma):
- insns.append(insn)
- if insn.mnemonic in ("ret", "retab"):
- break
- return insns
-
-
def _find_gate(insns):
"""Locate the conditional branch that gates the entitled result: the
`cbz`/`cbnz` on w0 whose fall-through instruction is `mov w<reg>,#1`
@@ -136,13 +87,13 @@ def patch_lsd_embedded_reg(chunks_dir, *, dry_run=False):
# Self-gating: the gate method only exists on iOS 27+ LaunchServices. On
# older userlands (26.x/18.x) it is absent, so this is a no-op there.
try:
- fn_vma = _resolve_local_symbol(chunks_dir, METHOD)
+ fn_vma = resolve_local_symbol(chunks_dir, METHOD)
except RuntimeError:
print(f" [=] {METHOD} not present (pre-iOS-27 userland); nothing to patch")
return 0
print(f" [.] {METHOD} @ 0x{fn_vma:X}")
- insns = _disasm_function(chunks, fn_vma)
+ insns = _disasm_function(chunks, fn_vma, 96)
found = _find_gate(insns)
if found is None:
raise ValueError(
diff --git a/scripts/patchers/cfw_patch_mobileactivationd.py b/scripts/patchers/cfw_patch_mobileactivationd.py
index c69b4636..ac876cf7 100644
--- a/scripts/patchers/cfw_patch_mobileactivationd.py
+++ b/scripts/patchers/cfw_patch_mobileactivationd.py
@@ -101,11 +101,6 @@ def _find_via_objc_metadata(data):
return -1
-# ══════════════════════════════════════════════════════════════════
-# 5. Mach-O dylib injection (optool replacement)
-# ══════════════════════════════════════════════════════════════════
-
-
def patch_mobileactivationd(filepath):
"""Dynamically find -[DeviceType should_hactivate] and patch to return YES.
@@ -154,9 +149,3 @@ def patch_mobileactivationd(filepath):
open(filepath, "wb").write(data)
print(f" [+] Patched at 0x{imp_foff:X}: mov x0, #1; ret")
return True
-
-
-# ══════════════════════════════════════════════════════════════════
-# 4. launchd — Jetsam panic bypass
-# ══════════════════════════════════════════════════════════════════
-
diff --git a/scripts/patchers/cfw_patch_post_restore_dt.py b/scripts/patchers/cfw_patch_post_restore_dt.py
index 84e141fb..1778bff3 100644
--- a/scripts/patchers/cfw_patch_post_restore_dt.py
+++ b/scripts/patchers/cfw_patch_post_restore_dt.py
@@ -252,7 +252,7 @@ def patch_devicetree_file(path: str, *, dry_run: bool = False) -> int:
if im4p.fourcc != "dtre":
raise ValueError(
- f"{path}: expected DT payload (fourcc='dtre'), got fourcc={im4p.fourcc!r}"
+ f"expected DT payload (fourcc='dtre'), got fourcc={im4p.fourcc!r}"
)
print(
f" [.] {path}: {'IMG4' if is_img4 else 'IM4P'} "
@@ -318,7 +318,7 @@ def _main(argv):
try:
patch_devicetree_file(path, dry_run=dry_run)
except Exception as e:
- print(f"[-] {type(e).__name__}: {e}", file=sys.stderr)
+ print(f"[-] {type(e).__name__}: Unable to patch {path}: {e}", file=sys.stderr)
return 1
return 0
diff --git a/scripts/patchers/cfw_patch_seputil.py b/scripts/patchers/cfw_patch_seputil.py
index 55fc7f86..246993f8 100644
--- a/scripts/patchers/cfw_patch_seputil.py
+++ b/scripts/patchers/cfw_patch_seputil.py
@@ -1,6 +1,5 @@
"""seputil patch module."""
-from .cfw_asm import *
def patch_seputil(filepath):
"""Dynamically find and patch the gigalocker path format string in seputil.
@@ -40,10 +39,3 @@ def patch_seputil(filepath):
print(f" [+] Patched at 0x{pct_s_off:X}: %s -> AA")
print(f" /{anchor[1:-1].decode()} -> /AA.gl")
return True
-
-
-# ══════════════════════════════════════════════════════════════════
-# 2. launchd_cache_loader — Unsecure cache bypass
-# ══════════════════════════════════════════════════════════════════
-
-
diff --git a/scripts/patchers/cfw_patch_watchdogd.py b/scripts/patchers/cfw_patch_watchdogd.py
index 99c835e6..9e71cf81 100644
--- a/scripts/patchers/cfw_patch_watchdogd.py
+++ b/scripts/patchers/cfw_patch_watchdogd.py
@@ -100,10 +100,8 @@ from .cfw_asm import (
_cs,
_log_asm,
asm,
- disasm_at,
find_section,
parse_macho_sections,
- wr32,
)
from .cfw_macho_codesign import reattest_modified_offsets
@@ -157,7 +155,6 @@ def _find_adrp_add_xrefs(code, base_va, target_va):
adrp_cache = {} # dst_reg -> (adrp_va, page_value, idx)
insns = list(_cs.disasm(code, base_va))
- insn_by_idx = {i: ins for i, ins in enumerate(insns)}
for idx, ins in enumerate(insns):
if ins.mnemonic == "adrp" and len(ins.operands) >= 2:
diff --git a/scripts/patchers/cfw_patch_xpc_lwcr.py b/scripts/patchers/cfw_patch_xpc_lwcr.py
index e23c514d..c13b18db 100644
--- a/scripts/patchers/cfw_patch_xpc_lwcr.py
+++ b/scripts/patchers/cfw_patch_xpc_lwcr.py
@@ -43,18 +43,15 @@ enforces per-page); the CDHash change is accepted by the JB's always-true AMFI
cdhash-trust patch.
"""
-import os
-import struct
-
from capstone.arm64_const import ARM64_OP_REG, ARM64_OP_IMM
try:
- from .cfw_asm import asm, _cs
- from .cfw_dsc_chunks import DSCChunks
+ from .cfw_asm import asm
+ from .cfw_dsc_chunks import DSCChunks, resolve_local_symbol, _disasm_function
from .cfw_dsc_codesign import reattest_modified_pages
except ImportError: # direct self-test / standalone execution
- from cfw_asm import asm, _cs
- from cfw_dsc_chunks import DSCChunks
+ from cfw_asm import asm
+ from cfw_dsc_chunks import DSCChunks, resolve_local_symbol, _disasm_function
from cfw_dsc_codesign import reattest_modified_pages
@@ -63,42 +60,6 @@ SYMBOL = "_xpc_token_satisfies_lwcr"
SYMBOL_CANDIDATES = ("__xpc_token_satisfies_lwcr", SYMBOL)
-def _resolve_local_symbol(chunks_dir, name):
- """Resolve a symbol to its vmaddr via the DSC's own `.symbols` local-symbol
- table (in-image; no repo-exported dumps)."""
- sym = os.path.join(chunks_dir, "dyld_shared_cache_arm64e.symbols")
- with open(sym, "rb") as f:
- hdr = f.read(0x100)
- if hdr[:15] != b"dyld_v1 arm64e":
- raise RuntimeError(f"unexpected .symbols magic in {sym}")
- local_off = struct.unpack_from("<Q", hdr, 72)[0]
- f.seek(local_off)
- nlist_off, nlist_cnt, str_off, str_sz, _eo, _ec = struct.unpack("<IIIIII", f.read(24))
- f.seek(local_off + str_off)
- strings = f.read(str_sz)
- f.seek(local_off + nlist_off)
- nl = f.read(nlist_cnt * 16)
- want = name.encode()
- for i in range(nlist_cnt):
- n_strx, _t, _s, _d, n_value = struct.unpack_from("<IBBHQ", nl, i * 16)
- if n_strx >= len(strings):
- continue
- end = strings.find(b"\x00", n_strx)
- if strings[n_strx:end] == want:
- return n_value
- raise RuntimeError(f"could not resolve {name!r} in .symbols")
-
-
-def _disasm_function(chunks, vma, max_insns=160):
- buf = chunks.bytes_at_vma(vma, max_insns * 4)
- insns = []
- for insn in _cs.disasm(buf, vma):
- insns.append(insn)
- if insn.mnemonic in ("ret", "retab"):
- break
- return insns
-
-
def _rn(insn, idx):
ops = insn.operands
if idx >= len(ops) or ops[idx].type != ARM64_OP_REG:
@@ -108,7 +69,7 @@ def _rn(insn, idx):
def _find_consistency_check(insns):
"""Locate the LWCR self-consistency idiom and return the (cset, eor, tbz)
- instructions plus the error_code register.
+ instructions.
Shape:
cset wC, ne
@@ -135,17 +96,14 @@ def _find_consistency_check(insns):
for j in range(i - 1, max(-1, i - 6), -1):
cand = insns[j]
if cand.mnemonic == "cset" and _rn(cand, 0) == wC:
- cops = cand.operands
- if len(cops) >= 2 and cops[1].type == ARM64_OP_IMM:
- # capstone renders the condition as an operand imm code;
- # use op_str to confirm it is `ne`.
- pass
+ # capstone renders the condition as an operand imm code;
+ # use op_str to confirm it is `ne`.
if cand.op_str.strip().endswith("ne"):
cset = cand
break
if cset is None:
continue
- return cset, eor, tbz, wC
+ return cset, eor, tbz
return None
@@ -159,7 +117,7 @@ def patch_xpc_lwcr(chunks_dir, *, dry_run=False):
resolved_name = None
for candidate in SYMBOL_CANDIDATES:
try:
- fn_vma = _resolve_local_symbol(chunks_dir, candidate)
+ fn_vma = resolve_local_symbol(chunks_dir, candidate)
resolved_name = candidate
break
except RuntimeError:
@@ -169,14 +127,14 @@ def patch_xpc_lwcr(chunks_dir, *, dry_run=False):
return 0
print(f" [.] {resolved_name} @ 0x{fn_vma:X}")
- insns = _disasm_function(chunks, fn_vma)
+ insns = _disasm_function(chunks, fn_vma, 160)
found = _find_consistency_check(insns)
if found is None:
raise ValueError(
f"{SYMBOL}: LWCR consistency idiom (cset wC,ne; eor wE,w0,wC; "
f"tbz wE,#0) not found"
)
- cset, eor, tbz, wC = found
+ cset, eor, tbz = found
print(f" [.] cset @ 0x{cset.address:X}: {cset.mnemonic} {cset.op_str}")
print(f" [.] eor @ 0x{eor.address:X}: {eor.mnemonic} {eor.op_str}")
print(f" [.] tbz @ 0x{tbz.address:X}: {tbz.mnemonic} {tbz.op_str}")
diff --git a/scripts/pymobiledevice3_bridge.py b/scripts/pymobiledevice3_bridge.py
index fb1f88a8..7a4b5a8b 100755
--- a/scripts/pymobiledevice3_bridge.py
+++ b/scripts/pymobiledevice3_bridge.py
@@ -107,8 +107,8 @@ async def resolve_device(ecid: Optional[int], udid: Optional[str]) -> Device:
if ecid is None and udid_normalized is not None:
raise RuntimeError(
- "Target UDID not available over usbmux in lockdownd mode and ECID is unset; "
- "set RESTORE_ECID for DFU/Recovery targeting"
+ "The device with that UDID was not found, and no ECID is set; "
+ "set RESTORE_ECID to target the device in DFU or Recovery mode"
)
return Device(irecv=IRecv(ecid=ecid))
diff --git a/scripts/setup_machine.sh b/scripts/setup_machine.sh
index 08c07cad..037e3b39 100755
--- a/scripts/setup_machine.sh
+++ b/scripts/setup_machine.sh
@@ -39,12 +39,7 @@ BOOT_PROMPT_FALLBACK_TIMEOUT="${BOOT_PROMPT_FALLBACK_TIMEOUT:-60}"
BOOT_BASH_PROMPT_REGEX="${BOOT_BASH_PROMPT_REGEX:-bash-[0-9]+(\.[0-9]+)+#|:/[^ ]* root#}"
BOOT_PANIC_REGEX="${BOOT_PANIC_REGEX:-(^|[^p])(panic|kernel panic|panic\\.apple\\.com|stackshot succeeded)}"
PMD3_BRIDGE="${PMD3_BRIDGE:-${PROJECT_ROOT}/scripts/pymobiledevice3_bridge.py}"
-INTERACTIVE_RAW="${INTERACTIVE:-0}"
NON_INTERACTIVE=1
-NO_BINPACK_RAW="${NO_BINPACK:-0}"
-NO_BINPACK=0
-NO_VPHONED_RAW="${NO_VPHONED:-0}"
-NO_VPHONED=0
JB_MODE=0
DEV_MODE=0
EXP_MODE=0
@@ -410,52 +405,6 @@ wait_for_first_boot_prompt_auto() {
esac
}
-wait_for_device_ssh() {
- local port="${1:-22222}"
- local timeout="${2:-120}"
- local pass="${3:-alpine}"
- local sshpass_bin waited=0
-
- sshpass_bin="$(command -v sshpass || true)"
- [[ -x "$sshpass_bin" ]] || die "sshpass not found (run: make setup_tools)"
-
- echo "[*] Waiting for device SSH on localhost:${port} (timeout=${timeout}s)..."
- while (( waited < timeout )); do
- if [[ -n "$BOOT_PID" ]] && ! kill -0 "$BOOT_PID" 2>/dev/null; then
- die "VM exited while waiting for device SSH."
- fi
- if "$sshpass_bin" -p "$pass" ssh \
- -o StrictHostKeyChecking=no \
- -o UserKnownHostsFile=/dev/null \
- -o PreferredAuthentications=password \
- -o ConnectTimeout=5 -q \
- -p "$port" root@localhost "echo ready" >/dev/null 2>&1; then
- echo "[+] Device SSH is ready on port ${port}"
- return
- fi
- if (( waited == 0 || waited % 10 == 0 )); then
- echo " waiting... ${waited}s elapsed"
- fi
- sleep 2
- (( waited += 2 ))
- done
- die "Device SSH not ready after ${timeout}s"
-}
-
-halt_device_ssh() {
- local port="${1:-22222}"
- local pass="${2:-alpine}"
- local sshpass_bin
- sshpass_bin="$(command -v sshpass)"
- echo "[*] Halting device via SSH..."
- "$sshpass_bin" -p "$pass" ssh \
- -o StrictHostKeyChecking=no \
- -o UserKnownHostsFile=/dev/null \
- -o PreferredAuthentications=password \
- -o ConnectTimeout=10 -q \
- -p "$port" root@localhost "halt" 2>/dev/null || true
-}
-
run_boot_analysis() {
local boot_state
@@ -692,10 +641,11 @@ Options:
Environment:
INTERACTIVE=1 Prompt at first-boot stages (default: non-interactive — auto-continue + boot analysis).
SUDO_PASSWORD=... Preload sudo credential via askpass.
- NO_BINPACK=1 Excludes the SSH, VNC, ... binaries from being installed (patchless-only, currently)
- NO_VPHONED=1 Excludes vphoned from being installed (patchless-only, currently)
+ NO_BINPACK=1 Skip installing the bundled binaries (SSH, VNC, and others).
+ Patchless variant only.
+ NO_VPHONED=1 Skip installing vphoned. Patchless variant only.
SPOOF_BUILD=<id> (EXP only) Rewrite SystemVersion.plist ProductBuildVersion
- to <id> (e.g. 23F77). Omitted/empty -> skipped.
+ to <id> (e.g. 23F77). Leave unset to skip.
EOF
exit 0
;;
@@ -708,14 +658,18 @@ EOF
main() {
parse_args "$@"
- if parse_bool "$INTERACTIVE_RAW"; then
+ if parse_bool "${INTERACTIVE:-0}"; then
NON_INTERACTIVE=0
fi
- if parse_bool "$NO_BINPACK_RAW"; then
+ if parse_bool "${NO_BINPACK:-0}"; then
NO_BINPACK=1
+ else
+ NO_BINPACK=0
fi
- if parse_bool "$NO_VPHONED_RAW"; then
+ if parse_bool "${NO_VPHONED:-0}"; then
NO_VPHONED=1
+ else
+ NO_VPHONED=0
fi
setup_sudo_noninteractive
@@ -801,9 +755,9 @@ main() {
echo ""
echo "=== First boot ==="
if [[ "$NON_INTERACTIVE" -eq 0 ]]; then
- read -r "?[*] press Enter to start VM, after the VM has finished booting, press Enter again to finish last stage"
+ read -r "?[*] Press Enter to start the VM. After it boots, press Enter again for the final stage."
else
- echo "[*] non-interactive (default): auto-starting first boot"
+ echo "[*] Non-interactive mode. Starting the first boot automatically…"
fi
start_first_boot "$LESS_MODE"
diff --git a/scripts/tail_jb_patch_logs.sh b/scripts/tail_jb_patch_logs.sh
index f76ce1ee..49b33e74 100755
--- a/scripts/tail_jb_patch_logs.sh
+++ b/scripts/tail_jb_patch_logs.sh
@@ -2,14 +2,18 @@
set -euo pipefail
unsetopt BG_NICE 2>/dev/null || true
-PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
-TARGET_DIR="${1:-${PROJECT_ROOT}/setup_logs/jb_patch_tests_20260306_113510}"
+TARGET_DIR="${1:-}"
TAIL_LINES="${2:-20}"
SCAN_INTERVAL="${SCAN_INTERVAL:-1}"
+if [[ -z "$TARGET_DIR" ]]; then
+ echo "Usage: $0 <log_dir> [tail_lines]" >&2
+ exit 1
+fi
+
if [[ ! -d "$TARGET_DIR" ]]; then
- echo "error: directory not found: $TARGET_DIR" >&2
- echo "usage: $0 [log_dir] [tail_lines]" >&2
+ echo "Error: log directory not found: $TARGET_DIR" >&2
+ echo "Usage: $0 <log_dir> [tail_lines]" >&2
exit 1
fi
diff --git a/scripts/tweakloader/README.md b/scripts/tweakloader/README.md
index 4cbed812..e5f4fe1a 100644
--- a/scripts/tweakloader/README.md
+++ b/scripts/tweakloader/README.md
@@ -10,9 +10,14 @@ Purpose
Current behavior
- Enumerates substrate-style `.plist` files in the tweak directory.
-- Supports:
- - `Filter.Bundles`
- - `Filter.Executables`
+- Two engagement tiers:
+ - `Filter.Frameworks` tweaks are scheduled in *every* process and
+ `dlopen`ed asynchronously once a matching `*.framework/` image loads
+ (`_dyld_register_func_for_add_image`); no `dlopen` happens in a process
+ where the named framework never appears.
+ - Tweaks filtered by `Filter.Bundles` / `Filter.Executables`, or with no
+ filter, load only in `.app/` processes plus the daemon allowlist in
+ `kVPhoneAllowedDaemonPaths`.
- `dlopen`s the corresponding `.dylib` when the current process matches.
Logging
diff --git a/scripts/tweakloader/TweakLoader.m b/scripts/tweakloader/TweakLoader.m
index 0ce05fe7..8ab85b24 100644
--- a/scripts/tweakloader/TweakLoader.m
+++ b/scripts/tweakloader/TweakLoader.m
@@ -79,9 +79,8 @@ static BOOL TLShouldRunInCurrentProcess(void) {
return NO;
}
-static BOOL TLArrayContainsString(id obj, NSString *value) {
- if (![obj isKindOfClass:[NSArray class]] || !value.length) return NO;
- for (id item in (NSArray *)obj) {
+static BOOL TLArrayContainsString(NSArray *array, NSString *value) {
+ for (id item in array) {
if ([item isKindOfClass:[NSString class]] &&
[(NSString *)item isEqualToString:value]) {
return YES;
@@ -90,8 +89,7 @@ static BOOL TLArrayContainsString(id obj, NSString *value) {
return NO;
}
-static BOOL TLFilterMatches(NSDictionary *plist, NSString *bundleID, NSString *executableName) {
- NSDictionary *filter = [plist isKindOfClass:[NSDictionary class]] ? plist[@"Filter"] : nil;
+static BOOL TLFilterMatches(NSDictionary *filter, NSString *bundleID, NSString *executableName) {
if (![filter isKindOfClass:[NSDictionary class]]) {
return YES;
}
@@ -149,7 +147,7 @@ static void TLOnImageAdded(const struct mach_header *mh, intptr_t slide) {
for (NSDictionary *pending in snapshot) {
NSArray *frameworks = pending[@"frameworks"];
for (NSString *fw in frameworks) {
- if (TLPathMatchesFramework(imagePath.UTF8String, fw)) {
+ if (TLPathMatchesFramework(cpath, fw)) {
[toLoad addObject:pending[@"dylib"]];
break;
}
@@ -233,12 +231,11 @@ static void TLLoadTweaks(void) {
}
if (!files.count) return;
- NSString *execPath = TLExecutablePath();
NSString *bundleID = NSBundle.mainBundle.bundleIdentifier ?: @"";
NSString *executableName = TLExecutableName();
BOOL processAllowed = TLShouldRunInCurrentProcess();
- if (gTLPendingLock == nil) gTLPendingLock = [[NSLock alloc] init];
+ gTLPendingLock = [[NSLock alloc] init];
for (NSString *filename in files) {
if (![filename.pathExtension isEqualToString:@"plist"]) continue;
@@ -272,7 +269,7 @@ static void TLLoadTweaks(void) {
// Non-framework-filtered: keep the .app/+allowlist gate.
if (!processAllowed) continue;
- if (!TLFilterMatches(plist, bundleID, executableName)) continue;
+ if (!TLFilterMatches(filter, bundleID, executableName)) continue;
void *handle = dlopen(dylibPath.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);
if (handle) {
@@ -285,7 +282,6 @@ static void TLLoadTweaks(void) {
TLLog(@"Exception loading %@: %@", dylibPath, e);
}
}
- (void)execPath;
}
__attribute__((constructor))
diff --git a/scripts/vcamcaptured/libvcamcaptured.m b/scripts/vcamcaptured/libvcamcaptured.m
index 7276463f..2483caf7 100644
--- a/scripts/vcamcaptured/libvcamcaptured.m
+++ b/scripts/vcamcaptured/libvcamcaptured.m
@@ -23,8 +23,7 @@
* No hardcoded image VMAs. All CMCapture addresses are recovered at
* runtime via:
* - dlsym for exported functions (FigCaptureSourceServerStart,
- * FigCaptureSourceCreateFromBacking, FigSimpleMutexLock/Unlock,
- * CMBaseObjectGetVTable).
+ * FigCaptureSourceCreateFromBacking, CMBaseObjectGetVTable).
* - getsectiondata to map CMCapture's __text bounds.
* - Structural xref pattern scan of __text to find the
* `_sSourceList` / `_sSourceListLock` slots:
@@ -553,18 +552,6 @@ static uintptr_t vcc_find_data_xref(const vcc_image_t *img, unsigned offset) {
return cands[best].addr;
}
-// Read a pointer-sized value from `addr` and store in `*out`. The
-// slot addresses we feed this function are always in CMCapture's
-// __DATA / __DATA_CONST segments (filtered upstream by
-// vcc_addr_in_data) so the read itself is safe — those pages are
-// mapped read-something into the process. Wrapped in a function for
-// future swap-in of a safer reader if the constraint changes.
-static BOOL vcc_safe_read_ptr(uintptr_t addr, uintptr_t *out) {
- if (!addr || !out) return NO;
- *out = *(uintptr_t *)addr;
- return YES;
-}
-
// arm64e ISA class-pointer mask, per libobjc's objc-private.h:
// `#define ISA_MASK 0x00007ffffffffff8ULL`. Bits 0-2 are isa flags
// (has_assoc / has_cxx_dtor / is_indexed), bits 3-46 are the class
@@ -578,8 +565,11 @@ static BOOL vcc_safe_read_ptr(uintptr_t addr, uintptr_t *out) {
// instances are always heap allocations from the default malloc zone,
// so a non-heap value can't be _sSourceList.
static BOOL vcc_slot_value_is_cfarray(uintptr_t slot_addr) {
- uintptr_t val_ptr = 0;
- if (!vcc_safe_read_ptr(slot_addr, &val_ptr)) return NO;
+ if (!slot_addr) return NO;
+ // The slot addresses read here are always in CMCapture's __DATA /
+ // __DATA_CONST segments (filtered upstream by vcc_addr_in_data) so the read
+ // itself is safe — those pages are mapped read-something into the process.
+ uintptr_t val_ptr = *(uintptr_t *)slot_addr;
if (!val_ptr) return NO;
if (val_ptr < 0x100000000ULL || val_ptr > 0x800000000000ULL) return NO;
// malloc_zone_from_ptr returns NULL for non-malloc pointers — this
@@ -669,6 +659,11 @@ static void *vcc_dlsym_fn(const char *name) {
// MARK: - synthetic source construction
+// Published as the synthetic source's CaptureDeviceID attribute, and matched
+// against by the -[BWFigCaptureDeviceVendor copyDeviceWithID:…] hook. One
+// declaration: the two must stay identical or the device lookup stops matching.
+static NSString *const kVccSynthDeviceID = @"vphone:vcam:device:0";
+
static id vcc_build_backing(void) {
Class backingClass = NSClassFromString(@"FigCaptureSourceBacking");
if (!backingClass) {
@@ -720,7 +715,7 @@ static id vcc_build_backing(void) {
// _createDevice:reason:clientPID:figCaptureDevice:] sends isEqualToString:
// to it; an NSNumber raises "unrecognized selector". Use a unique opaque
// string outside whatever pattern Apple uses for hardware cameras.
- if (k_cdid) attrs[(__bridge NSString *)k_cdid] = @"vphone:vcam:device:0";
+ if (k_cdid) attrs[(__bridge NSString *)k_cdid] = kVccSynthDeviceID;
// After hooking _FigCaptureSourceGetAttribute via lldb we observed
// Camera.app's graph builder also queries these 5 boolean / scheme keys
@@ -729,6 +724,10 @@ static id vcc_build_backing(void) {
// SmartCameraSupported, StillImageNoiseReductionAndFusionScheme,
// MidFrameSynchronizationNotSupported, TimeOfFlightAssistedAutoFocusSupported,
// StructuredLightAssistedAutoFocusSupported
+ // Resolve the canonical CFString constant by symbol name when possible (some
+ // are defined in a private framework not in the dyld exports trie, so we fall
+ // back to the plain string after the Fig naming convention:
+ // kFigSupportedFormat_VideoMinFrameRate → "VideoMinFrameRate").
NSString *(^figKeyN)(const char *) = ^NSString *(const char *symname) {
void **slot = dlsym(RTLD_DEFAULT, symname);
if (slot && *slot) return (__bridge NSString *)(CFStringRef)(*slot);
@@ -755,18 +754,6 @@ static id vcc_build_backing(void) {
NSArray *formats = @[];
Class fmtClass = NSClassFromString(@"FigCaptureSourceVideoFormat");
if (fmtClass) {
- // Resolve the canonical CFString constants by name when possible (some
- // are defined in a private framework not in the dyld exports trie, so
- // we fall back to the plain string after the Fig naming convention).
- NSString *(^figKey)(const char *) = ^NSString *(const char *symname) {
- void **slot = dlsym(RTLD_DEFAULT, symname);
- if (slot && *slot) return (__bridge NSString *)(CFStringRef)(*slot);
- // Convention: kFigSupportedFormat_VideoMinFrameRate → "VideoMinFrameRate"
- const char *cs = symname;
- const char *u = strrchr(cs, '_');
- if (u) cs = u + 1;
- return [NSString stringWithUTF8String:cs];
- };
// Publish TWO formats: one BGRA, one 420v at the same 1280x720
// dimensions. Clients that filter on BGRA (e.g. Loupe / Magnifier)
// see one; clients that pick the canonical ISP pixel format (AVF's
@@ -774,8 +761,8 @@ static id vcc_build_backing(void) {
// pick the 420v one. Same preset list + frame-rate range on both.
NSDictionary *commonKeys = @{
@"DefaultActiveFormat" : @NO, // overridden on the active one
- figKey("kFigSupportedFormat_VideoMinFrameRate") : @(1),
- figKey("kFigSupportedFormat_VideoMaxFrameRate") : @(60),
+ figKeyN("kFigSupportedFormat_VideoMinFrameRate") : @(1),
+ figKeyN("kFigSupportedFormat_VideoMaxFrameRate") : @(60),
// -[FigCaptureSourceVideoFormat maxZoomFactor] takes a fast path that
// returns 1.0 for raw bayer formats; for BGRA (our case) it falls to
// a fancy path that reads stabilizationTypeOverrideForCinematic / -ForStandard
@@ -812,12 +799,11 @@ static id vcc_build_backing(void) {
@"Width" : @1280,
@"Height" : @720,
@"PixelFormatType" : @(0x34323076u), // '420v'
- // Mark 420v as default — it's what AVF's preset matcher prefers
- // when picking _setActiveFormat: under standard presets.
- @"DefaultActiveFormat" : @YES,
} mutableCopy];
[y420v_fmt addEntriesFromDictionary:commonKeys];
- y420v_fmt[@"DefaultActiveFormat"] = @YES; // re-set after the merge
+ // Mark 420v as default — it's what AVF's preset matcher prefers when
+ // picking _setActiveFormat: under standard presets.
+ y420v_fmt[@"DefaultActiveFormat"] = @YES;
SEL fmtInitSel = NSSelectorFromString(
@"initWithFigCaptureStreamFormatDictionary:");
@@ -1166,7 +1152,7 @@ static void vcc_install_synthetic(void) {
for (unsigned i = 0; i < ng; i++) {
if (vcc_slot_value_is_cfarray(globals[i])) {
uintptr_t val = 0;
- vcc_safe_read_ptr(globals[i], &val);
+ if (globals[i]) val = *(uintptr_t *)globals[i];
vcc_log(@" _sSourceList chosen (init-store #%u, CFArray @ 0x%lx) at 0x%lx",
i, (unsigned long)val, (unsigned long)globals[i]);
sSourceListAddr = globals[i];
@@ -1195,11 +1181,9 @@ static void vcc_install_synthetic(void) {
// _sSourceList during this init window.
CFMutableArrayRef *sSourceListSlot =
(CFMutableArrayRef *)sSourceListAddr;
- void **sSourceListLockSlot = NULL;
- void *lockPtr = NULL;
vcc_log(@" lock acquisition skipped (single-threaded init window)");
- vcc_log(@" _sSourceList slot @ %p (list=%p), _sSourceListLock slot @ %p (lock=%p)",
- sSourceListSlot, *sSourceListSlot, sSourceListLockSlot, lockPtr);
+ vcc_log(@" _sSourceList slot @ %p (list=%p)", sSourceListSlot,
+ *sSourceListSlot);
// Resolve FigCaptureSourceCreateFromBacking. Marked `external` in
// CMCapture's symtab — should be in the dyld exports trie.
@@ -1210,15 +1194,6 @@ static void vcc_install_synthetic(void) {
}
VCC_CreateFn create_fn = (VCC_CreateFn)create_p;
- // FigSimpleMutex helpers — best-effort: we still call them when lockPtr
- // is non-null (the daemon's mutex is alive), but skip when we couldn't
- // safely resolve the lock global. Resolution failure of the lock is
- // not fatal anymore — we operate as a single writer during init.
- void (*FigSimpleMutexLock)(void *) =
- (void (*)(void *))dlsym(RTLD_DEFAULT, "FigSimpleMutexLock");
- void (*FigSimpleMutexUnlock)(void *) =
- (void (*)(void *))dlsym(RTLD_DEFAULT, "FigSimpleMutexUnlock");
-
id backing = vcc_build_backing();
if (!backing) return;
void *source = vcc_create_synthetic_source(create_fn, backing);
@@ -1233,7 +1208,6 @@ static void vcc_install_synthetic(void) {
// the daemon's stock (bring-up / hardware) sources use for keys like
// DeviceType, SmartCameraSupported, Streams, Ports, etc.
{
- if (lockPtr && FigSimpleMutexLock) FigSimpleMutexLock(lockPtr);
CFMutableArrayRef listSnap = *sSourceListSlot;
CFIndex cnt = listSnap ? CFArrayGetCount(listSnap) : 0;
vcc_log(@" --- existing sources (count=%ld) ---", (long)cnt);
@@ -1268,20 +1242,16 @@ static void vcc_install_synthetic(void) {
vcc_log(@" attrs ret=%d -> %@", e, (__bridge id)out);
if (out) CFRelease(out);
}
- if (lockPtr && FigSimpleMutexUnlock) FigSimpleMutexUnlock(lockPtr);
}
- if (lockPtr && FigSimpleMutexLock) FigSimpleMutexLock(lockPtr);
CFMutableArrayRef list = *sSourceListSlot;
if (!list) {
vcc_log(@" _sSourceList is NULL (server init not yet allocated it) — abort");
- if (lockPtr && FigSimpleMutexUnlock) FigSimpleMutexUnlock(lockPtr);
return;
}
CFIndex preCount = CFArrayGetCount(list);
CFArrayAppendValue(list, source);
CFIndex postCount = CFArrayGetCount(list);
- if (lockPtr && FigSimpleMutexUnlock) FigSimpleMutexUnlock(lockPtr);
vcc_log(@" appended source — list %ld -> %ld", (long)preCount,
(long)postCount);
@@ -1323,9 +1293,7 @@ static void vcc_install_synthetic(void) {
//
// This hook is observation-only; it does not deliver frames yet.
-static SEL vcc_add_endpoint_sel = NULL;
-static Method vcc_add_endpoint_method = NULL;
-static IMP vcc_add_endpoint_orig_imp = NULL;
+static IMP vcc_add_endpoint_orig_imp = NULL;
typedef BOOL (*VccAddEndpointFn)(id, SEL,
id /*endpoint*/,
@@ -1364,18 +1332,16 @@ static void vcc_install_endpoint_hook(void) {
vcc_log(@" endpoint hook: class missing");
return;
}
- vcc_add_endpoint_sel = NSSelectorFromString(
+ SEL sel = NSSelectorFromString(
@"addEndpoint:endpointUniqueID:endpointType:endpointPID:"
@"endpointProxyPID:endpointAuditToken:endpointProxyAuditToken:"
@"endpointCameraUniqueID:");
- vcc_add_endpoint_method = class_getClassMethod(cls,
- vcc_add_endpoint_sel);
- if (!vcc_add_endpoint_method) {
+ Method m = class_getClassMethod(cls, sel);
+ if (!m) {
vcc_log(@" endpoint hook: class_getClassMethod returned NULL");
return;
}
- vcc_add_endpoint_orig_imp = method_setImplementation(
- vcc_add_endpoint_method, (IMP)vcc_add_endpoint_hook);
+ vcc_add_endpoint_orig_imp = method_setImplementation(m, (IMP)vcc_add_endpoint_hook);
vcc_log(@" endpoint hook installed (orig=%p)",
vcc_add_endpoint_orig_imp);
}
@@ -1460,11 +1426,7 @@ static void vcc_dump_sink_node_methods(void) {
// 2) See whether ANY renderSampleBuffer:forInput: calls fire — if they do,
// we know the pipeline runs and we just need to substitute the
// sample-buffer contents.
-// 3) Capture sink instance + input identifier on first real call so we can
-// drive them ourselves on a timer if the source-side stays starved.
-static NSMutableArray *vcc_captured_sinks = nil; // weak refs via NSValue
-static NSValue *vcc_first_input_ref = nil;
static unsigned long vcc_render_call_count = 0;
static unsigned long vcc_iqsn_init_count = 0;
static unsigned long vcc_rqsn_init_count = 0;
@@ -1497,11 +1459,6 @@ static id vcc_iqsn_init_hook(
vcc_iqsn_init_count++;
vcc_log(@" [IQSN init] -> %p sinkID=%@ count=%lu",
ret, sinkID, vcc_iqsn_init_count);
- if (ret) {
- if (!vcc_captured_sinks)
- vcc_captured_sinks = [NSMutableArray array];
- [vcc_captured_sinks addObject:[NSValue valueWithPointer:(__bridge void *)ret]];
- }
return ret;
}
@@ -1515,11 +1472,6 @@ static id vcc_rqsn_init_hook(
vcc_rqsn_init_count++;
vcc_log(@" [RQSN init] -> %p mediaType=0x%x sinkID=%@ count=%lu",
ret, mediaType, sinkID, vcc_rqsn_init_count);
- if (ret) {
- if (!vcc_captured_sinks)
- vcc_captured_sinks = [NSMutableArray array];
- [vcc_captured_sinks addObject:[NSValue valueWithPointer:(__bridge void *)ret]];
- }
return ret;
}
@@ -1530,9 +1482,6 @@ static void vcc_iqsn_render_hook(
vcc_log(@" [IQSN render] self=%p cmsb=%p input=%p inputCls=%@ #%lu",
self, cmsb, input, NSStringFromClass([input class]),
vcc_render_call_count);
- if (input && !vcc_first_input_ref) {
- vcc_first_input_ref = [NSValue valueWithPointer:(__bridge void *)input];
- }
}
VccRenderFn orig = (VccRenderFn)vcc_iqsn_render_orig;
orig(self, _cmd, cmsb, input);
@@ -1580,8 +1529,7 @@ static IMP vcc_copy_device_orig = NULL;
typedef id (*VccCopyDeviceFn)(id self, SEL _cmd, NSString *deviceID,
int clientPID, BOOL informClient, int *err);
-static NSString *const kVccSynthDeviceID = @"vphone:vcam:device:0";
-static Class vcc_synth_device_class = Nil;
+static Class vcc_synth_device_class = Nil;
// Forward decls.
static void vcc_init_synth_device_class(void);
@@ -1654,13 +1602,11 @@ static ptrdiff_t vcc_resolve_ivar(Class cls, const char *what,
return -1;
}
-// Cached CF constants — resolved lazily from CMCaptureCore / CMCaptureDevice.
-static CFStringRef vcc_cf_kClock = NULL;
-static CFStringRef vcc_cf_kUnitInfo = NULL;
+// Cached CF constant — resolved lazily from CMCaptureCore / CMCaptureDevice.
+static CFStringRef vcc_cf_kClock = NULL;
static void vcc_load_synth_cfconsts(void) {
if (!vcc_cf_kClock) vcc_cf_kClock = vcc_cfconst("kFigCaptureDeviceProperty_Clock");
- if (!vcc_cf_kUnitInfo) vcc_cf_kUnitInfo = vcc_cfconst("kFigCaptureDeviceProperty_UnitInfo");
}
// Returns a CMClockRef (CoreMedia host time clock). Lifetime tied to the
@@ -2042,15 +1988,7 @@ static void vcc_install_copy_streams_hook(void) {
if (!cls) return;
SEL sel = NSSelectorFromString(
@"copyStreamsWithUniqueIDs:forDevice:deviceClientPriority:error:");
- Method m = class_getInstanceMethod(cls, sel);
- if (!m) {
- vcc_log(@" copyStreams hook: selector missing");
- return;
- }
- vcc_copy_streams_orig = method_setImplementation(m,
- (IMP)vcc_copy_streams_hook);
- vcc_log(@" swizzled -[BWFigCaptureDeviceVendor copyStreamsWithUniqueIDs:...] orig=%p",
- vcc_copy_streams_orig);
+ vcc_swizzle_method(cls, sel, (IMP)vcc_copy_streams_hook, &vcc_copy_streams_orig);
}
static IMP vcc_copy_streams_from_orig = NULL;
@@ -2089,15 +2027,8 @@ static void vcc_install_copy_streams_from_hook(void) {
if (!cls) return;
SEL sel = NSSelectorFromString(
@"copyStreamsFromDevice:positions:deviceTypes:deviceClientPriority:allowsStreamControlLoss:error:");
- Method m = class_getInstanceMethod(cls, sel);
- if (!m) {
- vcc_log(@" copyStreamsFromDevice hook: selector missing");
- return;
- }
- vcc_copy_streams_from_orig = method_setImplementation(m,
- (IMP)vcc_copy_streams_from_hook);
- vcc_log(@" swizzled -[BWFigCaptureDeviceVendor copyStreamsFromDevice:...] orig=%p",
- vcc_copy_streams_from_orig);
+ vcc_swizzle_method(cls, sel, (IMP)vcc_copy_streams_from_hook,
+ &vcc_copy_streams_from_orig);
}
__attribute__((ns_returns_retained))
@@ -2141,15 +2072,7 @@ static void vcc_install_device_vendor_hook(void) {
}
SEL sel = NSSelectorFromString(
@"copyDeviceWithID:forClient:informClientWhenDeviceAvailableAgain:error:");
- Method m = class_getInstanceMethod(cls, sel);
- if (!m) {
- vcc_log(@" device-vendor hook: selector missing");
- return;
- }
- vcc_copy_device_orig = method_setImplementation(m,
- (IMP)vcc_copy_device_hook);
- vcc_log(@" swizzled -[BWFigCaptureDeviceVendor copyDeviceWithID:...] orig=%p",
- vcc_copy_device_orig);
+ vcc_swizzle_method(cls, sel, (IMP)vcc_copy_device_hook, &vcc_copy_device_orig);
}
// MARK: - viewfinder stream injection
@@ -2169,9 +2092,6 @@ typedef struct vcc_latest_frame_s {
uint32_t width;
uint32_t height;
uint32_t bytes_per_row;
- uint32_t pixel_format;
- uint64_t timestamp_ns;
- uint64_t frame_index;
uint8_t *pixels;
size_t pixels_capacity;
size_t pixels_length;
@@ -2836,7 +2756,6 @@ static void vcc_install_csp_requires_master_clock_hook(void) {
// sink and delivers our shm frame through it.
static id vcc_synth_still_sink = nil;
-static dispatch_queue_t vcc_still_inject_q = NULL;
static void vcc_construct_still_sink(void) {
Class cls = NSClassFromString(@"BWStillImageSampleBufferSinkNode");
@@ -2887,9 +2806,6 @@ static void vcc_construct_still_sink(void) {
vcc_log(@" manual still-sink: probe exception: %@", e);
}
- vcc_still_inject_q =
- dispatch_queue_create("com.vphone.vcam.still-inject", DISPATCH_QUEUE_SERIAL);
-
// Synthesize a sampleBufferAvailableHandler block and set it on our sink.
//
// Per disasm of -[BWStillImageSampleBufferSinkNode renderSampleBuffer:forInput:]
@@ -3128,7 +3044,6 @@ static int vcc_shm_read_latest(void) {
uint32_t h = hdr->height;
uint32_t bpr = hdr->bytes_per_row;
uint32_t fmt = hdr->pixel_format;
- uint64_t ts = hdr->timestamp_ns;
uint64_t idx = hdr->frame_index;
uint32_t pix_len = hdr->pixels_length;
@@ -3149,9 +3064,6 @@ static int vcc_shm_read_latest(void) {
vcc_latest_frame.width = w;
vcc_latest_frame.height = h;
vcc_latest_frame.bytes_per_row = bpr;
- vcc_latest_frame.pixel_format = fmt;
- vcc_latest_frame.timestamp_ns = ts;
- vcc_latest_frame.frame_index = idx;
}
pthread_mutex_unlock(&vcc_latest_frame.lock);
diff --git a/scripts/vm_backup.sh b/scripts/vm_backup.sh
index 03229074..09c008d1 100755
--- a/scripts/vm_backup.sh
+++ b/scripts/vm_backup.sh
@@ -51,7 +51,7 @@ if [[ ! -d "${VM_DIR}" ]]; then
fi
if [[ ! -f "${VM_DIR}/config.plist" ]]; then
- echo "ERROR: ${VM_DIR}/config.plist not found — is this a valid VM directory?"
+ echo "ERROR: ${VM_DIR} is not a valid VM directory (config.plist is missing)."
exit 1
fi
diff --git a/scripts/vm_create.sh b/scripts/vm_create.sh
index b395c327..1ba93354 100755
--- a/scripts/vm_create.sh
+++ b/scripts/vm_create.sh
@@ -69,7 +69,7 @@ done
DISK_SIZE_BYTES=$((DISK_SIZE_GB * 1024 * 1024 * 1024))
-echo "=== vphone create_vm ==="
+echo "=== vphone vm_new ==="
echo "Directory : ${VM_DIR}"
echo "Disk size : ${DISK_SIZE_GB} GB"
echo "AVPBooter : ${ROM_SRC}"
@@ -100,30 +100,30 @@ if [[ -d "${VM_DIR}" ]]; then
echo " Delete ${VM_DIR}/Disk.img manually to recreate"
fi
else
- echo "[1/4] Creating ${VM_DIR}/"
+ echo "[1/5] Creating ${VM_DIR}/"
mkdir -p "${VM_DIR}"
fi
# --- Create sparse disk image ---
if [[ ! -f "${VM_DIR}/Disk.img" ]]; then
- echo "[2/4] Creating sparse disk image (${DISK_SIZE_GB} GB)"
+ echo "[2/5] Creating sparse disk image (${DISK_SIZE_GB} GB)"
# Use dd with seek to create a sparse file (same approach as vrevm)
dd if=/dev/zero of="${VM_DIR}/Disk.img" bs=1 count=0 seek="${DISK_SIZE_BYTES}" 2>/dev/null
echo " -> ${VM_DIR}/Disk.img ($(du -h "${VM_DIR}/Disk.img" | cut -f1) on disk)"
else
- echo "[2/4] Disk.img exists — skipping"
+ echo "[2/5] Disk.img exists — skipping"
fi
# --- Create SEP storage ---
if [[ ! -f "${VM_DIR}/SEPStorage" ]]; then
- echo "[3/4] Creating SEP storage (512 KB)"
+ echo "[3/5] Creating SEP storage (512 KB)"
dd if=/dev/zero of="${VM_DIR}/SEPStorage" bs=1 count="${SEP_STORAGE_SIZE}" 2>/dev/null
else
- echo "[3/4] SEPStorage exists — skipping"
+ echo "[3/5] SEPStorage exists — skipping"
fi
# --- Copy ROMs ---
-echo "[4/4] Copying ROMs"
+echo "[4/5] Copying ROMs"
ROM_DST="${VM_DIR}/AVPBooter.vresearch1.bin"
SEPROM_DST="${VM_DIR}/AVPSEPBooter.vresearch1.bin"
@@ -146,12 +146,11 @@ fi
touch "${VM_DIR}/.gitkeep"
# --- Generate VM manifest ---
-echo "[5/4] Generating VM manifest (config.plist)"
+echo "[5/5] Generating VM manifest (config.plist)"
"${SCRIPT_DIR}/vm_manifest.py" \
--vm-dir "${VM_DIR}" \
--cpu "${CPU_COUNT}" \
- --memory "${MEMORY_MB}" \
- --disk-size "${DISK_SIZE_GB}" || {
+ --memory "${MEMORY_MB}" || {
echo "ERROR: Failed to generate VM manifest"
exit 1
}
@@ -162,8 +161,8 @@ echo ""
echo "Contents:"
ls -lh "${VM_DIR}/"
echo ""
-echo "Manifest (config.plist) saved with VM configuration."
-echo "Future boots will read configuration from this manifest."
+echo "Configuration saved to ${VM_DIR}/config.plist."
+echo "Future boots read the VM configuration from this file."
echo ""
echo "Next steps:"
echo " 1. Prepare firmware: make fw_prepare"
diff --git a/scripts/vm_manifest.py b/scripts/vm_manifest.py
index a7105d25..49a83e01 100755
--- a/scripts/vm_manifest.py
+++ b/scripts/vm_manifest.py
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
-from __future__ import annotations
"""
vm_manifest.py — Generate VM manifest plist for vphone-cli.
Compatible with security-pcc's VMBundle.Config format.
"""
+from __future__ import annotations
+
import argparse
import plistlib
import sys
@@ -16,7 +17,6 @@ def create_manifest(
vm_dir: Path,
cpu_count: int,
memory_mb: int,
- disk_size_gb: int,
platform_fusing: str | None = None,
):
"""
@@ -26,7 +26,6 @@ def create_manifest(
vm_dir: Path to VM directory
cpu_count: Number of CPU cores
memory_mb: Memory size in MB
- disk_size_gb: Disk size in GB
platform_fusing: Platform fusing mode (prod/dev) or None for auto-detect
"""
# Convert to manifest units
@@ -38,7 +37,6 @@ def create_manifest(
manifest = {
"platformType": "vresearch101",
- # "platformFusing": platform_fusing, # None = auto-detect from host OS
"machineIdentifier": b"", # Generated on first boot, then persisted to manifest
"cpuCount": cpu_count,
"memorySize": memory_bytes,
@@ -69,7 +67,7 @@ def create_manifest(
with open(config_path, "wb") as f:
plistlib.dump(manifest, f)
- print(f"[5/4] Created VM manifest: {config_path}")
+ print(f"Created VM manifest: {config_path}")
return config_path
@@ -95,12 +93,6 @@ def main():
default=8192,
help="Memory size in MB (default: 8192)",
)
- parser.add_argument(
- "--disk-size",
- type=int,
- default=64,
- help="Disk size in GB (default: 64)",
- )
parser.add_argument(
"--platform-fusing",
type=str,
@@ -120,7 +112,6 @@ def main():
vm_dir=args.vm_dir,
cpu_count=args.cpu,
memory_mb=args.memory,
- disk_size_gb=args.disk_size,
platform_fusing=args.platform_fusing,
)
except Exception as e:
diff --git a/scripts/vm_restore.sh b/scripts/vm_restore.sh
index cd970b4a..d84790a0 100755
--- a/scripts/vm_restore.sh
+++ b/scripts/vm_restore.sh
@@ -100,7 +100,7 @@ if [[ ! -d "${SRC}" ]]; then
fi
if [[ ! -f "${SRC}/config.plist" ]]; then
- echo "ERROR: ${SRC}/config.plist not found — backup appears invalid."
+ echo "ERROR: Backup '${NAME}' is incomplete (config.plist is missing from ${SRC}/)."
exit 1
fi
diff --git a/scripts/vphone-amfidont b/scripts/vphone-amfidont
index 10ac149f..1873083a 100755
--- a/scripts/vphone-amfidont
+++ b/scripts/vphone-amfidont
@@ -8,16 +8,16 @@ set -euo pipefail
# `:A` resolves a Homebrew symlink back into the bundle).
app="${0:A:h:h:h}"
[[ "${app:e}" == app && -x "$app/Contents/MacOS/vphone-cli" ]] \
- || { print -u2 "error: run vphone-amfidont from inside vphone-cli.app"; exit 1 }
+ || { print -u2 "Error: run vphone-amfidont from inside vphone-cli.app."; exit 1 }
# Ensure amfidont is installed.
if ! command -v amfidont >/dev/null; then
printf "amfidont is not installed. Install it via pip now? [y/N] "
read -r ans || ans=n
- [[ "$ans" == [yY]* ]] || { print "Aborted."; exit 1 }
+ [[ "$ans" == [yY]* ]] || { print "Cancelled."; exit 1 }
xcrun python3 -m pip install -U amfidont
command -v amfidont >/dev/null \
- || { print -u2 "amfidont installed but not on PATH — open a new shell and retry."; exit 1 }
+ || { print -u2 "Error: amfidont is installed but not available in this shell. Open a new shell and retry."; exit 1 }
fi
# Absolute path: sudo's secure_path won't find a pip-user install by name.
bin="$(command -v amfidont)"
@@ -33,10 +33,10 @@ if [[ -n "${raw//[[:space:]]/}" ]]; then
info+=$'\n'"$(cat ~/.amfidont/paths 2>/dev/null || true)"
# Covered if this .app's path is allowed, or if it's running with --allow-all.
if print -r -- "$info" | grep -Fq -- "$app" || print -r -- "$info" | grep -Fq -- "--allow-all"; then
- print "amfidont is already running and allows this .app — nothing to do."
+ print "amfidont is already running and allows this app — nothing to do."
exit 0
fi
- print -u2 "amfidont is already running but does NOT allow this .app. Stop it, then re-run vphone-amfidont."
+ print -u2 "amfidont is already running but does not allow this app. Stop amfidont, then run vphone-amfidont again."
exit 1
fi
diff --git a/scripts/vphone_jb_setup.sh b/scripts/vphone_jb_setup.sh
index dc92f010..ede11722 100755
--- a/scripts/vphone_jb_setup.sh
+++ b/scripts/vphone_jb_setup.sh
@@ -15,14 +15,20 @@ DONE_MARKER="/var/mobile/.vphone_jb_setup_done"
export TERM=xterm-256color
export DEBIAN_FRONTEND=noninteractive
-P=""
-for d in \
- /var/jb/usr/bin /var/jb/bin /var/jb/sbin /var/jb/usr/sbin \
- /iosbinpack64/bin /iosbinpack64/usr/bin /iosbinpack64/sbin /iosbinpack64/usr/sbin \
- /usr/bin /usr/sbin /bin /sbin; do
- [ -d "$d" ] && P="$P:$d"
-done
-export PATH="${P#:}"
+
+# Defined here, not next to log(), because the first call below runs before
+# log() exists.
+rebuild_jb_path() {
+ P=""
+ for d in \
+ /var/jb/usr/bin /var/jb/bin /var/jb/sbin /var/jb/usr/sbin \
+ /iosbinpack64/bin /iosbinpack64/usr/bin /iosbinpack64/sbin /iosbinpack64/usr/sbin \
+ /usr/bin /usr/sbin /bin /sbin; do
+ [ -d "$d" ] && P="$P:$d"
+ done
+ export PATH="${P#:}"
+}
+rebuild_jb_path
# Redirect all output (stdout+stderr) through tee to the log + console.
exec > >(tee -a "$LOG") 2>&1
@@ -56,7 +62,7 @@ log "Boot hash: $BOOT_HASH"
JB_TARGET="/private/preboot/$BOOT_HASH/jb-vphone/procursus"
[ -d "$JB_TARGET" ] || die "Procursus not found at $JB_TARGET"
-# ═══════════ 0/7 REPLACE LAUNCHCTL ═════════════════════════════
+# ═══════════ 0/8 REPLACE LAUNCHCTL ═════════════════════════════
# Procursus launchctl crashes (missing _launch_active_user_switch symbol).
# iosbinpack64's launchctl talks to launchd fine and always exits 0,
# which is enough for dpkg postinst/prerm script compatibility.
@@ -79,7 +85,7 @@ else
log " WARNING: iosbinpack64 launchctl not found"
fi
-# ═══════════ 1/7 SYMLINK /var/jb ═════════════════════════════
+# ═══════════ 1/8 SYMLINK /var/jb ═════════════════════════════
log "[1/8] Creating /private/var/jb symlink..."
CURRENT_LINK=$(readlink /private/var/jb 2>/dev/null || true)
if [ "$CURRENT_LINK" = "$JB_TARGET" ]; then
@@ -89,7 +95,7 @@ else
log " /var/jb -> $JB_TARGET"
fi
-# ═══════════ 2/7 FIX OWNERSHIP / PERMISSIONS ═════════════════
+# ═══════════ 2/8 FIX OWNERSHIP / PERMISSIONS ═════════════════
log "[2/8] Fixing mobile Library ownership..."
mkdir -p /var/jb/var/mobile/Library/Preferences
mkdir -p /var/jb/Library/MobileSubstrate/DynamicLibraries
@@ -123,7 +129,7 @@ else
log " WARNING: dropbearkey not found"
fi
-# ═══════════ 3/7 RUN prep_bootstrap.sh ═══════════════════════
+# ═══════════ 3/8 RUN prep_bootstrap.sh ═══════════════════════
log "[3/8] Running prep_bootstrap.sh..."
if [ -f /var/jb/prep_bootstrap.sh ]; then
NO_PASSWORD_PROMPT=1 /var/jb/prep_bootstrap.sh || log " prep_bootstrap.sh exited with $?"
@@ -133,17 +139,10 @@ else
fi
# Re-discover PATH after prep_bootstrap
-P=""
-for d in \
- /var/jb/usr/bin /var/jb/bin /var/jb/sbin /var/jb/usr/sbin \
- /iosbinpack64/bin /iosbinpack64/usr/bin /iosbinpack64/sbin /iosbinpack64/usr/sbin \
- /usr/bin /usr/sbin /bin /sbin; do
- [ -d "$d" ] && P="$P:$d"
-done
-export PATH="${P#:}"
+rebuild_jb_path
log " PATH=$PATH"
-# ═══════════ 4/7 CREATE MARKER FILES ═════════════════════════
+# ═══════════ 4/8 CREATE MARKER FILES ═════════════════════════
log "[4/8] Creating marker files..."
for marker in .procursus_strapped .installed_dopamine; do
if [ -f "/var/jb/$marker" ]; then
@@ -156,7 +155,7 @@ for marker in .procursus_strapped .installed_dopamine; do
fi
done
-# ═══════════ 5/7 INSTALL SILEO ═══════════════════════════════
+# ═══════════ 5/8 INSTALL SILEO ═══════════════════════════════
log "[5/8] Installing Sileo..."
SILEO_DEB_PATH="/private/preboot/$BOOT_HASH/org.coolstar.sileo_2.5.1_iphoneos-arm64.deb"
@@ -212,7 +211,7 @@ fi
uicache -a 2>/dev/null || true
log " uicache refreshed"
-# ═══════════ 6/7 APT SETUP ══════════════════════════════════
+# ═══════════ 6/8 APT SETUP ══════════════════════════════════
log "[6/8] Running apt setup..."
# Determine apt sources directory
@@ -251,7 +250,7 @@ apt-get -o APT::Get::AllowUnauthenticated=true \
upgrade -y -qq 2>/dev/null || true
log " apt upgrade done"
-# ═══════════ 7/7 INSTALL TROLLSTORE LITE ═════════════════════
+# ═══════════ 7/8 INSTALL TROLLSTORE LITE ═════════════════════
log "[7/8] Installing TrollStore Lite..."
TROLLSTORE_READY=0
if dpkg -s com.opa334.trollstorelite >/dev/null 2>&1; then
diff --git a/scripts/vphoned/unarchive.m b/scripts/vphoned/unarchive.m
index fead10d1..6508898e 100644
--- a/scripts/vphoned/unarchive.m
+++ b/scripts/vphoned/unarchive.m
@@ -40,7 +40,7 @@ int vp_extract_archive(NSString *archivePath, NSString *extractionPath, NSString
int ret = 0;
if (archive_read_open_filename(a, archivePath.fileSystemRepresentation, 10240) != ARCHIVE_OK) {
- NSString *err = [NSString stringWithFormat:@"archive_read_open failed: %s", archive_error_string(a)];
+ NSString *err = [NSString stringWithFormat:@"Unable to open the app package (%s).", archive_error_string(a)];
NSLog(@"vphoned: %@", err);
if (errorOutput) *errorOutput = err;
ret = 1;
@@ -54,7 +54,7 @@ int vp_extract_archive(NSString *archivePath, NSString *extractionPath, NSString
if (r < ARCHIVE_OK)
NSLog(@"vphoned: archive_read_next_header: %s", archive_error_string(a));
if (r < ARCHIVE_WARN) {
- if (errorOutput) *errorOutput = [NSString stringWithFormat:@"archive_read_next_header failed: %s", archive_error_string(a)];
+ if (errorOutput) *errorOutput = [NSString stringWithFormat:@"Unable to read the app package (%s).", archive_error_string(a)];
ret = 1; goto cleanup;
}
@@ -69,7 +69,7 @@ int vp_extract_archive(NSString *archivePath, NSString *extractionPath, NSString
if (r < ARCHIVE_OK)
NSLog(@"vphoned: archive_write_header(%@): %s (r=%d)", currentFile, archive_error_string(ext), r);
if (r < ARCHIVE_WARN) {
- if (errorOutput) *errorOutput = [NSString stringWithFormat:@"archive_write_header failed for %@: %s", currentFile, archive_error_string(ext)];
+ if (errorOutput) *errorOutput = [NSString stringWithFormat:@"Unable to extract %@ (%s).", currentFile, archive_error_string(ext)];
ret = 1; goto cleanup;
}
if (archive_entry_size(entry) > 0) {
@@ -77,7 +77,7 @@ int vp_extract_archive(NSString *archivePath, NSString *extractionPath, NSString
if (r < ARCHIVE_OK)
NSLog(@"vphoned: copy_data(%@): %s (r=%d)", currentFile, archive_error_string(ext), r);
if (r < ARCHIVE_WARN) {
- if (errorOutput) *errorOutput = [NSString stringWithFormat:@"copy_data failed for %@: %s", currentFile, archive_error_string(ext)];
+ if (errorOutput) *errorOutput = [NSString stringWithFormat:@"Unable to extract %@ (%s).", currentFile, archive_error_string(ext)];
ret = 1; goto cleanup;
}
}
@@ -86,7 +86,7 @@ int vp_extract_archive(NSString *archivePath, NSString *extractionPath, NSString
if (r < ARCHIVE_OK)
NSLog(@"vphoned: archive_write_finish_entry(%@): %s (r=%d)", currentFile, archive_error_string(ext), r);
if (r < ARCHIVE_WARN) {
- if (errorOutput) *errorOutput = [NSString stringWithFormat:@"archive_write_finish_entry failed for %@: %s", currentFile, archive_error_string(ext)];
+ if (errorOutput) *errorOutput = [NSString stringWithFormat:@"Unable to extract %@ (%s).", currentFile, archive_error_string(ext)];
ret = 1; goto cleanup;
}
}
diff --git a/scripts/vphoned/vphoned.m b/scripts/vphoned/vphoned.m
index efd028d6..3bb618e9 100644
--- a/scripts/vphoned/vphoned.m
+++ b/scripts/vphoned/vphoned.m
@@ -212,7 +212,7 @@ static NSDictionary *handle_command(NSDictionary *msg) {
if ([type isEqualToString:@"devmode"]) {
if (!vp_devmode_available()) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"XPC not available";
+ r[@"msg"] = @"Developer Mode is not available on this guest.";
return r;
}
NSString *action = msg[@"action"];
@@ -229,10 +229,10 @@ static NSDictionary *handle_command(NSDictionary *msg) {
if (ok) {
r[@"already_enabled"] = @(alreadyEnabled);
r[@"msg"] = alreadyEnabled
- ? @"developer mode already enabled"
- : @"developer mode armed, reboot to activate";
+ ? @"Developer Mode is already enabled."
+ : @"Developer Mode will be enabled after you restart the guest.";
} else {
- r[@"msg"] = @"failed to arm developer mode";
+ r[@"msg"] = @"Unable to enable Developer Mode.";
}
return r;
}
@@ -377,83 +377,41 @@ static BOOL handle_client(int fd) {
NSLog(@"vphoned: receiving update (%lu bytes)", (unsigned long)size);
if (size > 0 && size < 10 * 1024 * 1024 && receive_update(fd, size)) {
NSMutableDictionary *r = vp_make_response(@"ok", reqId);
- r[@"msg"] = @"updated, restarting";
+ r[@"msg"] = @"Updated. Restarting the guest agent…";
vp_write_message(fd, r);
should_restart = YES;
break;
} else {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"update failed";
+ r[@"msg"] = @"Unable to update the guest agent. Try again.";
vp_write_message(fd, r);
}
continue;
}
- // File operations (need fd for inline binary transfer)
+ NSDictionary *resp;
if ([t hasPrefix:@"file_"]) {
- NSDictionary *resp = vp_handle_file_command(fd, msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // Keychain operations
- if ([t hasPrefix:@"keychain_"]) {
- NSDictionary *resp = vp_handle_keychain_command(msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // Clipboard operations (need fd for inline binary transfer)
- if ([t hasPrefix:@"clipboard_"]) {
- NSDictionary *resp = vp_handle_clipboard_command(fd, msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // App management operations
- if ([t hasPrefix:@"app_"]) {
- NSDictionary *resp = vp_handle_apps_command(msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // URL opening
- if ([t isEqualToString:@"open_url"]) {
- NSDictionary *resp = vp_handle_url_command(msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // Settings operations
- if ([t hasPrefix:@"settings_"]) {
- NSDictionary *resp = vp_handle_settings_command(msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // Accessibility tree
- if ([t isEqualToString:@"accessibility_tree"]) {
- NSDictionary *resp = vp_handle_accessibility_command(msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
- }
-
- // Low power mode sync
- if ([t isEqualToString:@"low_power_mode"]) {
- NSDictionary *resp = vp_handle_notify_command(msg);
- if (resp && !vp_write_message(fd, resp))
- break;
- continue;
+ // Needs fd for inline binary transfer.
+ resp = vp_handle_file_command(fd, msg);
+ } else if ([t hasPrefix:@"keychain_"]) {
+ resp = vp_handle_keychain_command(msg);
+ } else if ([t hasPrefix:@"clipboard_"]) {
+ // Needs fd for inline binary transfer.
+ resp = vp_handle_clipboard_command(fd, msg);
+ } else if ([t hasPrefix:@"app_"]) {
+ resp = vp_handle_apps_command(msg);
+ } else if ([t isEqualToString:@"open_url"]) {
+ resp = vp_handle_url_command(msg);
+ } else if ([t hasPrefix:@"settings_"]) {
+ resp = vp_handle_settings_command(msg);
+ } else if ([t isEqualToString:@"accessibility_tree"]) {
+ resp = vp_handle_accessibility_command(msg);
+ } else if ([t isEqualToString:@"low_power_mode"]) {
+ resp = vp_handle_notify_command(msg);
+ } else {
+ resp = handle_command(msg);
}
- NSDictionary *resp = handle_command(msg);
if (resp && !vp_write_message(fd, resp))
break;
}
diff --git a/scripts/vphoned/vphoned_accessibility.m b/scripts/vphoned/vphoned_accessibility.m
index 295bdee2..d70affc6 100644
--- a/scripts/vphoned/vphoned_accessibility.m
+++ b/scripts/vphoned/vphoned_accessibility.m
@@ -16,6 +16,6 @@ NSDictionary *vp_handle_accessibility_command(NSDictionary *msg) {
id reqId = msg[@"id"];
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"accessibility_tree not yet implemented — requires XPC research";
+ r[@"msg"] = @"The accessibility tree is not available on this guest yet.";
return r;
}
diff --git a/scripts/vphoned/vphoned_apps.m b/scripts/vphoned/vphoned_apps.m
index a7142023..cecf7452 100644
--- a/scripts/vphoned/vphoned_apps.m
+++ b/scripts/vphoned/vphoned_apps.m
@@ -74,12 +74,6 @@ static pid_t pid_for_app(NSString *bundleID) {
service, sel_registerName("pidForApplication:"), bundleID);
}
-static NSString *state_for_pid(pid_t pid) {
- if (pid > 0)
- return @"running";
- return @"not_running";
-}
-
// MARK: - Command Handler
NSDictionary *vp_handle_apps_command(NSDictionary *msg) {
@@ -118,7 +112,7 @@ NSDictionary *vp_handle_apps_command(NSDictionary *msg) {
@"name" : proxy.localizedName ?: @"",
@"version" : proxy.shortVersionString ?: @"",
@"type" : isSystem ? @"system" : @"user",
- @"state" : state_for_pid(pid),
+ @"state" : pid > 0 ? @"running" : @"not_running",
@"pid" : @(pid > 0 ? pid : 0),
@"path" : proxy.bundleURL.path ?: @"",
@"data_container" : proxy.dataContainerURL.path ?: @"",
@@ -142,18 +136,12 @@ NSDictionary *vp_handle_apps_command(NSDictionary *msg) {
LSApplicationWorkspace *ws = [LSApplicationWorkspace defaultWorkspace];
NSString *url = msg[@"url"];
+ // openURL:withOptions: is private and absent on some iOS versions; fall back to a plain launch.
+ SEL openURLSel = sel_registerName("openURL:withOptions:");
BOOL ok;
- if (url) {
- // Open URL (which will launch the handling app)
- NSURL *nsurl = [NSURL URLWithString:url];
- // Try openURL:withOptions: if available
- SEL openURLSel = sel_registerName("openURL:withOptions:");
- if ([ws respondsToSelector:openURLSel]) {
- ok = ((BOOL (*)(id, SEL, id, id))objc_msgSend)(ws, openURLSel, nsurl,
- nil);
- } else {
- ok = [ws openApplicationWithBundleID:bundleID];
- }
+ if (url && [ws respondsToSelector:openURLSel]) {
+ ok = ((BOOL (*)(id, SEL, id, id))objc_msgSend)(
+ ws, openURLSel, [NSURL URLWithString:url], nil);
} else {
ok = [ws openApplicationWithBundleID:bundleID];
}
diff --git a/scripts/vphoned/vphoned_clipboard.m b/scripts/vphoned/vphoned_clipboard.m
index a7b4cc03..073b10e0 100644
--- a/scripts/vphoned/vphoned_clipboard.m
+++ b/scripts/vphoned/vphoned_clipboard.m
@@ -53,7 +53,7 @@ NSDictionary *vp_handle_clipboard_command(int fd, NSDictionary *msg) {
if (!gClipboardLoaded) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"clipboard not available (UIKit not loaded)";
+ r[@"msg"] = @"The clipboard is unavailable on the guest.";
return r;
}
@@ -62,7 +62,7 @@ NSDictionary *vp_handle_clipboard_command(int fd, NSDictionary *msg) {
id pb = get_general_pasteboard();
if (!pb) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"failed to get general pasteboard";
+ r[@"msg"] = @"The clipboard is unavailable on the guest. Try again.";
return r;
}
@@ -111,7 +111,7 @@ NSDictionary *vp_handle_clipboard_command(int fd, NSDictionary *msg) {
id pb = get_general_pasteboard();
if (!pb) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"failed to get general pasteboard";
+ r[@"msg"] = @"The clipboard is unavailable on the guest. Try again.";
return r;
}
@@ -123,14 +123,14 @@ NSDictionary *vp_handle_clipboard_command(int fd, NSDictionary *msg) {
if (size > 0)
vp_drain(fd, size);
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"invalid image size";
+ r[@"msg"] = @"This image cannot be copied to the clipboard.";
return r;
}
NSMutableData *imgData = [NSMutableData dataWithLength:size];
if (!vp_read_fully(fd, imgData.mutableBytes, size)) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"failed to read image data";
+ r[@"msg"] = @"Unable to read the image. Try again.";
return r;
}
diff --git a/scripts/vphoned/vphoned_files.m b/scripts/vphoned/vphoned_files.m
index cb126e41..76178b64 100644
--- a/scripts/vphoned/vphoned_files.m
+++ b/scripts/vphoned/vphoned_files.m
@@ -3,6 +3,12 @@
#include <sys/stat.h>
#include <unistd.h>
+static NSMutableDictionary *vp_missing_path_error(id reqId) {
+ NSMutableDictionary *r = vp_make_response(@"err", reqId);
+ r[@"msg"] = @"missing path";
+ return r;
+}
+
NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
NSString *type = msg[@"t"];
id reqId = msg[@"id"];
@@ -10,11 +16,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
// -- file_list: list directory contents --
if ([type isEqualToString:@"file_list"]) {
NSString *path = msg[@"path"];
- if (!path) {
- NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"missing path";
- return r;
- }
+ if (!path) return vp_missing_path_error(reqId);
NSFileManager *fm = [NSFileManager defaultManager];
NSError *err = nil;
@@ -66,16 +68,12 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
// -- file_get: download file from guest to host --
if ([type isEqualToString:@"file_get"]) {
NSString *path = msg[@"path"];
- if (!path) {
- NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"missing path";
- return r;
- }
+ if (!path) return vp_missing_path_error(reqId);
int fileFd = open([path fileSystemRepresentation], O_RDONLY);
if (fileFd < 0) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = [NSString stringWithFormat:@"open failed: %s", strerror(errno)];
+ r[@"msg"] = [NSString stringWithFormat:@"Unable to open the file (%s).", strerror(errno)];
return r;
}
@@ -83,13 +81,13 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
if (fstat(fileFd, &st) != 0) {
close(fileFd);
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = [NSString stringWithFormat:@"stat failed: %s", strerror(errno)];
+ r[@"msg"] = [NSString stringWithFormat:@"Unable to read the file (%s).", strerror(errno)];
return r;
}
if (!S_ISREG(st.st_mode)) {
close(fileFd);
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"not a regular file";
+ r[@"msg"] = @"Only files can be downloaded. This path is not a file.";
return r;
}
@@ -124,9 +122,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
if (!path) {
// Must still drain the raw bytes to keep protocol in sync
if (size > 0) vp_drain(fd, size);
- NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"missing path";
- return r;
+ return vp_missing_path_error(reqId);
}
// Create parent directories if needed
@@ -143,7 +139,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
if (tmp_fd < 0) {
vp_drain(fd, size);
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = [NSString stringWithFormat:@"mkstemp failed: %s", strerror(errno)];
+ r[@"msg"] = [NSString stringWithFormat:@"Unable to create a temporary file (%s).", strerror(errno)];
return r;
}
@@ -161,7 +157,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
if (!ok) {
unlink(tmp_path);
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"file transfer failed";
+ r[@"msg"] = @"The file transfer was interrupted. Try again.";
return r;
}
@@ -176,7 +172,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
if (rename(tmp_path, [path fileSystemRepresentation]) != 0) {
unlink(tmp_path);
NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = [NSString stringWithFormat:@"rename failed: %s", strerror(errno)];
+ r[@"msg"] = [NSString stringWithFormat:@"Unable to save the file (%s).", strerror(errno)];
return r;
}
@@ -187,11 +183,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
// -- file_mkdir --
if ([type isEqualToString:@"file_mkdir"]) {
NSString *path = msg[@"path"];
- if (!path) {
- NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"missing path";
- return r;
- }
+ if (!path) return vp_missing_path_error(reqId);
NSError *err = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:YES
@@ -207,11 +199,7 @@ NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {
// -- file_delete --
if ([type isEqualToString:@"file_delete"]) {
NSString *path = msg[@"path"];
- if (!path) {
- NSMutableDictionary *r = vp_make_response(@"err", reqId);
- r[@"msg"] = @"missing path";
- return r;
- }
+ if (!path) return vp_missing_path_error(reqId);
NSError *err = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:path error:&err]) {
NSMutableDictionary *r = vp_make_response(@"err", reqId);
diff --git a/scripts/vphoned/vphoned_hid.m b/scripts/vphoned/vphoned_hid.m
index 9658bf98..c595ab28 100644
--- a/scripts/vphoned/vphoned_hid.m
+++ b/scripts/vphoned/vphoned_hid.m
@@ -28,7 +28,6 @@ static IOHIDEventSystemClientRef gClient;
static dispatch_queue_t gHIDQueue;
// Digitizer event-mask bits and transducer types (IOHIDEventTypes.h).
-#define VP_DIG_RANGE 0x00000001u
#define VP_DIG_TOUCH 0x00000002u
#define VP_DIG_POSITION 0x00000004u
#define VP_DIG_IDENTITY 0x00000020u
@@ -120,12 +119,7 @@ static void dispatch_digitizer(double x, double y, boolean_t range,
CFRelease(finger);
}
- IOHIDEventRef strong = (IOHIDEventRef)CFRetain(parent);
- dispatch_async(gHIDQueue, ^{
- pSetSender(strong, 0x8000000817319372);
- pDispatch(gClient, strong);
- CFRelease(strong);
- });
+ send_hid_event(parent);
CFRelease(parent);
}
diff --git a/scripts/vphoned/vphoned_install.m b/scripts/vphoned/vphoned_install.m
index 0f715a21..c7918f3b 100644
--- a/scripts/vphoned/vphoned_install.m
+++ b/scripts/vphoned/vphoned_install.m
@@ -278,26 +278,22 @@ static int vp_sign_binary(
NSString **errorOutput
) {
if (ldidPath.length == 0) {
- if (errorOutput) *errorOutput = @"ldid not found in guest or uploaded payload";
+ if (errorOutput) *errorOutput = @"The code-signing tool (ldid) is missing on the guest.";
return ENOENT;
}
NSString *entitlementsPath = nil;
NSMutableArray<NSString *> *args = [NSMutableArray array];
- if (entitlements) {
- NSData *entitlementsXML = [NSPropertyListSerialization
- dataWithPropertyList:entitlements
- format:NSPropertyListXMLFormat_v1_0
- options:0
- error:nil];
- if (entitlementsXML) {
- entitlementsPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:[NSUUID UUID].UUIDString]
- stringByAppendingPathExtension:@"plist"];
- [entitlementsXML writeToFile:entitlementsPath atomically:NO];
- [args addObject:[@"-S" stringByAppendingString:entitlementsPath]];
- } else {
- [args addObject:@"-S"];
- }
+ NSData *entitlementsXML = entitlements ? [NSPropertyListSerialization
+ dataWithPropertyList:entitlements
+ format:NSPropertyListXMLFormat_v1_0
+ options:0
+ error:nil] : nil;
+ if (entitlementsXML) {
+ entitlementsPath = [[NSTemporaryDirectory() stringByAppendingPathComponent:[NSUUID UUID].UUIDString]
+ stringByAppendingPathExtension:@"plist"];
+ [entitlementsXML writeToFile:entitlementsPath atomically:NO];
+ [args addObject:[@"-S" stringByAppendingString:entitlementsPath]];
} else {
[args addObject:@"-S"];
}
@@ -320,13 +316,13 @@ static int vp_sign_binary(
static int vp_sign_app(NSString *appPath, NSString *certPath, NSString *ldidPath, NSString **errorOutput) {
if (!vp_info_dictionary_for_app_path(appPath)) {
- if (errorOutput) *errorOutput = @"missing app Info.plist";
+ if (errorOutput) *errorOutput = @"The app package is incomplete and cannot be signed.";
return 172;
}
NSString *mainExecutablePath = vp_app_main_executable_path_for_app_path(appPath);
if (mainExecutablePath.length == 0 || ![[NSFileManager defaultManager] fileExistsAtPath:mainExecutablePath]) {
- if (errorOutput) *errorOutput = @"missing main executable";
+ if (errorOutput) *errorOutput = @"The app package is missing its program and cannot be signed.";
return 174;
}
@@ -473,6 +469,65 @@ static NSSet<NSString *> *vp_immutable_app_bundle_identifiers(void) {
return systemAppIdentifiers.copy;
}
+/// Build the LaunchServices registration dictionary shared by an app bundle and its PlugIns.
+/// The caller adds the keys that differ: ApplicationType, Path, and the app- or plugin-only keys.
+static NSMutableDictionary *vp_registration_dictionary(
+ NSString *bundleID,
+ NSString *executablePath,
+ Class containerClass
+) {
+ NSDictionary *entitlements = vp_dump_entitlements_from_binary_at_path(executablePath);
+
+ NSString *dataContainerID = bundleID;
+ BOOL containerized = vp_construct_containerization_for_entitlements(entitlements ?: @{}, &dataContainerID);
+
+ MCMContainer *dataContainer = [containerClass
+ containerWithIdentifier:dataContainerID
+ createIfNecessary:YES
+ existed:nil
+ error:nil];
+ NSString *containerPath = dataContainer.url.path;
+
+ NSMutableDictionary *dict = [NSMutableDictionary dictionary];
+ if (entitlements) {
+ dict[@"Entitlements"] = entitlements;
+ }
+ dict[@"CFBundleIdentifier"] = bundleID;
+ dict[@"CodeInfoIdentifier"] = bundleID;
+ dict[@"CompatibilityState"] = @0;
+ dict[@"IsContainerized"] = @(containerized);
+ if (containerPath.length > 0) {
+ dict[@"Container"] = containerPath;
+ dict[@"EnvironmentVariables"] =
+ vp_construct_environment_variables_for_container_path(containerPath, containerized);
+ }
+ dict[@"SignerOrganization"] = @"Apple Inc.";
+ dict[@"SignatureVersion"] = @132352;
+ dict[@"SignerIdentity"] = @"Apple iPhone OS Application Signing";
+
+ NSString *teamIdentifier = vp_construct_team_identifier_for_entitlements(entitlements ?: @{});
+ if (teamIdentifier.length > 0) {
+ dict[@"TeamIdentifier"] = teamIdentifier;
+ }
+
+ NSDictionary *appGroupContainers = vp_construct_groups_containers_for_entitlements(entitlements, NO);
+ NSDictionary *systemGroupContainers = vp_construct_groups_containers_for_entitlements(entitlements, YES);
+ NSMutableDictionary *groupContainers = [NSMutableDictionary dictionary];
+ [groupContainers addEntriesFromDictionary:appGroupContainers];
+ [groupContainers addEntriesFromDictionary:systemGroupContainers];
+ if (groupContainers.count > 0) {
+ if (appGroupContainers.count > 0) {
+ dict[@"HasAppGroupContainers"] = @YES;
+ }
+ if (systemGroupContainers.count > 0) {
+ dict[@"HasSystemGroupContainers"] = @YES;
+ }
+ dict[@"GroupContainers"] = groupContainers.copy;
+ }
+
+ return dict;
+}
+
static BOOL vp_register_path(NSString *path, BOOL unregister, BOOL forceSystem) {
if (path.length == 0) return NO;
@@ -492,43 +547,16 @@ static BOOL vp_register_path(NSString *path, BOOL unregister, BOOL forceSystem)
if (!unregister) {
NSString *appExecutablePath = [path stringByAppendingPathComponent:appInfoPlist[@"CFBundleExecutable"]];
- NSDictionary *entitlements = vp_dump_entitlements_from_binary_at_path(appExecutablePath);
-
- NSString *appDataContainerID = appBundleID;
- BOOL appContainerized = vp_construct_containerization_for_entitlements(entitlements ?: @{}, &appDataContainerID);
-
- Class appDataContainerClass = NSClassFromString(@"MCMAppDataContainer");
- MCMContainer *appDataContainer = [appDataContainerClass
- containerWithIdentifier:appDataContainerID
- createIfNecessary:YES
- existed:nil
- error:nil];
- NSString *containerPath = appDataContainer.url.path;
+ NSMutableDictionary *dictToRegister = vp_registration_dictionary(
+ appBundleID, appExecutablePath, NSClassFromString(@"MCMAppDataContainer"));
BOOL isRemovableSystemApp = [[NSFileManager defaultManager]
fileExistsAtPath:[@"/System/Library/AppSignatures" stringByAppendingPathComponent:appBundleID]];
BOOL registerAsUser = [path hasPrefix:@"/var/containers"] && !isRemovableSystemApp && !forceSystem;
- NSMutableDictionary *dictToRegister = [NSMutableDictionary dictionary];
- if (entitlements) {
- dictToRegister[@"Entitlements"] = entitlements;
- }
-
dictToRegister[@"ApplicationType"] = registerAsUser ? @"User" : @"System";
- dictToRegister[@"CFBundleIdentifier"] = appBundleID;
- dictToRegister[@"CodeInfoIdentifier"] = appBundleID;
- dictToRegister[@"CompatibilityState"] = @0;
- dictToRegister[@"IsContainerized"] = @(appContainerized);
- if (containerPath.length > 0) {
- dictToRegister[@"Container"] = containerPath;
- dictToRegister[@"EnvironmentVariables"] =
- vp_construct_environment_variables_for_container_path(containerPath, appContainerized);
- }
dictToRegister[@"IsDeletable"] = @YES;
dictToRegister[@"Path"] = path;
- dictToRegister[@"SignerOrganization"] = @"Apple Inc.";
- dictToRegister[@"SignatureVersion"] = @132352;
- dictToRegister[@"SignerIdentity"] = @"Apple iPhone OS Application Signing";
dictToRegister[@"IsAdHocSigned"] = @YES;
dictToRegister[@"LSInstallType"] = @1;
dictToRegister[@"HasMIDBasedSINF"] = @0;
@@ -536,26 +564,6 @@ static BOOL vp_register_path(NSString *path, BOOL unregister, BOOL forceSystem)
dictToRegister[@"FamilyID"] = @0;
dictToRegister[@"IsOnDemandInstallCapable"] = @0;
- NSString *teamIdentifier = vp_construct_team_identifier_for_entitlements(entitlements ?: @{});
- if (teamIdentifier.length > 0) {
- dictToRegister[@"TeamIdentifier"] = teamIdentifier;
- }
-
- NSDictionary *appGroupContainers = vp_construct_groups_containers_for_entitlements(entitlements, NO);
- NSDictionary *systemGroupContainers = vp_construct_groups_containers_for_entitlements(entitlements, YES);
- NSMutableDictionary *groupContainers = [NSMutableDictionary dictionary];
- [groupContainers addEntriesFromDictionary:appGroupContainers];
- [groupContainers addEntriesFromDictionary:systemGroupContainers];
- if (groupContainers.count > 0) {
- if (appGroupContainers.count > 0) {
- dictToRegister[@"HasAppGroupContainers"] = @YES;
- }
- if (systemGroupContainers.count > 0) {
- dictToRegister[@"HasSystemGroupContainers"] = @YES;
- }
- dictToRegister[@"GroupContainers"] = groupContainers.copy;
- }
-
NSString *pluginsPath = [path stringByAppendingPathComponent:@"PlugIns"];
NSArray<NSString *> *plugins = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pluginsPath error:nil];
NSMutableDictionary *bundlePlugins = [NSMutableDictionary dictionary];
@@ -570,60 +578,11 @@ static BOOL vp_register_path(NSString *path, BOOL unregister, BOOL forceSystem)
}
NSString *pluginExecutablePath = [pluginPath stringByAppendingPathComponent:pluginExecutable];
- NSDictionary *pluginEntitlements = vp_dump_entitlements_from_binary_at_path(pluginExecutablePath);
- NSString *pluginDataContainerID = pluginBundleID;
- BOOL pluginContainerized =
- vp_construct_containerization_for_entitlements(pluginEntitlements ?: @{}, &pluginDataContainerID);
-
- Class pluginContainerClass = NSClassFromString(@"MCMPluginKitPluginDataContainer");
- MCMContainer *pluginContainer = [pluginContainerClass
- containerWithIdentifier:pluginDataContainerID
- createIfNecessary:YES
- existed:nil
- error:nil];
- NSString *pluginContainerPath = pluginContainer.url.path;
-
- NSMutableDictionary *pluginDict = [NSMutableDictionary dictionary];
- if (pluginEntitlements) {
- pluginDict[@"Entitlements"] = pluginEntitlements;
- }
+ NSMutableDictionary *pluginDict = vp_registration_dictionary(
+ pluginBundleID, pluginExecutablePath, NSClassFromString(@"MCMPluginKitPluginDataContainer"));
pluginDict[@"ApplicationType"] = @"PluginKitPlugin";
- pluginDict[@"CFBundleIdentifier"] = pluginBundleID;
- pluginDict[@"CodeInfoIdentifier"] = pluginBundleID;
- pluginDict[@"CompatibilityState"] = @0;
- pluginDict[@"IsContainerized"] = @(pluginContainerized);
- if (pluginContainerPath.length > 0) {
- pluginDict[@"Container"] = pluginContainerPath;
- pluginDict[@"EnvironmentVariables"] =
- vp_construct_environment_variables_for_container_path(pluginContainerPath, pluginContainerized);
- }
pluginDict[@"Path"] = pluginPath;
pluginDict[@"PluginOwnerBundleID"] = appBundleID;
- pluginDict[@"SignerOrganization"] = @"Apple Inc.";
- pluginDict[@"SignatureVersion"] = @132352;
- pluginDict[@"SignerIdentity"] = @"Apple iPhone OS Application Signing";
-
- NSString *pluginTeamIdentifier = vp_construct_team_identifier_for_entitlements(pluginEntitlements ?: @{});
- if (pluginTeamIdentifier.length > 0) {
- pluginDict[@"TeamIdentifier"] = pluginTeamIdentifier;
- }
-
- NSDictionary *pluginAppGroupContainers =
- vp_construct_groups_containers_for_entitlements(pluginEntitlements, NO);
- NSDictionary *pluginSystemGroupContainers =
- vp_construct_groups_containers_for_entitlements(pluginEntitlements, YES);
- NSMutableDictionary *pluginGroupContainers = [NSMutableDictionary dictionary];
- [pluginGroupContainers addEntriesFromDictionary:pluginAppGroupContainers];
- [pluginGroupContainers addEntriesFromDictionary:pluginSystemGroupContainers];
- if (pluginGroupContainers.count > 0) {
- if (pluginAppGroupContainers.count > 0) {
- pluginDict[@"HasAppGroupContainers"] = @YES;
- }
- if (pluginSystemGroupContainers.count > 0) {
- pluginDict[@"HasSystemGroupContainers"] = @YES;
- }
- pluginDict[@"GroupContainers"] = pluginGroupContainers.copy;
- }
bundlePlugins[pluginBundleID] = pluginDict;
}
@@ -684,18 +643,18 @@ static int vp_install_app_from_package(
NSString *appPayloadPath = [appPackagePath stringByAppendingPathComponent:@"Payload"];
NSString *appBundleToInstallPath = vp_find_app_path_in_bundle_path(appPayloadPath);
if (appBundleToInstallPath.length == 0) {
- if (detailOutput) *detailOutput = @"IPA does not contain an .app payload";
+ if (detailOutput) *detailOutput = @"The app package does not contain an app.";
return 167;
}
NSString *appId = vp_app_id_for_app_path(appBundleToInstallPath);
if (appId.length == 0) {
- if (detailOutput) *detailOutput = @"missing CFBundleIdentifier";
+ if (detailOutput) *detailOutput = @"The app package has no bundle identifier.";
return 176;
}
if ([vp_immutable_app_bundle_identifiers() containsObject:appId.lowercaseString]) {
- if (detailOutput) *detailOutput = @"cannot overwrite immutable system app";
+ if (detailOutput) *detailOutput = @"This app is part of iOS and cannot be replaced.";
return 179;
}
@@ -708,7 +667,7 @@ static int vp_install_app_from_package(
Class appContainerClass = NSClassFromString(@"MCMAppContainer");
if (!appContainerClass) {
- if (detailOutput) *detailOutput = @"MCMAppContainer unavailable";
+ if (detailOutput) *detailOutput = @"The app container service is unavailable.";
return 170;
}
@@ -717,7 +676,7 @@ static int vp_install_app_from_package(
NSURL *bundleContainerURL = appContainer.url;
NSURL *appBundleURL = vp_find_app_url_in_bundle_url(bundleContainerURL);
if (appBundleURL.path.length > 0 && !vp_container_has_known_marker(bundleContainerURL.path)) {
- if (detailOutput) *detailOutput = @"a non-managed app with the same bundle identifier is already installed";
+ if (detailOutput) *detailOutput = @"An app with the same bundle identifier is already installed. Remove it and try again.";
return 171;
}
if (appBundleURL.path.length > 0) {
@@ -727,7 +686,7 @@ static int vp_install_app_from_package(
NSError *mcmError = nil;
appContainer = [appContainerClass containerWithIdentifier:appId createIfNecessary:YES existed:nil error:&mcmError];
if (!appContainer || mcmError) {
- if (detailOutput) *detailOutput = mcmError.localizedDescription ?: @"failed to create app container";
+ if (detailOutput) *detailOutput = mcmError.localizedDescription ?: @"Unable to prepare storage for the app.";
return 170;
}
}
@@ -735,24 +694,24 @@ static int vp_install_app_from_package(
NSString *newAppBundlePath = [appContainer.url.path stringByAppendingPathComponent:appBundleToInstallPath.lastPathComponent];
NSError *copyError = nil;
if (![[NSFileManager defaultManager] copyItemAtPath:appBundleToInstallPath toPath:newAppBundlePath error:&copyError]) {
- if (detailOutput) *detailOutput = copyError.localizedDescription ?: @"failed to copy app bundle";
+ if (detailOutput) *detailOutput = copyError.localizedDescription ?: @"Unable to copy the app onto the guest.";
return 178;
}
if (!vp_mark_container_as_managed(appContainer.url.path)) {
- if (detailOutput) *detailOutput = @"installed app but failed to write management marker";
+ if (detailOutput) *detailOutput = @"The app was installed but could not be marked as managed.";
return 177;
}
NSURL *updatedAppURL = vp_find_app_url_in_bundle_url(appContainer.url);
if (updatedAppURL.path.length == 0) {
- if (detailOutput) *detailOutput = @"installed app but failed to resolve final app path";
+ if (detailOutput) *detailOutput = @"The app was installed but could not be located afterwards.";
return 178;
}
vp_fix_permissions_of_app_bundle(updatedAppURL.path);
if (!vp_register_path(updatedAppURL.path, NO, forceSystem)) {
- if (detailOutput) *detailOutput = @"install copied files but LaunchServices registration failed";
+ if (detailOutput) *detailOutput = @"The app was copied but could not be registered with the system.";
return 181;
}
@@ -770,7 +729,7 @@ static int vp_extract_package_to_directory(
NSString *archiveError = nil;
int ret = vp_extract_archive(fileToExtract, extractionPath, &archiveError);
if (ret != 0) {
- if (detailOutput) *detailOutput = archiveError ?: @"libarchive extraction failed";
+ if (detailOutput) *detailOutput = archiveError ?: @"Unable to extract the app package.";
return 168;
}
return 0;
@@ -793,12 +752,12 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {
if (ipaPath.length == 0) {
NSMutableDictionary *response = vp_make_response(@"err", reqId);
- response[@"msg"] = @"missing ipa path";
+ response[@"msg"] = @"No app package was specified.";
return response;
}
if (![[NSFileManager defaultManager] fileExistsAtPath:ipaPath]) {
NSMutableDictionary *response = vp_make_response(@"err", reqId);
- response[@"msg"] = [NSString stringWithFormat:@"IPA not found: %@", ipaPath];
+ response[@"msg"] = [NSString stringWithFormat:@"App package not found at %@.", ipaPath];
return response;
}
if (!vp_custom_installer_available()) {
@@ -807,12 +766,13 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {
if (NSClassFromString(@"MCMAppContainer") == Nil) [missing addObject:@"MCMAppContainer"];
if (NSClassFromString(@"LSApplicationWorkspace") == Nil) [missing addObject:@"LSApplicationWorkspace"];
NSString *detail = missing.count > 0 ? [missing componentsJoinedByString:@", "] : @"unknown";
- response[@"msg"] = [NSString stringWithFormat:@"Built-in IPA installer prerequisites are missing: %@", detail];
+ NSLog(@"vphoned: custom installer unavailable: %@", detail);
+ response[@"msg"] = @"This guest cannot install apps. The built-in installer is not supported here.";
return response;
}
if (ldidPath.length == 0) {
NSMutableDictionary *response = vp_make_response(@"err", reqId);
- response[@"msg"] = @"Built-in IPA installer could not find a guest-side iOS ldid.";
+ response[@"msg"] = @"The code-signing tool (ldid) is missing on the guest. Install it and try again.";
return response;
}
if (certPath.length > 0 && ![[NSFileManager defaultManager] fileExistsAtPath:certPath]) {
@@ -822,7 +782,7 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {
NSString *tmpPackagePath = [[NSTemporaryDirectory() stringByResolvingSymlinksInPath] stringByAppendingPathComponent:[NSUUID UUID].UUIDString];
if (![[NSFileManager defaultManager] createDirectoryAtPath:tmpPackagePath withIntermediateDirectories:NO attributes:nil error:nil]) {
NSMutableDictionary *response = vp_make_response(@"err", reqId);
- response[@"msg"] = @"failed to create temporary extraction directory";
+ response[@"msg"] = @"Unable to prepare the guest for installation. Try again.";
return response;
}
@@ -843,14 +803,14 @@ NSDictionary *vp_handle_custom_install(NSDictionary *msg) {
int retCode = extractRet != 0 ? extractRet : installRet;
NSString *trimmed = vp_trimmed_output(detail ?: @"");
response[@"msg"] = trimmed.length > 0
- ? [NSString stringWithFormat:@"built-in installer failed (%d)\n%@", retCode, trimmed]
- : [NSString stringWithFormat:@"built-in installer failed (%d)", retCode];
+ ? [NSString stringWithFormat:@"Unable to install the app (code %d).\n%@", retCode, trimmed]
+ : [NSString stringWithFormat:@"Unable to install the app (code %d).", retCode];
return response;
}
NSMutableDictionary *response = vp_make_response(@"ok", reqId);
response[@"msg"] = forceSystem
- ? [NSString stringWithFormat:@"Installed via built-in installer as System: %@", detail]
- : [NSString stringWithFormat:@"Installed via built-in installer as User: %@", detail];
+ ? [NSString stringWithFormat:@"Installed %@ as a system app.", detail]
+ : [NSString stringWithFormat:@"Installed %@ as a user app.", detail];
return response;
}
diff --git a/scripts/vphoned/vphoned_keychain.m b/scripts/vphoned/vphoned_keychain.m
index 38f05373..2a97130b 100644
--- a/scripts/vphoned/vphoned_keychain.m
+++ b/scripts/vphoned/vphoned_keychain.m
@@ -11,38 +11,10 @@
#import <Security/Security.h>
#import <sqlite3.h>
-// MARK: - Helpers
-
-/// Convert a CFType keychain attribute value to a JSON-safe NSObject.
-static id safe_value(id val) {
- if (!val || val == (id)kCFNull) return [NSNull null];
- if ([val isKindOfClass:[NSString class]]) return val;
- if ([val isKindOfClass:[NSNumber class]]) return val;
- if ([val isKindOfClass:[NSDate class]]) {
- return @([(NSDate *)val timeIntervalSince1970]);
- }
- if ([val isKindOfClass:[NSData class]]) {
- NSString *str = [[NSString alloc] initWithData:val encoding:NSUTF8StringEncoding];
- if (str) return str;
- return [(NSData *)val base64EncodedStringWithOptions:0];
- }
- return [val description];
-}
-
// MARK: - SQLite-based keychain reader
static NSString *KEYCHAIN_DB_PATH = @"/var/Keychains/keychain-2.db";
-/// Map sqlite table name to our class abbreviation.
-static NSDictionary *tableToClass(void) {
- return @{
- @"genp": @"genp",
- @"inet": @"inet",
- @"cert": @"cert",
- @"keys": @"keys",
- };
-}
-
/// Read a text column, returning @"" if NULL.
static NSString *col_text(sqlite3_stmt *stmt, int col) {
const unsigned char *val = sqlite3_column_text(stmt, col);
@@ -50,18 +22,6 @@ static NSString *col_text(sqlite3_stmt *stmt, int col) {
return [NSString stringWithUTF8String:(const char *)val];
}
-/// Read a blob column as base64 string.
-static NSString *col_blob_base64(sqlite3_stmt *stmt, int col) {
- const void *blob = sqlite3_column_blob(stmt, col);
- int size = sqlite3_column_bytes(stmt, col);
- if (!blob || size <= 0) return @"";
- NSData *data = [NSData dataWithBytes:blob length:size];
- // Try UTF-8 first
- NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- if (str) return str;
- return [data base64EncodedStringWithOptions:0];
-}
-
/// Query one table from the keychain DB via sqlite3.
static NSArray *query_db_table(sqlite3 *db, NSString *table, NSString *className, NSMutableArray *diag) {
// Columns available in genp/inet tables:
@@ -69,13 +29,12 @@ static NSArray *query_db_table(sqlite3 *db, NSString *table, NSString *className
// inet also has: srvr, ptcl, port, path
NSString *sql;
BOOL isInet = [table isEqualToString:@"inet"];
- BOOL isCert = [table isEqualToString:@"cert"];
- BOOL isKeys = [table isEqualToString:@"keys"];
+ BOOL hasAccountColumns = !([table isEqualToString:@"cert"] || [table isEqualToString:@"keys"]);
if (isInet) {
sql = [NSString stringWithFormat:
@"SELECT rowid, acct, svce, agrp, labl, data, cdat, mdat, pdmn, srvr, ptcl, port, path FROM %@", table];
- } else if (isCert || isKeys) {
+ } else if (!hasAccountColumns) {
sql = [NSString stringWithFormat:
@"SELECT rowid, agrp, labl, data, cdat, mdat, pdmn FROM %@", table];
} else {
@@ -98,7 +57,7 @@ static NSArray *query_db_table(sqlite3 *db, NSString *table, NSString *className
int col = 0;
int rowid = sqlite3_column_int(stmt, col++);
- if (!isCert && !isKeys) {
+ if (hasAccountColumns) {
entry[@"account"] = col_text(stmt, col++);
entry[@"service"] = col_text(stmt, col++);
}
@@ -161,34 +120,28 @@ static NSArray *query_db_table(sqlite3 *db, NSString *table, NSString *className
}
/// Read all keychain items directly from the sqlite database.
-static NSDictionary *query_keychain_db(NSString *filterClass, NSMutableArray *diag) {
+static NSArray *query_keychain_db(NSString *filterClass, NSMutableArray *diag) {
sqlite3 *db = NULL;
int rc = sqlite3_open_v2(KEYCHAIN_DB_PATH.UTF8String, &db, SQLITE_OPEN_READONLY, NULL);
if (rc != SQLITE_OK) {
[diag addObject:[NSString stringWithFormat:@"db open failed: %d", rc]];
NSLog(@"vphoned: sqlite3_open(%@) failed: %d", KEYCHAIN_DB_PATH, rc);
- return @{@"items": @[], @"diag": diag};
+ return @[];
}
[diag addObject:[NSString stringWithFormat:@"opened %@", KEYCHAIN_DB_PATH]];
NSMutableArray *allItems = [NSMutableArray array];
- struct { NSString *table; NSString *name; } tables[] = {
- { @"genp", @"genp" },
- { @"inet", @"inet" },
- { @"cert", @"cert" },
- { @"keys", @"keys" },
- };
-
- for (size_t i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
- if (filterClass && ![filterClass isEqualToString:tables[i].name]) continue;
- NSArray *items = query_db_table(db, tables[i].table, tables[i].name, diag);
- [allItems addObjectsFromArray:items];
+ NSArray<NSString *> *tables = @[ @"genp", @"inet", @"cert", @"keys" ];
+
+ for (NSString *table in tables) {
+ if (filterClass && ![filterClass isEqualToString:table]) continue;
+ [allItems addObjectsFromArray:query_db_table(db, table, table, diag)];
}
sqlite3_close(db);
- return @{@"items": allItems};
+ return allItems;
}
// MARK: - Command Handler
@@ -225,7 +178,7 @@ NSDictionary *vp_handle_keychain_command(NSDictionary *msg) {
resp[@"status"] = @(status);
resp[@"ok"] = @(status == errSecSuccess);
if (status != errSecSuccess) {
- resp[@"msg"] = [NSString stringWithFormat:@"SecItemAdd failed: %d", (int)status];
+ resp[@"msg"] = [NSString stringWithFormat:@"Unable to add the keychain item (status %d).", (int)status];
}
return resp;
}
@@ -235,8 +188,7 @@ NSDictionary *vp_handle_keychain_command(NSDictionary *msg) {
NSMutableArray *diag = [NSMutableArray array];
// Primary: read directly from sqlite DB (bypasses entitlement checks)
- NSDictionary *dbResult = query_keychain_db(filterClass, diag);
- NSArray *dbItems = dbResult[@"items"];
+ NSArray *dbItems = query_keychain_db(filterClass, diag);
NSLog(@"vphoned: keychain_list: %lu items (sqlite), diag: %@",
(unsigned long)dbItems.count, diag);
diff --git a/scripts/vpregister/vpregister.m b/scripts/vpregister/vpregister.m
index cfa94a79..eac8380b 100644
--- a/scripts/vpregister/vpregister.m
+++ b/scripts/vpregister/vpregister.m
@@ -14,20 +14,29 @@
saveObserver:(id)observer
registrationError:(NSError **)error;
@end
-static BOOL regapp(LSApplicationWorkspace *ws, NSString *path) {
+static BOOL register_app(LSApplicationWorkspace *ws, NSString *path) {
NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:@"Info.plist"]];
- NSString *bid = info[@"CFBundleIdentifier"];
- if (bid.length == 0) return NO;
- NSMutableDictionary *d = [NSMutableDictionary dictionary];
- d[@"Path"] = path; d[@"CFBundleIdentifier"] = bid; d[@"CodeInfoIdentifier"] = bid;
- d[@"ApplicationType"] = @"System"; d[@"CompatibilityState"] = @0;
- d[@"SignerIdentity"] = @"Apple iPhone OS Application Signing";
- d[@"SignerOrganization"] = @"Apple Inc."; d[@"IsAdHocSigned"] = @YES;
- d[@"SignatureVersion"] = @132352; d[@"IsDeletable"] = @YES;
+ NSString *bundleID = info[@"CFBundleIdentifier"];
+ if (bundleID.length == 0) return NO;
+ NSDictionary *dictToRegister = @{
+ @"Path" : path,
+ @"CFBundleIdentifier" : bundleID,
+ @"CodeInfoIdentifier" : bundleID,
+ @"ApplicationType" : @"System",
+ @"CompatibilityState" : @0,
+ @"SignerIdentity" : @"Apple iPhone OS Application Signing",
+ @"SignerOrganization" : @"Apple Inc.",
+ @"IsAdHocSigned" : @YES,
+ @"SignatureVersion" : @132352,
+ @"IsDeletable" : @YES,
+ };
NSError *err = nil;
- [ws registerContainerizedApplicationWithInfoDictionaries:@[d] operationUUID:[NSUUID UUID]
+ // The containerized API returns NO even when registration succeeds, so a nil
+ // registrationError is the success signal (same rule as vphoned_install.m's
+ // containerized path).
+ [ws registerContainerizedApplicationWithInfoDictionaries:@[dictToRegister] operationUUID:[NSUUID UUID]
requestContext:nil saveObserver:nil registrationError:&err];
- if (err) fprintf(stderr, " err: %s\n", err.description.UTF8String);
+ if (err) fprintf(stderr, " Unable to register: %s\n", err.description.UTF8String);
return err == nil;
}
int main(int argc, char **argv) {
@@ -35,15 +44,19 @@ int main(int argc, char **argv) {
dlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_NOW);
LSApplicationWorkspace *ws = [LSApplicationWorkspace defaultWorkspace];
NSMutableArray *paths = [NSMutableArray array];
- if (argc > 1) { for (int i = 1; i < argc; i++) [paths addObject:@(argv[i])]; }
- else {
+ for (int i = 1; i < argc; i++) [paths addObject:@(argv[i])];
+ if (paths.count == 0) {
NSString *dir = @"/var/jb/Applications";
- for (NSString *n in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil])
- if ([n hasSuffix:@".app"]) [paths addObject:[dir stringByAppendingPathComponent:n]];
+ for (NSString *bundleName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil])
+ if ([bundleName hasSuffix:@".app"]) [paths addObject:[dir stringByAppendingPathComponent:bundleName]];
}
- int ok = 0, fail = 0;
- for (NSString *p in paths) { BOOL r = regapp(ws, p); printf("%-4s %s\n", r ? "OK" : "FAIL", p.UTF8String); r ? ok++ : fail++; }
- printf("registered %d, failed %d\n", ok, fail);
+ int fail = 0;
+ for (NSString *appPath in paths) {
+ BOOL registered = register_app(ws, appPath);
+ printf("%-10s %s\n", registered ? "Registered" : "Failed", appPath.UTF8String);
+ if (!registered) fail++;
+ }
+ printf("Registered %d, failed %d\n", (int)paths.count - fail, fail);
return fail ? 1 : 0;
}
}
diff --git a/skills/kernel-analysis-vphone600/SKILL.md b/skills/kernel-analysis-vphone600/SKILL.md
index 6a46efd8..ead2eaf1 100644
--- a/skills/kernel-analysis-vphone600/SKILL.md
+++ b/skills/kernel-analysis-vphone600/SKILL.md
@@ -11,11 +11,15 @@ Use `research/reference/xnu` as the source-level reference for semantics and str
## Required Paths
- `research/kernel_info/kernel_symbols.db`
-- `research/kernel_info/kernel_index.tsv`
-- `research/kernel_info/json/kernelcache.release.vphone600.bin.symbols.json`
-- `research/kernel_info/json/kernelcache.research.vphone600.bin.symbols.json`
+- `research/kernel_info/kernel_index.tsv` (plain-text `kernel_name → json_path` index with `json_sha256`)
+- `research/kernel_info/json/` — the recovered symbol datasets:
+ - `kernelcache.release.vphone600.bin.symbols.json`
+ - `kernelcache.research.vphone600.bin.symbols.json`
- `research/reference/xnu`
+The `json_path` column in both the database and `kernel_index.tsv` records the absolute path from symbolication
+time and may not match this checkout; resolve the JSON files under `research/kernel_info/json/` instead.
+
If `research/reference/xnu` is missing, create it with a shallow clone:
```bash
@@ -31,17 +35,6 @@ git clone --depth 1 https://github.com/apple-oss-distributions/xnu.git research/
4. Cross-reference candidate code paths in `research/reference/xnu`.
5. Report findings with explicit kernel name, symbol path, and address.
-## Standard Queries
-
-- List known kernels:
- - `sqlite3 research/kernel_info/kernel_symbols.db "select kernel_name, json_path from kernel_symbols order by kernel_name;"`
-- Find one kernel by name:
- - `sqlite3 research/kernel_info/kernel_symbols.db "select * from kernel_symbols where kernel_name='kernelcache.release.vphone600';"`
-- Search symbol by substring in release JSON:
- - `rg -n 'symbol_name_fragment' research/kernel_info/json/kernelcache.release.vphone600.bin.symbols.json`
-- Search symbol by address in research JSON:
- - `rg -n '0xfffffe00...' research/kernel_info/json/kernelcache.research.vphone600.bin.symbols.json`
-
## Output Rules
- Always include which kernel was used: `kernelcache.release.vphone600` or `kernelcache.research.vphone600`.
diff --git a/skills/kernel-analysis-vphone600/references/kernel-info-queries.md b/skills/kernel-analysis-vphone600/references/kernel-info-queries.md
index a4452c6e..6d77f664 100644
--- a/skills/kernel-analysis-vphone600/references/kernel-info-queries.md
+++ b/skills/kernel-analysis-vphone600/references/kernel-info-queries.md
@@ -8,6 +8,7 @@ Use these commands from repo root (`vphone-cli`).
sqlite3 research/kernel_info/kernel_symbols.db ".schema kernel_symbols"
sqlite3 research/kernel_info/kernel_symbols.db "select count(*) from kernel_symbols;"
sqlite3 research/kernel_info/kernel_symbols.db "select kernel_name, matched, missed, percent, total from kernel_symbols order by kernel_name;"
+sqlite3 research/kernel_info/kernel_symbols.db "select kernel_name, json_path from kernel_symbols order by kernel_name;"
```
## Resolve JSON Path By Kernel Name
diff --git a/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift b/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift
index dff70b86..026c0544 100644
--- a/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift
+++ b/sources/FirmwarePatcher/ARM64/ARM64Disassembler.swift
@@ -4,9 +4,6 @@ import Capstone
import Foundation
public final class ARM64Disassembler: Sendable {
- /// Shared singleton instance with detail mode enabled.
- public static let shared: ARM64Disassembler = .init()
-
private let cs: Disassembler
public init() {
diff --git a/sources/FirmwarePatcher/Binary/BinaryBuffer.swift b/sources/FirmwarePatcher/Binary/BinaryBuffer.swift
index ad19ad8b..17382641 100644
--- a/sources/FirmwarePatcher/Binary/BinaryBuffer.swift
+++ b/sources/FirmwarePatcher/Binary/BinaryBuffer.swift
@@ -90,16 +90,6 @@ public final class BinaryBuffer: @unchecked Sendable {
return results
}
- /// Find a null-terminated C string at the given offset.
- public func readCString(at offset: Int) -> String? {
- data.withUnsafeBytes { buf in
- guard offset < buf.count else { return nil }
- let ptr = buf.baseAddress!.advanced(by: offset)
- .assumingMemoryBound(to: CChar.self)
- return String(cString: ptr)
- }
- }
-
/// Find the first occurrence of a C string in the data.
/// Matches Python `find_string()`: walks backward from the match to the
/// preceding NUL byte so that the returned offset is the C-string start.
@@ -126,10 +116,4 @@ public final class BinaryBuffer: @unchecked Sendable {
}
return nil
}
-
- /// Find all occurrences of a C string in the data.
- public func findAllStrings(_ string: String) -> [Int] {
- guard let encoded = string.data(using: .utf8) else { return [] }
- return findAll(encoded)
- }
}
diff --git a/sources/FirmwarePatcher/Binary/MachOHelpers.swift b/sources/FirmwarePatcher/Binary/MachOHelpers.swift
index 771a4ab3..9d945608 100644
--- a/sources/FirmwarePatcher/Binary/MachOHelpers.swift
+++ b/sources/FirmwarePatcher/Binary/MachOHelpers.swift
@@ -1,7 +1,6 @@
// MachOHelpers.swift — Mach-O parsing utilities for firmware patching.
import Foundation
-import MachOKit
// MARK: - Segment/Section Info
@@ -118,12 +117,6 @@ public enum MachOParser {
return nil
}
- /// Convert a virtual address to a file offset by parsing segments from data.
- public static func vaToFileOffset(_ va: UInt64, in data: Data) -> Int? {
- let segments = parseSegments(from: data)
- return vaToFileOffset(va, segments: segments)
- }
-
/// Parse LC_SYMTAB information.
/// Returns (symoff, nsyms, stroff, strsize) or nil.
public static func parseSymtab(from data: Data) -> (symoff: Int, nsyms: Int, stroff: Int, strsize: Int)? {
diff --git a/sources/FirmwarePatcher/Core/PatcherError.swift b/sources/FirmwarePatcher/Core/PatcherError.swift
index a074e4cb..282f9879 100644
--- a/sources/FirmwarePatcher/Core/PatcherError.swift
+++ b/sources/FirmwarePatcher/Core/PatcherError.swift
@@ -7,8 +7,6 @@ public enum PatcherError: Error, CustomStringConvertible, Sendable {
case invalidFormat(String)
case patchSiteNotFound(String)
case patchVerificationFailed(String)
- case encodingFailed(String)
- case multipleMatchesFound(String, count: Int)
public var description: String {
switch self {
@@ -20,10 +18,6 @@ public enum PatcherError: Error, CustomStringConvertible, Sendable {
"Patch site not found: \(msg)"
case let .patchVerificationFailed(msg):
"Patch verification failed: \(msg)"
- case let .encodingFailed(msg):
- "Instruction encoding failed: \(msg)"
- case let .multipleMatchesFound(msg, count):
- "Expected 1 match for \(msg), found \(count)"
}
}
}
diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
index 48867aa6..c4291c55 100644
--- a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
@@ -702,12 +702,11 @@ public final class DeviceTreePatcher: Patcher {
if patches.isEmpty, rebuiltData == nil {
let _ = try findAll()
}
+ // `findAll()` always ends by rebuilding the payload, and node additions are
+ // emitted with `fileOffset: 0`, so the rebuilt payload is the only thing that
+ // can land on disk.
if let rebuiltData {
buffer.data = rebuiltData
- } else {
- for record in patches {
- buffer.writeBytes(at: record.fileOffset, bytes: record.patchedBytes)
- }
}
if verbose, !patches.isEmpty {
print("\n [\(patches.count) DeviceTree patch(es) applied]")
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
index 8d133205..c26c890b 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
@@ -20,10 +20,6 @@ enum ProcessError: Error {
}
extension Data {
- var hexString: String {
- self.map { String(format: "%02x", $0) }.joined()
- }
-
init?(fromHexString hex: String) {
guard hex.count.isMultiple(of: 2) else {
return nil
@@ -84,18 +80,18 @@ public final class CryptexFilesystemPatcher: Patcher {
@discardableResult
public func apply() throws -> Int {
- print("Merging Filesystems")
+ print("Merging filesystems…")
let (unencryptedImage, aeaImage) = try mergeFilesystems()
defer { try? FileManager.default.removeItem(at: unencryptedImage) }
- print("Creating Trustcache")
+ print("Creating trustcache…")
let trustcachePath = try createTrustcache(filesystem: unencryptedImage)
- print("Creating mtree")
+ print("Creating mtree…")
let didEdit = try removeSpecificSystemFiles(filesystem: unencryptedImage)
let mtreePath = try createMtree(filesystem: unencryptedImage)
- print("Creating DigestDB and Root Hash")
+ print("Creating digest database and root hash…")
let (digestDbPath, rootHashPath) = try createDigestAndHash(filesystem: unencryptedImage, mtree: mtreePath, remap: didEdit)
let metadataPath = try compressCanonicalMetadata(mtree: mtreePath, digestDb: digestDbPath)
let rootHashContainer = try wrapRootHash(rootHashPath)
@@ -115,11 +111,11 @@ public final class CryptexFilesystemPatcher: Patcher {
// mergeFilesystems merges the main OS filesystem with the Cryptexes filesystems.
// It returns the path of the merged image (plain and encrypted)
func mergeFilesystems() throws -> (URL, URL) {
- let osPath = try getOSFilesystemPath()
+ let osPath = try componentPath("OS")
let osDmgPath = try decryptAeaFile(self.restoreDir.appending(path: osPath))
let newDmgPath = self.restoreDir.appending(path: "new-filesystem.dmg")
- print("- Converting OS image")
+ print("- Converting OS image…")
let tmpDir = try createTmpDir()
let targetImagePath = tmpDir.appending(path: "disk.dmg")
do {
@@ -127,13 +123,13 @@ public final class CryptexFilesystemPatcher: Patcher {
let (targetDevice, targetMount) = try attachImage(path: targetImagePath, forceRW: true)
defer { try? detachImage(deviceNode: targetDevice) }
- print("- Merging App OS Cryptex")
+ print("- Merging App OS cryptex…")
try copyCryptex(targetMount: targetMount, appOS: true)
- print("- Merging System OS Cryptex")
+ print("- Merging System OS cryptex…")
try copyCryptex(targetMount: targetMount, systemOS: true)
- print("- Fix Dyld Cache")
+ print("- Fixing dyld cache…")
try addDyldSymlinks(targetMount: targetMount)
let cfwInputOgPath = resources.resourceArchivesDir.appendingPathComponent("cfw_input.tar.zst")
@@ -142,18 +138,18 @@ public final class CryptexFilesystemPatcher: Patcher {
"--zstd", "-xf", cfwInputOgPath.path, "-C", cfwInputPath.path
])
- print("- Fix GPU Driver")
+ print("- Fixing GPU driver…")
try addGpuDriver(targetMount: targetMount, cfwInput: cfwInputPath)
- print("- Patch Mobile Activation")
+ print("- Patching mobile activation…")
try patchMobileActivation(targetMount: targetMount, cfwInput: cfwInputPath)
if !noVphoned {
- print("- Add vphoned")
+ print("- Adding vphoned…")
try addVphoned(targetMount: targetMount, cfwInput: cfwInputPath)
}
if !noBinpack {
- print("- Add binpack")
+ print("- Adding binpack…")
try addExtraServices(targetMount: targetMount, cfwInput: cfwInputPath)
}
if !noVphoned || !noBinpack {
@@ -162,7 +158,7 @@ public final class CryptexFilesystemPatcher: Patcher {
}
}
- print("- Finalizing merged image")
+ print("- Finalizing merged image…")
try shrinkImage(dmg: targetImagePath)
try convertToUDRWImage(input: targetImagePath, output: newDmgPath)
let metadata = try getAeaMetadata(self.restoreDir.appending(path: osPath))
@@ -446,7 +442,7 @@ public final class CryptexFilesystemPatcher: Patcher {
</dict>
</plist>
"""
- print("Used time: \(remap ? modificationTime : "none")")
+ print("Modification time: \(remap ? modificationTime : "none")")
FileManager.default.createFile(atPath: mtreeRemapPath.path, contents: remapContent.data(using: .utf8))
try unmount(mount: mount)
@@ -486,7 +482,7 @@ public final class CryptexFilesystemPatcher: Patcher {
// Extract time=...
guard let match = line.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#,
options: .regularExpression) else {
- throw FirmwareManifest.ManifestError.fileNotFound("time")
+ throw FirmwareManifest.ManifestError.fileNotFound("modification time for /private/var in \(mtree.path)")
}
let matchedText = String(line[match])
@@ -495,7 +491,7 @@ public final class CryptexFilesystemPatcher: Patcher {
.replacingOccurrences(of: ".", with: "")
}
- throw FirmwareManifest.ManifestError.fileNotFound("metadata")
+ throw FirmwareManifest.ManifestError.fileNotFound("the /private/var entry in \(mtree.path)")
}
func createMtree(filesystem: URL) throws -> URL {
@@ -535,7 +531,7 @@ public final class CryptexFilesystemPatcher: Patcher {
let (device, mount) = try attachImage(path: filesystem, readonly: true)
defer { try? detachImage(deviceNode: device) }
- let oldTrustcache = try getTrustcachePath()
+ let oldTrustcache = try componentPath("StaticTrustCache")
let oldTrustcachePath = self.restoreDir.appending(path: oldTrustcache)
let newTrustcachePath = self.restoreDir.appending(path: "Firmware/new.trustcache")
let tmpDir = try createTmpDir()
@@ -562,9 +558,9 @@ public final class CryptexFilesystemPatcher: Patcher {
}
let osPath = if appOS {
- self.restoreDir.appending(path: try getAppOsFilesystemPath())
+ self.restoreDir.appending(path: try componentPath("Cryptex1,AppOS"))
} else {
- try decryptAeaFile(self.restoreDir.appending(path: try getSystemOsFilesystemPath()))
+ try decryptAeaFile(self.restoreDir.appending(path: try componentPath("Cryptex1,SystemOS")))
}
let (osDevice, osMount) = try attachImage(path: osPath, readonly: true)
defer { try? detachImage(deviceNode: osDevice) }
@@ -651,30 +647,12 @@ public final class CryptexFilesystemPatcher: Patcher {
return productVersion
}
- func getTrustcachePath() throws -> String {
- let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")
- let manifest = try getBuildIdentityManifest(path: path)
- return try getComponentPath(component: "StaticTrustCache", buildManifest: manifest)
- }
-
- func getOSFilesystemPath() throws -> String {
- let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")
- let manifest = try getBuildIdentityManifest(path: path)
- return try getComponentPath(component: "OS", buildManifest: manifest)
- }
-
- func getAppOsFilesystemPath() throws -> String {
- let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")
- let manifest = try getBuildIdentityManifest(path: path)
- return try getComponentPath(component: "Cryptex1,AppOS", buildManifest: manifest)
- }
-
- func getSystemOsFilesystemPath() throws -> String {
+ func componentPath(_ component: String) throws -> String {
let path = self.restoreDir.appending(path: "iPhone-BuildManifest.plist")
let manifest = try getBuildIdentityManifest(path: path)
- return try getComponentPath(component: "Cryptex1,SystemOS", buildManifest: manifest)
+ return try getComponentPath(component: component, buildManifest: manifest)
}
-
+
func getComponentPath(component: String, buildManifest: PlistDict) throws -> String {
let comp = try getChildPlistDict(parent: buildManifest, key: component)
let info = try getChildPlistDict(parent: comp, key: "Info")
@@ -734,7 +712,9 @@ public final class CryptexFilesystemPatcher: Patcher {
// We delete the files first as we want to replace symlinks with actual files.
let keys: [URLResourceKey] = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]
guard let enumerator = FileManager.default.enumerator(at: sourceRoot, includingPropertiesForKeys: keys) else {
- throw FirmwareManifest.ManifestError.fileNotFound("enumerator")
+ throw FirmwareManifest.ManifestError.fileNotFound(
+ "Unable to read \(sourceRoot.path). Check that the image is still mounted, then try again."
+ )
}
for case let fileURL as URL in enumerator {
guard fileURL.path.hasPrefix(sourcePath) else { continue }
@@ -750,7 +730,7 @@ public final class CryptexFilesystemPatcher: Patcher {
// try FileManager.default.copyItem(at: fileURL, to: destinationPath)
let result = copyfile(fileURL.path, destinationPath.path, nil, copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA))
if result < 0 {
- print("Failed to copy: \(destinationPath)")
+ print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")
}
continue
}
@@ -763,7 +743,7 @@ public final class CryptexFilesystemPatcher: Patcher {
// try FileManager.default.copyItem(at: fileURL, to: destinationPath)
let result = copyfile(fileURL.path, destinationPath.path, nil, copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA))
if result < 0 {
- print("Failed to copy: \(destinationPath)")
+ print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")
}
}
}
@@ -868,14 +848,14 @@ public final class CryptexFilesystemPatcher: Patcher {
let hexBytes = nonEmpty.flatMap { parseHexDumpLine($0) }
if !hexBytes.isEmpty {
let b64Encoded = Data(hexBytes).base64EncodedString()
- return "hex:\(Data(b64Encoded.utf8).hexString)"
+ return "hex:\(Data(b64Encoded.utf8).hex)"
}
// Otherwise treat it as plain text / JSON / whatever the section contains.
let text = bodyLines.joined(separator: "\n")
.trimmingCharacters(in: .whitespacesAndNewlines)
- return "hex:\(Data(text.utf8).hexString)"
+ return "hex:\(Data(text.utf8).hex)"
}
private func parseHexDumpLine(_ line: String) -> [UInt8] {
@@ -999,7 +979,7 @@ public final class CryptexFilesystemPatcher: Patcher {
if sudo {
let whoami = try runProcess("/usr/bin/whoami", [])
if !whoami.contains("root") {
- print("Please rerun as root or fix this program")
+ print("This step requires root. Run the command again with sudo.")
exit(42)
}
}
diff --git a/sources/FirmwarePatcher/IBoot/IBootPatcher.swift b/sources/FirmwarePatcher/IBoot/IBootPatcher.swift
index a80f15a0..820f52d2 100644
--- a/sources/FirmwarePatcher/IBoot/IBootPatcher.swift
+++ b/sources/FirmwarePatcher/IBoot/IBootPatcher.swift
@@ -65,16 +65,14 @@ public class IBootPatcher: Patcher {
patchSerialLabels()
patchImage4Callback()
- if mode == .llb {
- patchBootArgs()
- }
-
- if mode == .ibec {
+ switch mode {
+ case .ibss:
+ break
+ case .ibec:
patchBootArgs()
patchBootxPrecondition()
- }
-
- if mode == .llb {
+ case .llb:
+ patchBootArgs()
patchRootfssBypass()
patchPanicBypass()
}
@@ -173,12 +171,6 @@ public class IBootPatcher: Patcher {
return withUnsafeBytes(of: insn.littleEndian) { Data($0) }
}
- /// Find all file offsets where the given 4-byte pattern appears.
- /// Equivalent to Python `_find_asm_pattern(data, asm_str)`.
- func findPattern(_ pattern: Data) -> [Int] {
- buffer.findAll(pattern)
- }
-
// MARK: - Chunked Disassembly
/// Yield chunks of disassembled instructions over the whole binary.
@@ -471,7 +463,7 @@ public class IBootPatcher: Patcher {
/// Python: `_patch_cbz_before_error()`
private func patchCbzBeforeError(errorCode: UInt32, description: String) {
let pattern = encodedMovW8(errorCode)
- let locs = findPattern(pattern)
+ let locs = buffer.findAll(pattern)
guard locs.count == 1 else {
if verbose {
@@ -532,7 +524,7 @@ public class IBootPatcher: Patcher {
/// Python: `_patch_null_check_0x78()`
private func patchNullCheck0x78() {
let pattern = encodedMovW8(0x110)
- let locs = findPattern(pattern)
+ let locs = buffer.findAll(pattern)
guard locs.count == 1 else {
if verbose { print(" [-] rootfs null check: expected 1 'mov w8, #0x110', found \(locs.count)") }
@@ -574,7 +566,7 @@ public class IBootPatcher: Patcher {
/// Python: `patch_panic_bypass()`
func patchPanicBypass() {
let mov328 = encodedMovW8(0x328)
- let locs = findPattern(mov328)
+ let locs = buffer.findAll(mov328)
for loc in locs {
// Verify movk w8, #0x40, lsl #16 follows
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchBsdInitAuth.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchBsdInitAuth.swift
index 1ffa3770..c9376594 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchBsdInitAuth.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchBsdInitAuth.swift
@@ -122,7 +122,7 @@ extension KernelJBPatcher {
private func findPanicCallNear(_ addOff: Int) -> Int? {
let limit = min(addOff + 0x40, buffer.count)
for scan in stride(from: addOff, to: limit, by: 4) {
- if let target = jbDecodeBL(at: scan),
+ if let target = decodeBL(at: scan),
let panicOff = panicOffset,
target == panicOff
{
@@ -174,7 +174,7 @@ extension KernelJBPatcher {
private func hasImagebootCallNear(_ off: Int, imagebootNeeded: Int?) -> Bool {
let limit = min(off + 0x18, buffer.count)
for scan in stride(from: off + 4, to: limit, by: 4) {
- guard let target = jbDecodeBL(at: scan) else { continue }
+ guard let target = decodeBL(at: scan) else { continue }
// If we know _imageboot_needed, require an exact match;
// otherwise any BL counts (stripped kernel).
if let ib = imagebootNeeded {
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchCredLabel.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchCredLabel.swift
index 3c075fe6..59ff0361 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchCredLabel.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchCredLabel.swift
@@ -93,7 +93,7 @@ extension KernelJBPatcher {
// 7. Build deny shellcode (8 bytes): MOV W0,#0 + B epilogue.
if !denyAlreadyAllowed, let dOff = denyOff, let dCaveOff = denyCaveOff {
- guard let branchBack = encodeB(from: dCaveOff + 4, to: epilogueOff) else {
+ guard let branchBack = ARM64Encoder.encodeB(from: dCaveOff + 4, to: epilogueOff) else {
log(" [-] deny trampoline → epilogue branch out of range")
return
}
@@ -108,7 +108,7 @@ extension KernelJBPatcher {
}
// Redirect deny site → deny cave
- guard let branchToCave = encodeB(from: dOff, to: dCaveOff) else {
+ guard let branchToCave = ARM64Encoder.encodeB(from: dOff, to: dCaveOff) else {
log(" [-] branch from deny site 0x\(String(format: "%X", dOff)) to cave out of range")
return
}
@@ -126,7 +126,7 @@ extension KernelJBPatcher {
// str w8, [x26]
// mov w0, #0
// b epilogue
- guard let successBranchBack = encodeB(from: successCaveOff + 28, to: epilogueOff) else {
+ guard let successBranchBack = ARM64Encoder.encodeB(from: successCaveOff + 28, to: epilogueOff) else {
log(" [-] success trampoline → epilogue branch out of range")
return
}
@@ -155,7 +155,7 @@ extension KernelJBPatcher {
// 9. Redirect success exits → success cave.
for exitOff in successExits {
- guard let branchToCave = encodeB(from: exitOff, to: successCaveOff) else {
+ guard let branchToCave = ARM64Encoder.encodeB(from: exitOff, to: successCaveOff) else {
log(" [-] branch from success exit 0x\(String(format: "%X", exitOff)) to cave out of range")
return
}
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchDounmount.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchDounmount.swift
index 046f4eec..e8e8e0cd 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchDounmount.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchDounmount.swift
@@ -35,14 +35,6 @@ extension KernelJBPatcher {
// MARK: - Private helpers
- /// Find a function that contains a reference to `string` (null-terminated).
- private func findFuncByString(_ string: String) -> Int? {
- guard let strOff = buffer.findString(string) else { return nil }
- let refs = findStringRefs(strOff)
- guard let firstRef = refs.first else { return nil }
- return findFunctionStart(firstRef.adrpOff)
- }
-
/// Scan for the 8-instruction upstream cleanup call pattern and return
/// the file offset of the first BL, or nil if not uniquely found.
private func findUpstreamCleanupCall(_ start: Int, end: Int) -> Int? {
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchFpfsScopedOpen.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchFpfsScopedOpen.swift
index 15934567..18f73319 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchFpfsScopedOpen.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchFpfsScopedOpen.swift
@@ -73,7 +73,7 @@ extension KernelJBPatcher {
}
w[beqA] = beq(from: beqA)
w[beqB] = beq(from: beqB)
- guard let bData = encodeB(from: caveOff + enforce * 4, to: realHookOff) else { return nil }
+ guard let bData = ARM64Encoder.encodeB(from: caveOff + enforce * 4, to: realHookOff) else { return nil }
w[enforce] = bData.withUnsafeBytes { $0.load(as: UInt32.self) }.littleEndian
guard w.count == 20 else { log(" [-] cave length drifted: \(w.count)"); return nil }
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift
index ba0980ad..14fd897d 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchHookCredLabel.swift
@@ -259,11 +259,7 @@ extension KernelJBPatcher {
var scanOff = refOff - 4
let scanLimit = max(0, refOff - 80)
while scanOff >= scanLimit {
- let insn = buffer.readU32(at: scanOff)
- if insn >> 26 == 0b100101 { // BL
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- let target = scanOff + Int(signedImm) * 4
+ if let target = decodeBL(at: scanOff) {
let inCode = codeRanges.contains { target >= $0.start && target < $0.end }
if inCode {
log(" [+] vnode_getattr at 0x\(String(format: "%X", target)) (via BL at 0x\(String(format: "%X", scanOff)))")
@@ -342,103 +338,103 @@ extension KernelJBPatcher {
// 0: nop
code.append(ARM64.nop)
// 1: cbz x3, #0xa8 (skip entire body = 42 instructions forward)
- code.append(encodeU32(ARM64.c23_cbzX3_0xA8))
+ code.append(ARM64.encodeU32(ARM64.c23_cbzX3_0xA8))
// 2: sub sp, sp, #0x400
- code.append(encodeU32(ARM64.c23_subSP_0x400))
+ code.append(ARM64.encodeU32(ARM64.c23_subSP_0x400))
// 3: stp x29, x30, [sp]
- code.append(encodeU32(ARM64.c23_stpFP_LR))
+ code.append(ARM64.encodeU32(ARM64.c23_stpFP_LR))
// 4: stp x0, x1, [sp, #0x10]
- code.append(encodeU32(ARM64.c23_stpX0X1_0x10))
+ code.append(ARM64.encodeU32(ARM64.c23_stpX0X1_0x10))
// 5: stp x2, x3, [sp, #0x20]
- code.append(encodeU32(ARM64.c23_stpX2X3_0x20))
+ code.append(ARM64.encodeU32(ARM64.c23_stpX2X3_0x20))
// 6: stp x4, x5, [sp, #0x30]
- code.append(encodeU32(ARM64.c23_stpX4X5_0x30))
+ code.append(ARM64.encodeU32(ARM64.c23_stpX4X5_0x30))
// 7: stp x6, x7, [sp, #0x40]
- code.append(encodeU32(ARM64.c23_stpX6X7_0x40))
+ code.append(ARM64.encodeU32(ARM64.c23_stpX6X7_0x40))
// 8: nop
code.append(ARM64.nop)
// 9: bl vfs_context_current
let blVfsOff = caveOff + code.count * 4
- guard let blVfs = encodeBL(from: blVfsOff, to: vfsContextCurrentOff) else { return nil }
+ guard let blVfs = ARM64Encoder.encodeBL(from: blVfsOff, to: vfsContextCurrentOff) else { return nil }
code.append(blVfs)
// 10: mov x2, x0
- code.append(encodeU32(ARM64.c23_movX2_X0))
+ code.append(ARM64.encodeU32(ARM64.c23_movX2_X0))
// 11: ldr x0, [sp, #0x28] (saved x3 = vp)
- code.append(encodeU32(ARM64.c23_ldrX0_sp_0x28))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrX0_sp_0x28))
// 12: add x1, sp, #0x80
- code.append(encodeU32(ARM64.c23_addX1_sp_0x80))
+ code.append(ARM64.encodeU32(ARM64.c23_addX1_sp_0x80))
// 13: mov w8, #0x380
- code.append(encodeU32(ARM64.c23_movzW8_0x380))
+ code.append(ARM64.encodeU32(ARM64.c23_movzW8_0x380))
// 14: stp xzr, x8, [x1]
- code.append(encodeU32(ARM64.c23_stpXZR_X8))
+ code.append(ARM64.encodeU32(ARM64.c23_stpXZR_X8))
// 15: stp xzr, xzr, [x1, #0x10]
- code.append(encodeU32(ARM64.c23_stpXZR_XZR_0x10))
+ code.append(ARM64.encodeU32(ARM64.c23_stpXZR_XZR_0x10))
// 16: nop
code.append(ARM64.nop)
// 17: bl vnode_getattr
let blGetAttrOff = caveOff + code.count * 4
- guard let blGetAttr = encodeBL(from: blGetAttrOff, to: vnodeGetattrOff) else { return nil }
+ guard let blGetAttr = ARM64Encoder.encodeBL(from: blGetAttrOff, to: vnodeGetattrOff) else { return nil }
code.append(blGetAttr)
// 18: cbnz x0, #0x4c (skip 19 instructions)
- code.append(encodeU32(ARM64.c23_cbnzX0_0x4c))
+ code.append(ARM64.encodeU32(ARM64.c23_cbnzX0_0x4c))
// 19: mov w2, #0
- code.append(encodeU32(ARM64.c23_movW2_0))
+ code.append(ARM64.encodeU32(ARM64.c23_movW2_0))
// 20: ldr w8, [sp, #0xcc]
- code.append(encodeU32(ARM64.c23_ldrW8_sp_0xcc))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrW8_sp_0xcc))
// 21: tbz w8, #0xb, #0x14 (skip 5 instrs)
- code.append(encodeU32(ARM64.c23_tbzW8_11_0x14))
+ code.append(ARM64.encodeU32(ARM64.c23_tbzW8_11_0x14))
// 22: ldr w8, [sp, #0xc4]
- code.append(encodeU32(ARM64.c23_ldrW8_sp_0xc4))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrW8_sp_0xc4))
// 23: ldr x0, [sp, #0x18]
- code.append(encodeU32(ARM64.c23_ldrX0_sp_0x18))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrX0_sp_0x18))
// 24: str w8, [x0, #0x18]
- code.append(encodeU32(ARM64.c23_strW8_x0_0x18))
+ code.append(ARM64.encodeU32(ARM64.c23_strW8_x0_0x18))
// 25: mov w2, #1
- code.append(encodeU32(ARM64.c23_movW2_1))
+ code.append(ARM64.encodeU32(ARM64.c23_movW2_1))
// 26: ldr w8, [sp, #0xcc]
- code.append(encodeU32(ARM64.c23_ldrW8_sp_0xcc))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrW8_sp_0xcc))
// 27: tbz w8, #0xa, #0x14 (skip 5 instrs)
- code.append(encodeU32(ARM64.c23_tbzW8_10_0x14))
+ code.append(ARM64.encodeU32(ARM64.c23_tbzW8_10_0x14))
// 28: mov w2, #1
- code.append(encodeU32(ARM64.c23_movW2_1))
+ code.append(ARM64.encodeU32(ARM64.c23_movW2_1))
// 29: ldr w8, [sp, #0xc8]
- code.append(encodeU32(ARM64.c23_ldrW8_sp_0xc8))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrW8_sp_0xc8))
// 30: ldr x0, [sp, #0x18]
- code.append(encodeU32(ARM64.c23_ldrX0_sp_0x18))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrX0_sp_0x18))
// 31: str w8, [x0, #0x28]
- code.append(encodeU32(ARM64.c23_strW8_x0_0x28))
+ code.append(ARM64.encodeU32(ARM64.c23_strW8_x0_0x28))
// 32: cbz w2, #0x14 (skip 5 instrs)
- code.append(encodeU32(ARM64.c23_cbzW2_0x14))
+ code.append(ARM64.encodeU32(ARM64.c23_cbzW2_0x14))
// 33: ldr x0, [sp, #0x20]
- code.append(encodeU32(ARM64.c23_ldrX0_sp_0x20))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrX0_sp_0x20))
// 34: ldr w8, [x0, #0x454]
- code.append(encodeU32(ARM64.c23_ldrW8_x0_0x454))
+ code.append(ARM64.encodeU32(ARM64.c23_ldrW8_x0_0x454))
// 35: orr w8, w8, #0x100
- code.append(encodeU32(ARM64.c23_orrW8_0x100))
+ code.append(ARM64.encodeU32(ARM64.c23_orrW8_0x100))
// 36: str w8, [x0, #0x454]
- code.append(encodeU32(ARM64.c23_strW8_x0_0x454))
+ code.append(ARM64.encodeU32(ARM64.c23_strW8_x0_0x454))
// 37: ldp x0, x1, [sp, #0x10]
- code.append(encodeU32(ARM64.c23_ldpX0X1_0x10))
+ code.append(ARM64.encodeU32(ARM64.c23_ldpX0X1_0x10))
// 38: ldp x2, x3, [sp, #0x20]
- code.append(encodeU32(ARM64.c23_ldpX2X3_0x20))
+ code.append(ARM64.encodeU32(ARM64.c23_ldpX2X3_0x20))
// 39: ldp x4, x5, [sp, #0x30]
- code.append(encodeU32(ARM64.c23_ldpX4X5_0x30))
+ code.append(ARM64.encodeU32(ARM64.c23_ldpX4X5_0x30))
// 40: ldp x6, x7, [sp, #0x40]
- code.append(encodeU32(ARM64.c23_ldpX6X7_0x40))
+ code.append(ARM64.encodeU32(ARM64.c23_ldpX6X7_0x40))
// 41: ldp x29, x30, [sp]
- code.append(encodeU32(ARM64.c23_ldpFP_LR))
+ code.append(ARM64.encodeU32(ARM64.c23_ldpFP_LR))
// 42: add sp, sp, #0x400
- code.append(encodeU32(ARM64.c23_addSP_0x400))
+ code.append(ARM64.encodeU32(ARM64.c23_addSP_0x400))
// 43: nop
code.append(ARM64.nop)
// 44: b wrapperOff
let branchBackOff = caveOff + code.count * 4
- guard let branchBack = encodeB(from: branchBackOff, to: wrapperOff) else { return nil }
+ guard let branchBack = ARM64Encoder.encodeB(from: branchBackOff, to: wrapperOff) else { return nil }
code.append(branchBack)
// 45: nop
@@ -460,10 +456,4 @@ extension KernelJBPatcher {
let newVal = (origVal & ~UInt64(0xFFFF_FFFF)) | (UInt64(targetFoff) & 0xFFFF_FFFF)
return withUnsafeBytes(of: newVal.littleEndian) { Data($0) }
}
-
- // MARK: - Encoding Helper
-
- private func encodeU32(_ value: UInt32) -> Data {
- ARM64.encodeU32(value)
- }
}
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchIoucMacf.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchIoucMacf.swift
index ad542286..02d43c9b 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchIoucMacf.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchIoucMacf.swift
@@ -50,7 +50,7 @@ extension KernelJBPatcher {
defer { off += 4 }
// Require BL at [off].
- guard let blTarget = jbDecodeBL(at: off) else { continue }
+ guard let blTarget = decodeBL(at: off) else { continue }
// Require CBZ W0, <target> at [off + 4].
let cbzInsn = buffer.readU32(at: off + 4)
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift
index 48392578..e5ab7700 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchKcall10.swift
@@ -218,55 +218,55 @@ extension KernelJBPatcher {
// pacibsp
code.append(ARM64.pacibsp)
// sub sp, sp, #0x30
- code.append(encodeU32k(0xD100_C3FF)) // sub sp, sp, #0x30
+ code.append(ARM64.encodeU32(0xD100_C3FF)) // sub sp, sp, #0x30
// stp x21, x22, [sp]
- code.append(encodeU32k(0xA900_5BF5)) // stp x21, x22, [sp]
+ code.append(ARM64.encodeU32(0xA900_5BF5)) // stp x21, x22, [sp]
// stp x19, x20, [sp, #0x10]
- code.append(encodeU32k(0xA901_53F3)) // stp x19, x20, [sp, #0x10]
+ code.append(ARM64.encodeU32(0xA901_53F3)) // stp x19, x20, [sp, #0x10]
// stp x29, x30, [sp, #0x20]
- code.append(encodeU32k(0xA902_7BFD)) // stp x29, x30, [sp, #0x20]
+ code.append(ARM64.encodeU32(0xA902_7BFD)) // stp x29, x30, [sp, #0x20]
// add x29, sp, #0x20
- code.append(encodeU32k(0x9100_83FD)) // add x29, sp, #0x20
+ code.append(ARM64.encodeU32(0x9100_83FD)) // add x29, sp, #0x20
// mov w19, #22 (EINVAL = 22 = 0x16)
- code.append(encodeU32k(0x5280_02D3)) // movz w19, #0x16
+ code.append(ARM64.encodeU32(0x5280_02D3)) // movz w19, #0x16
// mov x20, x1 (save uap)
- code.append(encodeU32k(0xAA01_03F4)) // mov x20, x1
+ code.append(ARM64.encodeU32(0xAA01_03F4)) // mov x20, x1
// mov x21, x2 (save retval)
- code.append(encodeU32k(0xAA02_03F5)) // mov x21, x2
+ code.append(ARM64.encodeU32(0xAA02_03F5)) // mov x21, x2
// cbz x20, #0x30 (null uap → skip to exit, 12 instrs forward)
- code.append(encodeU32k(0xB400_0194)) // cbz x20, #+0x30
+ code.append(ARM64.encodeU32(0xB400_0194)) // cbz x20, #+0x30
// cbz x21, #0x2c (null retval → skip to exit)
- code.append(encodeU32k(0xB400_0175)) // cbz x21, #+0x2c
+ code.append(ARM64.encodeU32(0xB400_0175)) // cbz x21, #+0x2c
// ldr x16, [x20] (target = uap[0])
- code.append(encodeU32k(0xF940_0290)) // ldr x16, [x20]
+ code.append(ARM64.encodeU32(0xF940_0290)) // ldr x16, [x20]
// cbz x16, #0x24 (null target → skip, 9 instrs)
- code.append(encodeU32k(0xB400_0130)) // cbz x16, #+0x24
+ code.append(ARM64.encodeU32(0xB400_0130)) // cbz x16, #+0x24
// ldp x0, x1, [x20, #0x8]
- code.append(encodeU32k(0xA940_8680)) // ldp x0, x1, [x20, #0x8]
+ code.append(ARM64.encodeU32(0xA940_8680)) // ldp x0, x1, [x20, #0x8]
// ldp x2, x3, [x20, #0x18]
- code.append(encodeU32k(0xA941_8E82)) // ldp x2, x3, [x20, #0x18]
+ code.append(ARM64.encodeU32(0xA941_8E82)) // ldp x2, x3, [x20, #0x18]
// ldp x4, x5, [x20, #0x28]
- code.append(encodeU32k(0xA942_9684)) // ldp x4, x5, [x20, #0x28]
+ code.append(ARM64.encodeU32(0xA942_9684)) // ldp x4, x5, [x20, #0x28]
// ldr x6, [x20, #0x38]
- code.append(encodeU32k(0xF940_1E86)) // ldr x6, [x20, #0x38]
+ code.append(ARM64.encodeU32(0xF940_1E86)) // ldr x6, [x20, #0x38]
// mov x7, xzr
- code.append(encodeU32k(0xAA1F_03E7)) // mov x7, xzr
+ code.append(ARM64.encodeU32(0xAA1F_03E7)) // mov x7, xzr
// blr x16
- code.append(encodeU32k(0xD63F_0200)) // blr x16
+ code.append(ARM64.encodeU32(0xD63F_0200)) // blr x16
// str x0, [x21] (store result in retval)
- code.append(encodeU32k(0xF900_02A0)) // str x0, [x21]
+ code.append(ARM64.encodeU32(0xF900_02A0)) // str x0, [x21]
// mov w19, #0
- code.append(encodeU32k(0x5280_0013)) // movz w19, #0
+ code.append(ARM64.encodeU32(0x5280_0013)) // movz w19, #0
// mov w0, w19 (return value)
- code.append(encodeU32k(0x2A13_03E0)) // mov w0, w19
+ code.append(ARM64.encodeU32(0x2A13_03E0)) // mov w0, w19
// ldp x21, x22, [sp]
- code.append(encodeU32k(0xA940_5BF5)) // ldp x21, x22, [sp]
+ code.append(ARM64.encodeU32(0xA940_5BF5)) // ldp x21, x22, [sp]
// ldp x19, x20, [sp, #0x10]
- code.append(encodeU32k(0xA941_53F3)) // ldp x19, x20, [sp, #0x10]
+ code.append(ARM64.encodeU32(0xA941_53F3)) // ldp x19, x20, [sp, #0x10]
// ldp x29, x30, [sp, #0x20]
- code.append(encodeU32k(0xA942_7BFD)) // ldp x29, x30, [sp, #0x20]
+ code.append(ARM64.encodeU32(0xA942_7BFD)) // ldp x29, x30, [sp, #0x20]
// add sp, sp, #0x30
- code.append(encodeU32k(0x9100_C3FF)) // add sp, sp, #0x30
+ code.append(ARM64.encodeU32(0x9100_C3FF)) // add sp, sp, #0x30
// retab
code.append(ARM64.retab)
@@ -308,10 +308,4 @@ extension KernelJBPatcher {
private func extractChainKey(_ raw: UInt64) -> UInt32 {
UInt32((raw >> 49) & 3)
}
-
- // MARK: - Encoding Helper
-
- private func encodeU32k(_ value: UInt32) -> Data {
- ARM64.encodeU32(value)
- }
}
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift
index cf2233ce..a8104c0f 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchMacMount.swift
@@ -38,7 +38,7 @@ extension KernelJBPatcher {
var candidates: [Int: (Int, Int)] = [:] // caller → (flagGate, stateGate)
var off = searchStart
while off < searchEnd {
- guard let blTarget = jbDecodeBL(at: off), blTarget == mountCommon else { off += 4; continue }
+ guard let blTarget = decodeBL(at: off), blTarget == mountCommon else { off += 4; continue }
guard let caller = findFunctionStart(off), caller != mountCommon,
candidates[caller] == nil
else { off += 4; continue }
@@ -82,7 +82,7 @@ extension KernelJBPatcher {
// Require the wrapper to actually call mount_common.
var callsMountCommon = false
for off in stride(from: start, to: end, by: 4) {
- if jbDecodeBL(at: off) == mountCommon { callsMountCommon = true; break }
+ if decodeBL(at: off) == mountCommon { callsMountCommon = true; break }
}
guard callsMountCommon else { return nil }
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchPostValidation.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchPostValidation.swift
index 7c918868..fd018979 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchPostValidation.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchPostValidation.swift
@@ -40,7 +40,7 @@ extension KernelJBPatcher {
// Collect BL targets within the caller.
var blTargets = Set<Int>()
for scan in stride(from: callerStart, to: callerEnd, by: 4) {
- if let target = jbDecodeBL(at: scan) {
+ if let target = decodeBL(at: scan) {
blTargets.insert(target)
}
}
@@ -66,7 +66,7 @@ extension KernelJBPatcher {
// Must be preceded by a BL within 3 instructions.
var hasBlBefore = false
for back in stride(from: off - 4, through: max(off - 12, target), by: -4) {
- if jbDecodeBL(at: back) != nil {
+ if decodeBL(at: back) != nil {
hasBlBefore = true
break
}
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift
index 871a2d0b..d6f3efdb 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSpawnPersona.swift
@@ -55,7 +55,7 @@ extension KernelJBPatcher {
var seen = Set<Int>()
for off in stride(from: anchorStart, to: anchorEnd, by: 4) {
- guard let blTarget = jbDecodeBL(at: off), !seen.contains(blTarget) else { continue }
+ guard let blTarget = decodeBL(at: off), !seen.contains(blTarget) else { continue }
guard jbIsInCodeRange(blTarget) else { continue }
seen.insert(blTarget)
let callee_end = findFuncEnd(blTarget, maxSize: 0x400)
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSyscallmask.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSyscallmask.swift
index b418fd13..c0947537 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSyscallmask.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchSyscallmask.swift
@@ -48,7 +48,7 @@ extension KernelJBPatcher {
}
// 4. Resolve the mutation helper (structural: next function after helper's containing func).
- let helperTarget = jbDecodeBL(at: callOff) ?? -1
+ let helperTarget = decodeBL(at: callOff) ?? -1
guard let mutatorOff = resolveSyscallmaskMutator(funcOff: funcOff, helperTarget: helperTarget) else {
log(" [-] syscallmask mutation helper not resolved structurally")
return false
@@ -72,7 +72,7 @@ extension KernelJBPatcher {
}
// 7. Patch: redirect tail branch to cave entry (code section, not blob).
- guard let branchToCave = encodeB(from: branchOff, to: codeOff) else {
+ guard let branchToCave = ARM64Encoder.encodeB(from: branchOff, to: codeOff) else {
log(" [-] tail branch cannot reach C22 cave")
return false
}
@@ -140,7 +140,7 @@ extension KernelJBPatcher {
var targetCalls: [Int: [Int]] = [:]
var off = managerOff
while off < funcEnd {
- if let target = jbDecodeBL(at: off) {
+ if let target = decodeBL(at: off) {
targetCalls[target, default: []].append(off)
}
off += 4
@@ -188,7 +188,7 @@ extension KernelJBPatcher {
let op = insn.operandString.replacingOccurrences(of: " ", with: "")
if insn.mnemonic == "cbz", op.hasPrefix("x2,") {
seenCbzX2 = true
- } else if seenCbzX2, jbDecodeBL(at: off) != nil {
+ } else if seenCbzX2, decodeBL(at: off) != nil {
return off
}
off += 4
@@ -208,7 +208,7 @@ extension KernelJBPatcher {
let signedImm = Int32(bitPattern: imm26 << 6) >> 6
let target = off + Int(signedImm) * 4
let inText = kernTextRange.map { target >= $0.0 && target < $0.1 } ?? false
- if inText, jbDecodeBL(at: off) == nil {
+ if inText, decodeBL(at: off) == nil {
return (off, target)
}
}
@@ -331,7 +331,7 @@ extension KernelJBPatcher {
// 18: bl mutatorOff
let blOff = codeOff + code.count * 4
- guard let blMutator = encodeBL(from: blOff, to: zallocOff) else { return nil }
+ guard let blMutator = ARM64Encoder.encodeBL(from: blOff, to: zallocOff) else { return nil }
code.append(blMutator)
// 19: mov x0, x19
@@ -353,7 +353,7 @@ extension KernelJBPatcher {
// 27: b setterOff (tail-call)
let branchBackOff = codeOff + code.count * 4
- guard let branchBack = encodeB(from: branchBackOff, to: setterOff) else { return nil }
+ guard let branchBack = ARM64Encoder.encodeB(from: branchBackOff, to: setterOff) else { return nil }
code.append(branchBack)
let codeBytes = code.reduce(Data(), +)
diff --git a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift
index 7d7dbd97..9e019253 100644
--- a/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift
+++ b/sources/FirmwarePatcher/Kernel/JBPatches/KernelJBPatchVmProtect.swift
@@ -45,7 +45,7 @@ extension KernelJBPatcher {
// Shape A: explicit skip branch (26.1 / 26.3). Rewrite `b.ne skip` -> `b skip`.
if let (brOff, target) = findWriteDowngradeGate(start: funcStart, end: funcEnd) {
- guard let bBytes = encodeB(from: brOff, to: target) else {
+ guard let bBytes = ARM64Encoder.encodeB(from: brOff, to: target) else {
log(" [-] branch rewrite out of range")
return false
}
diff --git a/sources/FirmwarePatcher/Kernel/KernelEXPPatcher.swift b/sources/FirmwarePatcher/Kernel/KernelEXPPatcher.swift
index 41c75cd7..596521dd 100644
--- a/sources/FirmwarePatcher/Kernel/KernelEXPPatcher.swift
+++ b/sources/FirmwarePatcher/Kernel/KernelEXPPatcher.swift
@@ -33,10 +33,8 @@ public final class KernelEXPPatcher: KernelJBPatcherBase, Patcher {
}
public func apply() throws -> Int {
+ // `emit()` already wrote every record through to `buffer.data`.
let records = try (patches.isEmpty ? findAll() : patches)
- for record in records {
- buffer.writeBytes(at: record.fileOffset, bytes: record.patchedBytes)
- }
return records.count
}
}
diff --git a/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift b/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift
index 95f0d956..07102bcc 100644
--- a/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift
+++ b/sources/FirmwarePatcher/Kernel/KernelJBPatcher.swift
@@ -113,10 +113,8 @@ public final class KernelJBPatcher: KernelJBPatcherBase, Patcher {
}
public func apply() throws -> Int {
+ // `emit()` already wrote every record through to `buffer.data`.
let records = try (patches.isEmpty ? findAll() : patches)
- for record in records {
- buffer.writeBytes(at: record.fileOffset, bytes: record.patchedBytes)
- }
return records.count
}
}
diff --git a/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift b/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift
index ccfff118..013a5dbd 100644
--- a/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift
+++ b/sources/FirmwarePatcher/Kernel/KernelJBPatcherBase.swift
@@ -8,8 +8,7 @@ import Foundation
/// Base class for JB kernel patching, extending KernelPatcherBase with:
/// - Symbol table parsing (nlist64 from LC_SYMTAB + fileset entries)
/// - Code cave finder (zeros/0xFF/UDF in executable segments)
-/// - Branch encoding helpers (encodeB, encodeBL)
-/// - Function boundary finders (findFuncEnd, findBLToPanicInRange)
+/// - Function boundary finders (findFuncEnd)
/// - String-anchored function finders
/// - proc_info anchor cache
public class KernelJBPatcherBase: KernelPatcherBase {
@@ -175,18 +174,6 @@ public class KernelJBPatcherBase: KernelPatcherBase {
return nil
}
- // MARK: - Branch Encoding
-
- /// Encode an unconditional B instruction.
- func encodeB(from fromOff: Int, to toOff: Int) -> Data? {
- ARM64Encoder.encodeB(from: fromOff, to: toOff)
- }
-
- /// Encode a BL instruction.
- func encodeBL(from fromOff: Int, to toOff: Int) -> Data? {
- ARM64Encoder.encodeBL(from: fromOff, to: toOff)
- }
-
// MARK: - Function Finders
/// Find the end of a function by scanning forward for the next PACIBSP boundary.
@@ -205,27 +192,6 @@ public class KernelJBPatcherBase: KernelPatcherBase {
return limit
}
- /// Find the first BL to `_panic` in `range`. Returns the file offset or nil.
- ///
- /// Reads from `buffer.original` (Python: `_rd32(self.raw, off)` via `_is_bl`).
- /// Mirrors Python `_find_bl_to_panic_in_range(start, end)`.
- func findBLToPanic(in range: Range<Int>) -> Int? {
- guard let panicOff = panicOffset else { return nil }
- let raw = buffer.original
- var off = range.lowerBound
- while off + 4 <= range.upperBound {
- guard off + 4 <= raw.count else { break }
- let insn = raw.loadLE(UInt32.self, at: off)
- if insn >> 26 == 0b100101 { // BL
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- if off + Int(signedImm) * 4 == panicOff { return off }
- }
- off += 4
- }
- return nil
- }
-
/// Find a function that references a given string constant.
/// Returns the function-start file offset, or nil.
/// Mirrors Python `_find_func_by_string(string, code_range)`.
@@ -240,25 +206,6 @@ public class KernelJBPatcherBase: KernelPatcherBase {
return findFunctionStart(firstRef.adrpOff)
}
- /// Find a function containing a string reference.
- /// Returns (funcStart, funcEnd, refs) or nil.
- /// Mirrors Python `_find_func_containing_string(string, code_range)`.
- func findFuncContainingString(
- _ string: String,
- codeRange: (Int, Int)? = nil
- ) -> (Int, Int, [(adrpOff: Int, addOff: Int)])? {
- guard let strOff = buffer.findString(string) else { return nil }
- let refs: [(adrpOff: Int, addOff: Int)] = if let (cs, ce) = codeRange {
- findStringRefs(strOff, in: (start: cs, end: ce))
- } else {
- findStringRefs(strOff)
- }
- guard let firstRef = refs.first else { return nil }
- guard let funcStart = findFunctionStart(firstRef.adrpOff) else { return nil }
- let funcEnd = findFuncEnd(funcStart)
- return (funcStart, funcEnd, refs)
- }
-
// MARK: - proc_info Family Anchors (B6/B7)
/// Find `_proc_security_policy` by its unique reference to `PRIV_GLOBAL_PROC_INFO`.
@@ -319,17 +266,7 @@ public class KernelJBPatcherBase: KernelPatcherBase {
return disasm.disassembleOne(in: buffer.data, at: off)
}
- // MARK: - BL Decode Helper
-
- /// Decode the BL target at `offset`, or nil if not a BL.
- func jbDecodeBL(at offset: Int) -> Int? {
- guard offset + 4 <= buffer.count else { return nil }
- let insn = buffer.readU32(at: offset)
- guard insn >> 26 == 0b100101 else { return nil }
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- return offset + Int(signedImm) * 4
- }
+ // MARK: - Branch Decode Helper
/// Decode unconditional B target at `offset`, or nil if not a B.
func jbDecodeBBranch(at offset: Int) -> Int? {
diff --git a/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift b/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift
index e17dbf12..54b0607b 100644
--- a/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift
+++ b/sources/FirmwarePatcher/Kernel/KernelPatcherBase.swift
@@ -113,12 +113,10 @@ open class KernelPatcherBase {
}
}
- /// Apply all collected patches to the buffer.
+ /// Number of collected patches. `emit()` already wrote every record through to
+ /// `buffer.data`, so there is nothing left to apply here.
public func applyPatches() -> Int {
- for record in patches {
- buffer.writeBytes(at: record.fileOffset, bytes: record.patchedBytes)
- }
- return patches.count
+ patches.count
}
// MARK: - Index Building
@@ -131,7 +129,7 @@ open class KernelPatcherBase {
while offset + 4 <= end {
let insn = buffer.readU32(at: offset)
// ADRP: [31]=1, [28:24]=10000
- if insn & 0x9F00_0000 == 0x9000_0000 {
+ if ARM64Inst.isADRP(insn) {
// Decode page address
let immhi = (insn >> 5) & 0x7FFFF
let immlo = (insn >> 29) & 0x3
@@ -153,12 +151,7 @@ open class KernelPatcherBase {
for (start, end) in codeRanges {
var offset = start
while offset + 4 <= end {
- let insn = buffer.readU32(at: offset)
- // BL: [31:26] = 100101
- if insn >> 26 == 0b100101 {
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- let target = offset + Int(signedImm) * 4
+ if let target = decodeBL(at: offset) {
blIndex[target, default: []].append(offset)
}
offset += 4
@@ -209,24 +202,25 @@ open class KernelPatcherBase {
return findStringRefs(strOff, in: range)
}
- /// Convenience: find a string by file offset, with range filter.
- public func findStringRefs(in range: (start: Int, end: Int), stringOffset: Int) -> [(adrpOff: Int, addOff: Int)] {
- findStringRefs(stringOffset, in: range)
- }
-
// MARK: - Branch Helpers
- /// Check whether the instruction at `offset` is a BL targeting `target` (file offset).
- /// Returns true if the BL opcode decodes to the exact target offset.
- public func isBL(at offset: Int, target: Int) -> Bool {
- guard offset + 4 <= buffer.count else { return false }
+ /// Decode the BL at `offset` and return its target as a file offset,
+ /// or nil when the instruction there is not a BL.
+ ///
+ /// BL encoding: [31:26] = 0b100101, imm26 is PC-relative in 4-byte units.
+ public func decodeBL(at offset: Int) -> Int? {
+ guard offset >= 0, offset + 4 <= buffer.count else { return nil }
let insn = buffer.readU32(at: offset)
- // BL encoding: [31:26] = 0b100101
- guard insn >> 26 == 0b100101 else { return false }
+ guard ARM64Inst.isBL(insn) else { return nil }
let imm26 = insn & 0x03FF_FFFF
let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- let resolved = offset + Int(signedImm) * 4
- return resolved == target
+ return offset + Int(signedImm) * 4
+ }
+
+ /// Check whether the instruction at `offset` is a BL targeting `target` (file offset).
+ /// Returns true if the BL opcode decodes to the exact target offset.
+ public func isBL(at offset: Int, target: Int) -> Bool {
+ decodeBL(at: offset) == target
}
// MARK: - Conditional Branch Helpers
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift
index 2224b693..f9544bdf 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsGraft.swift
@@ -66,7 +66,7 @@ extension KernelPatcher {
if scan > graftStart + 8, buffer.readU32(at: scan) == ARM64.pacibspU32 {
break
}
- if let blTarget = decodeBLTarget(at: scan), blTarget == vrhFunc {
+ if let blTarget = decodeBL(at: scan), blTarget == vrhFunc {
let va = fileOffsetToVA(scan)
emit(scan, ARM64.movW0_0,
patchID: "apfs_graft",
@@ -104,18 +104,4 @@ extension KernelPatcher {
return findFunctionStart(firstRef.adrpOff)
}
-
- /// Decode a BL instruction at the given file offset and return the target file offset,
- /// or nil if the instruction at that offset is not a BL.
- ///
- /// ARM64 BL encoding: bits [31:26] = 0b100101, bits [25:0] = signed imm26
- /// Target = PC + SignExt(imm26) * 4 (all in file-offset space)
- private func decodeBLTarget(at offset: Int) -> Int? {
- guard offset + 4 <= buffer.count else { return nil }
- let insn = buffer.readU32(at: offset)
- guard insn >> 26 == 0b100101 else { return nil } // BL opcode
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- return offset + Int(signedImm) * 4
- }
}
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift
index b9a1a0e3..c9f4d918 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsMount.swift
@@ -9,16 +9,6 @@ import Foundation
extension KernelPatcher {
// MARK: - Private Helpers
- /// Decode a BL instruction at `offset`. Returns the target file offset, or nil.
- private func apfsMountDecodeBL(at offset: Int) -> Int? {
- guard offset + 4 <= buffer.count else { return nil }
- let insn = buffer.readU32(at: offset)
- guard insn >> 26 == 0b100101 else { return nil }
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- return offset + Int(signedImm) * 4
- }
-
/// Return true if the function at `funcOff` contains a RET within `maxBytes`.
private func apfsMountIsLeaf(at funcOff: Int, maxBytes: Int = 0x20) -> Bool {
let limit = min(funcOff + maxBytes, buffer.count)
@@ -73,7 +63,7 @@ extension KernelPatcher {
for (rangeStart, rangeEnd) in codeRanges {
var off = rangeStart
while off + 4 <= rangeEnd {
- if let target = apfsMountDecodeBL(at: off),
+ if let target = decodeBL(at: off),
target >= funcStart, target <= funcStart + 4
{
callers.append(off)
@@ -171,7 +161,7 @@ extension KernelPatcher {
break
}
- guard let blTarget = apfsMountDecodeBL(at: scan) else {
+ guard let blTarget = decodeBL(at: scan) else {
scan += 4; continue
}
// Target must be a small leaf function.
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsSeal.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsSeal.swift
index 62ce78d6..aac65fc9 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsSeal.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchApfsSeal.swift
@@ -25,7 +25,7 @@ extension KernelPatcher {
}
let apfsRange = apfsTextRange()
- let refs = findStringRefs(in: apfsRange, stringOffset: strOff)
+ let refs = findStringRefs(strOff, in: apfsRange)
if refs.isEmpty {
log(" [-] no ADRP+ADD refs to 'root volume seal is broken'")
return false
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift
index 6486eea0..ab3247a0 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchBsdInit.swift
@@ -80,16 +80,9 @@ extension KernelPatcher {
var scan = addOff
while scan <= fwdLimit {
- let insn = buffer.readU32(at: scan)
- // BL: top 6 bits = 0b100101
- if insn >> 26 == 0b100101 {
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- let target = scan + Int(signedImm) * 4
- if target == panicOff {
- blPanicOff = scan
- break
- }
+ if decodeBL(at: scan) == panicOff {
+ blPanicOff = scan
+ break
}
scan += 4
}
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift
index a88caeef..03d93fb3 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDebugger.swift
@@ -73,7 +73,7 @@ extension KernelPatcher {
/// ADRP encoding: [31]=1, [28:24]=10000, [4:0]=Rd
/// Rd == 8 (x8).
private func isADRPx8(_ insn: UInt32) -> Bool {
- (insn & 0x9F00_0000) == 0x9000_0000 && (insn & 0x1F) == 8
+ ARM64Inst.isADRP(insn) && (insn & 0x1F) == 8
}
/// Return true if the 32-bit value is a recognised function-boundary instruction.
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift
index 72292314..4ca7393f 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchDyldPolicy.swift
@@ -85,20 +85,6 @@ extension KernelPatcher {
// MARK: - Private Helpers
- /// Decode a BL instruction at `offset` and return its absolute file-offset target,
- /// or nil if the instruction at that offset is not a BL.
- ///
- /// BL encoding: bits [31:26] = 0b100101, imm26 is PC-relative in 4-byte units.
- private func decodeBL(at offset: Int) -> Int? {
- guard offset >= 0, offset + 4 <= buffer.count else { return nil }
- let insn = buffer.readU32(at: offset)
- guard insn >> 26 == 0b100101 else { return nil }
- let imm26 = insn & 0x03FF_FFFF
- // Sign-extend the 26-bit immediate
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- return offset + Int(signedImm) * 4
- }
-
/// Return true when the instruction at `offset` is a conditional branch
/// that tests w0 or x0 (CBZ, CBNZ, TBZ, TBNZ on register 0).
private func isCondBranchOnW0(at offset: Int) -> Bool {
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift
index a6f83c3c..fd772420 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchExcGuard.swift
@@ -54,11 +54,7 @@ extension KernelPatcher {
let scanStart = max(0, addOff - 200)
let scanEnd = min(buffer.count - 4, addOff + 400)
for off in stride(from: scanStart, to: scanEnd, by: 4) {
- let insn = buffer.readU32(at: off)
- guard insn >> 26 == 0b100101 else { continue } // BL
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- let target = off + Int(signedImm) * 4
+ guard let target = decodeBL(at: off) else { continue }
guard target > 0, target + 40 <= buffer.count else { continue }
// Check if target starts with PACIBSP
guard buffer.readU32(at: target) == ARM64.pacibspU32 else { continue }
@@ -75,7 +71,7 @@ extension KernelPatcher {
hasTbCheck = true
}
// After TBZ, look for BL
- if hasTbCheck, iraw >> 26 == 0b100101 {
+ if hasTbCheck, ARM64Inst.isBL(iraw) {
let iimm26 = iraw & 0x03FF_FFFF
let isigned = Int32(bitPattern: iimm26 << 6) >> 6
let bt = ioff + Int(isigned) * 4
diff --git a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift
index 5679e00e..e970cb2d 100644
--- a/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift
+++ b/sources/FirmwarePatcher/Kernel/Patches/KernelPatchPostValidation.swift
@@ -96,7 +96,7 @@ extension KernelPatcher {
var blTargets = Set<Int>()
for scan in stride(from: callerStart, to: callerEnd, by: 4) {
if scan > callerStart, buffer.readU32(at: scan) == ARM64.pacibspU32 { break }
- if let target = decodeBLOffset(at: scan) {
+ if let target = decodeBL(at: scan) {
blTargets.insert(target)
}
}
@@ -125,7 +125,7 @@ extension KernelPatcher {
// Must be preceded by a BL within 2 instructions (4 or 8 bytes back).
var hasBlBefore = false
for back in stride(from: off - 4, through: max(off - 8, target), by: -4) {
- if decodeBLOffset(at: back) != nil {
+ if decodeBL(at: back) != nil {
hasBlBefore = true
break
}
@@ -152,18 +152,6 @@ extension KernelPatcher {
// MARK: - Private helpers
- /// Decode a BL instruction at `offset`. Returns the absolute file offset of the
- /// target, or nil if the instruction at that offset is not a BL.
- private func decodeBLOffset(at offset: Int) -> Int? {
- guard offset >= 0, offset + 4 <= buffer.count else { return nil }
- let insn = buffer.readU32(at: offset)
- // BL: [31:26] = 0b100101
- guard insn >> 26 == 0b100101 else { return nil }
- let imm26 = insn & 0x03FF_FFFF
- let signedImm = Int32(bitPattern: imm26 << 6) >> 6
- return offset + Int(signedImm) * 4
- }
-
/// Find the start offset of the next function after `start` (exclusive),
/// up to `maxSize` bytes ahead. Returns `start + maxSize` if none found.
private func nextFunctionBoundary(after start: Int, maxSize: Int) -> Int {
diff --git a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
index 8a53d958..8e83a4d5 100644
--- a/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
+++ b/sources/FirmwarePatcher/Pipeline/FirmwarePipeline.swift
@@ -84,19 +84,6 @@ public final class FirmwarePipeline {
let enableFrida: Bool
let loader: any FirmwareLoader
- /// Set when the iPhone base is iOS 18.x (read from iPhone-BuildManifest.plist).
- /// Gates the skywalk-netagent boot-arg workaround (18.x-specific mDNSResponder
- /// crash-loop). Computed in `patchAll()` before `buildComponentList()` runs.
- private var iosBaseIs18 = false
-
- /// Set when the iPhone base is iOS 27.x. Gates the iOS-27-only JB kernel patches
- /// (KernelJBPatcher.applyIOS27); false for 18.x/26.x so those bases are
- /// byte-identical to pre-branch. Computed in `patchAll()` alongside iosBaseIs18.
- private var iosBaseIs27 = false
-
- /// Set when the cloudOS kernel is 26.4+; gates the opt-in Frida kernel patches.
- private var cloudOSIsFridaCapable = false
-
// MARK: - Init
public init(
@@ -135,8 +122,8 @@ public final class FirmwarePipeline {
// fw_prepare preserves — the live BuildManifest.plist reads the cloudOS
// version, not the base). iOS 18 bases need the skywalk-netagent boot-arg.
let baseVersion = Self.readBaseProductVersion(restoreDir)
- iosBaseIs18 = baseVersion?.hasPrefix("18.") ?? false
- iosBaseIs27 = baseVersion?.hasPrefix("27.") ?? false
+ let iosBaseIs18 = baseVersion?.hasPrefix("18.") ?? false
+ let iosBaseIs27 = baseVersion?.hasPrefix("27.") ?? false
let baseGateNote = iosBaseIs18 ? " (enabling iOS-18 netagent boot-arg)"
: iosBaseIs27 ? " (enabling iOS-27 JB kernel patches)" : ""
log("[*] iPhone base iOS: \(baseVersion ?? "unknown")\(baseGateNote)")
@@ -145,14 +132,19 @@ public final class FirmwarePipeline {
// were validated); older kernels are left untouched. The Frida deb install is
// separate and version-independent.
let cloudOSVersion = Self.readCloudOSProductVersion(restoreDir)
- cloudOSIsFridaCapable = Self.productVersionAtLeast(cloudOSVersion, 26, 4)
+ let cloudOSIsFridaCapable = Self.productVersionAtLeast(cloudOSVersion, 26, 4)
if enableFrida {
log("[*] cloudOS kernel: \(cloudOSVersion ?? "unknown")"
+ (cloudOSIsFridaCapable ? " (Frida kernel patches enabled)"
: " (< 26.4 — Frida kernel patches skipped)"))
}
- let components = buildComponentList()
+ let components = buildComponentList(
+ restoreDir: restoreDir,
+ iosBaseIs18: iosBaseIs18,
+ iosBaseIs27: iosBaseIs27,
+ cloudOSIsFridaCapable: cloudOSIsFridaCapable
+ )
log("[*] Patching \(components.count) boot-chain components ...")
var allRecords: [PatchRecord] = []
@@ -217,7 +209,24 @@ public final class FirmwarePipeline {
// MARK: - Component List Builder
/// Build the ordered component list based on the variant.
- func buildComponentList() -> [ComponentDescriptor] {
+ ///
+ /// - Parameters:
+ /// - restoreDir: The `*Restore*` directory `patchAll()` resolved, captured by value
+ /// into the patcher factory closures below.
+ /// - iosBaseIs18: True when the iPhone base is iOS 18.x (read from
+ /// `iPhone-BuildManifest.plist`). Gates the skywalk-netagent boot-arg workaround
+ /// (18.x-specific mDNSResponder crash-loop).
+ /// - iosBaseIs27: True when the iPhone base is iOS 27.x. Gates the iOS-27-only JB
+ /// kernel patches (`KernelJBPatcher.applyIOS27`); false for 18.x/26.x so those
+ /// bases are byte-identical to pre-branch.
+ /// - cloudOSIsFridaCapable: True when the cloudOS kernel is 26.4+; gates the opt-in
+ /// Frida kernel patches.
+ func buildComponentList(
+ restoreDir: URL,
+ iosBaseIs18: Bool,
+ iosBaseIs27: Bool,
+ cloudOSIsFridaCapable: Bool
+ ) -> [ComponentDescriptor] {
var components: [ComponentDescriptor] = []
// Captured by value into the patcher factory closures below (avoids
@@ -410,7 +419,7 @@ public final class FirmwarePipeline {
return switch variant {
case .less:
[{ data, verbose in
- CryptexFilesystemPatcher(buildManiest: data, restoreDir: try! self.findRestoreDirectory(), verbose: verbose, noBinpack: self.noBinpack, noVphoned: self.noVphoned)
+ CryptexFilesystemPatcher(buildManiest: data, restoreDir: restoreDir, verbose: verbose, noBinpack: self.noBinpack, noVphoned: self.noVphoned)
}]
case .regular, .dev, .jb, .exp:
[]
@@ -427,7 +436,7 @@ public final class FirmwarePipeline {
return switch variant {
case .less:
[{ data, verbose in
- ManifestHashPatcher(data: data, restoreDir: try? self.findRestoreDirectory(), verbose: verbose)
+ ManifestHashPatcher(data: data, restoreDir: restoreDir, verbose: verbose)
}]
case .regular, .dev, .jb, .exp:
[]
@@ -453,7 +462,7 @@ public final class FirmwarePipeline {
.sorted(by: compareRestoreDirectories)
guard let restoreDir = contents.first else {
- throw PatcherError.fileNotFound("No *Restore* directory found in \(vmDirectory.path). Run prepare_firmware first.")
+ throw PatcherError.fileNotFound("Restore directory in \(vmDirectory.path). Run make fw_prepare first.")
}
return restoreDir
}
@@ -560,7 +569,7 @@ public final class FirmwarePipeline {
}
}
let searched = patterns.map { baseDir.appendingPathComponent($0).path }.joined(separator: "\n ")
- throw PatcherError.fileNotFound("\(label) not found. Searched:\n \(searched)")
+ throw PatcherError.fileNotFound("\(label). Looked in:\n \(searched)")
}
// MARK: - Data Extraction
diff --git a/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift b/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift
index 4f169e62..4a17fd8e 100644
--- a/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift
+++ b/sources/FirmwarePatcher/TXM/TXMDevPatcher.swift
@@ -41,7 +41,7 @@ public final class TXMDevPatcher: TXMPatcher {
let rawB = buffer.readU32(at: off + 4)
// ADRP: bits[31]=1, bits[28:24]=10000
- guard rawA & 0x9F00_0000 == 0x9000_0000 else { off += 4; continue }
+ guard ARM64Inst.isADRP(rawA) else { off += 4; continue }
// ADD immediate (64-bit): bits[31:24] = 0x91
guard rawB & 0xFF80_0000 == 0x9100_0000 else { off += 4; continue }
diff --git a/sources/Info.plist b/sources/Info.plist
index a2c04586..4d659dd4 100644
--- a/sources/Info.plist
+++ b/sources/Info.plist
@@ -19,10 +19,10 @@
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>NSLocationUsageDescription</key>
- <string>vphone-cli forwards your location to the guest VM for location simulation.</string>
+ <string>Shares your location with the virtual iPhone so apps running inside it see the same location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
- <string>vphone-cli forwards your location to the guest VM for location simulation.</string>
+ <string>Shares your location with the virtual iPhone so apps running inside it see the same location.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
- <string>vphone-cli forwards your location to the guest VM for location simulation.</string>
+ <string>Shares your location with the virtual iPhone so apps running inside it see the same location.</string>
</dict>
</plist>
diff --git a/sources/VPhoneCore/VPhoneBundleOps.swift b/sources/VPhoneCore/VPhoneBundleOps.swift
index eb6e6961..7269ca1e 100644
--- a/sources/VPhoneCore/VPhoneBundleOps.swift
+++ b/sources/VPhoneCore/VPhoneBundleOps.swift
@@ -8,12 +8,12 @@ public enum VPhoneBundleOpsError: Error, Equatable {
public enum VPhoneBundleOps {
public struct NewBundleSpec: Sendable {
- public var name: String
- public var cpuCount: UInt
- public var memoryMB: UInt64
- public var diskSizeGB: UInt64
- public var romSource: URL
- public var sepromSource: URL
+ public let name: String
+ public let cpuCount: UInt
+ public let memoryMB: UInt64
+ public let diskSizeGB: UInt64
+ public let romSource: URL
+ public let sepromSource: URL
public init(name: String, cpuCount: UInt, memoryMB: UInt64, diskSizeGB: UInt64,
romSource: URL, sepromSource: URL) {
@@ -102,7 +102,6 @@ public enum VPhoneBundleOps {
let updated = bundle.manifest.updating(
cpuCount: cpuCount,
memorySize: memoryMB.map { $0 * 1024 * 1024 },
- screenConfig: nil,
networkConfig: network)
try updated.write(to: bundle.configURL)
return VPhoneBundle(url: bundle.url, manifest: updated)
@@ -289,7 +288,7 @@ public enum VPhoneBundleOps {
let entries = try fm.contentsOfDirectory(atPath: staging.path)
guard entries.count == 1, let archived = entries.first else {
throw VPhoneBundleOpsError.badArchive(
- "expected a single top-level bundle directory, found \(entries.sorted())")
+ "This archive is not a VM export. Choose an archive created by 'vphone-cli vm export'.")
}
let finalName = name ?? archived
try requireValidName(finalName)
@@ -298,7 +297,7 @@ public enum VPhoneBundleOps {
let extracted = staging.appendingPathComponent(archived)
guard fm.fileExists(atPath: extracted.appendingPathComponent("config.plist").path) else {
throw VPhoneBundleOpsError.badArchive(
- "archive did not contain a valid bundle (\(archived)/config.plist)")
+ "This archive does not contain a valid VM. Choose an archive created by 'vphone-cli vm export'.")
}
let bundle = try VPhoneBundle.load(at: extracted)
try fm.moveItem(at: extracted, to: dst)
diff --git a/sources/VPhoneCore/VPhoneFirmwarePicker.swift b/sources/VPhoneCore/VPhoneFirmwarePicker.swift
index 607977ff..eff00901 100644
--- a/sources/VPhoneCore/VPhoneFirmwarePicker.swift
+++ b/sources/VPhoneCore/VPhoneFirmwarePicker.swift
@@ -8,8 +8,8 @@ public enum VPhoneFirmwarePickerError: Error, CustomStringConvertible, Equatable
public var description: String {
switch self {
- case .aborted: "firmware selection aborted"
- case .invalidSelection: "no valid firmware selection made"
+ case .aborted: "Firmware selection cancelled."
+ case .invalidSelection: "No valid selection. Enter a number from the list."
}
}
}
diff --git a/sources/VPhoneCore/VPhoneLaunchLayout.swift b/sources/VPhoneCore/VPhoneLaunchLayout.swift
index ff7f88bb..50323224 100644
--- a/sources/VPhoneCore/VPhoneLaunchLayout.swift
+++ b/sources/VPhoneCore/VPhoneLaunchLayout.swift
@@ -9,13 +9,8 @@ public struct VPhoneLaunchLayout: Sendable {
public init(projectRoot: URL) { self.init(resources: VPhoneResources(base: projectRoot)) }
public var preflightScript: URL { resources.preflightScript }
- public var fwPrepareScript: URL { resources.fwPrepareScript }
- public var cfwInstallHostScript: URL { resources.cfwInstallHostScript }
- public var pmd3Bridge: URL { resources.pmd3Bridge }
public var vphoned: URL { resources.vphoned }
- public func python() throws -> URL { try resources.pythonExecutable() }
-
/// Copy the built vphoned into the bundle if present and different.
@discardableResult
public func stageVphoned(into bundle: VPhoneBundle) throws -> Bool {
diff --git a/sources/VPhoneCore/VPhoneLibrary.swift b/sources/VPhoneCore/VPhoneLibrary.swift
index 6e864a91..bcc49f53 100644
--- a/sources/VPhoneCore/VPhoneLibrary.swift
+++ b/sources/VPhoneCore/VPhoneLibrary.swift
@@ -11,7 +11,8 @@ extension VPhoneLibraryError: CustomStringConvertible, LocalizedError {
switch self {
case let .notFound(name): "VM '\(name)' not found"
case let .alreadyExists(name): "VM '\(name)' already exists"
- case let .invalidName(name): "Invalid VM name '\(name)' (must be non-empty, contain no '/', and not start with '.')"
+ case let .invalidName(name):
+ "Invalid VM name '\(name)'. Use a name that is not empty, has no '/', and does not start with '.'."
}
}
public var errorDescription: String? { description }
diff --git a/sources/VPhoneCore/VPhoneNetworking.swift b/sources/VPhoneCore/VPhoneNetworking.swift
index 5448e857..ae4472a8 100644
--- a/sources/VPhoneCore/VPhoneNetworking.swift
+++ b/sources/VPhoneCore/VPhoneNetworking.swift
@@ -18,13 +18,13 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {
public var description: String {
switch self {
case .hostOnlyUnsupported:
- "network mode 'hostOnly' is not supported (Virtualization.framework has no host-only attachment); use nat, bridged, or none"
+ "Network mode 'hostOnly' is not supported. Use nat, bridged, or none."
case let .bridgeInterfaceNotFound(requested, available):
- "bridge interface '\(requested)' not found; available: \(available.isEmpty ? "(none)" : available.joined(separator: ", "))"
+ "Bridge interface '\(requested)' not found. Available: \(available.isEmpty ? "none" : available.joined(separator: ", "))."
case .noBridgeInterfaces:
- "bridged mode requires a host interface, but none are available for bridging"
+ "Bridged mode needs a host network interface, but none are available. Use nat instead."
case .bridgeInterfaceWithoutBridgedMode:
- "--bridge-interface is only valid with --network bridged"
+ "--bridge-interface is only valid with --network bridged."
}
}
public var errorDescription: String? { description }
diff --git a/sources/VPhoneCore/VPhoneResources.swift b/sources/VPhoneCore/VPhoneResources.swift
index 3b80a1aa..3f842cc7 100644
--- a/sources/VPhoneCore/VPhoneResources.swift
+++ b/sources/VPhoneCore/VPhoneResources.swift
@@ -3,7 +3,6 @@ import Foundation
// MARK: - VPhoneResourcesError
public enum VPhoneResourcesError: Error, Equatable {
- case pythonNotFound(String)
case venvBootstrapFailed(String)
}
@@ -57,7 +56,6 @@ public struct VPhoneResources: Sendable {
public var preflightScript: URL { scriptsDir.appendingPathComponent("boot_host_preflight.sh") }
public var pmd3Bridge: URL { scriptsDir.appendingPathComponent("pymobiledevice3_bridge.py") }
public var cfwPy: URL { patchersDir.appendingPathComponent("cfw.py") }
- public var apfsSnapRename: URL { base.appendingPathComponent("tools/apfs_snap_rename.py") }
public var signcert: URL { scriptsDir.appendingPathComponent("vphoned/signcert.p12") }
public var vphoned: URL {
@@ -80,11 +78,9 @@ public struct VPhoneResources: Sendable {
return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".vphone")
}
- public var userCacheDir: URL { Self.userDataRoot() }
- public var ipswCacheDir: URL { userCacheDir.appendingPathComponent("ipsws") }
- public var sealVolumeCacheDir: URL { userCacheDir.appendingPathComponent("tools") }
- public var debsCacheDir: URL { userCacheDir.appendingPathComponent("debs") }
- public var toolsBinDir: URL { base.appendingPathComponent(".tools/bin") }
+ public var ipswCacheDir: URL { Self.userDataRoot().appendingPathComponent("ipsws") }
+ public var sealVolumeCacheDir: URL { Self.userDataRoot().appendingPathComponent("tools") }
+ public var debsCacheDir: URL { Self.userDataRoot().appendingPathComponent("debs") }
// MARK: - Python
@@ -103,7 +99,7 @@ public struct VPhoneResources: Sendable {
if let dir = ProcessInfo.processInfo.environment["VPHONE_VENV_DIR"], !dir.isEmpty {
return URL(fileURLWithPath: dir)
}
- return userCacheDir.appendingPathComponent("venv")
+ return Self.userDataRoot().appendingPathComponent("venv")
}
private var managedVenvPython: URL { managedVenvDir.appendingPathComponent("bin/python3") }
@@ -211,32 +207,33 @@ public struct VPhoneResources: Sendable {
let candidates = candidateHostPythons()
guard !candidates.isEmpty else {
throw VPhoneResourcesError.venvBootstrapFailed(
- "no host python3 found — install one (e.g. `brew install [email protected]`) or set VPHONE_PYTHON")
+ "No python3 found on this system. Install it with 'brew install [email protected]', or set VPHONE_PYTHON.")
}
- log("[*] First run: provisioning the vphone Python environment at \(managedVenvDir.path) (one-time)…")
+ log("[*] First run: setting up the Python environment at \(managedVenvDir.path)…")
let py = managedVenvPython
let install: [String] = FileManager.default.fileExists(atPath: requirementsFile.path)
? ["-m", "pip", "install", "-r", requirementsFile.path]
: ["-m", "pip", "install"] + Self.fallbackRequirements
- var lastError = "no candidate python could build a usable venv"
+ var lastError = "No usable Python could be found on this system"
for host in candidates {
- log(" → trying \(host.path) …")
+ log(" → Trying \(host.path)…")
try? FileManager.default.removeItem(at: managedVenvDir)
- try FileManager.default.createDirectory(at: userCacheDir, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: Self.userDataRoot(), withIntermediateDirectories: true)
guard (try? VPhoneProcessRunner.runStreaming(host, ["-m", "venv", managedVenvDir.path])) == 0 else {
- lastError = "python -m venv failed with \(host.path)"; continue
+ lastError = "Could not create a Python environment with \(host.path)"; continue
}
_ = try? VPhoneProcessRunner.runStreaming(py, ["-m", "pip", "install", "--upgrade", "-q", "pip"])
guard (try? VPhoneProcessRunner.runStreaming(py, install)) == 0 else {
- lastError = "pip install failed with \(host.path)"; continue
+ lastError = "Could not install the required Python packages with \(host.path)"; continue
}
guard pythonIsUsable(py) else {
- lastError = "venv from \(host.path) still lacks a usable ipsw_parser (too old?)"; continue
+ lastError = "The Python environment built with \(host.path) is missing a required package"; continue
}
guard keystoneIsUsable(py) || repairKeystone(py) else {
- lastError = "venv from \(host.path) has no working libkeystone — "
- + "`brew install keystone`, or install cmake so pip can build it"
+ lastError = "Could not set up keystone in the Python environment built with \(host.path). "
+ + "Install it with 'brew install keystone', or install cmake so it can be built"
continue
}
log("[+] Python environment ready: \(py.path)")
@@ -244,7 +241,8 @@ public struct VPhoneResources: Sendable {
}
try? FileManager.default.removeItem(at: managedVenvDir)
throw VPhoneResourcesError.venvBootstrapFailed(
- lastError + " — install a modern python3 (e.g. `brew install [email protected]`) or set VPHONE_PYTHON")
+ lastError + ". If the problem persists, install a modern python3 with "
+ + "'brew install [email protected]', or set VPHONE_PYTHON.")
}
/// Ordered, existence-checked host python3 candidates to bootstrap from.
diff --git a/sources/VPhoneCore/VPhoneRestoreInfo.swift b/sources/VPhoneCore/VPhoneRestoreInfo.swift
index f1bff053..75424245 100644
--- a/sources/VPhoneCore/VPhoneRestoreInfo.swift
+++ b/sources/VPhoneCore/VPhoneRestoreInfo.swift
@@ -28,8 +28,8 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {
static let fileName = "restore-info.json"
- public static let baseDevice = "iPhone99,11"
- public static let experimentalDevice = "iPhone17,3"
+ private static let baseDevice = "iPhone99,11"
+ private static let experimentalDevice = "iPhone17,3"
/// Only `exp` rewrites the DeviceTree identity; others keep the base type.
public static func device(forVariant variant: String) -> String {
diff --git a/sources/VPhoneCore/VPhoneRestoreOps.swift b/sources/VPhoneCore/VPhoneRestoreOps.swift
index c14c5b4a..60c425c7 100644
--- a/sources/VPhoneCore/VPhoneRestoreOps.swift
+++ b/sources/VPhoneCore/VPhoneRestoreOps.swift
@@ -14,23 +14,22 @@ public enum VPhoneRestoreOps {
/// ECID from `--ecid`, else the `ECID=` line of the bundle's udid-prediction.txt.
public static func resolveECID(explicit: String?, bundle: VPhoneBundle) -> String? {
if let explicit, !explicit.isEmpty { return explicit }
- let pred = bundle.url.appendingPathComponent("udid-prediction.txt")
- guard let text = try? String(contentsOf: pred, encoding: .utf8) else { return nil }
- for line in text.split(whereSeparator: \.isNewline) where line.hasPrefix("ECID=") {
- let value = line.dropFirst("ECID=".count).trimmingCharacters(in: .whitespaces)
- return value.isEmpty ? nil : value
- }
- return nil
+ return predictedValue(forKey: "ECID=", bundle: bundle)
}
// MARK: - UDID
/// UDID from the `UDID=` line of the bundle's udid-prediction.txt, or nil.
public static func resolveUDID(bundle: VPhoneBundle) -> String? {
+ predictedValue(forKey: "UDID=", bundle: bundle)
+ }
+
+ /// First `<key>value` line of the bundle's udid-prediction.txt, or nil.
+ private static func predictedValue(forKey key: String, bundle: VPhoneBundle) -> String? {
let pred = bundle.url.appendingPathComponent("udid-prediction.txt")
guard let text = try? String(contentsOf: pred, encoding: .utf8) else { return nil }
- for line in text.split(whereSeparator: \.isNewline) where line.hasPrefix("UDID=") {
- let value = line.dropFirst("UDID=".count).trimmingCharacters(in: .whitespaces)
+ for line in text.split(whereSeparator: \.isNewline) where line.hasPrefix(key) {
+ let value = line.dropFirst(key.count).trimmingCharacters(in: .whitespaces)
return value.isEmpty ? nil : value
}
return nil
diff --git a/sources/VPhoneCore/VPhoneVMPicker.swift b/sources/VPhoneCore/VPhoneVMPicker.swift
index 32979c74..97520c9f 100644
--- a/sources/VPhoneCore/VPhoneVMPicker.swift
+++ b/sources/VPhoneCore/VPhoneVMPicker.swift
@@ -9,13 +9,13 @@ public enum VPhoneVMPickerError: Error, CustomStringConvertible, Equatable {
public var description: String {
switch self {
case .emptyLibrary(let root):
- "no VMs found in \(root) — create one with 'vphone-cli vm create <name>'"
+ "No VMs found in \(root). Create one with 'vphone-cli vm create <name>'."
case .notInteractive:
- "no VM name given and stdin is not a terminal — pass the name explicitly"
+ "No VM name given, and this is not an interactive terminal. Pass the VM name as an argument."
case .aborted:
- "selection aborted"
+ "Selection cancelled."
case .invalidSelection:
- "no valid selection made"
+ "No valid selection. Enter a number from the list, or the exact VM name."
}
}
}
diff --git a/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift b/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift
index 370a3a62..32ed5978 100644
--- a/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift
+++ b/sources/VPhoneCore/VPhoneVirtualMachineManifest.swift
@@ -1,20 +1,22 @@
import Foundation
-import Virtualization
// MARK: - Errors
public enum VPhoneManifestError: Error {
- case loadFailed(path: String, underlying: Error)
- case parseFailed(path: String, underlying: Error)
- case writeFailed(path: String, underlying: Error)
+ case loadFailed(path: String)
+ case parseFailed(path: String)
+ case writeFailed(path: String)
}
extension VPhoneManifestError: CustomStringConvertible, LocalizedError {
public var description: String {
switch self {
- case let .loadFailed(path, underlying): "Failed to load manifest from \(path): \(underlying)"
- case let .parseFailed(path, underlying): "Failed to parse manifest at \(path): \(underlying)"
- case let .writeFailed(path, underlying): "Failed to write manifest to \(path): \(underlying)"
+ case let .loadFailed(path):
+ "Unable to read the VM configuration at \(path). Check that the file exists and try again."
+ case let .parseFailed(path):
+ "The VM configuration at \(path) is not valid. Recreate the VM, or restore a backup of config.plist."
+ case let .writeFailed(path):
+ "Unable to save the VM configuration to \(path). Check that the file is writable and try again."
}
}
public var errorDescription: String? { description }
@@ -172,14 +174,14 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
do {
data = try Data(contentsOf: url)
} catch {
- throw VPhoneManifestError.loadFailed(path: url.path, underlying: error)
+ throw VPhoneManifestError.loadFailed(path: url.path)
}
let decoder = PropertyListDecoder()
do {
return try decoder.decode(VPhoneVirtualMachineManifest.self, from: data)
} catch {
- throw VPhoneManifestError.parseFailed(path: url.path, underlying: error)
+ throw VPhoneManifestError.parseFailed(path: url.path)
}
}
@@ -192,39 +194,22 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
let data = try encoder.encode(self)
try data.write(to: url)
} catch {
- throw VPhoneManifestError.writeFailed(path: url.path, underlying: error)
+ throw VPhoneManifestError.writeFailed(path: url.path)
}
}
// MARK: - Convenience
- /// Convert to JSON string for logging/debugging
- public func asJSON() -> String {
- let encoder = JSONEncoder()
- encoder.outputFormatting = .withoutEscapingSlashes
- do {
- return try String(decoding: encoder.encode(self), as: UTF8.self)
- } catch {
- return "{ }"
- }
- }
-
/// Resolve relative path to absolute URL within VM directory
public func resolve(path: String, in vmDirectory: URL) -> URL {
vmDirectory.appendingPathComponent(path)
}
- /// Get VZMacMachineIdentifier from manifest data
- public func vzMachineIdentifier() -> VZMacMachineIdentifier? {
- VZMacMachineIdentifier(dataRepresentation: machineIdentifier)
- }
-
// MARK: - Editing
public func updating(
cpuCount: UInt? = nil,
memorySize: UInt64? = nil,
- screenConfig: ScreenConfig? = nil,
machineIdentifier: Data? = nil,
networkConfig: NetworkConfig? = nil
) -> VPhoneVirtualMachineManifest {
@@ -234,7 +219,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
machineIdentifier: machineIdentifier ?? self.machineIdentifier,
cpuCount: cpuCount ?? self.cpuCount,
memorySize: memorySize ?? self.memorySize,
- screenConfig: screenConfig ?? self.screenConfig,
+ screenConfig: screenConfig,
networkConfig: networkConfig ?? self.networkConfig,
diskImage: diskImage,
nvramStorage: nvramStorage,
diff --git a/sources/vphone-cli/VPhoneAppBrowserView.swift b/sources/vphone-cli/VPhoneAppBrowserView.swift
index ffc0c3f3..789afc00 100644
--- a/sources/vphone-cli/VPhoneAppBrowserView.swift
+++ b/sources/vphone-cli/VPhoneAppBrowserView.swift
@@ -14,7 +14,11 @@ struct VPhoneAppBrowserView: View {
ContentUnavailableView(
"No Apps",
systemImage: "app.dashed",
- description: Text(model.searchText.isEmpty ? "No apps found." : "No matching apps.")
+ description: Text(
+ model.searchText.isEmpty
+ ? "No apps are installed on the guest."
+ : "No apps match your search."
+ )
)
} else {
appTable
@@ -54,7 +58,7 @@ struct VPhoneAppBrowserView: View {
Spacer()
- Text("\(model.filteredApps.count) apps")
+ Text(model.filteredApps.count == 1 ? "1 app" : "\(model.filteredApps.count) apps")
.font(.system(.body, design: .monospaced))
.foregroundStyle(.secondary)
diff --git a/sources/vphone-cli/VPhoneControl.swift b/sources/vphone-cli/VPhoneControl.swift
index e5982b72..3e030712 100644
--- a/sources/vphone-cli/VPhoneControl.swift
+++ b/sources/vphone-cli/VPhoneControl.swift
@@ -26,7 +26,6 @@ class VPhoneControl {
private var connection: VZVirtioSocketConnection?
private weak var device: VZVirtioSocketDevice?
private(set) var isConnected = false
- private(set) var guestName = ""
private(set) var guestCaps: [String] = []
private(set) var guestIP: String?
/// Guest userland iOS version reported at handshake (e.g. "18.6.2"), if known.
@@ -99,7 +98,6 @@ class VPhoneControl {
enum ControlError: Error, CustomStringConvertible {
case notConnected
case unsupportedCapability(String)
- case cancelled(String)
case requestTimedOut(type: String, seconds: Int)
case protocolError(String)
case guestError(String)
@@ -109,7 +107,6 @@ class VPhoneControl {
case .notConnected: "not connected to vphoned"
case let .unsupportedCapability(capability):
"guest does not support capability: \(capability)"
- case let .cancelled(reason): "request cancelled: \(reason)"
case let .requestTimedOut(type, seconds):
"request timed out (\(type), \(seconds)s)"
case let .protocolError(msg): "protocol error: \(msg)"
@@ -213,7 +210,6 @@ class VPhoneControl {
self.disconnect(ifCurrentAttempt: attemptToken)
return
}
- self.guestName = name
self.guestCaps = caps
self.guestIP = ip
self.guestIOSVersion = iosVersion
@@ -323,14 +319,9 @@ class VPhoneControl {
// MARK: - Developer Mode
- struct DevModeStatus {
- let enabled: Bool
- }
-
- func sendDevModeStatus() async throws -> DevModeStatus {
+ func sendDevModeStatus() async throws -> Bool {
let (resp, _) = try await sendRequest(["t": "devmode", "action": "status"])
- let enabled = resp["enabled"] as? Bool ?? false
- return DevModeStatus(enabled: enabled)
+ return resp["enabled"] as? Bool ?? false
}
func sendPing() async throws {
@@ -342,11 +333,6 @@ class VPhoneControl {
return resp["hash"] as? String ?? "unknown"
}
- /// Cancel all currently pending request continuations.
- func cancelPendingRequests(reason: String = "cancelled by host") {
- failAllPending(with: .cancelled(reason))
- }
-
// MARK: - Async Request-Response
/// Send a request and await the response. Returns the response dict and optional raw data.
@@ -513,9 +499,8 @@ class VPhoneControl {
let diagnostics: [String]
}
- func listKeychainItems(filterClass: String? = nil) async throws -> KeychainResult {
- var req: [String: Any] = ["t": "keychain_list"]
- if let filterClass { req["class"] = filterClass }
+ func listKeychainItems() async throws -> KeychainResult {
+ let req: [String: Any] = ["t": "keychain_list"]
let (resp, _) = try await sendRequest(req)
guard let items = resp["items"] as? [[String: Any]] else {
throw ControlError.protocolError("missing items in keychain response")
@@ -526,7 +511,7 @@ class VPhoneControl {
func addKeychainItem(
account: String = "vphone-test", service: String = "vphone", password: String = "testpass123"
- ) async throws -> Bool {
+ ) async throws {
let req: [String: Any] = [
"t": "keychain_add", "account": account, "service": service, "password": password,
]
@@ -536,7 +521,6 @@ class VPhoneControl {
let msg = resp["msg"] as? String ?? "unknown error"
throw ControlError.protocolError("keychain_add: \(msg)")
}
- return true
}
// MARK: - Clipboard
@@ -616,7 +600,6 @@ class VPhoneControl {
let state: String
let pid: Int
let path: String
- let dataContainer: String
}
func appList(filter: String = "all") async throws -> [AppInfo] {
@@ -632,8 +615,7 @@ class VPhoneControl {
type: app["type"] as? String ?? "",
state: app["state"] as? String ?? "",
pid: app["pid"] as? Int ?? 0,
- path: app["path"] as? String ?? "",
- dataContainer: app["data_container"] as? String ?? ""
+ path: app["path"] as? String ?? ""
)
}
}
@@ -737,7 +719,7 @@ class VPhoneControl {
"t": "location_stop",
"id": String(nextRequestId, radix: 16),
]
- guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else { return }
+ if let fd = connection?.fileDescriptor { writeMessage(fd: fd, dict: msg) }
}
// MARK: - Disconnect & Reconnect
@@ -753,7 +735,6 @@ class VPhoneControl {
let fd = connection?.fileDescriptor
connection = nil
isConnected = false
- guestName = ""
guestCaps = []
guestIP = nil
diff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
index da0e77f0..31ada9d3 100644
--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift
+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
@@ -31,44 +31,45 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {
var description: String {
switch self {
case .nestedVirtualization:
- "Virtualization.framework guest boot is unavailable inside a VM — run vm create on a non-nested macOS 15+ host"
+ "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)' (regular|dev|jb|exp|less)"
+ "Unknown variant '\(v)'. Choose regular, dev, jb, exp, or less."
case .lessRequiresRoot:
- "fw patch for 'less' must be run as root (matches Makefile's `fw_patch_less must be run via sudo`)"
+ "The 'less' variant requires root. Run vm create with sudo."
case let .fwPrepareFailed(code):
- "fw prepare failed (exit \(code))"
+ "Firmware preparation failed (exit code \(code))."
case let .identityTimedOut(path):
- "missing \(path.path); rebuild and retry to regenerate it"
+ "Device identity file not found: \(path.path). Run vm create again to regenerate it."
case let .invalidUDID(v):
- "invalid UDID in udid-prediction.txt: '\(v)'"
+ "Invalid UDID in the device identity file: '\(v)'. Run vm create again to regenerate it."
case let .invalidECID(v):
- "invalid ECID in udid-prediction.txt: '\(v)'"
+ "Invalid ECID in the device identity file: '\(v)'. Run vm create again to regenerate it."
case let .udidECIDMismatch(udid, ecid):
- "UDID/ECID mismatch in udid-prediction.txt: \(udid) vs 0x\(ecid)"
+ "The UDID and ECID in the device identity file do not match: \(udid) vs 0x\(ecid). "
+ + "Run vm create again to regenerate it."
case .recoveryTimeout:
- "timed out waiting for the recovery/DFU endpoint"
+ "Timed out waiting for the device to enter recovery mode."
case let .restoreGetSHSHFailed(code):
- "restore-get-shsh failed (exit \(code))"
+ "Unable to fetch the signing ticket (exit code \(code))."
case let .restoreUpdateFailed(code):
- "restore-update failed (exit \(code))"
+ "Device restore failed (exit code \(code))."
case let .cfwInstallFailed(code):
- "CFW install failed (exit \(code))"
+ "Custom firmware installation failed (exit code \(code))."
case .sudoPasswordRequired:
- "CFW install needs root but no sudo password is available — pass --sudo-password "
- + "or run vm create in an interactive terminal"
+ "Custom firmware installation requires root, but no sudo password is available. "
+ + "Pass --sudo-password, or run vm create in an interactive terminal."
case .firstBootPanic:
- "first boot panicked before command injection"
+ "First boot panicked before the setup commands could run."
case let .firstBootExitedBeforePrompt(code):
- "first boot exited before command injection (exit \(code))"
+ "First boot exited before the setup commands could run (exit code \(code))."
case .bootAnalysisPanic:
- "boot analysis: panic detected"
+ "Boot analysis failed: the guest panicked."
case let .bootAnalysisExited(code):
- "boot analysis: process exited before success marker (exit \(code))"
+ "Boot analysis ended before the guest finished booting (exit code \(code))."
case .bootAnalysisTimeout:
- "boot analysis timed out"
+ "Boot analysis timed out."
case let .lessBootFailed(code):
- "start VM (less) failed (exit \(code))"
+ "The VM failed to start with the 'less' variant (exit code \(code))."
}
}
}
diff --git a/sources/vphone-cli/VPhoneFileBrowserModel.swift b/sources/vphone-cli/VPhoneFileBrowserModel.swift
index e1bc30a8..d83d09fa 100644
--- a/sources/vphone-cli/VPhoneFileBrowserModel.swift
+++ b/sources/vphone-cli/VPhoneFileBrowserModel.swift
@@ -94,12 +94,8 @@ class VPhoneFileBrowserModel {
}
func goToBreadcrumb(_ path: String) {
- if path == currentPath { return }
- pathHistory.append(currentPath)
- forwardHistory.removeAll()
- currentPath = path
- selection.removeAll()
- Task { await refresh() }
+ guard path != currentPath else { return }
+ navigate(to: path)
}
var canGoBack: Bool { !pathHistory.isEmpty }
diff --git a/sources/vphone-cli/VPhoneFileBrowserView.swift b/sources/vphone-cli/VPhoneFileBrowserView.swift
index 23a0e5bc..d7434687 100644
--- a/sources/vphone-cli/VPhoneFileBrowserView.swift
+++ b/sources/vphone-cli/VPhoneFileBrowserView.swift
@@ -154,7 +154,7 @@ struct VPhoneFileBrowserView: View {
.progressViewStyle(.linear)
}
HStack {
- Text(model.transferName ?? "Transferring...")
+ Text(model.transferName ?? "Transferring…")
.lineLimit(1)
Spacer()
if model.transferTotal > 0 {
@@ -250,8 +250,8 @@ struct VPhoneFileBrowserView: View {
Button("Copy Name") { copyNames(ids: ids) }
Button("Copy Path") { copyPaths(ids: ids) }
Divider()
- Button("Upload...") { uploadAction() }
- Button("New Folder...") {
+ Button("Upload…") { uploadAction() }
+ Button("New Folder…") {
newFolderName = ""
showNewFolder = true
}
@@ -324,7 +324,7 @@ struct VPhoneFileBrowserView: View {
}
}
if urls.isEmpty {
- model.error = "Could not load any files from the dropped items."
+ model.error = "Unable to read the dropped items. Drag files from Finder, then try again."
} else {
await model.uploadFiles(urls: urls)
}
diff --git a/sources/vphone-cli/VPhoneFrameProducer.swift b/sources/vphone-cli/VPhoneFrameProducer.swift
index cb587fd9..43e492a9 100644
--- a/sources/vphone-cli/VPhoneFrameProducer.swift
+++ b/sources/vphone-cli/VPhoneFrameProducer.swift
@@ -33,7 +33,6 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendable
private let width: Int
private let height: Int
private let bytesPerRow: Int
- private var frameIndex: UInt64 = 0
private let startedAt: TimeInterval
init(width: Int, height: Int) {
@@ -92,7 +91,6 @@ final class VPhoneTestPatternProducer: VPhoneFrameProducer, @unchecked Sendable
}
}
- frameIndex &+= 1
let ts = UInt64(now * 1_000_000_000)
return VPhoneCameraFrame(
width: width,
diff --git a/sources/vphone-cli/VPhoneHostControl.swift b/sources/vphone-cli/VPhoneHostControl.swift
index e6f6d564..cbd842ab 100644
--- a/sources/vphone-cli/VPhoneHostControl.swift
+++ b/sources/vphone-cli/VPhoneHostControl.swift
@@ -132,7 +132,7 @@ class VPhoneHostControl {
}
// Reuse the existing private-API capture
- guard let cgImage = await captureStillImage(recorder: recorder, view: view) else {
+ guard let cgImage = try? await recorder.captureStillImage(from: view) else {
return nil
}
@@ -166,55 +166,6 @@ class VPhoneHostControl {
return (data as Data).base64EncodedString()
}
- /// Access the recorder's private capture method via the existing async wrapper.
- private func captureStillImage(recorder: VPhoneScreenRecorder, view: NSView) async -> CGImage? {
- // Use the public saveScreenshot path but intercept before encoding.
- // We call the recorder's internal captureStillImage indirectly by
- // going through saveScreenshot to a temp file, then reading back.
- // This is suboptimal but avoids exposing internal API.
- //
- // Better: use the same private API directly.
- guard let vmView = view as? VPhoneVirtualMachineView,
- let display = vmView.recordingGraphicsDisplay
- else { return nil }
-
- return await withCheckedContinuation { continuation in
- let selector = NSSelectorFromString("_takeScreenshotWithCompletionHandler:")
- guard display.responds(to: selector),
- let cls = object_getClass(display),
- let method = class_getInstanceMethod(cls, selector)
- else {
- continuation.resume(returning: nil)
- return
- }
-
- typealias CompletionBlock = @convention(block) (AnyObject?) -> Void
- typealias IMP = @convention(c) (AnyObject, Selector, AnyObject) -> Void
-
- let impl = method_getImplementation(method)
- let fn = unsafeBitCast(impl, to: IMP.self)
-
- let block: CompletionBlock = { imageObject in
- guard let imageObject else {
- continuation.resume(returning: nil)
- return
- }
- if let nsImage = imageObject as? NSImage {
- continuation.resume(returning: nsImage.cgImage(forProposedRect: nil, context: nil, hints: nil))
- return
- }
- let cf = imageObject as CFTypeRef
- if CFGetTypeID(cf) == CGImage.typeID {
- continuation.resume(returning: (cf as! CGImage))
- return
- }
- continuation.resume(returning: nil)
- }
- let blockObj = unsafeBitCast(block, to: AnyObject.self)
- fn(display, selector, blockObj)
- }
- }
-
// MARK: - Accept Loop
private nonisolated static func acceptLoop(listenFD: Int32, controller: VPhoneHostControl?) {
diff --git a/sources/vphone-cli/VPhoneKeyHelper.swift b/sources/vphone-cli/VPhoneKeyHelper.swift
index c5350468..fea18d4e 100644
--- a/sources/vphone-cli/VPhoneKeyHelper.swift
+++ b/sources/vphone-cli/VPhoneKeyHelper.swift
@@ -33,10 +33,12 @@ class VPhoneKeyHelper {
backing: .buffered,
defer: false
)
- panel.title = "vphoned Not Connected"
+ panel.title = "Guest Agent Not Connected"
panel.center()
- let msg = NSTextField(labelWithString: "The guest agent is not connected. Key injection requires vphoned running inside the VM.")
+ let msg = NSTextField(
+ labelWithString: "The guest agent is not connected. Wait for it to connect, then try again."
+ )
msg.frame = NSRect(x: 20, y: 50, width: 340, height: 44)
msg.lineBreakMode = .byWordWrapping
msg.maximumNumberOfLines = 3
diff --git a/sources/vphone-cli/VPhoneKeychainBrowserModel.swift b/sources/vphone-cli/VPhoneKeychainBrowserModel.swift
index d5c57a98..8a41b1d5 100644
--- a/sources/vphone-cli/VPhoneKeychainBrowserModel.swift
+++ b/sources/vphone-cli/VPhoneKeychainBrowserModel.swift
@@ -50,7 +50,7 @@ class VPhoneKeychainBrowserModel {
return "\(count)/\(total) \(suffix)"
}
if count == 0, !diagnostics.isEmpty {
- return diagnostics.joined(separator: " | ")
+ return "No items"
}
return "\(count) \(suffix)"
}
@@ -68,11 +68,11 @@ class VPhoneKeychainBrowserModel {
func addTestItem() async {
do {
- _ = try await control.addKeychainItem()
+ try await control.addKeychainItem()
print("[keychain] test item added, refreshing...")
await refresh()
} catch {
- self.error = "Add failed: \(error)"
+ self.error = "Unable to add the keychain item. Try again."
print("[keychain] add failed: \(error)")
}
}
@@ -81,7 +81,7 @@ class VPhoneKeychainBrowserModel {
func refresh() async {
guard control.isConnected else {
- error = "Waiting for vphoned connection..."
+ error = "The guest agent is not connected. Wait for it to connect, then try again."
return
}
isLoading = true
@@ -94,7 +94,7 @@ class VPhoneKeychainBrowserModel {
print("[keychain] 0 items, diag: \(diagnostics)")
}
} catch {
- self.error = "\(error)"
+ self.error = "Unable to load keychain items. Check that the guest agent is connected, then try again."
items = []
}
isLoading = false
diff --git a/sources/vphone-cli/VPhoneMenuCamera.swift b/sources/vphone-cli/VPhoneMenuCamera.swift
index c02292d5..37624220 100644
--- a/sources/vphone-cli/VPhoneMenuCamera.swift
+++ b/sources/vphone-cli/VPhoneMenuCamera.swift
@@ -45,7 +45,7 @@ extension VPhoneMenuController {
func updateCameraConnectionState(connected: Bool) {
cameraStatusItem?.title = connected
- ? "Camera server: connected (vsock 1338)"
+ ? "Camera server: connected"
: "Camera server: disconnected"
cameraStartStopItem?.isEnabled = connected &&
(cameraServer?.sourceKind ?? .off) != .off
@@ -88,7 +88,7 @@ extension VPhoneMenuController {
UTType(filenameExtension: "m4v") ?? .movie,
]
panel.prompt = "Use as Camera Source"
- panel.title = "Pick a video file"
+ panel.title = "Choose Video File"
panel.runModal()
guard let url = panel.url else { return }
cameraServer?.setSource(.videoFile, videoURL: url)
diff --git a/sources/vphone-cli/VPhoneMenuConnect.swift b/sources/vphone-cli/VPhoneMenuConnect.swift
index 3ff00885..47c650fc 100644
--- a/sources/vphone-cli/VPhoneMenuConnect.swift
+++ b/sources/vphone-cli/VPhoneMenuConnect.swift
@@ -44,19 +44,19 @@ extension VPhoneMenuController {
clipboardGetItem = clipGet
menu.addItem(clipGet)
- let clipSet = makeItem("Set Clipboard Text...", action: #selector(setClipboardText))
+ let clipSet = makeItem("Set Clipboard Text…", action: #selector(setClipboardText))
clipSet.isEnabled = false
clipboardSetItem = clipSet
menu.addItem(clipSet)
menu.addItem(NSMenuItem.separator())
- let settingsGet = makeItem("Read Setting...", action: #selector(readSetting))
+ let settingsGet = makeItem("Read Setting…", action: #selector(readSetting))
settingsGet.isEnabled = false
settingsGetItem = settingsGet
menu.addItem(settingsGet)
- let settingsSet = makeItem("Write Setting...", action: #selector(writeSetting))
+ let settingsSet = makeItem("Write Setting…", action: #selector(writeSetting))
settingsSet.isEnabled = false
settingsSetItem = settingsSet
menu.addItem(settingsSet)
@@ -95,14 +95,19 @@ extension VPhoneMenuController {
@objc func devModeStatus() {
Task {
do {
- let status = try await control.sendDevModeStatus()
+ let enabled = try await control.sendDevModeStatus()
showAlert(
title: "Developer Mode",
- message: status.enabled ? "Developer Mode is enabled." : "Developer Mode is disabled.",
+ message: enabled ? "Developer Mode is enabled." : "Developer Mode is disabled.",
style: .informational
)
} catch {
- showAlert(title: "Developer Mode", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Developer Mode",
+ message: "Unable to read Developer Mode status. Check that the guest agent is connected, "
+ + "then try again.",
+ style: .warning
+ )
}
}
}
@@ -111,9 +116,13 @@ extension VPhoneMenuController {
Task {
do {
try await control.sendPing()
- showAlert(title: "Ping", message: "pong", style: .informational)
+ showAlert(title: "Ping", message: "The guest responded.", style: .informational)
} catch {
- showAlert(title: "Ping", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Ping",
+ message: "The guest did not respond. Check that the guest agent is connected, then try again.",
+ style: .warning
+ )
}
}
}
@@ -122,9 +131,14 @@ extension VPhoneMenuController {
Task {
do {
let hash = try await control.sendVersion()
- showAlert(title: "Guest Version", message: "build: \(hash)", style: .informational)
+ showAlert(title: "Guest Version", message: "Build \(hash)", style: .informational)
} catch {
- showAlert(title: "Guest Version", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Guest Version",
+ message: "Unable to read the guest version. Check that the guest agent is connected, "
+ + "then try again.",
+ style: .warning
+ )
}
}
}
@@ -142,15 +156,19 @@ extension VPhoneMenuController {
let content = try await control.clipboardGet()
var message = ""
if let text = content.text {
- let truncated = text.count > 500 ? String(text.prefix(500)) + "..." : text
+ let truncated = text.count > 500 ? String(text.prefix(500)) + "…" : text
message += "Text: \(truncated)\n"
}
message += "Types: \(content.types.joined(separator: ", "))\n"
- message += "Has Image: \(content.hasImage)\n"
+ message += "Image: \(content.hasImage ? "Yes" : "No")\n"
message += "Change Count: \(content.changeCount)"
showAlert(title: "Clipboard Content", message: message, style: .informational)
} catch {
- showAlert(title: "Clipboard", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Clipboard",
+ message: "Unable to read the guest clipboard. Try again.",
+ style: .warning
+ )
}
}
}
@@ -201,7 +219,11 @@ extension VPhoneMenuController {
try await control.clipboardSet(text: text)
showAlert(title: "Clipboard", message: "Text set successfully.", style: .informational)
} catch {
- showAlert(title: "Clipboard", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Clipboard",
+ message: "Unable to set the guest clipboard. Try again.",
+ style: .warning
+ )
}
}
}
@@ -267,16 +289,20 @@ extension VPhoneMenuController {
)
display = String(data: data, encoding: .utf8) ?? "\(dict)"
} else {
- display = "\(value ?? "nil")"
+ display = "\(value ?? "Not set")"
}
- let truncated = display.count > 2000 ? String(display.prefix(2000)) + "\n..." : display
+ let truncated = display.count > 2000 ? String(display.prefix(2000)) + "\n…" : display
showAlert(
title: "Setting: \(domain)\(key.map { ".\($0)" } ?? "")",
message: truncated,
style: .informational
)
} catch {
- showAlert(title: "Read Setting", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Read Setting",
+ message: "Unable to read that setting. Check the domain and key, then try again.",
+ style: .warning
+ )
}
}
}
@@ -304,7 +330,7 @@ extension VPhoneMenuController {
let lbl3 = NSTextField(labelWithString: "Type:")
lbl3.frame = NSRect(x: 20, y: 98, width: 380, height: 18)
let typeField = NSTextField(frame: NSRect(x: 20, y: 72, width: 380, height: 22))
- typeField.placeholderString = "Type: boolean | string | integer | float"
+ typeField.placeholderString = "boolean | string | integer | float"
let lbl4 = NSTextField(labelWithString: "Value:")
lbl4.frame = NSRect(x: 20, y: 48, width: 380, height: 18)
@@ -368,7 +394,11 @@ extension VPhoneMenuController {
style: .informational
)
} catch {
- showAlert(title: "Write Setting", message: "\(error)", style: .warning)
+ showAlert(
+ title: "Write Setting",
+ message: "Unable to write that setting. Check the domain, key and type, then try again.",
+ style: .warning
+ )
}
}
}
diff --git a/sources/vphone-cli/VPhoneMenuRecord.swift b/sources/vphone-cli/VPhoneMenuRecord.swift
index 100d6189..274b2caf 100644
--- a/sources/vphone-cli/VPhoneMenuRecord.swift
+++ b/sources/vphone-cli/VPhoneMenuRecord.swift
@@ -27,14 +27,18 @@ extension VPhoneMenuController {
}
} else {
guard let view = activeCaptureView() else {
- showAlert(title: "Recording", message: "No active VM window.", style: .warning)
+ showAlert(
+ title: "Recording",
+ message: "No VM window is open. Start a VM, then try again.",
+ style: .warning
+ )
return
}
do {
try screenRecorder?.startRecording(view: view)
recordingItem?.title = "Stop Recording"
} catch {
- showAlert(title: "Recording", message: "\(error)", style: .warning)
+ showAlert(title: "Recording", message: "Unable to start recording. Try again.", style: .warning)
}
}
}
@@ -42,7 +46,11 @@ extension VPhoneMenuController {
@objc func copyScreenshotToClipboard() {
guard let recorder = screenRecorder else { return }
guard let view = activeCaptureView() else {
- showAlert(title: "Screenshot", message: "No active VM window.", style: .warning)
+ showAlert(
+ title: "Screenshot",
+ message: "No VM window is open. Start a VM, then try again.",
+ style: .warning
+ )
return
}
@@ -51,7 +59,7 @@ extension VPhoneMenuController {
try await recorder.copyScreenshotToPasteboard(view: view)
showAlert(title: "Screenshot", message: "Copied to clipboard.", style: .informational)
} catch {
- showAlert(title: "Screenshot", message: "\(error)", style: .warning)
+ showAlert(title: "Screenshot", message: "Unable to copy the screenshot. Try again.", style: .warning)
}
}
}
@@ -59,7 +67,11 @@ extension VPhoneMenuController {
@objc func saveScreenshotToFile() {
guard let recorder = screenRecorder else { return }
guard let view = activeCaptureView() else {
- showAlert(title: "Screenshot", message: "No active VM window.", style: .warning)
+ showAlert(
+ title: "Screenshot",
+ message: "No VM window is open. Start a VM, then try again.",
+ style: .warning
+ )
return
}
@@ -68,7 +80,7 @@ extension VPhoneMenuController {
let url = try await recorder.saveScreenshot(view: view)
showAlert(title: "Screenshot", message: "Saved to \(url.path)", style: .informational)
} catch {
- showAlert(title: "Screenshot", message: "\(error)", style: .warning)
+ showAlert(title: "Screenshot", message: "Unable to save the screenshot. Try again.", style: .warning)
}
}
}
@@ -107,14 +119,6 @@ extension VPhoneMenuController {
panel.contentView?.addSubview(reveal)
panel.contentView?.addSubview(ok)
- var shouldReveal = false
- reveal.target = nil
- reveal.action = nil
-
- let capturedURL = url
- reveal.target = NSApp
- reveal.action = #selector(NSApplication.stopModal(withCode:))
-
// Use a custom approach: reveal button stops modal with code 100
class RevealHelper: NSObject {
var action: () -> Void
@@ -131,7 +135,7 @@ extension VPhoneMenuController {
panel.orderOut(nil)
if response.rawValue == 100 {
- NSWorkspace.shared.activateFileViewerSelecting([capturedURL])
+ NSWorkspace.shared.activateFileViewerSelecting([url])
}
}
}
diff --git a/sources/vphone-cli/VPhoneScreenRecorder.swift b/sources/vphone-cli/VPhoneScreenRecorder.swift
index 1269438c..10cba51a 100644
--- a/sources/vphone-cli/VPhoneScreenRecorder.swift
+++ b/sources/vphone-cli/VPhoneScreenRecorder.swift
@@ -17,20 +17,15 @@ class VPhoneScreenRecorder {
var errorDescription: String? {
switch self {
case .captureFailed:
- "Failed to capture a frame from the virtual machine."
+ "Unable to capture the screen. Try again."
case .clipboardWriteFailed:
- "Failed to copy the screenshot to the pasteboard."
+ "Unable to copy the screenshot to the clipboard. Try again."
case .encodingFailed:
- "Failed to encode the screenshot as PNG."
+ "Unable to save the screenshot. Try again."
}
}
}
- private struct CaptureSource {
- let graphicsDisplay: VZGraphicsDisplay
- let description: String
- }
-
private typealias ScreenshotCompletionBlock = @convention(block) (AnyObject?) -> Void
private typealias ScreenshotIMP = @convention(c) (AnyObject, Selector, AnyObject) -> Void
@@ -41,7 +36,6 @@ class VPhoneScreenRecorder {
private var frameCount: Int64 = 0
private var outputURL: URL?
private var graphicsDisplay: VZGraphicsDisplay?
- private var captureModeDescription = "private VZGraphicsDisplay screenshots"
private var screenshotInFlight = false
private var didLogCaptureFailure = false
@@ -52,8 +46,8 @@ class VPhoneScreenRecorder {
func startRecording(view: NSView) throws {
guard !isRecording else { return }
- let source = try resolveCaptureSource(for: view)
- let captureSize = source.graphicsDisplay.sizeInPixels
+ let display = try resolveCaptureSource(for: view)
+ let captureSize = display.sizeInPixels
let width = max(Int(captureSize.width), 1)
let height = max(Int(captureSize.height), 1)
@@ -87,8 +81,7 @@ class VPhoneScreenRecorder {
self.writer = writer
videoInput = input
self.adaptor = adaptor
- graphicsDisplay = source.graphicsDisplay
- captureModeDescription = source.description
+ graphicsDisplay = display
frameCount = 0
screenshotInFlight = false
didLogCaptureFailure = false
@@ -101,7 +94,7 @@ class VPhoneScreenRecorder {
}
print(
- "[record] started - \(url.lastPathComponent) (\(width)x\(height), source: \(captureModeDescription))"
+ "[record] started - \(url.lastPathComponent) (\(width)x\(height), source: private VZGraphicsDisplay screenshots)"
)
}
@@ -210,9 +203,9 @@ class VPhoneScreenRecorder {
}
}
- private func captureStillImage(from view: NSView) async throws -> CGImage {
- let source = try resolveCaptureSource(for: view)
- guard let cgImage = await takeGraphicsScreenshot(from: source.graphicsDisplay) else {
+ func captureStillImage(from view: NSView) async throws -> CGImage {
+ let display = try resolveCaptureSource(for: view)
+ guard let cgImage = await takeGraphicsScreenshot(from: display) else {
throw CaptureError.captureFailed
}
return cgImage
@@ -248,17 +241,14 @@ class VPhoneScreenRecorder {
frameCount += 1
}
- private func resolveCaptureSource(for view: NSView) throws -> CaptureSource {
+ private func resolveCaptureSource(for view: NSView) throws -> VZGraphicsDisplay {
guard let vmView = view as? VPhoneVirtualMachineView,
let graphicsDisplay = vmView.recordingGraphicsDisplay
else {
throw CaptureError.captureFailed
}
- return CaptureSource(
- graphicsDisplay: graphicsDisplay,
- description: "private VZGraphicsDisplay screenshots"
- )
+ return graphicsDisplay
}
private func takeGraphicsScreenshot(
diff --git a/sources/vphone-cli/VPhoneVirtualMachine.swift b/sources/vphone-cli/VPhoneVirtualMachine.swift
index 14c80ae5..b03847ef 100644
--- a/sources/vphone-cli/VPhoneVirtualMachine.swift
+++ b/sources/vphone-cli/VPhoneVirtualMachine.swift
@@ -55,33 +55,15 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
let machineIdentifier: VZMacMachineIdentifier
var manifest = try VPhoneVirtualMachineManifest.load(from: options.configURL)
- if manifest.machineIdentifier.isEmpty {
- // Create new machineIdentifier and save to manifest
- let newID = VZMacMachineIdentifier()
- machineIdentifier = newID
-
- // Update manifest with new machineIdentifier
- manifest = VPhoneVirtualMachineManifest(
- platformType: manifest.platformType,
- platformFusing: manifest.platformFusing,
- machineIdentifier: newID.dataRepresentation,
- cpuCount: manifest.cpuCount,
- memorySize: manifest.memorySize,
- screenConfig: manifest.screenConfig,
- networkConfig: manifest.networkConfig,
- diskImage: manifest.diskImage,
- nvramStorage: manifest.nvramStorage,
- romImages: manifest.romImages,
- sepStorage: manifest.sepStorage
- )
- try manifest.write(to: options.configURL)
-
- print("[vphone] Created new machineIdentifier -> saved to config.plist")
- } else if let savedID = VZMacMachineIdentifier(dataRepresentation: manifest.machineIdentifier) {
+ if !manifest.machineIdentifier.isEmpty,
+ let savedID = VZMacMachineIdentifier(dataRepresentation: manifest.machineIdentifier)
+ {
machineIdentifier = savedID
print("[vphone] Loaded machineIdentifier from config.plist (ECID stable)")
} else {
- // Invalid data in manifest, create new
+ let reason = manifest.machineIdentifier.isEmpty
+ ? "Created new machineIdentifier -> saved to config.plist"
+ : "Invalid machineIdentifier in config.plist, created new"
let newID = VZMacMachineIdentifier()
machineIdentifier = newID
@@ -100,7 +82,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
)
try manifest.write(to: options.configURL)
- print("[vphone] Invalid machineIdentifier in config.plist, created new")
+ print("[vphone] \(reason)")
}
// --- Platform ---
diff --git a/sources/vphone-cli/VPhoneVirtualMachineView.swift b/sources/vphone-cli/VPhoneVirtualMachineView.swift
index 6d3f3f5e..8154e314 100644
--- a/sources/vphone-cli/VPhoneVirtualMachineView.swift
+++ b/sources/vphone-cli/VPhoneVirtualMachineView.swift
@@ -93,8 +93,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {
return .copy
}
- override func draggingExited(_ sender: (any NSDraggingInfo)?) {
- _ = sender
+ override func draggingExited(_: (any NSDraggingInfo)?) {
updateDragHighlight(false)
}
@@ -107,11 +106,7 @@ class VPhoneVirtualMachineView: VZVirtualMachineView {
guard let url = droppedInstallPackageURL(from: sender) else { return false }
Task { @MainActor in
- guard let control else {
- showAlert(title: "Install App Package", message: "Guest is not connected.", style: .warning)
- return
- }
- guard control.isConnected else {
+ guard let control, control.isConnected else {
showAlert(title: "Install App Package", message: "Guest is not connected.", style: .warning)
return
}
diff --git a/sources/vphone-cli/VPhoneWindowController.swift b/sources/vphone-cli/VPhoneWindowController.swift
index d5ec7cf6..f8903900 100644
--- a/sources/vphone-cli/VPhoneWindowController.swift
+++ b/sources/vphone-cli/VPhoneWindowController.swift
@@ -46,7 +46,7 @@ class VPhoneWindowController: NSObject, NSToolbarDelegate {
window.isReleasedWhenClosed = false
window.contentAspectRatio = windowSize
- window.title = "VPHONE [loading]"
+ window.title = "vphone — Starting…"
window.subtitle = makeSubtitle(ip: nil)
window.contentView = vmView
if let ecid {
@@ -82,7 +82,7 @@ class VPhoneWindowController: NSObject, NSToolbarDelegate {
[weak self, weak window] _ in
Task { @MainActor in
guard let self, let window, let control = self.control else { return }
- window.title = control.isConnected ? "VPHONE [connected]" : "VPHONE [disconnected]"
+ window.title = control.isConnected ? "vphone — Connected" : "vphone — Disconnected"
window.subtitle = self.makeSubtitle(ip: control.isConnected ? control.guestIP : nil)
}
}
diff --git a/tests/VPhoneCoreTests/LaunchLayoutTests.swift b/tests/VPhoneCoreTests/LaunchLayoutTests.swift
index 511d8faf..cc72995e 100644
--- a/tests/VPhoneCoreTests/LaunchLayoutTests.swift
+++ b/tests/VPhoneCoreTests/LaunchLayoutTests.swift
@@ -8,17 +8,9 @@ struct LaunchLayoutTests {
#expect(layout.preflightScript.path == "/proj/scripts/boot_host_preflight.sh")
}
- @Test func resolvesToolPaths() {
- let layout = VPhoneLaunchLayout(projectRoot: URL(fileURLWithPath: "/proj"))
- #expect(layout.fwPrepareScript.path == "/proj/scripts/fw_prepare.sh")
- #expect(layout.cfwInstallHostScript.path == "/proj/scripts/cfw_install_host.sh")
- #expect(layout.pmd3Bridge.path == "/proj/scripts/pymobiledevice3_bridge.py")
- }
-
@Test func delegatesToResources() {
let resources = VPhoneResources(base: URL(fileURLWithPath: "/proj"))
let layout = VPhoneLaunchLayout(resources: resources)
- #expect(layout.fwPrepareScript.path == resources.fwPrepareScript.path)
#expect(layout.vphoned.path == resources.vphoned.path)
}
diff --git a/tests/VPhoneCoreTests/ManifestTests.swift b/tests/VPhoneCoreTests/ManifestTests.swift
index 69bb0c0f..a4f94dcf 100644
--- a/tests/VPhoneCoreTests/ManifestTests.swift
+++ b/tests/VPhoneCoreTests/ManifestTests.swift
@@ -28,7 +28,7 @@ struct ManifestTests {
}
@Test func updatingReplacesOnlyGivenFields() {
- let updated = sampleManifest().updating(cpuCount: 4, memorySize: nil, screenConfig: nil)
+ let updated = sampleManifest().updating(cpuCount: 4, memorySize: nil)
#expect(updated.cpuCount == 4)
#expect(updated.memorySize == 8 * 1024 * 1024 * 1024)
// networkConfig is preserved when not passed.
diff --git a/tests/VPhoneCoreTests/ResourcesTests.swift b/tests/VPhoneCoreTests/ResourcesTests.swift
index 4a721501..7937a726 100644
--- a/tests/VPhoneCoreTests/ResourcesTests.swift
+++ b/tests/VPhoneCoreTests/ResourcesTests.swift
@@ -26,12 +26,10 @@ struct ResourcesTests {
.appendingPathComponent("scripts/resources").path)
}
- @Test func cacheDirsAreHomeRelativeAndToolsBinIsBaseRelative() {
+ @Test func cacheDirsAreHomeRelative() {
// The VPHONE_ROOT override would relocate the cache; only assert the default.
if ProcessInfo.processInfo.environment["VPHONE_ROOT"] != nil { return }
- let r = VPhoneResources(base: URL(fileURLWithPath: "/Applications/vphone-cli.app/Contents/Resources"))
- #expect(r.userCacheDir.path.hasSuffix("/.vphone"))
- #expect(r.toolsBinDir.path == r.base.appendingPathComponent(".tools/bin").path)
+ #expect(VPhoneResources.userDataRoot().path.hasSuffix("/.vphone"))
}
/// These all shell out; a missing interpreter must return false, not throw.
@@ -52,12 +50,12 @@ struct ResourcesTests {
#expect(r.managedVenvDir.path.hasSuffix("/.vphone/venv"))
}
- @Test func userCacheDirHonorsVPHONERoot() {
+ @Test func userDataRootHonorsVPHONERoot() {
unsetenv("VPHONE_VENV_DIR")
setenv("VPHONE_ROOT", "/tmp/vphone-test-root", 1)
defer { unsetenv("VPHONE_ROOT") }
let r = VPhoneResources(base: URL(fileURLWithPath: "/x"))
- #expect(r.userCacheDir.path == "/tmp/vphone-test-root")
+ #expect(VPhoneResources.userDataRoot().path == "/tmp/vphone-test-root")
#expect(r.ipswCacheDir.path == "/tmp/vphone-test-root/ipsws")
#expect(r.sealVolumeCacheDir.path == "/tmp/vphone-test-root/tools")
#expect(r.debsCacheDir.path == "/tmp/vphone-test-root/debs")
diff --git a/tools/apfs_snap_rename.py b/tools/apfs_snap_rename.py
index 92d93429..0334fbba 100755
--- a/tools/apfs_snap_rename.py
+++ b/tools/apfs_snap_rename.py
@@ -14,7 +14,9 @@
# Auto-detects the com.apple.os.update-* snapshot; only edits records that
# live in a valid APFS object block (checksum verified), so identical
# strings baked into on-volume binaries are never touched.
-import struct, sys, mmap
+import mmap
+import struct
+import sys
BS = 4096
OLD_PREFIX = b"com.apple.os.update-" # 20 bytes
@@ -36,56 +38,58 @@ def main():
args = [a for a in args if a != "--dry-run"]
new_prefix = b"orig-fs.disabled.rn-"
if "--new-prefix" in args:
- i = args.index("--new-prefix"); new_prefix = args[i+1].encode(); del args[i:i+2]
+ i = args.index("--new-prefix")
+ new_prefix = args[i+1].encode()
+ del args[i:i+2]
if not args:
sys.exit("usage: apfs_snap_rename.py <Disk.img> [--dry-run] [--new-prefix PREFIX]")
img = args[0]
if len(new_prefix) != len(OLD_PREFIX):
sys.exit("--new-prefix must be exactly %d bytes" % len(OLD_PREFIX))
- f = open(img, 'r+b')
- mm = mmap.mmap(f.fileno(), 0)
+ with open(img, 'r+b') as f, mmap.mmap(f.fileno(), 0) as mm:
+ # Auto-detect: every "com.apple.os.update-" followed by 64 hex chars, that
+ # sits inside a block whose APFS fletcher64 verifies (i.e. a real metadata
+ # object, not a string constant inside a Mach-O on the volume).
+ hits = {} # block_off -> list of within-block offsets
+ i = 0
+ name = None
+ while True:
+ j = mm.find(OLD_PREFIX, i)
+ if j < 0:
+ break
+ i = j + 1
+ hexpart = mm[j+len(OLD_PREFIX):j+len(OLD_PREFIX)+64]
+ if len(hexpart) < 64 or any(c not in HEXSET for c in hexpart):
+ continue # not a snapshot name
+ blk = (j // BS) * BS
+ block = bytes(mm[blk:blk+BS])
+ if cksum(block) != struct.unpack('<Q', block[0:8])[0]:
+ continue # not a valid APFS object block
+ if name is None:
+ name = mm[j:j+len(OLD_PREFIX)+64].decode(errors="replace")
+ hits.setdefault(blk, []).append(j - blk)
- # Auto-detect: every "com.apple.os.update-" followed by 64 hex chars, that
- # sits inside a block whose APFS fletcher64 verifies (i.e. a real metadata
- # object, not a string constant inside a Mach-O on the volume).
- hits = {} # block_off -> list of (within, fullname)
- i = 0
- while True:
- j = mm.find(OLD_PREFIX, i)
- if j < 0:
- break
- i = j + 1
- hexpart = mm[j+len(OLD_PREFIX):j+len(OLD_PREFIX)+64]
- if len(hexpart) < 64 or any(c not in HEXSET for c in hexpart):
- continue # not a snapshot name
- blk = (j // BS) * BS
- block = bytes(mm[blk:blk+BS])
- if cksum(block) != struct.unpack('<Q', block[0:8])[0]:
- continue # not a valid APFS object block
- hits.setdefault(blk, []).append((j - blk, mm[j:j+len(OLD_PREFIX)+64]))
+ if not hits:
+ print("No com.apple.os.update-* root snapshot found. The snapshot may already be renamed.")
+ return
- if not hits:
- print("no com.apple.os.update-* root snapshot found (already flipped?)")
- mm.close(); f.close(); return
+ total = sum(len(v) for v in hits.values())
+ print("Detected snapshot: %s" % name)
+ print("Records: %d in %d block(s): %s" % (total, len(hits), [hex(b) for b in hits]))
+ if dry:
+ print("Dry run: the prefix would be renamed to %s." % new_prefix.decode())
+ return
- total = sum(len(v) for v in hits.values())
- name = next(iter(hits.values()))[0][1].decode(errors="replace")
- print("detected snapshot: %s" % name)
- print("records: %d in %d block(s): %s" % (total, len(hits), [hex(b) for b in hits]))
- if dry:
- print("[dry-run] would rename prefix -> %s" % new_prefix.decode())
- mm.close(); f.close(); return
-
- for blk, recs in sorted(hits.items()):
- block = bytearray(mm[blk:blk+BS])
- for within, _ in recs:
- assert bytes(block[within:within+len(OLD_PREFIX)]) == OLD_PREFIX
- block[within:within+len(new_prefix)] = new_prefix
- block[0:8] = struct.pack('<Q', cksum(bytes(block)))
- mm[blk:blk+BS] = bytes(block)
- print("block @0x%x: renamed %d record(s), checksum fixed" % (blk, len(recs)))
- mm.flush(); mm.close(); f.close()
- print("done: root snapshot renamed -> %s* (VM will boot the live volume)" % new_prefix.decode())
+ for blk, recs in sorted(hits.items()):
+ block = bytearray(mm[blk:blk+BS])
+ for within in recs:
+ assert bytes(block[within:within+len(OLD_PREFIX)]) == OLD_PREFIX
+ block[within:within+len(new_prefix)] = new_prefix
+ block[0:8] = struct.pack('<Q', cksum(bytes(block)))
+ mm[blk:blk+BS] = bytes(block)
+ print("Block 0x%x: renamed %d record(s) and fixed the checksum." % (blk, len(recs)))
+ mm.flush()
+ print("Done. Root snapshot renamed to %s*. The VM will boot the live volume." % new_prefix.decode())
main()