Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Hand the guest the VM's name as its device name before boot

Jackya312b8fbf5e1
diff --git a/Documents/Guides/create-and-run.md b/Documents/Guides/create-and-run.md
index 32bff0ad..d95dd60c 100644
--- a/Documents/Guides/create-and-run.md
+++ b/Documents/Guides/create-and-run.md
@@ -32,6 +32,10 @@ Closing the VM window, ⌘Q, `vm stop` and Control-C in the `vm launch` terminal
`vm launch` starts the guest without waiting for vphoned; the daemon connects during boot. The VM window and menu provide Home/power keys, app installation and file browsing. The host control socket is `<VM bundle>/vphone.sock`: one JSON line in, one out. Connections are served concurrently, and the socket also exists with `--no-graphics`, where `tap` and `swipe` go through vphoned's touch injection and screen images come from the guest. Besides `tap`, `swipe`, `key` and `screenshot`, `{"t":"rpc","method":"<vphoned method>","params":{…}}` calls any method in `Research/vphoned_http_api.md`. For example, `input.key` with `{"name":"cmd+v"}` pastes and `input.type` types text. No SSH or VNC endpoint is installed by this workflow.
+## Device name
+
+The guest shows the VM's name as its device name, in Xcode's device list and `xcrun devicectl list devices`, and cannot be renamed from inside the guest or from Finder, Xcode or `idevicename`: a rename there reports success and changes nothing. `vphone-vm` hands the name to the guest in NVRAM each time it starts, so `vm rename` applies from the next boot. The guest's own name stays in its preferences, untouched. A VM name of more than 255 UTF-8 bytes, or with a control character, is not used, and the guest shows its own name. See `Research/Guest/device_name_pinning.md`.
+
## Manual stages
Use these when investigating or repeating one phase. Keep a DFU boot running while `restore` talks to it:
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift
index 7d887e02..ebab5d2a 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift
@@ -32,6 +32,7 @@ extension VPhoneBootCommand {
screenScale: manifest.screenConfig.scale,
kernelDebugPort: kernelDebugPort,
isPadGuest: manifest.guestDevice.isPad,
+ deviceName: vmDir.lastPathComponent,
)
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift
index d3881051..4cfe3b4d 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift
@@ -44,6 +44,9 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
var kernelDebugPort: Int?
/// The guest runs iPadOS: Esc is a key there, not the back gesture.
var isPadGuest = false
+ /// The VM's name, written to NVRAM before boot as the guest's device
+ /// name; nil removes it.
+ var deviceName: String?
}
private struct DeviceIdentity {
@@ -140,6 +143,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
print("[vphone] NVRAM boot-args: \(bootArgs)")
}
}
+ Self.applyGuestDeviceName(options.deviceName, to: auxStorage)
// --- Boot loader with custom ROM ---
let bootloader = VZMacOSBootLoader()
@@ -375,6 +379,60 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {
try content.write(to: outputURL, atomically: true, encoding: .utf8)
}
+ // MARK: - Guest Device Name
+
+ /// Hand the guest the VM's name as its device name in NVRAM before boot.
+ /// Written on every launch, so a rename applies from the next boot. A name
+ /// that cannot be a device name is removed instead, and the guest goes back
+ /// to its own. Never fails the boot: a guest without the name only shows
+ /// its own.
+ private static func applyGuestDeviceName(_ name: String?, to auxStorage: VZMacAuxiliaryStorage) {
+ let variable = VPhoneGuestDeviceName.nvramVariable
+ guard let name else {
+ removeNVRAMVariable(variable, from: auxStorage)
+ return
+ }
+ do {
+ try VPhoneGuestDeviceName.validate(name)
+ } catch {
+ print("[vphone] Warning: the VM name is not used as the device name: \(error)")
+ removeNVRAMVariable(variable, from: auxStorage)
+ return
+ }
+ // The bytes alone: no terminating NUL.
+ let ok = Dynamic(auxStorage)
+ ._setDataValue(Data(name.utf8), forNVRAMVariableNamed: variable, error: nil)
+ .asBool ?? false
+ if ok {
+ print("[vphone] NVRAM \(variable): \(name)")
+ } else {
+ print("[vphone] Warning: could not set NVRAM \(variable); the guest keeps its own name")
+ }
+ }
+
+ /// Remove an NVRAM variable if it is there. `_removeNVRAMVariableNamed:error:`
+ /// is private and returns a BOOL, so its presence is checked first; a
+ /// missing variable is left alone rather than reported as a failure.
+ private static func removeNVRAMVariable(_ variable: String, from auxStorage: VZMacAuxiliaryStorage) {
+ let remove = NSSelectorFromString("_removeNVRAMVariableNamed:error:")
+ guard auxStorage.responds(to: remove) else {
+ print("[vphone] Warning: this macOS has no VZMacAuxiliaryStorage._removeNVRAMVariableNamed:error:; NVRAM \(variable) left as it is")
+ return
+ }
+ let read = NSSelectorFromString("_dataValueForNVRAMVariableNamed:error:")
+ if auxStorage.responds(to: read),
+ Dynamic(auxStorage)._dataValueForNVRAMVariableNamed(variable, error: nil).asObject == nil
+ {
+ return
+ }
+ let ok = Dynamic(auxStorage)._removeNVRAMVariableNamed(variable, error: nil).asBool ?? false
+ if ok {
+ print("[vphone] NVRAM \(variable): removed")
+ } else {
+ print("[vphone] Warning: could not remove NVRAM \(variable)")
+ }
+ }
+
// MARK: - Battery
/// Update the synthetic battery charge and connectivity at runtime.
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDeviceName.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDeviceName.swift
new file mode 100644
index 00000000..a1cb83ed
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestDeviceName.swift
@@ -0,0 +1,65 @@
+import Foundation
+
+// MARK: - Errors
+
+public enum VPhoneGuestDeviceNameError: Error, Equatable {
+ case empty
+ case tooLong(byteCount: Int)
+ case controlCharacter
+}
+
+extension VPhoneGuestDeviceNameError: CustomStringConvertible, LocalizedError {
+ public var description: String {
+ switch self {
+ case .empty:
+ "The name is blank, so it cannot be a device name."
+ case let .tooLong(byteCount):
+ "The name is \(byteCount) bytes long in UTF-8; a device name is at most \(VPhoneGuestDeviceName.maximumByteCount)."
+ case .controlCharacter:
+ "The name contains a control character such as a line break or tab, which a device name cannot."
+ }
+ }
+
+ public var errorDescription: String? {
+ description
+ }
+}
+
+// MARK: - Device Name
+
+/// The guest shows the VM's name as its device name: what Xcode's device list
+/// and `xcrun devicectl list devices` report. vphone-vm hands it to the guest
+/// before every boot in the NVRAM variable `nvramVariable`, as the name's UTF-8
+/// bytes with no terminating NUL; guest hooks have configd publish it and
+/// lockdownd refuse to change it. A VM name that cannot be a device name is
+/// not handed over, and the guest keeps its own. A rename applies from the
+/// next boot.
+public enum VPhoneGuestDeviceName {
+ /// The NVRAM variable vphone-vm writes and the guest reads.
+ public static let nvramVariable = "vphone-device-name"
+
+ /// The longest name accepted, in UTF-8 bytes. The guest applies the same
+ /// limit (VPhoneGuestComponents/DeviceName/DeviceNamePolicy.c).
+ public static let maximumByteCount = 255
+
+ /// Throws unless `name` can be a device name: not blank, at most
+ /// `maximumByteCount` UTF-8 bytes, and no control character (C0, DEL or
+ /// C1). Any other character, spaces and emoji included, is allowed.
+ public static func validate(_ name: String) throws {
+ if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ throw VPhoneGuestDeviceNameError.empty
+ }
+ // Checked before the length, so a name with a line break is reported
+ // as that rather than as too long.
+ if name.unicodeScalars.contains(where: { $0.properties.generalCategory == .control }) {
+ throw VPhoneGuestDeviceNameError.controlCharacter
+ }
+ if name.utf8.count > maximumByteCount {
+ throw VPhoneGuestDeviceNameError.tooLong(byteCount: name.utf8.count)
+ }
+ }
+
+ public static func isValid(_ name: String) -> Bool {
+ (try? validate(name)) != nil
+ }
+}
diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceNameTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceNameTests.swift
new file mode 100644
index 00000000..b5ccaaa0
--- /dev/null
+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/GuestDeviceNameTests.swift
@@ -0,0 +1,45 @@
+import Foundation
+import Testing
+@testable import VPhoneCoreKit
+
+struct GuestDeviceNameTests {
+ @Test func `the NVRAM variable name is the one the guest reads`() {
+ #expect(VPhoneGuestDeviceName.nvramVariable == "vphone-device-name")
+ }
+
+ @Test(arguments: [
+ "lab-a",
+ "Jacky's iPhone",
+ "Jacky’s iPhone",
+ " padded ",
+ "测试机 01",
+ "📱 Lab",
+ "👩‍💻 Desk",
+ String(repeating: "a", count: 255),
+ String(repeating: "测", count: 85), // 255 bytes
+ ])
+ func `accepts printable names`(name: String) throws {
+ try VPhoneGuestDeviceName.validate(name)
+ #expect(VPhoneGuestDeviceName.isValid(name))
+ }
+
+ @Test(arguments: ["", " ", " ", "\u{3000}"])
+ func `rejects blank names`(name: String) {
+ #expect(throws: VPhoneGuestDeviceNameError.empty) { try VPhoneGuestDeviceName.validate(name) }
+ }
+
+ @Test(arguments: ["a\nb", "a\rb", "a\tb", "a\0b", "a\u{1B}b", "a\u{7F}b", "a\u{85}b", "a\u{9F}b", "name\n"])
+ func `rejects control characters`(name: String) {
+ #expect(throws: VPhoneGuestDeviceNameError.controlCharacter) { try VPhoneGuestDeviceName.validate(name) }
+ }
+
+ @Test func `rejects names over 255 UTF-8 bytes`() {
+ #expect(throws: VPhoneGuestDeviceNameError.tooLong(byteCount: 256)) {
+ try VPhoneGuestDeviceName.validate(String(repeating: "a", count: 256))
+ }
+ // 86 three-byte characters: 86 characters, 258 bytes.
+ #expect(throws: VPhoneGuestDeviceNameError.tooLong(byteCount: 258)) {
+ try VPhoneGuestDeviceName.validate(String(repeating: "测", count: 86))
+ }
+ }
+}