Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

style: apply swift format and refresh file headers

Lakr6c36086b11e6
diff --git a/Package.swift b/Package.swift
index cefd4d49..ccbb7d2f 100644
--- a/Package.swift
+++ b/Package.swift
@@ -60,7 +60,7 @@ let package = Package(
"VPhoneArchive",
"VPhoneCore",
],
- path: "sources/FirmwarePatcher"
+ path: "sources/FirmwarePatcher",
),
.target(
name: "VPhoneCore",
@@ -70,7 +70,7 @@ let package = Package(
path: "sources/VPhoneCore",
linkerSettings: [
.linkedFramework("Virtualization"),
- ]
+ ],
),
// Archive reading and writing: the one place that knows how ownership,
// permissions and path safety differ between unpacking onto a mounted
@@ -83,7 +83,7 @@ let package = Package(
.product(name: "LibArchive", package: "libarchive.xcframework"),
"VPhoneCore",
],
- path: "sources/VPhoneArchive"
+ path: "sources/VPhoneArchive",
),
// Ad-hoc and PKCS#12 Mach-O code signing, byte for byte what ldid
// writes. It replaces ldid, which is the only program this project
@@ -96,7 +96,7 @@ let package = Package(
path: "sources/VPhoneSign",
linkerSettings: [
.linkedFramework("Security"),
- ]
+ ],
),
// libirecovery 1.3.1, vendored. It talks to iBoot/iBSS over USB, which
// is the half of a restore that `idevicerestore` does not get from
@@ -136,7 +136,7 @@ let package = Package(
linkerSettings: [
.linkedFramework("IOKit"),
.linkedFramework("CoreFoundation"),
- ]
+ ],
),
// idevicerestore, vendored. This is the restore backend itself — the
// thing scripts/pymobiledevice3_bridge.py has been standing in for,
@@ -183,7 +183,7 @@ let package = Package(
// check_aux.sh's system whitelist; nothing else is linked.
.linkedLibrary("curl"),
.linkedLibrary("z"),
- ]
+ ],
),
// The Swift face of the two C targets above, and what actually
// replaces scripts/pymobiledevice3_bridge.py: probe for a DFU/recovery
@@ -204,7 +204,7 @@ let package = Package(
path: "sources/VPhoneRestore",
linkerSettings: [
.linkedLibrary("z"),
- ]
+ ],
),
// Everything that touches a running guest: the machine, its window and
// menus, the vsock channel and the host device bridges. It is a library
@@ -226,7 +226,7 @@ let package = Package(
.linkedFramework("SwiftUI"),
.linkedFramework("CoreLocation"),
.linkedFramework("AVFoundation"),
- ]
+ ],
),
// The only binary signed with sources/vphone.entitlements.
.executableTarget(
@@ -241,7 +241,7 @@ let package = Package(
// dependencies even when this executable has no symbol references.
// Strip those unused load commands so the shipped app remains
// independent of the build machine's Swift toolchain.
- linkerSettings: [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])]
+ linkerSettings: [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])],
),
// The user-facing entry point. Note it depends on neither VPhoneVirtualMachineKit
// nor any of the five frameworks above: it never builds a machine, it
@@ -264,7 +264,7 @@ let package = Package(
"VPhoneCore",
"VPhoneRestore",
],
- path: "sources/vphone-cli"
+ path: "sources/vphone-cli",
),
.executableTarget(
name: "vphone-archive",
@@ -273,7 +273,7 @@ let package = Package(
"VPhoneArchive",
"VPhoneCore",
],
- path: "sources/vphone-archive"
+ path: "sources/vphone-archive",
),
// The SUDO_ASKPASS program, and the probe behind `VPhoneSudo.route()`.
// No ArgumentParser and no VPhoneCore: it is two verbs, it runs while
@@ -282,7 +282,7 @@ let package = Package(
// put AppKit under vphone-cli.
.executableTarget(
name: "vphone-ask-for-permission",
- path: "sources/vphone-ask-for-permission"
+ path: "sources/vphone-ask-for-permission",
),
// `vphone-amfi-allow` is NOT here, and cannot be: SwiftPM emits arm64
// and it has to be arm64e to read amfid's ObjC runtime. `scripts/build.sh`
@@ -297,17 +297,17 @@ let package = Package(
.testTarget(
name: "FirmwarePatcherTests",
dependencies: ["FirmwarePatcher"],
- path: "tests/FirmwarePatcherTests"
+ path: "tests/FirmwarePatcherTests",
),
.testTarget(
name: "VPhoneCoreTests",
dependencies: ["VPhoneCore"],
- path: "tests/VPhoneCoreTests"
+ path: "tests/VPhoneCoreTests",
),
.testTarget(
name: "VPhoneArchiveTests",
dependencies: ["VPhoneArchive"],
- path: "tests/VPhoneArchiveTests"
+ path: "tests/VPhoneArchiveTests",
),
.testTarget(
name: "VPhoneSignTests",
@@ -318,7 +318,7 @@ let package = Package(
// `#filePath`, so they need to be on disk and not in a bundle,
// and left in place SwiftPM would try to compile the .c and refuse
// the target for mixing languages.
- exclude: ["Fixtures"]
+ exclude: ["Fixtures"],
),
// Everything here runs without a device attached: argument parsing,
// the restore-tree rules, the .shsh naming and the C struct the
@@ -327,7 +327,7 @@ let package = Package(
.testTarget(
name: "VPhoneRestoreTests",
dependencies: ["VPhoneRestore"],
- path: "tests/VPhoneRestoreTests"
+ path: "tests/VPhoneRestoreTests",
),
- ]
+ ],
)
diff --git a/scripts/vphoned/Daemon/APIWire.swift b/scripts/vphoned/Daemon/APIWire.swift
index b2a64d12..2cd682ae 100644
--- a/scripts/vphoned/Daemon/APIWire.swift
+++ b/scripts/vphoned/Daemon/APIWire.swift
@@ -29,7 +29,7 @@ enum APIWire {
throw GuestAPIError.invalidRequest("Expected {method, params?, id?}")
}
let id = object["id"]
- if let id, !(id is String) && !(id is NSNumber) {
+ if let id, !(id is String), !(id is NSNumber) {
throw GuestAPIError.invalidRequest("id must be a string or number")
}
return APIRequest(method: method, params: object["params"] as? [String: Any] ?? [:], id: id)
diff --git a/scripts/vphoned/Daemon/GuestAPI.swift b/scripts/vphoned/Daemon/GuestAPI.swift
index 91392693..90b1e9a4 100644
--- a/scripts/vphoned/Daemon/GuestAPI.swift
+++ b/scripts/vphoned/Daemon/GuestAPI.swift
@@ -1,6 +1,6 @@
-import Foundation
import CryptoKit
import Darwin
+import Foundation
import IcliKit
import VphonedNative
@@ -11,8 +11,8 @@ enum GuestAPIError: Error, CustomStringConvertible {
var description: String {
switch self {
- case .invalidRequest(let message), .operationFailed(let message): message
- case .unsupportedMethod(let method): "Unknown method: \(method)"
+ case let .invalidRequest(message), let .operationFailed(message): message
+ case let .unsupportedMethod(method): "Unknown method: \(method)"
}
}
}
@@ -57,8 +57,8 @@ enum GuestAPI {
"keychain",
"ipa_install",
"camera",
- "icli"
- ]
+ "icli",
+ ],
]
}
@@ -85,9 +85,15 @@ enum GuestAPI {
let path = app["bundle_path"] as? String ?? ""
let type = app["type"] as? String
?? (path.hasPrefix("/System/") || id.hasPrefix("com.apple.") ? "system" : "user")
- if filter == "running" && pid == 0 { return nil }
- if filter == "user" && type != "user" { return nil }
- if filter == "system" && type != "system" { return nil }
+ if filter == "running" && pid == 0 {
+ return nil
+ }
+ if filter == "user" && type != "user" {
+ return nil
+ }
+ if filter == "system" && type != "system" {
+ return nil
+ }
info["pid"] = pid
info["type"] = type
info["state"] = pid > 0 ? "running" : "not_running"
@@ -96,15 +102,18 @@ enum GuestAPI {
return info
}]
case "apps.search":
- return try searchApps(try string(params, "query"))
+ return try searchApps(string(params, "query"))
case "apps.launch":
let id = try string(params, "bundle_id")
- if let url = params["url"] as? String { _ = try openAppURL(url, bundleID: id) }
- else { _ = try launchApp(id) }
+ if let url = params["url"] as? String {
+ _ = try openAppURL(url, bundleID: id)
+ } else {
+ _ = try launchApp(id)
+ }
let running = try? runningApps()["apps"] as? [[String: Any]]
return ["pid": running?.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0]
case "apps.terminate":
- return try killApp(try string(params, "bundle_id"), force: true)
+ return try killApp(string(params, "bundle_id"), force: true)
case "apps.foreground":
let front = frontmostApp()
let id = front["bundle_id"] as? String ?? ""
@@ -113,14 +122,14 @@ enum GuestAPI {
return [
"bundle_id": id,
"name": apps.first?["name"] ?? "",
- "pid": running.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0
+ "pid": running.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0,
]
case "apps.open_url":
- return try openAppURL(try string(params, "url"), bundleID: params["bundle_id"] as? String)
+ return try openAppURL(string(params, "url"), bundleID: params["bundle_id"] as? String)
case "apps.install":
return try native([
"t": "ipa_install",
- "path": try string(params, "path"),
+ "path": string(params, "path"),
"registration": params["registration"] as? String ?? "User",
"cert_path": params["cert_path"] as? String ?? "",
])
@@ -145,7 +154,7 @@ enum GuestAPI {
horizontalAccuracy: number(params, "horizontal_accuracy", default: 5),
verticalAccuracy: number(params, "vertical_accuracy", default: 5),
speed: (params["speed"] as? NSNumber)?.doubleValue,
- course: (params["course"] as? NSNumber)?.doubleValue
+ course: (params["course"] as? NSNumber)?.doubleValue,
)
case "location.clear":
return try clearSimulatedLocation()
@@ -163,32 +172,33 @@ enum GuestAPI {
case "clipboard.get":
return try clipboardInfo()
case "clipboard.set":
- return try setClipboard(try string(params, "text"))
+ return try setClipboard(string(params, "text"))
case "files.list":
- return try fileList(try string(params, "path"))
+ return try fileList(string(params, "path"))
case "files.mkdir":
- return try makeDirectory(try string(params, "path"), mode: nil)
+ return try makeDirectory(string(params, "path"), mode: nil)
case "files.remove":
- return try removePath(try string(params, "path"), recursive: params["recursive"] as? Bool ?? false,
+ return try removePath(string(params, "path"), recursive: params["recursive"] as? Bool ?? false,
force: true)
case "files.rename":
- return try movePath(try string(params, "from"), to: try string(params, "to"))
+ return try movePath(string(params, "from"), to: string(params, "to"))
case "settings.get":
- return try readPreference(domain: try string(params, "domain"), key: params["key"] as? String)
+ return try readPreference(domain: string(params, "domain"), key: params["key"] as? String)
case "settings.set":
let rawValue = params["value"] ?? NSNull()
let type = params["type"] as? String
?? (rawValue is Bool ? "bool"
: rawValue is NSNumber ? "float"
: rawValue is String ? "string" : "json")
- let text: String
- if type == "json" {
- text = String(data: try JSONSerialization.data(withJSONObject: rawValue), encoding: .utf8) ?? ""
- } else { text = String(describing: rawValue) }
+ let text: String = if type == "json" {
+ try String(data: JSONSerialization.data(withJSONObject: rawValue), encoding: .utf8) ?? ""
+ } else {
+ String(describing: rawValue)
+ }
return try writePreference(
- domain: try string(params, "domain"),
- key: try string(params, "key"),
- value: PreferenceValue(text: text, type: type)
+ domain: string(params, "domain"),
+ key: string(params, "key"),
+ value: PreferenceValue(text: text, type: type),
)
case "accessibility.tree":
throw GuestAPIError.operationFailed("The accessibility tree is not available on this guest yet.")
@@ -197,9 +207,9 @@ enum GuestAPI {
case "keychain.add":
return try native([
"t": "keychain_add",
- "account": try string(params, "account"),
- "service": try string(params, "service"),
- "password": try string(params, "password"),
+ "account": string(params, "account"),
+ "service": string(params, "service"),
+ "password": string(params, "password"),
])
case "agent.apply_update":
let expected = try string(params, "sha256")
@@ -214,7 +224,7 @@ enum GuestAPI {
guard rename(next, cache) == 0 else { throw GuestAPIError.operationFailed("Could not install update") }
try Data(expected.utf8).write(
to: URL(fileURLWithPath: "/var/root/Library/Caches/vphoned.api-v2"),
- options: .atomic
+ options: .atomic,
)
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { exit(0) }
return ["restarting": true]
diff --git a/scripts/vphoned/Daemon/GuestFileTransfer.swift b/scripts/vphoned/Daemon/GuestFileTransfer.swift
index ab26cc5d..276e62aa 100644
--- a/scripts/vphoned/Daemon/GuestFileTransfer.swift
+++ b/scripts/vphoned/Daemon/GuestFileTransfer.swift
@@ -32,13 +32,13 @@ enum GuestFileTransfer {
headers.add(name: "Connection", value: "close")
channel.write(
HTTPServerResponsePart.head(.init(version: .http1_1, status: .ok, headers: headers)),
- promise: nil
+ promise: nil,
)
fileIO.readChunked(
fileRegion: region,
chunkSize: 64 * 1024,
allocator: channel.allocator,
- eventLoop: channel.eventLoop
+ eventLoop: channel.eventLoop,
) { bytes in
channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(bytes)))
}.whenComplete { result in
@@ -74,7 +74,7 @@ final class GuestFileUpload: @unchecked Sendable {
fileIO: NonBlockingFileIO,
channel: Channel,
mode: mode_t = 0o644,
- onCommit: ((String) throws -> Void)? = nil
+ onCommit: ((String) throws -> Void)? = nil,
) throws {
let parent = (destination as NSString).deletingLastPathComponent
try FileManager.default.createDirectory(atPath: parent, withIntermediateDirectories: true)
@@ -83,9 +83,9 @@ final class GuestFileUpload: @unchecked Sendable {
guard fd >= 0 else { throw GuestAPIError.operationFailed("Could not create upload file") }
self.destination = destination
self.temporary = temporary
- self.handle = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fd)
+ handle = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fd)
self.fileIO = fileIO
- self.writes = channel.eventLoop.makeSucceededFuture(())
+ writes = channel.eventLoop.makeSucceededFuture(())
self.onCommit = onCommit
self.mode = mode
}
@@ -108,7 +108,7 @@ final class GuestFileUpload: @unchecked Sendable {
do {
try handle.close()
switch result {
- case .failure(let error): throw error
+ case let .failure(error): throw error
case .success: break
}
guard chmod(temporary, mode) == 0 else {
@@ -127,7 +127,9 @@ final class GuestFileUpload: @unchecked Sendable {
}
deinit {
- if handle.isOpen { try? handle.close() }
+ if handle.isOpen {
+ try? handle.close()
+ }
unlink(temporary)
}
}
diff --git a/scripts/vphoned/Daemon/GuestHTTPHandler.swift b/scripts/vphoned/Daemon/GuestHTTPHandler.swift
index 51109a6d..b4ab1470 100644
--- a/scripts/vphoned/Daemon/GuestHTTPHandler.swift
+++ b/scripts/vphoned/Daemon/GuestHTTPHandler.swift
@@ -24,14 +24,14 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch unwrapInboundIn(data) {
- case .head(let request):
+ case let .head(request):
head = request
body.removeAll(keepingCapacity: true)
exceededLimit = false
upload = nil
uploadError = nil
let requestPath = request.uri.split(separator: "?", maxSplits: 1).first
- if request.method == .PUT && (requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image") {
+ if request.method == .PUT, requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image" {
do {
upload = try GuestFileUpload(
destination: requestPath == "/v1/clipboard/image"
@@ -39,17 +39,17 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
: GuestFileTransfer.path(from: request.uri),
fileIO: fileIO,
channel: context.channel,
- mode: try Self.uploadMode(from: request.uri),
+ mode: Self.uploadMode(from: request.uri),
onCommit: requestPath == "/v1/clipboard/image" ? { path in
_ = try setClipboardImage(Data(contentsOf: URL(fileURLWithPath: path)))
unlink(path)
- } : nil
+ } : nil,
)
} catch { uploadError = error }
}
- case .body(var buffer):
+ case var .body(buffer):
let requestPath = head?.uri.split(separator: "?", maxSplits: 1).first
- if head?.method == .PUT && (requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image") {
+ if head?.method == .PUT, requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image" {
upload?.append(buffer, channel: context.channel)
return
}
@@ -72,7 +72,7 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
upload?.finish(channel: context.channel)
}
upload = nil
- } else if head.method == .GET && path == "/v1/clipboard/image" {
+ } else if head.method == .GET, path == "/v1/clipboard/image" {
do {
guard let image = try clipboardImagePNG() else {
Self.send(APIWire.error("Clipboard has no image", status: 404), on: context.channel)
@@ -82,10 +82,10 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
} catch { Self.send(APIWire.error(String(describing: error)), on: context.channel) }
} else if head.method == .GET {
do {
- GuestFileTransfer.download(
- path: try GuestFileTransfer.path(from: head.uri),
+ try GuestFileTransfer.download(
+ path: GuestFileTransfer.path(from: head.uri),
fileIO: fileIO,
- channel: context.channel
+ channel: context.channel,
)
} catch {
Self.send(APIWire.error(String(describing: error)), on: context.channel)
@@ -105,11 +105,11 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
private func handle(_ head: HTTPRequestHead, body: Data, channel: Channel) {
let path = head.uri.split(separator: "?", maxSplits: 1).first.map(String.init) ?? head.uri
- if head.method == .GET && path == "/openapi.json" {
+ if head.method == .GET, path == "/openapi.json" {
Self.send(APIReply(status: 200, data: OpenAPIDocument.data), on: channel)
return
}
- if head.method == .GET && path == "/v1/health" {
+ if head.method == .GET, path == "/v1/health" {
Self.send(.json(GuestAPI.health()), on: channel)
return
}
@@ -127,7 +127,9 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
var params = try Self.parameters(body)
let components = URLComponents(string: "http://vphoned\(head.uri)")
for item in components?.queryItems ?? [] {
- if let value = item.value { params[item.name] = value }
+ if let value = item.value {
+ params[item.name] = value
+ }
}
request = APIRequest(method: method, params: params, id: nil)
}
@@ -140,7 +142,9 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
}
private static func parameters(_ body: Data) throws -> [String: Any] {
- if body.isEmpty { return [:] }
+ if body.isEmpty {
+ return [:]
+ }
guard let object = try JSONSerialization.jsonObject(with: body) as? [String: Any] else {
throw GuestAPIError.invalidRequest("Request body must be a JSON object")
}
@@ -153,7 +157,7 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
return 0o644
}
guard !value.isEmpty, value.count <= 4,
- value.utf8.allSatisfy({ (48...55).contains($0) }),
+ value.utf8.allSatisfy({ (48 ... 55).contains($0) }),
let mode = UInt16(value, radix: 8), mode <= 0o777
else { throw GuestAPIError.invalidRequest("mode must be an octal permission, up to 0777") }
return mode_t(mode)
@@ -201,7 +205,7 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
let status = HTTPResponseStatus(statusCode: reply.status)
channel.write(
HTTPServerResponsePart.head(.init(version: .http1_1, status: status, headers: headers)),
- promise: nil
+ promise: nil,
)
var buffer = channel.allocator.buffer(capacity: reply.data.count)
buffer.writeBytes(reply.data)
@@ -210,7 +214,11 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
channel.close(promise: nil)
}
}
- if channel.eventLoop.inEventLoop { write() } else { channel.eventLoop.execute(write) }
+ if channel.eventLoop.inEventLoop {
+ write()
+ } else {
+ channel.eventLoop.execute(write)
+ }
}
func channelInactive(context: ChannelHandlerContext) {
@@ -218,7 +226,7 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
context.fireChannelInactive()
}
- func errorCaught(context: ChannelHandlerContext, error: Error) {
+ func errorCaught(context: ChannelHandlerContext, error _: Error) {
context.close(promise: nil)
}
}
@@ -236,7 +244,9 @@ private final class HTTPJob: @unchecked Sendable {
func run() {
let reply = APIWire.execute(request)
- if reply.status == 200 { hub.broadcast(name: "operation.completed", data: ["method": request.method]) }
+ if reply.status == 200 {
+ hub.broadcast(name: "operation.completed", data: ["method": request.method])
+ }
GuestHTTPHandler.send(reply, on: channel)
}
}
diff --git a/scripts/vphoned/Daemon/GuestWebSocketHandler.swift b/scripts/vphoned/Daemon/GuestWebSocketHandler.swift
index 2d064239..e747978e 100644
--- a/scripts/vphoned/Daemon/GuestWebSocketHandler.swift
+++ b/scripts/vphoned/Daemon/GuestWebSocketHandler.swift
@@ -7,7 +7,9 @@ final class GuestWebSocketHandler: ChannelInboundHandler, @unchecked Sendable {
typealias OutboundOut = WebSocketFrame
private let hub: APIEventHub
- init(hub: APIEventHub) { self.hub = hub }
+ init(hub: APIEventHub) {
+ self.hub = hub
+ }
func handlerAdded(context: ChannelHandlerContext) {
hub.add(context.channel)
@@ -46,7 +48,7 @@ final class GuestWebSocketHandler: ChannelInboundHandler, @unchecked Sendable {
context.fireChannelInactive()
}
- func errorCaught(context: ChannelHandlerContext, error: Error) {
+ func errorCaught(context: ChannelHandlerContext, error _: Error) {
context.close(promise: nil)
}
@@ -57,7 +59,11 @@ final class GuestWebSocketHandler: ChannelInboundHandler, @unchecked Sendable {
buffer.writeBytes(data)
channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .text, data: buffer), promise: nil)
}
- if channel.eventLoop.inEventLoop { write() } else { channel.eventLoop.execute(write) }
+ if channel.eventLoop.inEventLoop {
+ write()
+ } else {
+ channel.eventLoop.execute(write)
+ }
}
}
@@ -75,6 +81,8 @@ private final class WebSocketJob: @unchecked Sendable {
func run() {
let reply = APIWire.execute(request)
GuestWebSocketHandler.send(reply.data, on: channel)
- if reply.status == 200 { hub.broadcast(name: "operation.completed", data: ["method": request.method]) }
+ if reply.status == 200 {
+ hub.broadcast(name: "operation.completed", data: ["method": request.method])
+ }
}
}
diff --git a/scripts/vphoned/Daemon/IcliCommand.swift b/scripts/vphoned/Daemon/IcliCommand.swift
index 1cba2948..1c517808 100644
--- a/scripts/vphoned/Daemon/IcliCommand.swift
+++ b/scripts/vphoned/Daemon/IcliCommand.swift
@@ -39,9 +39,15 @@ enum IcliCommand {
let stdoutFD = open(outputURL.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
let stderrFD = open(errorURL.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
guard stdinFD >= 0, stdoutFD >= 0, stderrFD >= 0 else {
- if stdinFD >= 0 { close(stdinFD) }
- if stdoutFD >= 0 { close(stdoutFD) }
- if stderrFD >= 0 { close(stderrFD) }
+ if stdinFD >= 0 {
+ close(stdinFD)
+ }
+ if stdoutFD >= 0 {
+ close(stdoutFD)
+ }
+ if stderrFD >= 0 {
+ close(stderrFD)
+ }
throw GuestAPIError.operationFailed("Could not prepare icli output")
}
defer { close(stdinFD); close(stdoutFD); close(stderrFD) }
@@ -54,7 +60,11 @@ enum IcliCommand {
posix_spawn_file_actions_adddup2(&actions, stderrFD, STDERR_FILENO)
var argv = (["/usr/bin/icli"] + arguments).map { strdup($0) as UnsafeMutablePointer<CChar>? }
argv.append(nil)
- defer { argv.forEach { if let value = $0 { free(value) } } }
+ defer { for item in argv {
+ if let value = item {
+ free(value)
+ }
+ } }
var pid: pid_t = 0
let spawnStatus = argv.withUnsafeMutableBufferPointer { pointer in
posix_spawn(&pid, "/usr/bin/icli", &actions, nil, pointer.baseAddress, environ)
@@ -67,9 +77,13 @@ enum IcliCommand {
var status: Int32 = 0
while true {
let waited = waitpid(pid, &status, WNOHANG)
- if waited == pid { break }
+ if waited == pid {
+ break
+ }
if waited < 0 {
- if errno == EINTR { continue }
+ if errno == EINTR {
+ continue
+ }
kill(pid, SIGKILL)
_ = waitpid(pid, &status, 0)
throw GuestAPIError.operationFailed("Could not wait for icli")
@@ -84,13 +98,14 @@ enum IcliCommand {
let stdoutSize = try FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? NSNumber
let stderrSize = try FileManager.default.attributesOfItem(atPath: errorURL.path)[.size] as? NSNumber
guard (stdoutSize?.int64Value ?? 0) <= 64 << 20,
- (stderrSize?.int64Value ?? 0) <= 1 << 20 else {
+ (stderrSize?.int64Value ?? 0) <= 1 << 20
+ else {
throw GuestAPIError.operationFailed("icli output exceeded the API limit")
}
let stdout = try Data(contentsOf: outputURL, options: .mappedIfSafe)
let stderr = try Data(contentsOf: errorURL, options: .mappedIfSafe)
let parsed = try? JSONSerialization.jsonObject(with: stdout, options: [.fragmentsAllowed])
- let code = (status & 0x7f) == 0 ? Int((status >> 8) & 0xff) : -Int(status & 0x7f)
+ let code = (status & 0x7F) == 0 ? Int((status >> 8) & 0xFF) : -Int(status & 0x7F)
return [
"exit_code": code,
"output": parsed ?? String(decoding: stdout, as: UTF8.self),
diff --git a/scripts/vphoned/Daemon/main.swift b/scripts/vphoned/Daemon/main.swift
index 5a51ebc6..8c255e65 100644
--- a/scripts/vphoned/Daemon/main.swift
+++ b/scripts/vphoned/Daemon/main.swift
@@ -31,15 +31,15 @@ do {
NIOWebSocketFrameAggregator(
minNonFinalFragmentSize: 1,
maxAccumulatedFrameCount: 32,
- maxAccumulatedFrameSize: 1 << 20
+ maxAccumulatedFrameSize: 1 << 20,
),
GuestWebSocketHandler(hub: hub),
])
}
- }
+ },
)
return channel.pipeline.configureHTTPServerPipeline(
- withServerUpgrade: (upgraders: [upgrader], completionHandler: { _ in })
+ withServerUpgrade: (upgraders: [upgrader], completionHandler: { _ in }),
).flatMap { channel.pipeline.addHandler(http) }
}
.bind(to: VsockAddress(cid: .any, port: 1339))
diff --git a/scripts/vphoned/Package.swift b/scripts/vphoned/Package.swift
index 4976370e..eb0a6f6c 100644
--- a/scripts/vphoned/Package.swift
+++ b/scripts/vphoned/Package.swift
@@ -31,7 +31,7 @@ let package = Package(
.linkedFramework("Foundation"),
.linkedFramework("Security"),
.linkedFramework("CoreServices"),
- ]
+ ],
),
.executableTarget(
name: "vphoned",
@@ -44,7 +44,7 @@ let package = Package(
.product(name: "NIOWebSocket", package: "swift-nio"),
],
path: "Daemon",
- linkerSettings: [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])]
+ linkerSettings: [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])],
),
- ]
+ ],
)
diff --git a/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift b/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
index 6a5aae52..f78d0fe3 100644
--- a/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
@@ -320,7 +320,8 @@ public enum CustomFirmwareInjectDylib {
)
}
if !options.allowNonEmptyPadding,
- data[commandOffset ..< commandOffset + commandSize].contains(where: { $0 != 0 }) {
+ data[commandOffset ..< commandOffset + commandSize].contains(where: { $0 != 0 })
+ {
// insert_dylib --all-yes overwrites here. Refusing is the whole
// reason this is a Swift port: the bytes past the load commands are
// the first section, and clobbering them is silent.
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader+Results.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader+Results.swift
index 0442ef46..39556521 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader+Results.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader+Results.swift
@@ -1,8 +1,8 @@
-extension CustomFirmwareCacheLoaderPatcher {
+public extension CustomFirmwareCacheLoaderPatcher {
// MARK: - Results
/// The boot-arg string the gate is built around, and the code that loads it.
- public struct Anchor: Sendable, Equatable {
+ struct Anchor: Sendable, Equatable {
/// Which of ``anchorTokens`` matched.
public let token: String
/// The whole null-terminated string the token sits inside.
@@ -22,7 +22,7 @@ extension CustomFirmwareCacheLoaderPatcher {
/// The conditional branch that skips the unsecure-cache path — or the NOP a
/// previous run already left in its place.
- public struct Gate: Sendable, Equatable {
+ struct Gate: Sendable, Equatable {
public let fileOffset: Int
public let vma: UInt64
/// Capstone's mnemonic: `cbz`/`cbnz`/`tbz`/`tbnz`/`b.<cond>`, or `nop`
@@ -49,7 +49,7 @@ extension CustomFirmwareCacheLoaderPatcher {
}
/// What a run did.
- public enum Outcome: String, Sendable, Equatable {
+ enum Outcome: String, Sendable, Equatable {
/// The gate already held a NOP. Nothing was written.
case alreadyPatched
/// `dryRun` was set, so the site was located and reported only.
@@ -59,7 +59,7 @@ extension CustomFirmwareCacheLoaderPatcher {
}
/// The outcome of one run, and the site it acted on.
- public struct Report: Sendable {
+ struct Report: Sendable {
public let outcome: Outcome
public let anchor: Anchor
public let gate: Gate
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader.swift
index 658e395f..c1f376b3 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareCacheLoader.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareCacheloader.swift — open launchd_cache_loader's unsecure-cache gate.
+// CustomFirmwareCacheLoader.swift — open launchd_cache_loader's unsecure-cache gate.
//
// Swift port of `scripts/patchers/cfw_patch_cache_loader.py`, driven today by
// `cfw.py patch-launchd-cache-loader <binary>`.
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage+DynamicMetadata.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage+DynamicMetadata.swift
index a1053d0f..1229374b 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage+DynamicMetadata.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage+DynamicMetadata.swift
@@ -23,14 +23,14 @@ extension CustomFirmwareDiskImage {
sections,
"__DATA_CONST,__objc_selrefs",
"__DATA,__objc_selrefs",
- "__AUTH_CONST,__objc_selrefs"
+ "__AUTH_CONST,__objc_selrefs",
),
- let selrefVA = selectorReferenceVA(
- in: data,
- selrefs: selrefsSection,
- selectorVA: selectorVA,
- imageBase: imageBase(sections),
- )
+ let selrefVA = selectorReferenceVA(
+ in: data,
+ selrefs: selrefsSection,
+ selectorVA: selectorVA,
+ imageBase: imageBase(sections),
+ )
{
targets.insert(selrefVA)
}
@@ -257,5 +257,4 @@ extension CustomFirmwareDiskImage {
let impRelative = Int32(bitPattern: data.loadLE(UInt32.self, at: impFieldOffset))
return UInt64(bitPattern: Int64(bitPattern: impFieldVA) &+ Int64(impRelative))
}
-
}
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage.swift
index 2b9f693d..9c1d71a3 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskImage.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareDiskimagesiod.swift — force diskimagesiod's DDI mount-completion gate open.
+// CustomFirmwareDiskImage.swift — force diskimagesiod's DDI mount-completion gate open.
//
// Swift port of `scripts/patchers/cfw_patch_diskimagesiod.py`, driven by
// `cfw.py patch-diskimagesiod <binary>` and, in the shipped installers, by
@@ -58,7 +58,7 @@
// caller's (unsigned) LR without ever having pushed a frame, so overwriting
// `pacibsp; stp …` loses nothing that the new epilogue needs. Both words come
// from the encoder — `ARM64Encoder.encodeMovzX` builds MOVZ from its ISA fields
-// and `ARM64.ret` is the keystone-derived constant; `CustomFirmwareDiskimagesiodTests`
+// and `ARM64.ret` is the keystone-derived constant; `CustomFirmwareDiskImageTests`
// asserts the two agree with `ARM64.movX0_1`.
//
// Re-signing
@@ -103,7 +103,7 @@ public enum CustomFirmwareDiskImage {
/// MOVZ is built from its ISA fields by ``ARM64Encoder/encodeMovzX(rd:imm16:shift:)``;
/// the `?? ARM64.movX0_1` arm is unreachable (that encoder returns `nil`
/// only for a shift above 48) and exists so this stays a plain `let` with
- /// no trap in it. `CustomFirmwareDiskimagesiodTests` asserts the two spellings are the
+ /// no trap in it. `CustomFirmwareDiskImageTests` asserts the two spellings are the
/// same four bytes.
public static let replacement: Data =
(ARM64Encoder.encodeMovzX(rd: 0, imm16: 1) ?? ARM64.movX0_1) + ARM64.ret
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation+Anchoring.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation+Anchoring.swift
index bead1c93..4c4d6626 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation+Anchoring.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation+Anchoring.swift
@@ -312,5 +312,4 @@ extension CustomFirmwareMobileActivation {
}
return nil
}
-
}
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation.swift
index 9cff59a1..d387e72f 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileActivation.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareMobileactivationd.swift — force `-[DeviceType should_hactivate]` to YES.
+// CustomFirmwareMobileActivation.swift — force `-[DeviceType should_hactivate]` to YES.
//
// Swift port of `scripts/patchers/cfw_patch_mobileactivationd.py`, driven by
// `cfw.py patch-mobileactivationd <binary>` from `cfw_install{,_dev}.sh` and
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDog.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDog.swift
index f21d957f..3fdea3ed 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDog.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDog.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareWatchdogd.swift — force watchdogd's cached "am I a VM?" byte to 1.
+// CustomFirmwareWatchDog.swift — force watchdogd's cached "am I a VM?" byte to 1.
//
// Port of `scripts/patchers/cfw_patch_watchdogd.py` (453 lines). EXP only.
//
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogDiscovery.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogDiscovery.swift
index 01cd8fb0..b9392d6d 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogDiscovery.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogDiscovery.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareWatchdogdDiscovery.swift — Locate watchdogd VM-presence cache sites.
+// CustomFirmwareWatchDogDiscovery.swift — Locate watchdogd VM-presence cache sites.
import Capstone
import Foundation
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogSymbolTargets.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogSymbolTargets.swift
index 9640d113..da3e42f4 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogSymbolTargets.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchDogSymbolTargets.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareWatchdogdSymbolTargets.swift — Resolve watchdogd branch targets.
+// CustomFirmwareWatchDogSymbolTargets.swift — Resolve watchdogd branch targets.
import Foundation
diff --git a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
index 4daf2d13..f58f42fe 100644
--- a/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
+++ b/sources/FirmwarePatcher/DeviceTree/DeviceTreePatcher.swift
@@ -30,7 +30,10 @@ public final class DeviceTreePatcher: Patcher {
/// A single property in a device tree node.
final class DTProperty {
var name: String
- var length: Int { value.count }
+ var length: Int {
+ value.count
+ }
+
var flags: UInt16
var value: Data
/// File offset of the property value within the flat binary.
diff --git a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift
index 0878bf65..0669911e 100644
--- a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift
+++ b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher+MachOStringSites.swift
@@ -1,8 +1,8 @@
import Foundation
-extension DyldSharedCacheHypervisorVirtualMachinePatcher {
+public extension DyldSharedCacheHypervisorVirtualMachinePatcher {
/// One occurrence of the pristine cstring in a standalone Mach-O.
- public struct MachOStringSite: Sendable, Equatable {
+ struct MachOStringSite: Sendable, Equatable {
/// Address the literal is mapped at.
public let stringVMA: UInt64
/// Offset of the literal in the file.
@@ -19,7 +19,7 @@ extension DyldSharedCacheHypervisorVirtualMachinePatcher {
///
/// - Throws: ``PatcherError/invalidFormat(_:)`` when `data` is not a 64-bit
/// little-endian Mach-O. A fat binary has to be sliced first.
- public static func findStringSites(inMachO data: Data) throws -> [MachOStringSite] {
+ static func findStringSites(inMachO data: Data) throws -> [MachOStringSite] {
let image = data.startIndex == 0 ? data : Data(data)
var sites: [MachOStringSite] = []
for (name, section) in try machOSections(of: image)
@@ -55,14 +55,14 @@ extension DyldSharedCacheHypervisorVirtualMachinePatcher {
/// Only for saying something useful in the log: ``findStringSites(inMachO:)``
/// already returns nothing for an already-patched binary, so the patch flow
/// is idempotent with or without this.
- public static func isAlreadyMangled(_ data: Data) -> Bool {
+ static func isAlreadyMangled(_ data: Data) -> Bool {
data.range(of: mangledNeedle) != nil
}
// MARK: - Minimal Mach-O section table
/// One `section_64`, reduced to what the string scan needs.
- struct MachOSection {
+ internal struct MachOSection {
let segmentName: String
let sectionName: String
let address: UInt64
@@ -77,7 +77,7 @@ extension DyldSharedCacheHypervisorVirtualMachinePatcher {
/// ones while keeping the earlier one's position, which is what the
/// reference's dict does and is the only reason the two agree on the order
/// sites come back in.
- static func machOSections(of data: Data) throws -> [(String, MachOSection)] {
+ internal static func machOSections(of data: Data) throws -> [(String, MachOSection)] {
guard data.count >= 32 else {
throw PatcherError.invalidFormat("truncated Mach-O header (\(data.count) bytes)")
}
@@ -133,5 +133,4 @@ extension DyldSharedCacheHypervisorVirtualMachinePatcher {
let terminated = field.prefix { $0 != 0 }
return String(decoding: terminated, as: UTF8.self)
}
-
}
diff --git a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
index e4ed20a8..676fe8fa 100644
--- a/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
+++ b/sources/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheHypervisorVirtualMachinePatcher.swift
@@ -1,4 +1,4 @@
-// DyldSharedCacheHVVMMPatcher.swift — the `kern.hv_vmm_present` user-mode cstring mangle.
+// DyldSharedCacheHypervisorVirtualMachinePatcher.swift — the `kern.hv_vmm_present` user-mode cstring mangle.
//
// Port of BOTH `scripts/patchers/cfw_patch_hv_vmm_dsc.py` (the DSC orchestrator)
// and `scripts/patchers/cfw_patch_hv_vmm.py` (the cstring definition and the
diff --git a/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift b/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift
index c95fe143..23e80606 100644
--- a/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift
+++ b/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift
@@ -205,9 +205,9 @@ extension KernelPatcher {
guard let plist = try? PropertyListSerialization.propertyList(
from: Data(xmlData),
- format: nil
+ format: nil,
) as? [String: Any],
- let items = plist["_PrelinkInfoDictionary"] as? [[String: Any]]
+ let items = plist["_PrelinkInfoDictionary"] as? [[String: Any]]
else {
return nil
}
@@ -222,7 +222,7 @@ extension KernelPatcher {
// _PrelinkExecutableLoadAddr is the kext's load address
guard let loadAddrRaw = item["_PrelinkExecutableLoadAddr"],
let loadAddrInt = (loadAddrRaw as? UInt64)
- ?? (loadAddrRaw as? Int).map({ UInt64(bitPattern: Int64($0)) })
+ ?? (loadAddrRaw as? Int).map({ UInt64(bitPattern: Int64($0)) })
else {
continue
}
diff --git a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
index 55fb2f98..d388023b 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
@@ -55,7 +55,7 @@ extension KernelJailbreakPatcher {
off,
errLo: errLo,
errHi: errHi,
- imagebootNeeded: imagebootNeeded
+ imagebootNeeded: imagebootNeeded,
) else { continue }
candidates.append((off, state))
}
diff --git a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
index dede7046..4997f005 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
@@ -138,14 +138,14 @@ extension KernelJailbreakPatcher {
funcEnd: rnpEnd,
mnemonic: "ldrh",
disp: 0xD8,
- requireWDest: false
+ requireWDest: false,
),
let f2 = findUniqueFieldLoad(
funcStart: rnpStart,
funcEnd: rnpEnd,
mnemonic: "ldr",
disp: 0xE8,
- requireWDest: true
+ requireWDest: true,
)
else {
log(" [~] notification-port bound-check loads not both present — skipping GATE2 (all-or-nothing)")
diff --git a/sources/VPhoneAPIKit/VPhoneAPIClient.swift b/sources/VPhoneAPIKit/VPhoneAPIClient.swift
index d95bdbb4..9e7370cb 100644
--- a/sources/VPhoneAPIKit/VPhoneAPIClient.swift
+++ b/sources/VPhoneAPIKit/VPhoneAPIClient.swift
@@ -11,22 +11,29 @@ public indirect enum VPhoneJSONValue: Codable, Sendable, Equatable {
public init(from decoder: any Decoder) throws {
let value = try decoder.singleValueContainer()
- if value.decodeNil() { self = .null }
- else if let bool = try? value.decode(Bool.self) { self = .bool(bool) }
- else if let number = try? value.decode(Double.self) { self = .number(number) }
- else if let string = try? value.decode(String.self) { self = .string(string) }
- else if let object = try? value.decode([String: VPhoneJSONValue].self) { self = .object(object) }
- else { self = .array(try value.decode([VPhoneJSONValue].self)) }
+ if value.decodeNil() {
+ self = .null
+ } else if let bool = try? value.decode(Bool.self) {
+ self = .bool(bool)
+ } else if let number = try? value.decode(Double.self) {
+ self = .number(number)
+ } else if let string = try? value.decode(String.self) {
+ self = .string(string)
+ } else if let object = try? value.decode([String: VPhoneJSONValue].self) {
+ self = .object(object)
+ } else {
+ self = try .array(value.decode([VPhoneJSONValue].self))
+ }
}
public func encode(to encoder: any Encoder) throws {
var value = encoder.singleValueContainer()
switch self {
- case .object(let object): try value.encode(object)
- case .array(let array): try value.encode(array)
- case .string(let string): try value.encode(string)
- case .number(let number): try value.encode(number)
- case .bool(let bool): try value.encode(bool)
+ case let .object(object): try value.encode(object)
+ case let .array(array): try value.encode(array)
+ case let .string(string): try value.encode(string)
+ case let .number(number): try value.encode(number)
+ case let .bool(bool): try value.encode(bool)
case .null: try value.encodeNil()
}
}
@@ -35,7 +42,9 @@ public indirect enum VPhoneJSONValue: Codable, Sendable, Equatable {
public struct VPhoneAPIError: Error, Codable, Sendable, CustomStringConvertible {
public let code: String
public let message: String
- public var description: String { "\(code): \(message)" }
+ public var description: String {
+ "\(code): \(message)"
+ }
}
public struct VPhoneAPIResponse: Codable, Sendable {
@@ -70,7 +79,7 @@ public struct VPhoneAPIClient: Sendable {
public func call(
_ method: String,
params: [String: VPhoneJSONValue] = [:],
- id: VPhoneJSONValue = .string(UUID().uuidString)
+ id: VPhoneJSONValue = .string(UUID().uuidString),
) async throws -> VPhoneJSONValue {
let request = Request(id: id, method: method, params: params)
var http = URLRequest(url: baseURL.appending(path: "v1/rpc"))
@@ -83,8 +92,10 @@ public struct VPhoneAPIClient: Sendable {
throw VPhoneAPIError(code: "transport", message: "No HTTP response")
}
let value = try JSONDecoder().decode(VPhoneAPIResponse.self, from: data)
- if let error = value.error { throw error }
- guard (200..<300).contains(response.statusCode), let result = value.result else {
+ if let error = value.error {
+ throw error
+ }
+ guard (200 ..< 300).contains(response.statusCode), let result = value.result else {
throw VPhoneAPIError(code: "protocol", message: "Missing result (HTTP \(response.statusCode))")
}
return result
@@ -114,14 +125,18 @@ public struct VPhoneAPIClient: Sendable {
public func runIcli(
_ arguments: [String],
stdin: String? = nil,
- stdinData: Data? = nil
+ stdinData: Data? = nil,
) async throws -> VPhoneJSONValue {
guard stdin == nil || stdinData == nil else {
throw VPhoneAPIError(code: "input", message: "Pass either stdin or stdinData")
}
var params: [String: VPhoneJSONValue] = ["argv": .array(arguments.map(VPhoneJSONValue.string))]
- if let stdin { params["stdin"] = .string(stdin) }
- if let stdinData { params["stdin_base64"] = .string(stdinData.base64EncodedString()) }
+ if let stdin {
+ params["stdin"] = .string(stdin)
+ }
+ if let stdinData {
+ params["stdin_base64"] = .string(stdinData.base64EncodedString())
+ }
return try await call("icli.execute", params: params)
}
@@ -144,9 +159,9 @@ public struct VPhoneAPIClient: Sendable {
public func uploadFile(
from localURL: URL,
toGuestPath guestPath: String,
- permissions: String = "644"
+ permissions: String = "644",
) async throws -> VPhoneJSONValue {
- var request = URLRequest(url: try fileURL(guestPath, mode: permissions))
+ var request = try URLRequest(url: fileURL(guestPath, mode: permissions))
request.httpMethod = "PUT"
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
let (data, response) = try await session.upload(for: request, fromFile: localURL)
@@ -167,7 +182,9 @@ public struct VPhoneAPIClient: Sendable {
resolvingAgainstBaseURL: false)
else { throw VPhoneAPIError(code: "path", message: "Guest path must be absolute") }
components.queryItems = [URLQueryItem(name: "path", value: guestPath)]
- if let mode { components.queryItems?.append(URLQueryItem(name: "mode", value: mode)) }
+ if let mode {
+ components.queryItems?.append(URLQueryItem(name: "mode", value: mode))
+ }
guard let url = components.url else { throw VPhoneAPIError(code: "url", message: "Invalid file URL") }
return url
}
@@ -182,12 +199,14 @@ public struct VPhoneAPIClient: Sendable {
public actor VPhoneAPIWebSocket {
private let task: URLSessionWebSocketTask
- init(task: URLSessionWebSocketTask) { self.task = task }
+ init(task: URLSessionWebSocketTask) {
+ self.task = task
+ }
public func send(
_ method: String,
params: [String: VPhoneJSONValue] = [:],
- id: VPhoneJSONValue = .string(UUID().uuidString)
+ id: VPhoneJSONValue = .string(UUID().uuidString),
) async throws {
let object: [String: VPhoneJSONValue] = [
"id": id, "method": .string(method), "params": .object(params),
@@ -200,16 +219,16 @@ public actor VPhoneAPIWebSocket {
let message = try await task.receive()
let data: Data
switch message {
- case .data(let bytes): data = bytes
- case .string(let text): data = Data(text.utf8)
+ case let .data(bytes): data = bytes
+ case let .string(text): data = Data(text.utf8)
@unknown default: throw VPhoneAPIError(code: "protocol", message: "Unknown WebSocket message")
}
let object = try JSONDecoder().decode([String: VPhoneJSONValue].self, from: data)
switch object["type"] {
case .string("response"):
- return .response(try JSONDecoder().decode(VPhoneAPIResponse.self, from: data))
+ return try .response(JSONDecoder().decode(VPhoneAPIResponse.self, from: data))
case .string("event"):
- return .event(try JSONDecoder().decode(VPhoneAPIEvent.self, from: data))
+ return try .event(JSONDecoder().decode(VPhoneAPIEvent.self, from: data))
default:
throw VPhoneAPIError(code: "protocol", message: "Unknown WebSocket envelope")
}
diff --git a/sources/VPhoneCore/VPhoneBootCLI.swift b/sources/VPhoneCore/VPhoneBootCLI.swift
index 09ec65bb..04b32b7a 100644
--- a/sources/VPhoneCore/VPhoneBootCLI.swift
+++ b/sources/VPhoneCore/VPhoneBootCLI.swift
@@ -3,9 +3,9 @@ import Foundation
// MARK: - Manifest values the CLI can take as arguments
-// Kept here, with the other ArgumentParser conformances, rather than beside
-// the type: the manifest is a data model and has no other reason to know that
-// a command line exists.
+/// Kept here, with the other ArgumentParser conformances, rather than beside
+/// the type: the manifest is a data model and has no other reason to know that
+/// a command line exists.
extension VPhoneVirtualMachineManifest.PlatformFusing: ExpressibleByArgument {}
// MARK: - VPhoneBootCLI
@@ -41,13 +41,13 @@ public struct VPhoneBootCLI: ParsableCommand {
Example:
vphone-cli --config ./config.plist
- """
+ """,
)
@Option(
name: .shortAndLong,
help: "Path to VM manifest plist (config.plist). Required.",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
public var config: URL
@@ -68,7 +68,7 @@ public struct VPhoneBootCLI: ParsableCommand {
@Option(
help: "Automatically install the given IPA/TIPA after the guest control channel connects. Unavailable with --dfu.",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
public var installIPA: URL?
@@ -87,15 +87,16 @@ public struct VPhoneBootCLI: ParsableCommand {
if !dfu,
let bundle = try? VPhoneBundle.load(at: config.deletingLastPathComponent()),
let existingVariant = VPhoneRestoreInfo.load(fromBundle: bundle)?.variant,
- existingVariant != "jb" {
+ existingVariant != "jb"
+ {
throw ValidationError(
- "This VM was created as '\(existingVariant)'. Only JB VMs are supported by this build."
+ "This VM was created as '\(existingVariant)'. Only JB VMs are supported by this build.",
)
}
if dfu, let packageURL = installPackageURL {
throw ValidationError(
- "`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)"
+ "`--install-ipa` is unavailable with `--dfu` because DFU mode does not start the guest control channel: \(packageURL.path)",
)
}
@@ -105,7 +106,7 @@ public struct VPhoneBootCLI: ParsableCommand {
if let apiListen {
let address = URLComponents(string: "tcp://\(apiListen)")
guard let address, let host = address.host, !host.isEmpty,
- let port = address.port, (0...65535).contains(port),
+ let port = address.port, (0 ... 65535).contains(port),
address.path.isEmpty, address.query == nil, address.fragment == nil
else {
throw ValidationError("`--api-listen` requires host:port, for example 127.0.0.1:8765.")
@@ -120,7 +121,7 @@ public struct VPhoneBootCLI: ParsableCommand {
guard VPhoneInstallPackage.isSupportedFile(packageURL) else {
throw ValidationError(
- "`--install-ipa` only supports .ipa or .tipa packages: \(packageURL.lastPathComponent)"
+ "`--install-ipa` only supports .ipa or .tipa packages: \(packageURL.lastPathComponent)",
)
}
}
@@ -139,12 +140,24 @@ public struct VPhoneBootCLI: ParsableCommand {
/// command, so its arguments start at the first option.
public var bootArguments: [String] {
var args = ["--config", config.path]
- if dfu { args.append("--dfu") }
- if headless { args.append("--headless") }
- if let apiListen { args += ["--api-listen", apiListen] }
- if vphonedBin != ".vphoned.signed" { args += ["--vphoned-bin", vphonedBin] }
- if let port = kernelDebugPort { args += ["--kernel-debug-port", String(port)] }
- if let ipa = installIPA { args += ["--install-ipa", ipa.path] }
+ if dfu {
+ args.append("--dfu")
+ }
+ if headless {
+ args.append("--headless")
+ }
+ if let apiListen {
+ args += ["--api-listen", apiListen]
+ }
+ if vphonedBin != ".vphoned.signed" {
+ args += ["--vphoned-bin", vphonedBin]
+ }
+ if let port = kernelDebugPort {
+ args += ["--kernel-debug-port", String(port)]
+ }
+ if let ipa = installIPA {
+ args += ["--install-ipa", ipa.path]
+ }
return args
}
}
diff --git a/sources/VPhoneSign/VPhoneMachOImage.swift b/sources/VPhoneSign/VPhoneMachOImage.swift
index 10f9de95..fb09ba01 100644
--- a/sources/VPhoneSign/VPhoneMachOImage.swift
+++ b/sources/VPhoneSign/VPhoneMachOImage.swift
@@ -344,14 +344,14 @@ struct VPhoneMachOImage {
firstContent <= UInt64(codeEnd)
else {
throw VPhoneSignError.noRoom(
- "content starts at \(firstContent), \(Self.headerSize + rebuilt) bytes of commands"
+ "content starts at \(firstContent), \(Self.headerSize + rebuilt) bytes of commands",
)
}
var area = Data()
for command in carried {
var bytes = image.subdata(
- in: Self.headerSize + command.offset ..< Self.headerSize + command.offset + command.size
+ in: Self.headerSize + command.offset ..< Self.headerSize + command.offset + command.size,
)
// ldid sets the size of every __LINKEDIT there is
if command.command == UInt32(LC_SEGMENT_64), Self.name(in: bytes, at: 8) == Self.linkedit {
diff --git a/sources/VPhoneSign/VPhoneSignEntitlements.swift b/sources/VPhoneSign/VPhoneSignEntitlements.swift
index ee1e3647..743df7ad 100644
--- a/sources/VPhoneSign/VPhoneSignEntitlements.swift
+++ b/sources/VPhoneSign/VPhoneSignEntitlements.swift
@@ -219,7 +219,8 @@ struct VPhoneSignEntitlements: Equatable {
out += "<dict>\n".utf8
for entry in sorted
? entries.sorted(by: { $0.key.utf16.lexicographicallyPrecedes($1.key.utf16) })
- : entries {
+ : entries
+ {
out += indent + [0x09]
text("key", entry.key)
write(entry.value, depth: depth + 1, sorted: sorted, into: &out)
diff --git a/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneAPIProxy.swift b/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneAPIProxy.swift
index caa0fbf9..51d5c3b3 100644
--- a/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneAPIProxy.swift
+++ b/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneAPIProxy.swift
@@ -14,7 +14,7 @@ public final class VPhoneAPIProxy {
public var description: String {
switch self {
- case .invalidListenAddress(let value):
+ case let .invalidListenAddress(value):
"Invalid API listen address '\(value)'; use host:port, for example 127.0.0.1:8765"
}
}
@@ -29,19 +29,19 @@ public final class VPhoneAPIProxy {
public init(device: VZVirtioSocketDevice, listen: String) throws {
guard let components = URLComponents(string: "tcp://\(listen)"),
let host = components.host, !host.isEmpty,
- let port = components.port, (0...65535).contains(port),
+ let port = components.port, (0 ... 65535).contains(port),
components.path.isEmpty, components.query == nil, components.fragment == nil
else { throw ProxyError.invalidListenAddress(listen) }
self.host = host
self.port = port
- self.provider = GuestSocketProvider(device: device, group: group)
+ provider = GuestSocketProvider(device: device, group: group)
}
/// Starts only when the boot command explicitly supplied `--api-listen`.
/// The returned URL contains the actual port when the caller requested 0.
@discardableResult
public func start() async throws -> URL {
- let provider = self.provider
+ let provider = provider
let channel = try await ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 128)
.childChannelOption(ChannelOptions.autoRead, value: false)
@@ -61,7 +61,9 @@ public final class VPhoneAPIProxy {
server?.close(promise: nil)
server = nil
group.shutdownGracefully { error in
- if let error { print("[api] proxy shutdown: \(error)") }
+ if let error {
+ print("[api] proxy shutdown: \(error)")
+ }
}
}
}
@@ -82,10 +84,10 @@ private final class GuestSocketProvider: @unchecked Sendable {
device.connect(toPort: guestPort) { result in
Task { @MainActor in
switch result {
- case .failure(let error):
+ case let .failure(error):
print("[api] guest connection failed: \(error)")
promise.fail(error)
- case .success(let connection):
+ case let .success(connection):
let fd = dup(connection.fileDescriptor)
guard fd >= 0 else {
promise.fail(POSIXError(.EBADF))
@@ -105,7 +107,7 @@ private final class GuestSocketProvider: @unchecked Sendable {
switch result {
case .success:
host.setOption(ChannelOptions.autoRead, value: true).cascade(to: promise)
- case .failure(let error):
+ case let .failure(error):
print("[api] guest relay failed: \(error)")
promise.fail(error)
}
@@ -141,9 +143,11 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {
}
}
- init(connection: VZVirtioSocketConnection) { self.connection = connection }
+ init(connection: VZVirtioSocketConnection) {
+ self.connection = connection
+ }
- func channelRead(context: ChannelHandlerContext, data: NIOAny) {
+ func channelRead(context _: ChannelHandlerContext, data: NIOAny) {
guard let peer else { return }
peer.writeAndFlush(unwrapInboundIn(data), promise: nil)
}
@@ -162,7 +166,7 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {
context.fireChannelInactive()
}
- func errorCaught(context: ChannelHandlerContext, error: Error) {
+ func errorCaught(context: ChannelHandlerContext, error _: Error) {
context.close(promise: nil)
}
}
diff --git a/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift b/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift
index ff3c5f8b..fb135a52 100644
--- a/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift
+++ b/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift
@@ -16,9 +16,9 @@ final class VPhoneGuestControl {
var description: String {
switch self {
case .notConnected: "not connected to vphoned"
- case .unsupportedCapability(let value): "guest does not support capability: \(value)"
- case .protocolError(let value): "API protocol error: \(value)"
- case .guestError(let value): value
+ case let .unsupportedCapability(value): "guest does not support capability: \(value)"
+ case let .protocolError(value): "API protocol error: \(value)"
+ case let .guestError(value): value
}
}
}
@@ -74,11 +74,13 @@ final class VPhoneGuestControl {
let response = try await http(method: "GET", path: "/v1/health")
guard response.status == 200,
let info = try JSONSerialization.jsonObject(with: response.body) as? [String: Any],
- info["api_version"] as? Int == 1 else {
+ info["api_version"] as? Int == 1
+ else {
throw ControlError.protocolError("incompatible guest API")
}
if let binary = guestBinaryURL,
- let data = try? Data(contentsOf: binary, options: .mappedIfSafe) {
+ let data = try? Data(contentsOf: binary, options: .mappedIfSafe)
+ {
let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
if hash != info["binary_hash"] as? String {
print("[control] updating vphoned over HTTP...")
@@ -98,7 +100,9 @@ final class VPhoneGuestControl {
onConnect?(guestCapabilities)
}
} catch {
- if !isConnected { print("[control] probe failed: \(error)") }
+ if !isConnected {
+ print("[control] probe failed: \(error)")
+ }
setDisconnected()
}
}
@@ -109,16 +113,28 @@ final class VPhoneGuestControl {
guestCapabilities = []
guestIPAddress = nil
guestIOSVersion = nil
- if wasConnected { onDisconnect?() }
+ if wasConnected {
+ onDisconnect?()
+ }
+ }
+
+ func sendHIDPress(page: UInt32, usage: UInt32) {
+ sendHID(page: page, usage: usage, down: nil)
}
- func sendHIDPress(page: UInt32, usage: UInt32) { sendHID(page: page, usage: usage, down: nil) }
- func sendHIDDown(page: UInt32, usage: UInt32) { sendHID(page: page, usage: usage, down: true) }
- func sendHIDUp(page: UInt32, usage: UInt32) { sendHID(page: page, usage: usage, down: false) }
+ func sendHIDDown(page: UInt32, usage: UInt32) {
+ sendHID(page: page, usage: usage, down: true)
+ }
+
+ func sendHIDUp(page: UInt32, usage: UInt32) {
+ sendHID(page: page, usage: usage, down: false)
+ }
private func sendHID(page: UInt32, usage: UInt32, down: Bool?) {
var params: [String: Any] = ["page": page, "usage": usage]
- if let down { params["down"] = down }
+ if let down {
+ params["down"] = down
+ }
enqueueInput("input.hid", params: params)
}
@@ -141,7 +157,9 @@ final class VPhoneGuestControl {
try await call("developer_mode.status")["enabled"] as? Bool ?? false
}
- func sendPing() async throws { _ = try await http(method: "GET", path: "/v1/health") }
+ func sendPing() async throws {
+ _ = try await http(method: "GET", path: "/v1/health")
+ }
func guestBinaryHash() async throws -> String {
let response = try await http(method: "GET", path: "/v1/health")
@@ -156,7 +174,7 @@ final class VPhoneGuestControl {
throw ControlError.protocolError("missing operation")
}
if type == "file_get" {
- return ([:], try await downloadFile(path: request["path"] as? String ?? ""))
+ return try await ([:], downloadFile(path: request["path"] as? String ?? ""))
}
if type == "clipboard_get" {
var info = try await call("clipboard.get")
@@ -190,7 +208,9 @@ final class VPhoneGuestControl {
var params = request
params.removeValue(forKey: "t")
var result = try await call(method, params: params)
- if result["ok"] == nil { result["ok"] = true }
+ if result["ok"] == nil {
+ result["ok"] = true
+ }
return (result, nil)
}
@@ -217,7 +237,7 @@ final class VPhoneGuestControl {
}
func downloadFile(path: String) async throws -> Data {
- let response = try await http(method: "GET", path: try filePath(path))
+ let response = try await http(method: "GET", path: filePath(path))
guard response.status == 200 else { throw try httpError(response) }
return response.body
}
@@ -225,9 +245,9 @@ final class VPhoneGuestControl {
func uploadFile(path: String, data: Data, permissions: String = "644") async throws {
let response = try await http(
method: "PUT",
- path: try filePath(path, mode: permissions),
+ path: filePath(path, mode: permissions),
body: data,
- contentType: "application/octet-stream"
+ contentType: "application/octet-stream",
)
guard response.status == 200 else { throw try httpError(response) }
}
@@ -261,7 +281,7 @@ final class VPhoneGuestControl {
types: info["types"] as? [String] ?? [],
hasImage: info["has_image"] as? Bool ?? false,
changeCount: info["change_count"] as? Int ?? 0,
- imageData: image
+ imageData: image,
)
}
@@ -274,7 +294,7 @@ final class VPhoneGuestControl {
method: "PUT",
path: "/v1/clipboard/image",
body: imageData,
- contentType: "application/octet-stream"
+ contentType: "application/octet-stream",
)
guard response.status == 200 else { throw try httpError(response) }
}
@@ -286,7 +306,7 @@ final class VPhoneGuestControl {
horizontalAccuracy: Double,
verticalAccuracy: Double,
speed: Double,
- course: Double
+ course: Double,
) {
Task {
do { _ = try await call("location.set", params: [
@@ -299,7 +319,8 @@ final class VPhoneGuestControl {
func sendLocationStop() {
Task { do { _ = try await call("location.clear") }
- catch { print("[control] location clear: \(error)") } }
+ catch { print("[control] location clear: \(error)") }
+ }
}
private func filePath(_ guestPath: String, mode: String? = nil) throws -> String {
@@ -309,7 +330,9 @@ final class VPhoneGuestControl {
var components = URLComponents()
components.path = "/v1/files/content"
components.queryItems = [URLQueryItem(name: "path", value: guestPath)]
- if let mode { components.queryItems?.append(URLQueryItem(name: "mode", value: mode)) }
+ if let mode {
+ components.queryItems?.append(URLQueryItem(name: "mode", value: mode))
+ }
return components.string ?? ""
}
@@ -323,7 +346,7 @@ final class VPhoneGuestControl {
method: String,
path: String,
body: Data = Data(),
- contentType: String = "application/json"
+ contentType: String = "application/json",
) async throws -> VPhoneHTTPResponse {
guard let device else { throw ControlError.notConnected }
let socket = await withCheckedContinuation {
@@ -336,11 +359,11 @@ final class VPhoneGuestControl {
method: method,
path: path,
body: body,
- contentType: contentType
+ contentType: contentType,
)
return try await withCheckedThrowingContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
- do { continuation.resume(returning: try transaction.run()) }
+ do { try continuation.resume(returning: transaction.run()) }
catch { continuation.resume(throwing: error) }
}
}
@@ -354,7 +377,9 @@ private struct VPhoneHTTPResponse: Sendable {
private struct VPhoneSocketResult: @unchecked Sendable {
let result: Result<VZVirtioSocketConnection, any Error>
- init(_ result: Result<VZVirtioSocketConnection, any Error>) { self.result = result }
+ init(_ result: Result<VZVirtioSocketConnection, any Error>) {
+ self.result = result
+ }
}
private final class VPhoneHTTPTransaction: @unchecked Sendable {
@@ -369,7 +394,7 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
method: String,
path: String,
body: Data,
- contentType: String
+ contentType: String,
) {
self.connection = connection
self.method = method
@@ -386,13 +411,16 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
var timeout = timeval(tv_sec: 120, tv_usec: 0)
guard setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout,
socklen_t(MemoryLayout<timeval>.size)) == 0,
- setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
- socklen_t(MemoryLayout<timeval>.size)) == 0 else {
+ setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
+ socklen_t(MemoryLayout<timeval>.size)) == 0
+ else {
throw VPhoneGuestControl.ControlError.notConnected
}
let headers = "\(method) \(path) HTTP/1.1\r\nHost: vphoned\r\nConnection: close\r\nContent-Type: \(contentType)\r\nContent-Length: \(body.count)\r\n\r\n"
try write(fd, data: Data(headers.utf8))
- if !body.isEmpty { try write(fd, data: body) }
+ if !body.isEmpty {
+ try write(fd, data: body)
+ }
var received = Data()
let marker = Data("\r\n\r\n".utf8)
@@ -410,11 +438,14 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
}
guard let lengthLine = lines.first(where: { $0.lowercased().hasPrefix("content-length:") }),
let length = Int(lengthLine.split(separator: ":", maxSplits: 1)[1].trimmingCharacters(in: .whitespaces)),
- length >= 0, length <= 2_147_483_647 else {
+ length >= 0, length <= 2_147_483_647
+ else {
throw VPhoneGuestControl.ControlError.protocolError("missing HTTP content length")
}
var payload = Data(received[boundary.upperBound...])
- while payload.count < length { try readMore(fd, into: &payload) }
+ while payload.count < length {
+ try readMore(fd, into: &payload)
+ }
guard payload.count == length else {
throw VPhoneGuestControl.ControlError.protocolError("HTTP body length mismatch")
}
@@ -427,8 +458,12 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
var offset = 0
while offset < bytes.count {
let sent = Darwin.write(fd, base + offset, bytes.count - offset)
- if sent < 0 && errno == EINTR { continue }
- if sent <= 0 { throw VPhoneGuestControl.ControlError.notConnected }
+ if sent < 0, errno == EINTR {
+ continue
+ }
+ if sent <= 0 {
+ throw VPhoneGuestControl.ControlError.notConnected
+ }
offset += sent
}
}
@@ -437,8 +472,12 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
private func readMore(_ fd: Int32, into data: inout Data) throws {
var bytes = [UInt8](repeating: 0, count: 32 * 1024)
var count = 0
- repeat { count = Darwin.read(fd, &bytes, bytes.count) } while count < 0 && errno == EINTR
- guard count > 0 else { throw VPhoneGuestControl.ControlError.notConnected }
+ repeat {
+ count = Darwin.read(fd, &bytes, bytes.count)
+ } while count < 0 && errno == EINTR
+ guard count > 0 else {
+ throw VPhoneGuestControl.ControlError.notConnected
+ }
data.append(contentsOf: bytes[..<count])
}
}
diff --git a/sources/VPhoneVirtualMachineKit/HostDevices/VPhoneCameraServer.swift b/sources/VPhoneVirtualMachineKit/HostDevices/VPhoneCameraServer.swift
index d2904aa4..89a044e3 100644
--- a/sources/VPhoneVirtualMachineKit/HostDevices/VPhoneCameraServer.swift
+++ b/sources/VPhoneVirtualMachineKit/HostDevices/VPhoneCameraServer.swift
@@ -23,14 +23,14 @@ final class VPhoneCameraServer {
enum SourceKind: String {
case off
case testPattern
- case videoFile // .mov / .mp4 / .m4v via AVAssetReader
+ case videoFile // .mov / .mp4 / .m4v via AVAssetReader
}
nonisolated static let vsockPort: UInt32 = 1338
nonisolated static let defaultWidth: Int = 1280
nonisolated static let defaultHeight: Int = 720
nonisolated static let defaultFPS: Double = 30.0
- nonisolated static let pixelFormat: UInt32 = 0x4247_5241 // 'BGRA' — kCMPixelFormat_32BGRA
+ nonisolated static let pixelFormat: UInt32 = 0x4247_5241 // 'BGRA' — kCMPixelFormat_32BGRA
private(set) var sourceKind: SourceKind = .off
private(set) var isConnected = false
@@ -45,7 +45,7 @@ final class VPhoneCameraServer {
private let producerQueue = DispatchQueue(
label: "com.vphone.camera.producer",
- qos: .userInteractive
+ qos: .userInteractive,
)
var onConnectionStateChange: ((Bool) -> Void)?
@@ -73,9 +73,13 @@ final class VPhoneCameraServer {
// MARK: - Source selection
func setSource(_ kind: SourceKind, videoURL: URL? = nil) {
- if sourceKind == kind, kind != .videoFile { return }
+ if sourceKind == kind, kind != .videoFile {
+ return
+ }
let wasStreaming = (timer != nil)
- if wasStreaming { stopStreaming() }
+ if wasStreaming {
+ stopStreaming()
+ }
sourceKind = kind
switch kind {
case .off:
@@ -83,7 +87,7 @@ final class VPhoneCameraServer {
case .testPattern:
producer = VPhoneTestPatternProducer(
width: Self.defaultWidth,
- height: Self.defaultHeight
+ height: Self.defaultHeight,
)
case .videoFile:
guard let url = videoURL else {
@@ -96,7 +100,7 @@ final class VPhoneCameraServer {
producer = try VPhoneVideoFileProducer(
url: url,
width: Self.defaultWidth,
- height: Self.defaultHeight
+ height: Self.defaultHeight,
)
print("[camera] video file source = \(url.lastPathComponent)")
} catch {
@@ -114,7 +118,9 @@ final class VPhoneCameraServer {
func startStreaming() {
guard producer != nil, isConnected else { return }
- if timer != nil { return }
+ if timer != nil {
+ return
+ }
let interval = 1.0 / Self.defaultFPS
// Timer fires on the main queue so MainActor-isolated state
// (producer, connectionFD) can be read directly without tripping
@@ -125,31 +131,32 @@ final class VPhoneCameraServer {
t.schedule(deadline: .now(), repeating: interval, leeway: .milliseconds(2))
t.setEventHandler { [weak self] in
guard let self else { return }
- guard let producer = self.producer else { return }
- guard !self.framePending, self.connectionFD >= 0 else { return }
- let sourceFD = self.connectionFD
+ guard let producer else { return }
+ guard !framePending, connectionFD >= 0 else { return }
+ let sourceFD = connectionFD
let fd = dup(sourceFD)
- guard fd >= 0 else { self.handleDisconnect(); return }
+ guard fd >= 0 else { handleDisconnect(); return }
var timeout = timeval(tv_sec: 5, tv_usec: 0)
guard fcntl(fd, F_SETNOSIGPIPE, 1) != -1,
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
- socklen_t(MemoryLayout<timeval>.size)) == 0 else {
+ socklen_t(MemoryLayout<timeval>.size)) == 0
+ else {
close(fd)
- self.handleDisconnect()
+ handleDisconnect()
return
}
- self.framePending = true
- let connectionToken = self.connectionAttemptToken
- let q = self.producerQueue
+ framePending = true
+ let connectionToken = connectionAttemptToken
+ let q = producerQueue
q.async { [weak self] in
let frame = producer.nextFrame()
let ok = frame.map { Self.send(fd: fd, frame: $0) } ?? true
close(fd)
Task { @MainActor [weak self] in
guard let self else { return }
- self.framePending = false
- if !ok && self.connectionAttemptToken == connectionToken && self.connectionFD == sourceFD {
- self.handleDisconnect()
+ framePending = false
+ if !ok, connectionAttemptToken == connectionToken, connectionFD == sourceFD {
+ handleDisconnect()
}
}
}
@@ -200,7 +207,9 @@ final class VPhoneCameraServer {
self.isConnected = true
print("[camera] connected on vsock port \(Self.vsockPort)")
self.onConnectionStateChange?(true)
- if self.sourceKind != .off { self.startStreaming() }
+ if self.sourceKind != .off {
+ self.startStreaming()
+ }
case let .failure(error):
print("[camera] connect failed: \(error). Retrying in 3s.")
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { [weak self] in
@@ -218,7 +227,7 @@ final class VPhoneCameraServer {
// MARK: - Wire
@discardableResult
- nonisolated private static func send(fd: Int32, frame: VPhoneCameraFrame) -> Bool {
+ private nonisolated static func send(fd: Int32, frame: VPhoneCameraFrame) -> Bool {
// header
let headerDict: [String: Any] = [
"w": frame.width,
@@ -244,19 +253,23 @@ final class VPhoneCameraServer {
out.append(headerData)
out.append(frame.pixels)
var ok = true
- out.withUnsafeBytes { bytes -> Void in
+ out.withUnsafeBytes { bytes in
guard let base = bytes.baseAddress else { ok = false; return }
var remaining = bytes.count
var cursor = base
while remaining > 0 {
let n = write(fd, cursor, remaining)
if n < 0 {
- if errno == EINTR { continue }
+ if errno == EINTR {
+ continue
+ }
print("[camera] write errno=\(errno)")
ok = false
return
}
- if n == 0 { ok = false; return }
+ if n == 0 {
+ ok = false; return
+ }
remaining -= n
cursor = cursor.advanced(by: n)
}
diff --git a/sources/VPhoneVirtualMachineKit/VPhoneHostAutomationServer.swift b/sources/VPhoneVirtualMachineKit/VPhoneHostAutomationServer.swift
index bb4064ce..e664cde4 100644
--- a/sources/VPhoneVirtualMachineKit/VPhoneHostAutomationServer.swift
+++ b/sources/VPhoneVirtualMachineKit/VPhoneHostAutomationServer.swift
@@ -57,7 +57,7 @@ class VPhoneHostAutomationServer {
screenRecorder: VPhoneScreenRecorder,
control: VPhoneGuestControl,
screenWidth: Int,
- screenHeight: Int
+ screenHeight: Int,
) {
self.captureView = captureView
self.screenRecorder = screenRecorder
@@ -149,7 +149,7 @@ class VPhoneHostAutomationServer {
bitsPerComponent: 8,
bytesPerRow: dstW,
space: gray,
- bitmapInfo: CGImageAlphaInfo.none.rawValue
+ bitmapInfo: CGImageAlphaInfo.none.rawValue,
) else { return nil }
// High contrast: bump brightness
@@ -184,8 +184,9 @@ class VPhoneHostAutomationServer {
var timeout = timeval(tv_sec: 15, tv_usec: 0)
guard setsockopt(clientFD, SOL_SOCKET, SO_RCVTIMEO, &timeout,
socklen_t(MemoryLayout<timeval>.size)) == 0,
- setsockopt(clientFD, SOL_SOCKET, SO_SNDTIMEO, &timeout,
- socklen_t(MemoryLayout<timeval>.size)) == 0 else {
+ setsockopt(clientFD, SOL_SOCKET, SO_SNDTIMEO, &timeout,
+ socklen_t(MemoryLayout<timeval>.size)) == 0
+ else {
close(clientFD)
continue
}
@@ -284,7 +285,7 @@ class VPhoneHostAutomationServer {
pixelX: x,
pixelY: y,
screenWidth: controller.screenWidth,
- screenHeight: controller.screenHeight
+ screenHeight: controller.screenHeight,
)
result.ok = true
if wantScreen {
@@ -320,7 +321,7 @@ class VPhoneHostAutomationServer {
toY: y2,
screenWidth: controller.screenWidth,
screenHeight: controller.screenHeight,
- durationMs: durationMs
+ durationMs: durationMs,
)
result.ok = true
if wantScreen {
@@ -414,7 +415,9 @@ class VPhoneHostAutomationServer {
let n = read(fd, &buffer, buffer.count)
guard n > 0 else { break }
accumulated.append(contentsOf: buffer[..<n])
- if accumulated.contains(0x0A) { break }
+ if accumulated.contains(0x0A) {
+ break
+ }
}
if let nlRange = accumulated.firstIndex(of: 0x0A) {
@@ -428,12 +431,18 @@ class VPhoneHostAutomationServer {
ok: Bool,
path: String? = nil,
error: String? = nil,
- image: String? = nil
+ image: String? = nil,
) {
var dict: [String: Any] = ["ok": ok]
- if let path { dict["path"] = path }
- if let error { dict["error"] = error }
- if let image { dict["image"] = image }
+ if let path {
+ dict["path"] = path
+ }
+ if let error {
+ dict["error"] = error
+ }
+ if let image {
+ dict["image"] = image
+ }
guard let data = try? JSONSerialization.data(withJSONObject: dict),
var json = String(data: data, encoding: .utf8)
@@ -445,8 +454,12 @@ class VPhoneHostAutomationServer {
var offset = 0
while remaining > 0 {
let written = write(fd, ptr.advanced(by: offset), remaining)
- if written < 0 && errno == EINTR { continue }
- if written <= 0 { break }
+ if written < 0, errno == EINTR {
+ continue
+ }
+ if written <= 0 {
+ break
+ }
offset += written
remaining -= written
}
diff --git a/sources/vphone-archive/main.swift b/sources/vphone-archive/main.swift
index c820ffeb..435fd920 100644
--- a/sources/vphone-archive/main.swift
+++ b/sources/vphone-archive/main.swift
@@ -41,32 +41,32 @@ struct Extract: ParsableCommand {
@Option(
name: [.customShort("f"), .long],
help: "Archive to read",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var file: URL
@Option(
name: [.customShort("C"), .customLong("directory")],
help: "Where to unpack it",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var destination: URL = .init(fileURLWithPath: ".")
@Flag(
name: [.customShort("p"), .customLong("preserve-permissions")],
- help: "Restore modes, and — as root — the archive's numeric uid/gid"
+ help: "Restore modes, and — as root — the archive's numeric uid/gid",
)
var preservePermissions = false
@Flag(
name: .customLong("no-overwrite-dir"),
- help: "Leave an existing directory's mode, owner and mtime alone"
+ help: "Leave an existing directory's mode, owner and mtime alone",
)
var noOverwriteDir = false
@Flag(
name: .customLong("numeric-owner"),
- help: "Accepted for compatibility; ownership is always restored by number"
+ help: "Accepted for compatibility; ownership is always restored by number",
)
var numericOwner = false
@@ -107,14 +107,14 @@ struct Create: ParsableCommand {
@Option(
name: [.customShort("f"), .long],
help: "Archive to write",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var file: URL
@Option(
name: [.customShort("C"), .customLong("directory")],
help: "Directory to pack",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var source: URL = .init(fileURLWithPath: ".")
@@ -189,14 +189,14 @@ struct Decompress: ParsableCommand {
@Option(
name: [.customShort("f"), .long],
help: "File to decompress",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var file: URL
@Option(
name: [.customShort("o"), .long],
help: "Where to write the result",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var output: URL
@@ -217,7 +217,7 @@ struct List: ParsableCommand {
@Option(
name: [.customShort("f"), .long],
help: "Archive to read",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var file: URL
@@ -248,7 +248,7 @@ struct Cat: ParsableCommand {
@Option(
name: [.customShort("f"), .long],
help: "Archive to read",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var file: URL
@@ -284,13 +284,13 @@ struct Fingerprint: ParsableCommand {
@Argument(
help: "Second tree; given, the two are compared",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var other: URL?
@Flag(
name: .customLong("no-content-hashes"),
- help: "Skip file digests — much faster, and enough to compare metadata"
+ help: "Skip file digests — much faster, and enough to compare metadata",
)
var noContentHashes = false
diff --git a/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift b/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift
index 655a6ce3..0c988f50 100644
--- a/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift
+++ b/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift
@@ -37,7 +37,7 @@ struct VPhoneCustomFirmwareInstaller {
try VPhoneCustomFirmwareInstaller(
bundle: bundle,
resources: resources,
- forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide
+ forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,
).run()
return 0
}
@@ -160,7 +160,7 @@ struct VPhoneCustomFirmwareInstaller {
work: work,
path: "usr/libexec/seputil",
verb: "patch-seputil",
- identifier: "com.apple.seputil"
+ identifier: "com.apple.seputil",
)
if version.hasPrefix("27.") {
try patchMachO(
@@ -168,7 +168,7 @@ struct VPhoneCustomFirmwareInstaller {
work: work,
path: "usr/libexec/diskimagesiod",
verb: "patch-diskimagesiod",
- preserveEntitlements: true
+ preserveEntitlements: true,
)
}
try renameGigalocker(data: data)
@@ -204,13 +204,13 @@ struct VPhoneCustomFirmwareInstaller {
work: work,
path: "usr/libexec/launchd_cache_loader",
verb: "patch-launchd-cache-loader",
- identifier: "com.apple.launchd_cache_loader"
+ identifier: "com.apple.launchd_cache_loader",
)
try patchMachO(
system: system,
work: work,
path: "usr/libexec/mobileactivationd",
- verb: "patch-mobileactivationd"
+ verb: "patch-mobileactivationd",
)
try installVphoned(system: system, work: work)
try patchMachO(
@@ -218,7 +218,7 @@ struct VPhoneCustomFirmwareInstaller {
work: work,
path: "sbin/launchd",
verb: "patch-launchd-jetsam",
- preserveEntitlements: true
+ preserveEntitlements: true,
)
try patchDebugserver(system: system, work: work)
if version.hasPrefix("27.") {
@@ -242,7 +242,7 @@ struct VPhoneCustomFirmwareInstaller {
"/usr/bin/aea",
["decrypt", "-i", encrypted.path,
"-o", plain.path, "-key-value", key],
- quiet: true
+ quiet: true,
)
let osMount = work.appendingPathComponent("mnt-os")
let appMount = work.appendingPathComponent("mnt-app")
@@ -252,7 +252,7 @@ struct VPhoneCustomFirmwareInstaller {
"/usr/bin/hdiutil",
["attach", "-mountpoint", osMount.path,
plain.path, "-nobrowse", "-owners", "off"],
- quiet: true
+ quiet: true,
)
defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", osMount.path], quiet: true) }
try tool(
@@ -260,7 +260,7 @@ struct VPhoneCustomFirmwareInstaller {
["attach", "-mountpoint", appMount.path,
restore.appendingPathComponent(paths.appOS).path,
"-nobrowse", "-owners", "off"],
- quiet: true
+ quiet: true,
)
defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", appMount.path], quiet: true) }
for (source, destination) in [(osMount, os), (appMount, app)] {
@@ -318,9 +318,8 @@ struct VPhoneCustomFirmwareInstaller {
path: String,
verb: String,
identifier: String? = nil,
- preserveEntitlements: Bool = false
- ) throws
- {
+ preserveEntitlements: Bool = false,
+ ) throws {
let target = system.appendingPathComponent(path)
let backup = target.appendingPathExtension("bak")
if !fm.fileExists(atPath: backup.path) {
@@ -387,8 +386,8 @@ struct VPhoneCustomFirmwareInstaller {
fileAt: staged,
options: .init(
entitlements: Data(contentsOf: ent, options: .mappedIfSafe),
- mergesExisting: true
- )
+ mergesExisting: true,
+ ),
)
try replace(staged, at: target, mode: 0o755)
}
diff --git a/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift b/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift
index e66ec54a..c4770453 100644
--- a/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift
+++ b/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift
@@ -169,7 +169,7 @@ struct VPhoneCustomFirmwareInjectDylibCommand: ParsableCommand {
dylibPath: dylibPath,
into: binary,
weak: true,
- policy: .strip
+ policy: .strip,
)
for injection in injections {
let stripped = injection.removedCodeSignature ? ", signature stripped" : ""
diff --git a/sources/vphone-cli/VPhoneFirmwareAEACLI.swift b/sources/vphone-cli/VPhoneFirmwareAEACLI.swift
index 027e7aee..76a52bf9 100644
--- a/sources/vphone-cli/VPhoneFirmwareAEACLI.swift
+++ b/sources/vphone-cli/VPhoneFirmwareAEACLI.swift
@@ -93,7 +93,7 @@ struct VPhoneFirmwareIM4PExtractCommand: ParsableCommand {
@Option(
name: .customLong("output"),
help: "Where to write the payload",
- transform: URL.init(fileURLWithPath:)
+ transform: URL.init(fileURLWithPath:),
)
var output: URL
diff --git a/sources/vphone-cli/VPhonePCCGPURecovery.swift b/sources/vphone-cli/VPhonePCCGPURecovery.swift
index 6f6ae011..455bcf13 100644
--- a/sources/vphone-cli/VPhonePCCGPURecovery.swift
+++ b/sources/vphone-cli/VPhonePCCGPURecovery.swift
@@ -58,7 +58,8 @@ enum VPhonePCCGPURecovery {
var ecid: UInt64?
while Date() < deadline {
if let value = VPhoneRestoreOperations.resolveECID(explicit: nil, bundle: vm),
- let parsed = try VPhoneRestoreIdentity.parseECID(value) {
+ let parsed = try VPhoneRestoreIdentity.parseECID(value)
+ {
ecid = parsed
break
}
diff --git a/sources/vphone-cli/VPhoneVirtualMachineCreator.swift b/sources/vphone-cli/VPhoneVirtualMachineCreator.swift
index 1f127e90..4130c905 100644
--- a/sources/vphone-cli/VPhoneVirtualMachineCreator.swift
+++ b/sources/vphone-cli/VPhoneVirtualMachineCreator.swift
@@ -168,7 +168,7 @@ public struct VPhoneVirtualMachineCreator {
try runCustomFirmwareInstall(
options: options,
bundleURL: bundleURL,
- sudoEnvironmentExtras: sudoEnvironmentExtras
+ sudoEnvironmentExtras: sudoEnvironmentExtras,
)
// CFW install is the last consumer of the built restore tree (it copies
@@ -424,7 +424,7 @@ public struct VPhoneVirtualMachineCreator {
private func runCustomFirmwareInstall(
options: Options,
bundleURL: URL,
- sudoEnvironmentExtras: [String: String]
+ sudoEnvironmentExtras: [String: String],
) throws {
let v = options.verbosity
// --sudo-password (askpass) wins over --root-popup.
diff --git a/sources/vphone-cli/VPhoneVirtualMachineLaunchCLI.swift b/sources/vphone-cli/VPhoneVirtualMachineLaunchCLI.swift
index cac4d671..da326b6c 100644
--- a/sources/vphone-cli/VPhoneVirtualMachineLaunchCLI.swift
+++ b/sources/vphone-cli/VPhoneVirtualMachineLaunchCLI.swift
@@ -5,7 +5,7 @@ import VPhoneCore
struct VPhoneVirtualMachineLaunchCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "launch",
- abstract: "Boot a VM bundle (runs host preflight first)"
+ abstract: "Boot a VM bundle (runs host preflight first)",
)
@OptionGroup var lib: VPhoneLibraryOption
@@ -65,7 +65,7 @@ struct VPhoneVirtualMachineLaunchCommand: ParsableCommand {
// `vm launch` always streams the guest serial console (inherits our
// stdio); it is intentionally not gated on verbosity. run() also hands
// the terminal to the child, which is what lets Ctrl-C reach the guest.
- throw ExitCode(try launcher.run(args, cwd: bundle.url))
+ throw try ExitCode(launcher.run(args, cwd: bundle.url))
}
}
@@ -74,7 +74,7 @@ struct VPhoneVirtualMachineLaunchCommand: ParsableCommand {
struct VPhoneVirtualMachineStopCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "stop",
- abstract: "Stop a running VM bundle"
+ abstract: "Stop a running VM bundle",
)
@OptionGroup var lib: VPhoneLibraryOption
@@ -89,7 +89,7 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
func runningPIDs() -> [Int32] {
guard let r = try? VPhoneProcessRunner.runCapturing(
URL(fileURLWithPath: "/usr/sbin/lsof"),
- ["-t", "--", disk.path]
+ ["-t", "--", disk.path],
) else { return [] }
return VPhoneLsof.parsePIDs(r.stdout)
}
@@ -98,7 +98,9 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
guard !pids.isEmpty else { print("\(name): not running"); return }
print("\(name): sending SIGINT to \(pids.map(String.init).joined(separator: ", "))")
- for pid in pids { kill(pid, SIGINT) }
+ for pid in pids {
+ kill(pid, SIGINT)
+ }
var waited = 0
while waited < timeout, !runningPIDs().isEmpty {
@@ -108,7 +110,9 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {
let survivors = runningPIDs()
if !survivors.isEmpty {
print("\(name): force-killing \(survivors.map(String.init).joined(separator: ", "))")
- for pid in survivors { kill(pid, SIGKILL) }
+ for pid in survivors {
+ kill(pid, SIGKILL)
+ }
}
print("\(name): stopped")
}
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareCacheLoaderTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareCacheLoaderTests.swift
index 8e9ed71d..cc612465 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareCacheLoaderTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareCacheLoaderTests.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareCacheloaderTests.swift — parity for the launchd_cache_loader unsecure-cache gate.
+// CustomFirmwareCacheLoaderTests.swift — parity for the launchd_cache_loader unsecure-cache gate.
//
// The patch is one instruction in a boot-critical binary, and a wrong one is a
// guest that will not start rather than a failing assertion, so the reference
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift
index 890cfd7b..651d7de6 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift
@@ -187,7 +187,7 @@ struct CustomFirmwareDaemonsTests {
#expect(!strings.contains("-R"))
#expect(
Array(strings.suffix(CustomFirmwareDaemons.dropbearKeyArguments.count))
- == CustomFirmwareDaemons.dropbearKeyArguments
+ == CustomFirmwareDaemons.dropbearKeyArguments,
)
}
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareDiskImageTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareDiskImageTests.swift
index 8822611e..62c9355b 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareDiskImageTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareDiskImageTests.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareDiskimagesiodTests.swift — parity for the diskimagesiod DDI mount gate.
+// CustomFirmwareDiskImageTests.swift — parity for the diskimagesiod DDI mount gate.
//
// The patch is eight bytes over an ObjC method prologue, and a wrong eight
// bytes is a daemon that crashes on first call rather than a failing
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareMobileActivationTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareMobileActivationTests.swift
index d7ae8281..818e22f8 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareMobileActivationTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareMobileActivationTests.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareMobileactivationdTests.swift — `-[DeviceType should_hactivate]` -> YES.
+// CustomFirmwareMobileActivationTests.swift — `-[DeviceType should_hactivate]` -> YES.
//
// The bar here is not "the Swift patcher did something". It is that this port
// and `scripts/patchers/cfw_patch_mobileactivationd.py` produce the same bytes
diff --git a/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift b/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift
index 914b1387..5a031a6a 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift
@@ -394,7 +394,7 @@ struct CustomFirmwareBuildVersionTests {
let swiftOutput = directory.appending(path: "swift-\(format).plist")
try CustomFirmwarePatchFixtures.copyContents(
of: CustomFirmwarePatchFixtures.systemVersionPlist,
- to: swiftOutput
+ to: swiftOutput,
)
try CustomFirmwarePatchFixtures.run("/usr/bin/plutil", ["-convert", format, swiftOutput.path])
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareWatchDogTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareWatchDogTests.swift
index 3ef40267..0117007a 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareWatchDogTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareWatchDogTests.swift
@@ -1,4 +1,4 @@
-// CustomFirmwareWatchdogdTests.swift — parity, anchoring and idempotence for the
+// CustomFirmwareWatchDogTests.swift — parity, anchoring and idempotence for the
// watchdogd hv_vmm_present cache patch.
//
// Two independent references were available for this patch and both are used:
diff --git a/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift b/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift
index 03e42cb2..133734fb 100644
--- a/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift
+++ b/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift
@@ -65,37 +65,37 @@ private enum FrozenReference {
symbol: "+[_NUStyleTransferApplyProcessor processWithInputs:arguments:output:error:]",
vma: 0x1_BF43_0C04,
before: "7f2303d5ef3bb66d",
- after: "00008052c0035fd6"
+ after: "00008052c0035fd6",
),
Site(
symbol: "+[_NUStyleTransferInterpolateProcessor processWithInputs:arguments:output:error:]",
vma: 0x1_BF43_A3A8,
before: "7f2303d5ff0303d1",
- after: "00008052c0035fd6"
+ after: "00008052c0035fd6",
),
Site(
symbol: "+[_NUStyleTransferLearnProcessor processWithInputs:arguments:output:error:]",
vma: 0x1_BF42_EC54,
before: "7f2303d5ff0304d1",
- after: "00008052c0035fd6"
+ after: "00008052c0035fd6",
),
Site(
symbol: "+[_NUStyleTransferProcessor processWithInputs:arguments:output:error:]",
vma: 0x1_BF43_3BD0,
before: "7f2303d5ffc306d1",
- after: "00008052c0035fd6"
+ after: "00008052c0035fd6",
),
Site(
symbol: "+[_NUStyleTransferThumbnailProcessor processWithInputs:arguments:output:error:]",
vma: 0x1_BF43_5DB4,
before: "7f2303d5ff8303d1",
- after: "00008052c0035fd6"
+ after: "00008052c0035fd6",
),
Site(
symbol: "+[AVCaptureDevice authorizationStatusForMediaType:]",
vma: 0x1_AD8A_12D8,
before: "7f2303d5ffc301d1",
- after: "60008052c0035fd6"
+ after: "60008052c0035fd6",
),
]
@@ -476,7 +476,7 @@ struct DyldSharedCacheCameraPatcherBehaviourTests {
let second = try DyldSharedCacheCameraPatcher.applyAll(chunksDirectory: clone, log: nil)
#expect(second.siteCount == 6)
- let allAlreadyPatched = second.sites.allSatisfy { $0.wasAlreadyPatched }
+ let allAlreadyPatched = second.sites.allSatisfy(\.wasAlreadyPatched)
#expect(allAlreadyPatched, "a re-run did not recognise its own output")
#expect(second.reattestation?.updated.isEmpty == true, "a re-run rewrote slot hashes")
#expect(second.isComplete)
diff --git a/tests/FirmwarePatcherTests/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift b/tests/FirmwarePatcherTests/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift
index 1bf0ffb7..72fbdca8 100644
--- a/tests/FirmwarePatcherTests/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift
+++ b/tests/FirmwarePatcherTests/DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift
@@ -1,4 +1,4 @@
-// DyldSharedCacheHVVMMPatcherTests.swift — parity for the hv_vmm_present user-mode cstring
+// DyldSharedCacheHypervisorVirtualMachinePatcherTests.swift — parity for the hv_vmm_present user-mode cstring
// mangle.
//
// There is no external oracle for this patch. `codesign -v` does not apply to a
diff --git a/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift b/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift
index 324fa89f..8285a2fd 100644
--- a/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift
+++ b/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift
@@ -59,187 +59,187 @@ private enum FrozenReference {
publicName: "_IOMobileFramebufferSwapBegin",
publicAddress: 0x2_2AC0_C1B0,
kernName: "_kern_SwapBegin",
- kernAddress: 0x2_2AC0_C1CC
+ kernAddress: 0x2_2AC0_C1CC,
),
Pair(
publicName: "_IOMobileFramebufferSwapCancel",
publicAddress: 0x2_2AC1_23C8,
kernName: "_kern_SwapCancel",
- kernAddress: 0x2_2AC3_D4AC
+ kernAddress: 0x2_2AC3_D4AC,
),
Pair(
publicName: "_IOMobileFramebufferSwapCancelAll",
publicAddress: 0x2_2AC1_24F4,
kernName: "_kern_SwapCancelAll",
- kernAddress: 0x2_2AC1_2510
+ kernAddress: 0x2_2AC1_2510,
),
Pair(
publicName: "_IOMobileFramebufferSwapCancelAllGetCurrent",
publicAddress: 0x2_2AC1_2468,
kernName: "_kern_SwapCancelAllGetCurrent",
- kernAddress: 0x2_2AC1_2484
+ kernAddress: 0x2_2AC1_2484,
),
Pair(
publicName: "_IOMobileFramebufferSwapDebugInfo",
publicAddress: 0x2_2AC0_C734,
kernName: "_kern_SwapDebugInfo",
- kernAddress: 0x2_2AC0_C328
+ kernAddress: 0x2_2AC0_C328,
),
Pair(
publicName: "_IOMobileFramebufferSwapEnd",
publicAddress: 0x2_2AC0_C750,
kernName: "_kern_SwapEnd",
- kernAddress: 0x2_2AC0_C334
+ kernAddress: 0x2_2AC0_C334,
),
Pair(
publicName: "_IOMobileFramebufferSwapGetCurrent",
publicAddress: 0x2_2AC3_A85C,
kernName: "_kern_SwapGetCurrent",
- kernAddress: 0x2_2AC3_D518
+ kernAddress: 0x2_2AC3_D518,
),
Pair(
publicName: "_IOMobileFramebufferSwapSecureLayer",
publicAddress: 0x2_2AC3_A528,
kernName: "_kern_SwapSecureLayer",
- kernAddress: 0x2_2AC3_CB9C
+ kernAddress: 0x2_2AC3_CB9C,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetAmbientLux",
publicAddress: 0x2_2AC0_D0F4,
kernName: "_kern_SwapSetAmbientLux",
- kernAddress: 0x2_2AC0_D110
+ kernAddress: 0x2_2AC0_D110,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetBrightness",
publicAddress: 0x2_2AC0_D214,
kernName: "_kern_SwapSetBrightness",
- kernAddress: 0x2_2AC0_D230
+ kernAddress: 0x2_2AC0_D230,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetBrightnessLimit",
publicAddress: 0x2_2AC1_25B0,
kernName: "_kern_SwapSetBrightnessLimit",
- kernAddress: 0x2_2AC1_25CC
+ kernAddress: 0x2_2AC1_25CC,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetColorMatrix",
publicAddress: 0x2_2AC3_A800,
kernName: "_kern_SwapSetColorMatrix",
- kernAddress: 0x2_2AC3_D2E0
+ kernAddress: 0x2_2AC3_D2E0,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetDisplayEdr",
publicAddress: 0x2_2AC1_2634,
kernName: "_kern_SwapSetDisplayEdr",
- kernAddress: 0x2_2AC1_2650
+ kernAddress: 0x2_2AC1_2650,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetDisplayEdrHeadroom",
publicAddress: 0x2_2AC1_278C,
kernName: "_kern_SwapSetDisplayEdrHeadroom",
- kernAddress: 0x2_2AC1_2724
+ kernAddress: 0x2_2AC1_2724,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetEventSignal",
publicAddress: 0x2_2AC0_BE50,
kernName: "_kern_SwapSetEventSignal",
- kernAddress: 0x2_2AC0_CEBC
+ kernAddress: 0x2_2AC0_CEBC,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetEventSignalOnGlass",
publicAddress: 0x2_2AC3_A560,
kernName: "_kern_SwapSetEventSignalOnGlass",
- kernAddress: 0x2_2AC3_CDB0
+ kernAddress: 0x2_2AC3_CDB0,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetEventWait",
publicAddress: 0x2_2AC0_BE6C,
kernName: "_kern_SwapSetEventWait",
- kernAddress: 0x2_2AC0_BF58
+ kernAddress: 0x2_2AC0_BF58,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetIndicatorBrightnessLimit",
publicAddress: 0x2_2AC1_2594,
kernName: "_kern_SwapSetIndicatorBrightnessLimit",
- kernAddress: 0x2_2AC1_26B8
+ kernAddress: 0x2_2AC1_26B8,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetLFCTimestamps",
publicAddress: 0x2_2AC3_A7AC,
kernName: "_kern_SwapSetLFCTimestamps",
- kernAddress: 0x2_2AC3_DA6C
+ kernAddress: 0x2_2AC3_DA6C,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetLayer",
publicAddress: 0x2_2AC0_CEA0,
kernName: "_kern_SwapSetLayer",
- kernAddress: 0x2_2AC0_C8F4
+ kernAddress: 0x2_2AC0_C8F4,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetLayerEDRCompensation",
publicAddress: 0x2_2AC0_C194,
kernName: "_kern_SwapSetLayerEDRCompensation",
- kernAddress: 0x2_2AC0_BE88
+ kernAddress: 0x2_2AC0_BE88,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetPostBlendLayer",
publicAddress: 0x2_2AC3_A544,
kernName: "_kern_SwapSetPostBlendLayer",
- kernAddress: 0x2_2AC3_CC3C
+ kernAddress: 0x2_2AC3_CC3C,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventSignal",
publicAddress: 0x2_2AC3_A5B4,
kernName: "_kern_SwapSetPostBlendLayerEventSignal",
- kernAddress: 0x2_2AC3_CE98
+ kernAddress: 0x2_2AC3_CE98,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventSignalOnGlass",
publicAddress: 0x2_2AC3_A598,
kernName: "_kern_SwapSetPostBlendLayerEventSignalOnGlass",
- kernAddress: 0x2_2AC3_CE58
+ kernAddress: 0x2_2AC3_CE58,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventWait",
publicAddress: 0x2_2AC3_A57C,
kernName: "_kern_SwapSetPostBlendLayerEventWait",
- kernAddress: 0x2_2AC3_CDE8
+ kernAddress: 0x2_2AC3_CDE8,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetPulseWidthMaximization",
publicAddress: 0x2_2AC4_1AC0,
kernName: "_kern_SwapSetPulseWidthMaximization",
- kernAddress: 0x2_2AC3_D1F4
+ kernAddress: 0x2_2AC3_D1F4,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetResTransitionStrength",
publicAddress: 0x2_2AC4_1ADC,
kernName: "_kern_SwapSetResTransitionStrength",
- kernAddress: 0x2_2AC3_D238
+ kernAddress: 0x2_2AC3_D238,
),
Pair(
publicName: "_IOMobileFramebufferSwapSetSecureAnimation",
publicAddress: 0x2_2AC0_F354,
kernName: "_kern_SwapSetSecureAnimation",
- kernAddress: 0x2_2AC0_F370
+ kernAddress: 0x2_2AC0_F370,
),
Pair(
publicName: "_IOMobileFramebufferSwapSubtitleRegion",
publicAddress: 0x2_2AC3_A720,
kernName: "_kern_SwapSubtitleRegion",
- kernAddress: 0x2_2AC3_CF08
+ kernAddress: 0x2_2AC3_CF08,
),
Pair(
publicName: "_IOMobileFramebufferSwapWait",
publicAddress: 0x2_2AC0_C298,
kernName: "_kern_SwapWait",
- kernAddress: 0x2_2AC0_C2B4
+ kernAddress: 0x2_2AC0_C2B4,
),
Pair(
publicName: "_IOMobileFramebufferSwapWaitWithTimeout",
publicAddress: 0x2_2AC3_A840,
kernName: "_kern_SwapWaitWithTimeout",
- kernAddress: 0x2_2AC3_D420
+ kernAddress: 0x2_2AC3_D420,
),
]
diff --git a/tests/VPhoneCoreTests/FirmwareMatrixTests.swift b/tests/VPhoneCoreTests/FirmwareMatrixTests.swift
index 0f2c2af2..3dbd2887 100644
--- a/tests/VPhoneCoreTests/FirmwareMatrixTests.swift
+++ b/tests/VPhoneCoreTests/FirmwareMatrixTests.swift
@@ -409,7 +409,7 @@ struct FirmwareMatrixRealDataTests {
let tested = try VPhoneFirmwareMatrix.testedBuilds(
readme: RealData.repositoryCompatibilityGuide(),
- device: Fixture.d
+ device: Fixture.d,
)
var supported = 0, notTested = 0
for release in releases {