Run a virtual iPhone on an Apple Silicon Mac.
Swift
vm create --bootstrap: install Irisin and owngoal-bootstrap-vphone at first boot
zqxwcef9cca2f47c3a
diff --git a/Documents/Guides/package-environment.md b/Documents/Guides/package-environment.mdindex dab6f3bf..1da57fa8 100644--- a/Documents/Guides/package-environment.md+++ b/Documents/Guides/package-environment.md@@ -8,6 +8,8 @@ The VM has no package manager by default. To install one:This one package brings in everything a VM needs in a single pass: `apt` and `dpkg`, `bash`, `zsh` and `dash`, `sudo`, the core command-line tools, `openssh-server`, `curl`, `wget`, `vim`, `git`, `uikittools`, `launchctl`, and the OwnGoal apps. Do not install these packages one by one: several depend on one another, and `openssh-server` declares some dependencies circularly, so separate installs can fail partway.3. After the first installation, install further packages normally.+`vphone-cli vm create <name> --bootstrap roothide` does steps 1 and 2 during the new machine's first boot: it installs Irisin, then `owngoal-bootstrap-vphone` with Bootstrap Install through `irisin-cli`, from the repositories Irisin recommends. Step 2 needs an Irisin whose `irisin-cli install` has `--repository` and `--bootstrap-install`.+If the first installation fails, do not repair it in place. Choose **Apps > Uninstall Bootstrap…**, then start again from step 1.## Remove the Environmentdiff --git a/VPhoneDaemon/Daemon/Bootstrap/GuestBootstrapPlatform.swift b/VPhoneDaemon/Daemon/Bootstrap/GuestBootstrapPlatform.swiftindex 97aed9df..463c0fee 100644--- a/VPhoneDaemon/Daemon/Bootstrap/GuestBootstrapPlatform.swift+++ b/VPhoneDaemon/Daemon/Bootstrap/GuestBootstrapPlatform.swift@@ -29,6 +29,20 @@ enum GuestBootstrapPlatform {!architecture.hasPrefix("appletvos-")}+ /// The repositories Irisin's onboarding offers, as its+ /// `RecommendedRepositories` picks them from the app's bundle: the+ /// managed list when it has entries, else the one for the app's+ /// bootstrap, each entry kept when `majorVersion` is within its bounds.+ static func recommendedSources(managed: [[String: Any]]?, packaged: [[String: Any]]?, majorVersion: Int) -> [String] {+ let list = [managed, packaged].lazy.compactMap(\.self).first { !$0.isEmpty } ?? []+ return list.compactMap { entry in+ guard let source = entry["source"] as? String else { return nil }+ if let minimum = entry["minimumSystemVersion"] as? Int, majorVersion < minimum { return nil }+ if let maximum = entry["maximumSystemVersion"] as? Int, majorVersion > maximum { return nil }+ return source+ }+ }+/// Whether dyld runs this process as tvOS.static let isTVOS = mainExecutablePlatform() == UInt32(PLATFORM_TVOS)diff --git a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+InitialPackages.swift b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+InitialPackages.swiftnew file mode 100644index 00000000..1f49d55b--- /dev/null+++ b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+InitialPackages.swift@@ -0,0 +1,94 @@+import Darwin+import Foundation+import VphonedNative++// MARK: - Initial packages++extension GuestIrisinInstaller {+ /// What a guest installs first: the base system, apt and dpkg, the+ /// shells, OpenSSH and the OwnGoal apps, in one transaction.+ static let initialPackages = ["owngoal-bootstrap-vphone"]++ /// The first package installation, through Irisin's own command line:+ /// `irisin-cli install --bootstrap-install` from the repositories+ /// Irisin's onboarding recommends, which irisin-cli refreshes into a+ /// catalogue of its own. Bootstrap Install places every package's files+ /// before any script runs: a first installation's scripts need the shell+ /// and tools the same transaction brings. The app's catalogue is left+ /// alone; the repositories are the app's to add when it is opened.+ static func installPackages(_ packages: [String]) throws -> [String: Any] {+ guard !GuestBootstrapPlatform.isTVOS else {+ return ["packages": [String](), "skipped": "Irisin's Apple TV package has no irisin-cli"]+ }+ installLock.lock()+ defer { installLock.unlock() }+ guard let installation = try completedBootstrap() else {+ throw GuestAPIError.operationFailed("Install the bootstrap before its packages")+ }+ let cli = installation.root + "/usr/bin/irisin-cli"+ guard access(cli, X_OK) == 0 else {+ throw GuestAPIError.operationFailed("This Irisin has no irisin-cli")+ }+ let help = try run(cli, ["install", "--help"])+ guard help.output.contains("--bootstrap-install"), help.output.contains("--repository") else {+ throw GuestAPIError.operationFailed(+ "This Irisin's irisin-cli cannot install from named repositories with Bootstrap Install; a newer Irisin can"+ )+ }+ let repositories = try recommendedRepositories(root: installation.root)+ setProgress(["phase": "packages", "layout": installation.layout, "packages": packages])+ let arguments = ["install", "-y", "--bootstrap-install"]+ + repositories.flatMap { ["--repository", $0] } + packages+ let result = try run(cli, arguments)+ guard result.status == 0 else {+ let lines = (result.output + result.errors).split(separator: "\n").suffix(6).joined(separator: "\n")+ let error = "irisin-cli install exited with status \(result.status):\n\(lines)"+ setProgress(["phase": "failed", "layout": installation.layout, "packages": packages, "error": error])+ throw GuestAPIError.operationFailed(error)+ }+ setProgress(["phase": "completed", "layout": installation.layout, "packages": packages])+ return ["packages": packages, "repositories": repositories, "jbroot": installation.root]+ }++ private static func recommendedRepositories(root: String) throws -> [String] {+ let app = URL(fileURLWithPath: root + "/Applications/irisin.app", isDirectory: true)+ guard let architecture = NSDictionary(contentsOf: app.appendingPathComponent("Info.plist"))?["IrisinCurrentArchitecture"] as? String else {+ throw GuestAPIError.operationFailed("Irisin's Info.plist names no bootstrap architecture")+ }+ func list(_ name: String) -> [[String: Any]]? {+ NSArray(contentsOf: app.appendingPathComponent(name + ".plist")) as? [[String: Any]]+ }+ let sources = GuestBootstrapPlatform.recommendedSources(+ managed: list("default-list-managed"),+ packaged: list("default-list-\(architecture)"),+ majorVersion: ProcessInfo.processInfo.operatingSystemVersion.majorVersion,+ )+ guard !sources.isEmpty else {+ throw GuestAPIError.operationFailed("Irisin recommends no repositories for \(architecture) on this system")+ }+ return sources+ }++ private static func run(_ path: String, _ arguments: [String]) throws -> (status: Int32, output: String, errors: String) {+ let words = [path] + arguments+ var argv: [UnsafePointer<CChar>?] = words.map { UnsafePointer(strdup($0)) } + [nil]+ defer { argv.forEach { free(UnsafeMutablePointer(mutating: $0)) } }+ var status: Int32 = 0+ var output: UnsafeMutablePointer<CChar>?+ var errors: UnsafeMutablePointer<CChar>?+ defer {+ free(output)+ free(errors)+ }+ let failure = vp_spawn_collect(path, &argv, nil, &status, &output, &errors)+ guard failure == 0 else {+ throw GuestAPIError.operationFailed("\(path): \(String(cString: strerror(failure)))")+ }+ let signal = status & 0x7F+ return (+ signal == 0 ? (status >> 8) & 0xFF : -1,+ output.map { String(cString: $0) } ?? "",+ errors.map { String(cString: $0) } ?? "",+ )+ }+}diff --git a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+Release.swift b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+Release.swiftindex 46447c52..8211072a 100644--- a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+Release.swift+++ b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller+Release.swift@@ -83,6 +83,8 @@ extension GuestIrisinInstaller {let configuration = URLSessionConfiguration.ephemeralconfiguration.timeoutIntervalForRequest = 30configuration.timeoutIntervalForResource = 180+ // A guest that has just booted may not have a route yet.+ configuration.waitsForConnectivity = truelet session = URLSession(configuration: configuration)defer { session.invalidateAndCancel() }var request = URLRequest(url: url)diff --git a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swiftindex 79ff238f..b166961f 100644--- a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift+++ b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift@@ -230,7 +230,7 @@ enum GuestIrisinInstaller {// MARK: - Progress- private static func setProgress(_ value: [String: Any]) {+ static func setProgress(_ value: [String: Any]) {progressLock.lock()progress = valueprogressLock.unlock()diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 8e9ab27b..a5030729 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -110,6 +110,7 @@ enum GuestAPI {"keychain_edit","ipa_install","bootstrap_install",+ "bootstrap_packages","bootstrap_uninstall","port_forward","camera",@@ -299,6 +300,8 @@ enum GuestAPI {layout: layout,packagePath: params["package_path"] as? String,)+ case "bootstrap.packages":+ return try GuestIrisinInstaller.installPackages(GuestIrisinInstaller.initialPackages)case "bootstrap.status":return GuestIrisinInstaller.status()case "bootstrap.inspect":diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 7c40437a..3f8f004f 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -232,6 +232,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlecase (.POST, "/v1/apps/open-url"): "apps.open_url"case (.POST, "/v1/apps/install"): "apps.install"case (.POST, "/v1/bootstrap/install"): "bootstrap.install"+ case (.POST, "/v1/bootstrap/packages"): "bootstrap.packages"case (.GET, "/v1/bootstrap/status"): "bootstrap.status"case (.GET, "/v1/bootstrap/inspect"): "bootstrap.inspect"case (.POST, "/v1/bootstrap/uninstall"): "bootstrap.uninstall"diff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swiftindex c4b7b562..b8cebb10 100644--- a/VPhoneDaemon/Tests/LogicTests.swift+++ b/VPhoneDaemon/Tests/LogicTests.swift@@ -480,5 +480,17 @@ enum LogicTests {expect(!GuestBootstrapPlatform.packageRequiresApp(architecture: "appletvos-arm64e"), "the Apple TV package has none")expectEqual(GuestBootstrapPlatform.mainExecutablePlatform(), UInt32(PLATFORM_MACOS), "this test runs as macOS")expect(!GuestBootstrapPlatform.isTVOS, "the Mac is not tvOS")++ // Irisin 5.1.4's roothide list+ let roothide: [[String: Any]] = [+ ["source": "deb https://roothide.github.io/procursus iphoneos-arm64e/1800 main", "maximumSystemVersion": 15],+ ["source": "deb https://stripe.owngoal.dev 1900 main", "minimumSystemVersion": 16],+ ["source": "https://apt.owngoal.dev"],+ ]+ let sources = GuestBootstrapPlatform.recommendedSources+ expectEqual(sources([], roothide, 27), ["deb https://stripe.owngoal.dev 1900 main", "https://apt.owngoal.dev"])+ expectEqual(sources(nil, roothide, 15), ["deb https://roothide.github.io/procursus iphoneos-arm64e/1800 main", "https://apt.owngoal.dev"])+ expectEqual(sources([["source": "https://repo.example"]], roothide, 27), ["https://repo.example"], "a managed list with entries wins")+ expectEqual(sources(nil, nil, 27), [], "no list recommends nothing")}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swiftindex e6e7e365..37b2ea84 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateCommand.swift@@ -83,6 +83,11 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {var noTemplate = false@Flag(help: "Do not boot the new VM to check that vphoned answers")var skipFirstBoot = false+ @Option(help: ArgumentHelp(+ "During the first boot, install the Irisin bootstrap in this layout, then owngoal-bootstrap-vphone through irisin-cli: roothide | rootless (deprecated; not on tvOS)",+ valueName: "layout",+ ))+ var bootstrap: String?@OptionGroup(title: "Template slimming") var slimming: VPhoneTemplateSlimmingOptions@Flag(name: .customLong("keep-artifacts"),@@ -160,6 +165,17 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {if iphoneSource != nil, iphoneVersion != nil || iphoneBuild != nil {throw ValidationError("Use either --iphone-source or --iphone-version/--iphone-build.")}+ if let bootstrap {+ guard bootstrap == "roothide" || bootstrap == "rootless" else {+ throw ValidationError("--bootstrap takes roothide or rootless, not \(bootstrap).")+ }+ if skipFirstBoot {+ throw ValidationError("--bootstrap installs during the first boot; --skip-first-boot leaves it out.")+ }+ if bootstrap == "rootless", usesTVOS {+ throw ValidationError("Irisin serves only a roothide bootstrap on tvOS.")+ }+ }if template != nil, noTemplate {throw ValidationError("--template and --no-template exclude each other.")}@@ -308,6 +324,7 @@ struct VPhoneVirtualMachineCreateCommand: ParsableCommand {slimming: slimming.request.isEmpty ? nil : slimming.resolve(),),skipsFirstBoot: skipFirstBoot,+ bootstrapLayout: bootstrap,slimming: slimming.resolve(),))}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swiftindex 3f9363e6..97ee12e5 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreateOptions.swift@@ -49,6 +49,9 @@ public extension VPhoneVirtualMachineCreator {/// itself). This is the clone's boot; a template boots only for its/// setup boot, before it is frozen.public var skipsFirstBoot: Bool+ /// Install the Irisin bootstrap in this layout (`roothide` or `rootless`)+ /// during the first boot; nil leaves the guest without one.+ public var bootstrapLayout: String?/// What a template built for this create is slimmed of; part of the/// key it is looked up by.public var slimming: VPhoneMachineTemplateSlimming@@ -74,6 +77,7 @@ public extension VPhoneVirtualMachineCreator {template: TemplateUse = .none,templateRequest: VPhoneMachineTemplateRequest = VPhoneMachineTemplateRequest(),skipsFirstBoot: Bool = false,+ bootstrapLayout: String? = nil,slimming: VPhoneMachineTemplateSlimming = VPhoneTemplateSlimmingRequest.defaultSlimming,) {self.name = name@@ -96,6 +100,7 @@ public extension VPhoneVirtualMachineCreator {self.template = templateself.templateRequest = templateRequestself.skipsFirstBoot = skipsFirstBoot+ self.bootstrapLayout = bootstrapLayoutself.slimming = slimming}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swiftindex a5c685ed..4e0a280d 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift@@ -20,6 +20,8 @@ private enum VPhoneVirtualMachineCreationError: Error, CustomStringConvertible {case bootAnalysisPaniccase bootAnalysisExited(Int32)case bootAnalysisTimeout+ case bootstrapFailed(String)+ case bootstrapTimeoutvar description: String {switch self {@@ -47,6 +49,10 @@ private enum VPhoneVirtualMachineCreationError: Error, CustomStringConvertible {"Boot check ended before the guest connected (exit code \(code)). Run vm create again."case .bootAnalysisTimeout:"Boot check timed out waiting for the guest. Run vm create again."+ case let .bootstrapFailed(reason):+ "Bootstrap installation failed: \(reason). The machine is kept."+ case .bootstrapTimeout:+ "Bootstrap installation did not finish in time. The machine is kept."}}}@@ -148,7 +154,9 @@ public struct VPhoneVirtualMachineCreator {if options.skipsFirstBoot {print("CFW VM created; its first boot was skipped. Guest user environment is untouched.")} else {- print("CFW VM created; vphoned connected. Guest user environment is untouched.")+ print(options.bootstrapLayout == nil+ ? "CFW VM created; vphoned connected. Guest user environment is untouched."+ : "CFW VM created; vphoned connected and the \(options.bootstrapLayout!) bootstrap and its packages installed.")}}@@ -174,7 +182,7 @@ public struct VPhoneVirtualMachineCreator {try applySettings(options)if !options.skipsFirstBoot {print("\n=== First boot check ===")- try runBootAnalysis(bundleURL: bundle.url, verbosity: options.verbosity)+ try runBootAnalysis(bundleURL: bundle.url, bootstrapLayout: options.bootstrapLayout, verbosity: options.verbosity)}}@@ -463,7 +471,7 @@ public struct VPhoneVirtualMachineCreator {+ "(it shares SEP and Data volume keys with every machine from this template)")if !options.skipsFirstBoot {print("\n=== First boot check ===")- try runBootAnalysis(bundleURL: clone.url, verbosity: options.verbosity)+ try runBootAnalysis(bundleURL: clone.url, bootstrapLayout: options.bootstrapLayout, verbosity: options.verbosity)}}@@ -723,12 +731,14 @@ public struct VPhoneVirtualMachineCreator {// MARK: - first boot check- private func runBootAnalysis(bundleURL: URL, verbosity v: VPhoneVerbosity) throws {+ private func runBootAnalysis(bundleURL: URL, bootstrapLayout: String?, verbosity v: VPhoneVerbosity) throws {let configURL = bundleURL.appendingPathComponent("config.plist")// A newly restored guest may need its first graphical session to// finish setup before vphoned accepts a connection. A headless first// boot timed out on 26.6.2, while the same disk reached vphoned in// GUI mode; later headless boots then connected normally.+ // A clone carries the template's vphoned; boot this bundle's, as vm launch does.+ _ = try VPhoneLaunchLayout(resources: resources).stageVphoned(into: VPhoneBundle.load(at: bundleURL))let (vmExe, vmArgs) = try requireLauncher().plan(["--config", configURL.path])trace("spawn \(vmExe.path) \(vmArgs.joined(separator: " ")) (guest serial: off)", v)let vm = VPhoneManagedProcess(vmExe, vmArgs, cwd: bundleURL, echo: false)@@ -750,6 +760,12 @@ public struct VPhoneVirtualMachineCreator {}if VPhoneHostAutomationProbe.ping(socketPath: socketPath) {print("[+] First boot: vphoned ping succeeded.")+ if let bootstrapLayout {+ try installBootstrap(layout: bootstrapLayout, socketPath: socketPath)+ if !vm.interrupt(waitingUpTo: 30) {+ print("warning: the guest did not shut down within 30 s; stopping it")+ }+ }return}Thread.sleep(forTimeInterval: 1)@@ -757,6 +773,65 @@ public struct VPhoneVirtualMachineCreator {print("[-] Boot analysis timeout (300s); stopping VM.")throw VPhoneVirtualMachineCreationError.bootAnalysisTimeout}++ /// vphoned's `bootstrap.install`, then `bootstrap.packages`: Irisin, then+ /// the first packages through irisin-cli's Bootstrap Install.+ private func installBootstrap(layout: String, socketPath: String) throws {+ print("\n=== Bootstrap (\(layout)) ===")+ let irisin = try followBootstrap("bootstrap.install", params: ["layout": layout], socketPath: socketPath, within: 900) {+ $0["packages"] == nil+ }+ print("[+] Irisin \(irisin["version"] as? String ?? "") installed in \(irisin["jbroot"] as? String ?? "")")+ if let warning = irisin["service_start_warning"] as? String {+ print("warning: \(warning)")+ }++ print("\n=== Bootstrap packages ===")+ let packages = try followBootstrap("bootstrap.packages", params: [:], socketPath: socketPath, within: 1800) {+ $0["packages"] != nil+ }+ if let skipped = packages["skipped"] as? String {+ print("note: no packages installed: \(skipped)")+ } else {+ print("[+] Installed \((packages["packages"] as? [String] ?? []).joined(separator: ", ")) with Bootstrap Install")+ }+ }++ /// One bootstrap call. The VM gives up relaying a request after 180 s+ /// while the guest carries on, so a lost reply is followed by+ /// `bootstrap.status` until a status `isThisCall` recognizes ends.+ private func followBootstrap(+ _ method: String,+ params: [String: Any],+ socketPath: String,+ within seconds: Int,+ isThisCall: ([String: Any]) -> Bool,+ ) throws -> [String: Any] {+ let deadline = Date().addingTimeInterval(TimeInterval(seconds))+ do {+ return try VPhoneHostAutomationProbe.rpc(method, params: params, socketPath: socketPath, timeout: seconds)+ } catch let error as VPhoneGuestCallError where error.kind == .refused {+ throw VPhoneVirtualMachineCreationError.bootstrapFailed(error.message)+ } catch let error as VPhoneGuestCallError {+ print(" \(error.message); following it")+ }+ while Date() < deadline {+ if let status = try? VPhoneHostAutomationProbe.rpc("bootstrap.status", params: [:], socketPath: socketPath, timeout: 10),+ isThisCall(status)+ {+ switch status["phase"] as? String {+ case "completed":+ return status+ case "failed":+ throw VPhoneVirtualMachineCreationError.bootstrapFailed(status["error"] as? String ?? "unknown error")+ default:+ break+ }+ }+ Thread.sleep(forTimeInterval: 2)+ }+ throw VPhoneVirtualMachineCreationError.bootstrapTimeout+ }}// MARK: - VPhoneCreatedOutputs