Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

style: wrap calls and long lines without changing tokens

Lakr826d49c134a5
diff --git a/scripts/vphoned/Daemon/GuestAPI.swift b/scripts/vphoned/Daemon/GuestAPI.swift
index 94e5033f..91392693 100644
--- a/scripts/vphoned/Daemon/GuestAPI.swift
+++ b/scripts/vphoned/Daemon/GuestAPI.swift
@@ -39,9 +39,27 @@ enum GuestAPI {
let ip = addresses.first(where: { $0.hasPrefix("en") && !$0.contains("127.0.0.1") })?
.split(separator: " ").last.map(String.init)
let version = ProcessInfo.processInfo.operatingSystemVersion
- return ["name": "vphoned", "api_version": 1, "status": "ok", "binary_hash": binaryHash,
- "ios": "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)", "ip": ip ?? "",
- "capabilities": ["touch", "hid", "apps", "url", "files", "clipboard", "location", "keychain", "ipa_install", "camera", "icli"]]
+ return [
+ "name": "vphoned",
+ "api_version": 1,
+ "status": "ok",
+ "binary_hash": binaryHash,
+ "ios": "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)",
+ "ip": ip ?? "",
+ "capabilities": [
+ "touch",
+ "hid",
+ "apps",
+ "url",
+ "files",
+ "clipboard",
+ "location",
+ "keychain",
+ "ipa_install",
+ "camera",
+ "icli"
+ ]
+ ]
}
static func execute(method: String, params: [String: Any]) throws -> [String: Any] {
@@ -92,7 +110,11 @@ enum GuestAPI {
let id = front["bundle_id"] as? String ?? ""
let apps = try searchApps(id)["apps"] as? [[String: Any]] ?? []
let running = try runningApps()["apps"] as? [[String: Any]] ?? []
- return ["bundle_id": id, "name": apps.first?["name"] ?? "", "pid": running.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0]
+ return [
+ "bundle_id": id,
+ "name": apps.first?["name"] ?? "",
+ "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)
case "apps.install":
@@ -155,20 +177,29 @@ enum GuestAPI {
return try readPreference(domain: try 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 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) }
- return try writePreference(domain: try string(params, "domain"), key: try string(params, "key"), value: PreferenceValue(text: text, type: type))
+ return try writePreference(
+ domain: try string(params, "domain"),
+ key: try 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.")
case "keychain.list":
return try native(["t": "keychain_list", "class": params["class"] as? String ?? ""])
case "keychain.add":
return try native([
- "t": "keychain_add", "account": try string(params, "account"),
- "service": try string(params, "service"), "password": try string(params, "password"),
+ "t": "keychain_add",
+ "account": try string(params, "account"),
+ "service": try string(params, "service"),
+ "password": try string(params, "password"),
])
case "agent.apply_update":
let expected = try string(params, "sha256")
@@ -177,9 +208,14 @@ enum GuestAPI {
let data = try Data(contentsOf: URL(fileURLWithPath: next), options: .mappedIfSafe)
let actual = sha256Hex(data)
guard actual == expected else { throw GuestAPIError.invalidRequest("Update hash mismatch") }
- guard chmod(next, 0o755) == 0 else { throw GuestAPIError.operationFailed("Could not make update executable") }
+ guard chmod(next, 0o755) == 0 else {
+ throw GuestAPIError.operationFailed("Could not make update executable")
+ }
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)
+ try Data(expected.utf8).write(
+ to: URL(fileURLWithPath: "/var/root/Library/Caches/vphoned.api-v2"),
+ options: .atomic
+ )
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { exit(0) }
return ["restarting": true]
default:
diff --git a/scripts/vphoned/Daemon/GuestFileTransfer.swift b/scripts/vphoned/Daemon/GuestFileTransfer.swift
index bf209f31..ab26cc5d 100644
--- a/scripts/vphoned/Daemon/GuestFileTransfer.swift
+++ b/scripts/vphoned/Daemon/GuestFileTransfer.swift
@@ -30,9 +30,16 @@ enum GuestFileTransfer {
headers.add(name: "Content-Type", value: "application/octet-stream")
headers.add(name: "Content-Length", value: String(region.readableBytes))
headers.add(name: "Connection", value: "close")
- channel.write(HTTPServerResponsePart.head(.init(version: .http1_1, status: .ok, headers: headers)), promise: nil)
- fileIO.readChunked(fileRegion: region, chunkSize: 64 * 1024,
- allocator: channel.allocator, eventLoop: channel.eventLoop) { bytes in
+ channel.write(
+ HTTPServerResponsePart.head(.init(version: .http1_1, status: .ok, headers: headers)),
+ promise: nil
+ )
+ fileIO.readChunked(
+ fileRegion: region,
+ chunkSize: 64 * 1024,
+ allocator: channel.allocator,
+ eventLoop: channel.eventLoop
+ ) { bytes in
channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(bytes)))
}.whenComplete { result in
try? handle.close()
@@ -62,9 +69,13 @@ final class GuestFileUpload: @unchecked Sendable {
private let onCommit: ((String) throws -> Void)?
private let mode: mode_t
- init(destination: String, fileIO: NonBlockingFileIO, channel: Channel,
- mode: mode_t = 0o644,
- onCommit: ((String) throws -> Void)? = nil) throws {
+ init(
+ destination: String,
+ fileIO: NonBlockingFileIO,
+ channel: Channel,
+ mode: mode_t = 0o644,
+ onCommit: ((String) throws -> Void)? = nil
+ ) throws {
let parent = (destination as NSString).deletingLastPathComponent
try FileManager.default.createDirectory(atPath: parent, withIntermediateDirectories: true)
let temporary = destination + ".vphoned-" + UUID().uuidString + ".tmp"
diff --git a/scripts/vphoned/Daemon/GuestHTTPHandler.swift b/scripts/vphoned/Daemon/GuestHTTPHandler.swift
index 0d1cd33b..51109a6d 100644
--- a/scripts/vphoned/Daemon/GuestHTTPHandler.swift
+++ b/scripts/vphoned/Daemon/GuestHTTPHandler.swift
@@ -35,7 +35,8 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
do {
upload = try GuestFileUpload(
destination: requestPath == "/v1/clipboard/image"
- ? "/var/root/Library/Caches/vphoned-clipboard-image" : GuestFileTransfer.path(from: request.uri),
+ ? "/var/root/Library/Caches/vphoned-clipboard-image"
+ : GuestFileTransfer.path(from: request.uri),
fileIO: fileIO,
channel: context.channel,
mode: try Self.uploadMode(from: request.uri),
@@ -81,8 +82,11 @@ 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),
- fileIO: fileIO, channel: context.channel)
+ GuestFileTransfer.download(
+ path: try GuestFileTransfer.path(from: head.uri),
+ fileIO: fileIO,
+ channel: context.channel
+ )
} catch {
Self.send(APIWire.error(String(describing: error)), on: context.channel)
}
@@ -195,7 +199,10 @@ final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @u
headers.add(name: "Content-Length", value: String(reply.data.count))
headers.add(name: "Connection", value: "close")
let status = HTTPResponseStatus(statusCode: reply.status)
- channel.write(HTTPServerResponsePart.head(.init(version: .http1_1, status: status, headers: headers)), promise: nil)
+ channel.write(
+ HTTPServerResponsePart.head(.init(version: .http1_1, status: status, headers: headers)),
+ promise: nil
+ )
var buffer = channel.allocator.buffer(capacity: reply.data.count)
buffer.writeBytes(reply.data)
channel.write(HTTPServerResponsePart.body(.byteBuffer(buffer)), promise: nil)
diff --git a/scripts/vphoned/vphoned_keychain.m b/scripts/vphoned/vphoned_keychain.m
index 9265bf68..8541e56e 100644
--- a/scripts/vphoned/vphoned_keychain.m
+++ b/scripts/vphoned/vphoned_keychain.m
@@ -191,7 +191,8 @@ NSDictionary *vp_handle_keychain_command(NSDictionary *msg) {
NSArray *dbItems = query_keychain_db(filterClass, diag);
NSLog(@"vphoned: keychain_list: %lu items (sqlite), diag: %@",
- (unsigned long)dbItems.count, diag);
+ (unsigned long)dbItems.count,
+ diag);
NSMutableDictionary *resp = vp_make_response(@"keychain_list", reqId);
resp[@"items"] = dbItems;
diff --git a/scripts/vphoned/vphoned_vcam.m b/scripts/vphoned/vphoned_vcam.m
index ab53aadb..df9dd01a 100644
--- a/scripts/vphoned/vphoned_vcam.m
+++ b/scripts/vphoned/vphoned_vcam.m
@@ -68,7 +68,8 @@ static int open_shm(void) {
int fd = open(VPHONED_VCAM_SHM_PATH, O_RDWR | O_CREAT, 0644);
if (fd < 0) {
vvc_logf("vphoned_vcam: open(%s) failed: %s",
- VPHONED_VCAM_SHM_PATH, strerror(errno));
+ VPHONED_VCAM_SHM_PATH,
+ strerror(errno));
return -1;
}
if (ftruncate(fd, VPHONED_VCAM_SHM_TOTAL_SIZE) < 0) {
@@ -78,8 +79,13 @@ static int open_shm(void) {
}
/* Make sure other processes can map this file read-only. */
fchmod(fd, 0644);
- void *base = mmap(NULL, VPHONED_VCAM_SHM_TOTAL_SIZE,
- PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ void *base = mmap(
+ NULL,
+ VPHONED_VCAM_SHM_TOTAL_SIZE,
+ PROT_READ | PROT_WRITE,
+ MAP_SHARED,
+ fd,
+ 0);
close(fd);
if (base == MAP_FAILED) {
vvc_logf("vphoned_vcam: mmap failed: %s", strerror(errno));
@@ -123,8 +129,10 @@ static void publish_frame(uint32_t w,
(_Atomic uint64_t *)&hdr->seq, memory_order_acquire);
/* Mark write in progress (odd seq). */
uint64_t writing_seq = (prev_seq | 1ull) + 2ull;
- atomic_store_explicit((_Atomic uint64_t *)&hdr->seq, writing_seq,
- memory_order_release);
+ atomic_store_explicit(
+ (_Atomic uint64_t *)&hdr->seq,
+ writing_seq,
+ memory_order_release);
hdr->width = w;
hdr->height = h;
@@ -136,8 +144,10 @@ static void publish_frame(uint32_t w,
memcpy(dst, pixels, pixel_len);
/* Mark write done (even seq). */
- atomic_store_explicit((_Atomic uint64_t *)&hdr->seq, writing_seq + 1ull,
- memory_order_release);
+ atomic_store_explicit(
+ (_Atomic uint64_t *)&hdr->seq,
+ writing_seq + 1ull,
+ memory_order_release);
if (s_notify_token >= 0) {
notify_post(VPHONED_VCAM_NOTIFY_NAME);
@@ -154,7 +164,8 @@ static void handle_client(int fd) {
if (total_len < 4 || header_len + 4 > total_len ||
total_len > VPHONED_VCAM_SHM_MAX_PIXELS + 4096) {
vvc_logf("vphoned_vcam: framing error total=%u header=%u",
- total_len, header_len);
+ total_len,
+ header_len);
break;
}
uint8_t *header_buf = (uint8_t *)malloc(header_len);
@@ -202,7 +213,10 @@ static void handle_client(int fd) {
frames++;
if ((frames & 29) == 1) {
vvc_logf("vphoned_vcam: published frame #%llu w=%u h=%u bpr=%u",
- (unsigned long long)frames, w, h, bpr);
+ (unsigned long long)frames,
+ w,
+ h,
+ bpr);
}
}
vvc_logf("vphoned_vcam: client disconnected (%llu frames)",
@@ -235,7 +249,8 @@ static void *listener_thread(__unused void *unused) {
};
if (bind(srv, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
vvc_logf("vphoned_vcam: bind(%d) failed: %s",
- VPHONED_VCAM_VSOCK_PORT, strerror(errno));
+ VPHONED_VCAM_VSOCK_PORT,
+ strerror(errno));
close(srv);
return NULL;
}
@@ -245,7 +260,8 @@ static void *listener_thread(__unused void *unused) {
return NULL;
}
vvc_logf("vphoned_vcam: listening on vsock %d, shm=%s",
- VPHONED_VCAM_VSOCK_PORT, VPHONED_VCAM_SHM_PATH);
+ VPHONED_VCAM_VSOCK_PORT,
+ VPHONED_VCAM_SHM_PATH);
for (;;) {
int fd = accept(srv, NULL, NULL);
diff --git a/siblings/camfix/libcamfix.m b/siblings/camfix/libcamfix.m
index a11ee564..c405d6b6 100644
--- a/siblings/camfix/libcamfix.m
+++ b/siblings/camfix/libcamfix.m
@@ -168,7 +168,9 @@ static CMSampleBufferRef cfx_build_cmsb(void) {
if (cvr != kCVReturnSuccess || !pb) { free(pixels); return NULL; }
CMVideoFormatDescriptionRef desc = NULL;
OSStatus s = CMVideoFormatDescriptionCreateForImageBuffer(
- kCFAllocatorDefault, pb, &desc);
+ kCFAllocatorDefault,
+ pb,
+ &desc);
if (s != noErr || !desc) { CVPixelBufferRelease(pb); return NULL; }
CMSampleTimingInfo timing = {
.duration = CMTimeMake(1, 30),
@@ -177,7 +179,14 @@ static CMSampleBufferRef cfx_build_cmsb(void) {
};
CMSampleBufferRef cmsb = NULL;
s = CMSampleBufferCreateForImageBuffer(
- kCFAllocatorDefault, pb, true, NULL, NULL, desc, &timing, &cmsb);
+ kCFAllocatorDefault,
+ pb,
+ true,
+ NULL,
+ NULL,
+ desc,
+ &timing,
+ &cmsb);
CFRelease(desc);
CVPixelBufferRelease(pb);
return (s == noErr) ? cmsb : NULL;
@@ -237,9 +246,11 @@ static IMP cfx_orig_capturePhoto = NULL;
static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH) CF_RETURNS_RETAINED;
static CGImageRef cfx_build_cgimage_from_shm(void) CF_RETURNS_RETAINED;
static NSData *cfx_build_jpeg_from_shm(void);
-static id cfx_build_avcapturephoto_with_request(IOSurfaceRef surf,
- uint32_t w, uint32_t h,
- id captureRequest);
+static id cfx_build_avcapturephoto_with_request(
+ IOSurfaceRef surf,
+ uint32_t w,
+ uint32_t h,
+ id captureRequest);
static BOOL cfx_output_is_for_vcam(id self);
// Associated-object keys (used by fileDataRepresentation /
@@ -255,12 +266,17 @@ static const void *CFX_ASSOC_CGIMG_KEY = &CFX_ASSOC_CGIMG_KEY;
static NSData *cfx_stamp_photo(id photo) {
NSData *jpeg = cfx_build_jpeg_from_shm();
CGImageRef cgImg = cfx_build_cgimage_from_shm();
- if (jpeg) objc_setAssociatedObject(photo, CFX_ASSOC_JPEG_KEY, jpeg,
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ if (jpeg) objc_setAssociatedObject(
+ photo,
+ CFX_ASSOC_JPEG_KEY,
+ jpeg,
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (cgImg) {
- objc_setAssociatedObject(photo, CFX_ASSOC_CGIMG_KEY,
- (__bridge id)cgImg,
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ objc_setAssociatedObject(
+ photo,
+ CFX_ASSOC_CGIMG_KEY,
+ (__bridge id)cgImg,
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
CGImageRelease(cgImg);
}
return jpeg;
@@ -380,9 +396,11 @@ static void cfx_preview_start_timer(void) {
if (cfx_preview_timer) return;
dispatch_queue_t q = dispatch_queue_create("com.vphone.camfix.preview", DISPATCH_QUEUE_SERIAL);
cfx_preview_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q);
- dispatch_source_set_timer(cfx_preview_timer,
- dispatch_time(DISPATCH_TIME_NOW, 0),
- 33333333ull, 2000000ull);
+ dispatch_source_set_timer(
+ cfx_preview_timer,
+ dispatch_time(DISPATCH_TIME_NOW, 0),
+ 33333333ull,
+ 2000000ull);
dispatch_source_set_event_handler(cfx_preview_timer, ^{
@autoreleasepool { cfx_pump_preview_once(); }
});
@@ -423,12 +441,17 @@ static id cfx_pv_initWithSession_hook(id self, SEL _cmd, AVCaptureSession *sessi
}
__attribute__((ns_returns_retained))
-static id cfx_pv_initWithSessionMakeConnection_hook(id self, SEL _cmd,
- AVCaptureSession *session,
- BOOL makeConnection) {
+static id cfx_pv_initWithSessionMakeConnection_hook(
+ id self,
+ SEL _cmd,
+ AVCaptureSession *session,
+ BOOL makeConnection) {
typedef id (*Fn)(id, SEL, AVCaptureSession *, BOOL);
id ret = ((Fn)cfx_orig_pv_initWithSessionMakeConnection)(
- self, _cmd, session, makeConnection);
+ self,
+ _cmd,
+ session,
+ makeConnection);
BOOL forVcam = (session != nil) && cfx_session_is_for_vcam(session);
cfxlog(@"[PVLayer _initWithSession:%p makeConnection:%d] ret=%p forVcam=%d cls=%@",
session,
@@ -446,7 +469,10 @@ static void cfx_pv_setSession_hook(id self, SEL _cmd, AVCaptureSession *session)
((Fn)cfx_orig_pv_setSession)(self, _cmd, session);
BOOL forVcam = (session != nil) && cfx_session_is_for_vcam(session);
cfxlog(@"[PVLayer setSession:%p] self=%p forVcam=%d cls=%@",
- session, self, forVcam, NSStringFromClass([self class]));
+ session,
+ self,
+ forVcam,
+ NSStringFromClass([self class]));
if (session && forVcam) cfx_adopt_preview_layer(self);
}
@@ -507,7 +533,8 @@ static void cfx_scan_preview_layers(void) {
NSUInteger after = cfx_preview_layers.count;
if (after > before) {
cfxlog(@"[scan] adopted %lu preview layer(s) (total=%lu)",
- (unsigned long)(after - before), (unsigned long)after);
+ (unsigned long)(after - before),
+ (unsigned long)after);
cfx_preview_start_timer();
}
}
@@ -655,16 +682,25 @@ static BOOL cfx_stub_lensStabSupported(id self, SEL _cmd) {
static void cfx_install_capturerequest_stubs(void) {
Class cls = NSClassFromString(@"CAMStillImageCaptureRequest");
if (!cls) { cfxlog(@"CAMStillImageCaptureRequest missing"); return; }
- if (class_addMethod(cls, NSSelectorFromString(@"resolvedSettings"),
- (IMP)cfx_stub_resolvedSettings, "@@:")) {
+ if (class_addMethod(
+ cls,
+ NSSelectorFromString(@"resolvedSettings"),
+ (IMP)cfx_stub_resolvedSettings,
+ "@@:")) {
cfxlog(@"stubbed resolvedSettings on CAMStillImageCaptureRequest");
}
- if (class_addMethod(cls, NSSelectorFromString(@"unresolvedSettings"),
- (IMP)cfx_stub_unresolvedSettings, "@@:")) {
+ if (class_addMethod(
+ cls,
+ NSSelectorFromString(@"unresolvedSettings"),
+ (IMP)cfx_stub_unresolvedSettings,
+ "@@:")) {
cfxlog(@"stubbed unresolvedSettings on CAMStillImageCaptureRequest");
}
- if (class_addMethod(cls, NSSelectorFromString(@"lensStabilizationSupported"),
- (IMP)cfx_stub_lensStabSupported, "B@:")) {
+ if (class_addMethod(
+ cls,
+ NSSelectorFromString(@"lensStabilizationSupported"),
+ (IMP)cfx_stub_lensStabSupported,
+ "B@:")) {
cfxlog(@"stubbed lensStabilizationSupported on CAMStillImageCaptureRequest");
}
}
@@ -701,7 +737,10 @@ static NSData *cfx_build_jpeg_from_shm(void) {
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef dp = CGDataProviderCreateWithData(
- NULL, copy, len, cfx_cg_release_data);
+ NULL,
+ copy,
+ len,
+ cfx_cg_release_data);
CGImageRef img = CGImageCreate(
w,
h,
@@ -743,7 +782,10 @@ static CGImageRef cfx_build_cgimage_from_shm(void) CF_RETURNS_RETAINED {
memcpy(copy, cfx_shm_base + CFX_SHM_HEADER_SIZE, len);
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef dp = CGDataProviderCreateWithData(
- NULL, copy, len, cfx_cg_release_data);
+ NULL,
+ copy,
+ len,
+ cfx_cg_release_data);
CGImageRef img = CGImageCreate(
w,
h,
@@ -800,8 +842,10 @@ static IOSurfaceRef cfx_build_iosurface_from_shm(uint32_t *outW, uint32_t *outH)
// Walk class_copyMethodList for `cls` (or its metaclass when looking for
// class methods) and return the selector with the most colons that starts
// with `prefix`. Returns NULL if nothing matches.
-static SEL cfx_find_selector_by_prefix(Class cls, NSString *prefix,
- BOOL classMethod) {
+static SEL cfx_find_selector_by_prefix(
+ Class cls,
+ NSString *prefix,
+ BOOL classMethod) {
if (!cls || !prefix.length) return NULL;
Class c = classMethod ? object_getClass(cls) : cls;
unsigned int n = 0;
@@ -846,15 +890,19 @@ static NSString *cfx_normalize_first_label(NSString *label) {
// whether and what to write into `outBuf` (already zeroed). If the block
// doesn't recognize the label, leave outBuf alone — nil for objects,
// zeroed bytes for structs/primitives.
-typedef void (^cfx_arg_resolver_t)(NSString *label, const char *typeEnc,
- void *outBuf);
+typedef void (^cfx_arg_resolver_t)(
+ NSString *label,
+ const char *typeEnc,
+ void *outBuf);
// Build + invoke `[target selector]` with arguments filled by `resolver`.
// Works whether `target` is an alloc'd instance (for inits) or a Class
// (for class-method factories). Returns the result if it's an object
// return type, nil otherwise.
-static id cfx_invoke_with_labeled_args(id target, SEL selector,
- cfx_arg_resolver_t resolver) {
+static id cfx_invoke_with_labeled_args(
+ id target,
+ SEL selector,
+ cfx_arg_resolver_t resolver) {
NSMethodSignature *sig = nil;
@try { sig = [target methodSignatureForSelector:selector]; }
@catch (NSException *e) { return nil; }
diff --git a/siblings/vcamcaptured/libvcamcaptured.m b/siblings/vcamcaptured/libvcamcaptured.m
index c60e4135..945bb994 100644
--- a/siblings/vcamcaptured/libvcamcaptured.m
+++ b/siblings/vcamcaptured/libvcamcaptured.m
@@ -103,12 +103,16 @@ static void vcc_log(NSString *fmt, ...) {
va_end(args);
NSString *line = [NSString
stringWithFormat:@"%@ [vcamcaptured:%d:%@] %@\n",
- [NSDate.date description], getpid(),
- NSProcessInfo.processInfo.processName ?: @"?", msg];
+ [NSDate.date description],
+ getpid(),
+ NSProcessInfo.processInfo.processName ?: @"?",
+ msg];
NSData *data = [line dataUsingEncoding:NSUTF8StringEncoding];
if (!data.length) return;
- int fd = open(kSentinelPath.fileSystemRepresentation,
- O_WRONLY | O_CREAT | O_APPEND, 0644);
+ int fd = open(
+ kSentinelPath.fileSystemRepresentation,
+ O_WRONLY | O_CREAT | O_APPEND,
+ 0644);
if (fd >= 0) {
(void)write(fd, data.bytes, data.length);
close(fd);
@@ -298,14 +302,21 @@ static int vcc_patch_two_nops(uintptr_t pc) {
// (a) vm_protect with VM_PROT_COPY (= 0x10) to force COW.
kern_return_t kr = vm_protect(
- self_task, (vm_address_t)page_start, span, FALSE,
+ self_task,
+ (vm_address_t)page_start,
+ span,
+ FALSE,
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
if (kr == KERN_SUCCESS) {
uint32_t nop = 0xD503201Fu;
((uint32_t *)pc)[0] = nop;
((uint32_t *)pc)[1] = nop;
- kr = vm_protect(self_task, (vm_address_t)page_start, span, FALSE,
- VM_PROT_READ | VM_PROT_EXECUTE);
+ kr = vm_protect(
+ self_task,
+ (vm_address_t)page_start,
+ span,
+ FALSE,
+ VM_PROT_READ | VM_PROT_EXECUTE);
if (kr == KERN_SUCCESS) {
sys_icache_invalidate((void *)pc, 8);
vcc_log(@" vm_protect+COPY patch OK @ 0x%lx",
@@ -313,7 +324,8 @@ static int vcc_patch_two_nops(uintptr_t pc) {
return 1;
}
vcc_log(@" vm_protect restore RX failed: %d (page=0x%lx)",
- kr, (unsigned long)page_start);
+ kr,
+ (unsigned long)page_start);
// Continue to try (b).
} else {
vcc_log(@" vm_protect+COPY failed: %d", kr);
@@ -331,8 +343,12 @@ static int vcc_patch_two_nops(uintptr_t pc) {
uintptr_t scratch_pc = scratch + (pc - page_start);
((uint32_t *)scratch_pc)[0] = nop;
((uint32_t *)scratch_pc)[1] = nop;
- kr = vm_protect(self_task, scratch, span, FALSE,
- VM_PROT_READ | VM_PROT_EXECUTE);
+ kr = vm_protect(
+ self_task,
+ scratch,
+ span,
+ FALSE,
+ VM_PROT_READ | VM_PROT_EXECUTE);
if (kr != KERN_SUCCESS) {
vcc_log(@" vm_protect RX scratch failed: %d", kr);
vm_deallocate(self_task, scratch, span);
@@ -340,19 +356,32 @@ static int vcc_patch_two_nops(uintptr_t pc) {
}
vm_address_t target = (vm_address_t)page_start;
vm_prot_t cur_prot = 0, max_prot = 0;
- kr = vm_remap(self_task, &target, span, 0,
- VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
- self_task, scratch, FALSE,
- &cur_prot, &max_prot, VM_INHERIT_NONE);
+ kr = vm_remap(
+ self_task,
+ &target,
+ span,
+ 0,
+ VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
+ self_task,
+ scratch,
+ FALSE,
+ &cur_prot,
+ &max_prot,
+ VM_INHERIT_NONE);
if (kr != KERN_SUCCESS) {
vcc_log(@" vm_remap FIXED|OVERWRITE failed: %d (cur=0x%x max=0x%x)",
- kr, cur_prot, max_prot);
+ kr,
+ cur_prot,
+ max_prot);
vm_deallocate(self_task, scratch, span);
return 0;
}
sys_icache_invalidate((void *)pc, 8);
vcc_log(@" vm_remap OK: page=0x%lx span=%zu (cur=0x%x max=0x%x)",
- (unsigned long)page_start, (size_t)span, cur_prot, max_prot);
+ (unsigned long)page_start,
+ (size_t)span,
+ cur_prot,
+ max_prot);
return 1;
}
@@ -367,7 +396,9 @@ static int vcc_patch_word(uintptr_t pc,
uint32_t cur = ((const uint32_t *)pc)[0];
if (cur != expected_word) {
vcc_log(@" patch_word @ 0x%lx: expected 0x%08x, found 0x%08x — skip",
- (unsigned long)pc, expected_word, cur);
+ (unsigned long)pc,
+ expected_word,
+ cur);
return 0;
}
uintptr_t page_size = (uintptr_t)getpagesize();
@@ -378,22 +409,31 @@ static int vcc_patch_word(uintptr_t pc,
mach_port_t self_task = mach_task_self();
kern_return_t kr = vm_protect(
- self_task, (vm_address_t)page_start, span, FALSE,
+ self_task,
+ (vm_address_t)page_start,
+ span,
+ FALSE,
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
if (kr != KERN_SUCCESS) {
vcc_log(@" patch_word vm_protect+COPY failed: %d", kr);
return 0;
}
((uint32_t *)pc)[0] = new_word;
- kr = vm_protect(self_task, (vm_address_t)page_start, span, FALSE,
- VM_PROT_READ | VM_PROT_EXECUTE);
+ kr = vm_protect(
+ self_task,
+ (vm_address_t)page_start,
+ span,
+ FALSE,
+ VM_PROT_READ | VM_PROT_EXECUTE);
if (kr != KERN_SUCCESS) {
vcc_log(@" patch_word restore RX failed: %d", kr);
return 0;
}
sys_icache_invalidate((void *)pc, 4);
vcc_log(@" patch_word OK @ 0x%lx: 0x%08x -> 0x%08x",
- (unsigned long)pc, expected_word, new_word);
+ (unsigned long)pc,
+ expected_word,
+ new_word);
return 1;
}
@@ -414,7 +454,10 @@ static unsigned vcc_scan_and_patch(const vcc_image_t *img,
if (vcc_patch_word(pc, needle, replacement)) hits++;
}
vcc_log(@" scan_and_patch %s (0x%08x -> 0x%08x): %u hit(s)",
- what ? what : "?", needle, replacement, hits);
+ what ? what : "?",
+ needle,
+ replacement,
+ hits);
return hits;
}
@@ -546,11 +589,16 @@ static uintptr_t vcc_find_data_xref(const vcc_image_t *img, unsigned offset) {
}
if (tie) {
vcc_log(@" xref scan #%u: %u candidates tied at %u hits — refusing to pick",
- offset, n_cands, best_hits);
+ offset,
+ n_cands,
+ best_hits);
return 0;
}
vcc_log(@" xref scan #%u: %u candidates, winner 0x%lx with %u hits",
- offset, n_cands, (unsigned long)cands[best].addr, best_hits);
+ offset,
+ n_cands,
+ (unsigned long)cands[best].addr,
+ best_hits);
return cands[best].addr;
}
@@ -818,11 +866,14 @@ static id vcc_build_backing(void) {
@selector(alloc));
id fmtObj = nil;
if (fmtAlloc) {
- fmtObj = ((id (*)(id, SEL, id))objc_msgSend)(fmtAlloc, fmtInitSel,
- fmtDict);
+ fmtObj = ((id (*)(id, SEL, id))objc_msgSend)(
+ fmtAlloc,
+ fmtInitSel,
+ fmtDict);
}
vcc_log(@" FigCaptureSourceVideoFormat (%@) = %p",
- fmtDict[@"Name"], fmtObj);
+ fmtDict[@"Name"],
+ fmtObj);
if (fmtObj) [formatObjs addObject:fmtObj];
}
formats = formatObjs;
@@ -839,10 +890,18 @@ static id vcc_build_backing(void) {
if (!alloced) return nil;
uint32_t mediaTypeVideo = 0x76696465; // 'vide'
id backing = ((id (*)(id, SEL, uint32_t, id, id, id, id, id, id))objc_msgSend)(
- alloced, initSel, mediaTypeVideo, attrs,
- [NSMutableDictionary dictionary], formats, @[], @[], @[]);
+ alloced,
+ initSel,
+ mediaTypeVideo,
+ attrs,
+ [NSMutableDictionary dictionary],
+ formats,
+ @[],
+ @[],
+ @[]);
vcc_log(@" backing = %p (attrs.count=%lu formats.count=%lu)",
- backing, (unsigned long)attrs.count,
+ backing,
+ (unsigned long)attrs.count,
(unsigned long)formats.count);
return backing;
}
diff --git a/siblings/vpregister/vpregister.m b/siblings/vpregister/vpregister.m
index f994597b..617c6ad6 100644
--- a/siblings/vpregister/vpregister.m
+++ b/siblings/vpregister/vpregister.m
@@ -53,7 +53,8 @@ int main(int argc, char **argv) {
return 1;
}
LSApplicationWorkspace *ws = ((id (*)(id, SEL))objc_msgSend)(
- workspaceClass, @selector(defaultWorkspace));
+ workspaceClass,
+ @selector(defaultWorkspace));
if (!ws) {
fprintf(stderr, "LaunchServices workspace could not be opened\n");
return 1;
diff --git a/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift b/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
index 5cd2f31e..305783a4 100644
--- a/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
+++ b/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
@@ -95,7 +95,9 @@ extension CryptexFilesystemPatcher {
let body = output.range(of: "<?xml").map { String(output[$0.lowerBound...]) } ?? output
guard let data = body.data(using: .utf8),
let root = try? PropertyListSerialization.propertyList(
- from: data, options: [], format: nil,
+ from: data,
+ options: [],
+ format: nil,
) as? [String: Any]
else {
throw ProcessError.failed(0, "diskutil did not return a plist:\n\(output)")
diff --git a/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherFileOps.swift b/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherFileOps.swift
index b77e44a0..8a9f9525 100644
--- a/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherFileOps.swift
+++ b/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherFileOps.swift
@@ -39,7 +39,8 @@ extension CryptexFilesystemPatcher {
/// Follows symlinks, which is what chmod(1) does without `-h`.
func setMode(_ mode: Int, at url: URL) throws {
try FileManager.default.setAttributes(
- [.posixPermissions: mode], ofItemAtPath: url.path,
+ [.posixPermissions: mode],
+ ofItemAtPath: url.path,
)
}
@@ -77,7 +78,8 @@ extension CryptexFilesystemPatcher {
try FileManager.default.removeItem(at: link)
}
try FileManager.default.createSymbolicLink(
- atPath: link.path, withDestinationPath: destination,
+ atPath: link.path,
+ withDestinationPath: destination,
)
}
diff --git a/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift b/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
index 6492259e..9f16ebb7 100644
--- a/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
+++ b/sources/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
@@ -19,7 +19,8 @@ extension CryptexFilesystemPatcher {
// Mapped: the mtree .aar this wraps is the whole system volume's
// metadata and runs to hundreds of megabytes.
let im4p = try IM4P(
- fourcc: fourcc, description: description,
+ fourcc: fourcc,
+ description: description,
payload: Data(contentsOf: payload, options: .mappedIfSafe),
)
try im4p.data.write(to: im4pPath)
diff --git a/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift b/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
index 0b8ffae1..6a5aae52 100644
--- a/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
@@ -319,7 +319,8 @@ public enum CustomFirmwareInjectDylib {
"no room for a \(commandSize)-byte load command at 0x\(String(commandOffset, radix: 16))",
)
}
- if !options.allowNonEmptyPadding, data[commandOffset ..< commandOffset + commandSize].contains(where: { $0 != 0 }) {
+ if !options.allowNonEmptyPadding,
+ 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/CustomFirmwareDiskimagesiod+ObjCMetadata.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod+ObjCMetadata.swift
index 656fb4aa..6d4d75db 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod+ObjCMetadata.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareDiskimagesiod+ObjCMetadata.swift
@@ -19,7 +19,12 @@ extension CustomFirmwareDiskimagesiod {
// cstring in a "direct selector" list. Both are accepted, exactly as
// the Python does, so a missing selref is not fatal on its own.
var targets: Set<UInt64> = [selectorVA]
- if let selrefsSection = section(sections, "__DATA_CONST,__objc_selrefs", "__DATA,__objc_selrefs", "__AUTH_CONST,__objc_selrefs"),
+ if let selrefsSection = section(
+ sections,
+ "__DATA_CONST,__objc_selrefs",
+ "__DATA,__objc_selrefs",
+ "__AUTH_CONST,__objc_selrefs"
+ ),
let selrefVA = selectorReferenceVA(
in: data,
selrefs: selrefsSection,
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swift
index 3d31ae13..0bd45a63 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareMobileactivationd+Anchoring.swift
@@ -112,11 +112,16 @@ extension CustomFirmwareMobileactivationd {
return nil
}
guard let selrefVA = selectorReferenceVirtualAddress(
- to: selectorVA, in: data, sections: sections, imageBase: imageBase,
+ to: selectorVA,
+ in: data,
+ sections: sections,
+ imageBase: imageBase,
) else { return nil }
return methodImplementation(
- forSelectorReference: selrefVA, in: data, sections: sections,
+ forSelectorReference: selrefVA,
+ in: data,
+ sections: sections,
)
}
@@ -211,7 +216,9 @@ extension CustomFirmwareMobileactivationd {
for name in candidates {
guard let section = sections[name] else { continue }
if let imp = methodImplementation(
- forSelectorReference: selrefVA, in: data, section: section,
+ forSelectorReference: selrefVA,
+ in: data,
+ section: section,
) {
return imp
}
diff --git a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swift b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swift
index c5a60528..9d72f5c9 100644
--- a/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swift
+++ b/sources/FirmwarePatcher/CustomFirmware/ExecutablePatches/CustomFirmwareWatchdogdDiscovery.swift
@@ -109,18 +109,24 @@ extension CustomFirmwareWatchdogd {
) -> Site? {
// Layer 3: the call, and the import it resolves to.
guard let callIndex = firstIndex(
- in: instructions, from: addIndex + 1, within: argumentSetupWindow,
+ in: instructions,
+ from: addIndex + 1,
+ within: argumentSetupWindow,
where: { $0.mnemonic == "bl" },
) else { return nil }
let call = instructions[callIndex]
guard let target = ARM64Encoder.decodeBranchTarget(
- insn: word(of: call), pc: call.address,
+ insn: word(of: call),
+ pc: call.address,
), symbols.name(forBranchTarget: target) == sysctlFunction else { return nil }
// Layer 2, concluded: the literal has to be the call's `name` argument,
// not just something this stretch of code also mentions.
guard passesLiteral(
- inRegister: pointerRegister, from: addIndex, toCallAt: callIndex, in: instructions,
+ inRegister: pointerRegister,
+ from: addIndex,
+ toCallAt: callIndex,
+ in: instructions,
) else { return nil }
// Layer 4a: the gate, which must be the very next instruction — the
@@ -158,14 +164,18 @@ extension CustomFirmwareWatchdogd {
// Layer 5: the store of that same register into an ADRP-relative
// __DATA address — the cached global.
guard let storeIndex = firstIndex(
- in: instructions, from: valueIndex + 1, within: valueToStoreWindow,
+ in: instructions,
+ from: valueIndex + 1,
+ within: valueToStoreWindow,
where: { $0.mnemonic == "strb" && registerName($0, 0) == valueRegister },
) else { return nil }
let store = instructions[storeIndex]
guard let memory = memoryOperand(store) else { return nil }
guard let basePage = pageAddress(
ofRegister: UInt32(memory.base.rawValue),
- before: storeIndex, notBefore: addIndex, in: instructions,
+ before: storeIndex,
+ notBefore: addIndex,
+ in: instructions,
) else { return nil }
let cachedByte = basePage &+ UInt64(bitPattern: Int64(memory.disp))
guard let segment = segments.first(where: {
diff --git a/sources/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift b/sources/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
index 2280e557..e8694fec 100644
--- a/sources/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
+++ b/sources/FirmwarePatcher/DyldSharedCache/DyldSharedCacheChunkSet.swift
@@ -379,7 +379,9 @@ public final class DyldSharedCacheChunkSet {
var results: [UInt64] = []
for mapping in mappings where mapping.isExecutable {
let buffer = try Self.window(
- over: mapping, at: mapping.fileOffset, length: Int(mapping.size),
+ over: mapping,
+ at: mapping.fileOffset,
+ length: Int(mapping.size),
)
var searchFrom = buffer.startIndex
while searchFrom < buffer.endIndex,
diff --git a/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift b/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift
index 598294cf..c95fe143 100644
--- a/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift
+++ b/sources/FirmwarePatcher/Kernel/BasePatches/KernelPatchSandbox.swift
@@ -203,7 +203,10 @@ extension KernelPatcher {
let xmlRange = xmlStart.lowerBound ..< (plistEnd.upperBound)
let xmlData = prelinkData[xmlRange]
- guard let plist = try? PropertyListSerialization.propertyList(from: Data(xmlData), format: nil) as? [String: Any],
+ guard let plist = try? PropertyListSerialization.propertyList(
+ from: Data(xmlData),
+ format: nil
+ ) as? [String: Any],
let items = plist["_PrelinkInfoDictionary"] as? [[String: Any]]
else {
return nil
@@ -218,7 +221,8 @@ 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)) })
+ let loadAddrInt = (loadAddrRaw as? UInt64)
+ ?? (loadAddrRaw as? Int).map({ UInt64(bitPattern: Int64($0)) })
else {
continue
}
diff --git a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift
index 9a418aa4..a4720879 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Frida/KernelJailbreakPatchVmMapDelete.swift
@@ -43,8 +43,11 @@ extension KernelJailbreakPatcher {
var replacements: [(VmMapDeleteGate, Data)] = []
for gate in gates.sorted(by: { $0.offset < $1.offset }) {
guard let bytes = ARM64Encoder.encodeTestBitBranch(
- nonzero: gate.nonzero, register: gate.register, bit: 13,
- from: gate.offset, to: gate.target,
+ nonzero: gate.nonzero,
+ register: gate.register,
+ bit: 13,
+ from: gate.offset,
+ to: gate.target,
),
let decoded = disasm.disassembleOne(bytes, at: UInt64(gate.offset)),
decoded.mnemonic == (gate.nonzero ? "tbnz" : "tbz"),
diff --git a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift
index 5ebe5851..37c2535f 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Memory/KernelJailbreakPatchVmProtect.swift
@@ -182,7 +182,10 @@ extension KernelJailbreakPatcher {
// explicit shape tested, so this stays anchored on that flag and cannot
// drift onto an unrelated fused compare.
guard findEntryFlagMask(
- before: off, limit: start, reg: flagsReg, bit: entryFlagBit,
+ before: off,
+ limit: start,
+ reg: flagsReg,
+ bit: entryFlagBit,
) != nil else { continue }
// And the block it guards must be the downgrade.
diff --git a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift
index 4fc94bcc..7a165c26 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Sandbox/KernelJailbreakPatchMacMount.swift
@@ -158,7 +158,8 @@ extension KernelJailbreakPatcher {
ldrOps[1].type == AARCH64_OP_MEM
else { off += 4; continue }
let ldrDstReg = ldrOps[0].reg
- guard let ldrDstName = disasm.firstRegisterName(ldrInsn), ldrDstName.hasPrefix("w") else { off += 4; continue }
+ guard let ldrDstName = disasm.firstRegisterName(ldrInsn),
+ ldrDstName.hasPrefix("w") else { off += 4; continue }
// tbz/tbnz wN, #6, <target> (same register the byte was loaded into)
guard brInsn.mnemonic == "tbz" || brInsn.mnemonic == "tbnz",
diff --git a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
index e3cea1d5..55fb2f98 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchBsdInitAuth.swift
@@ -51,7 +51,12 @@ extension KernelJailbreakPatcher {
var candidates: [(off: Int, state: String)] = []
for off in stride(from: scanStart, to: adrpOff, by: 4) {
- guard let state = matchRootauthBranchSite(off, errLo: errLo, errHi: errHi, imagebootNeeded: imagebootNeeded) else { continue }
+ guard let state = matchRootauthBranchSite(
+ off,
+ errLo: errLo,
+ errHi: errHi,
+ 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 e8f9aee2..dede7046 100644
--- a/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
+++ b/sources/FirmwarePatcher/Kernel/JailbreakPatches/Storage/KernelJailbreakPatchDiskImages2.swift
@@ -133,8 +133,20 @@ extension KernelJailbreakPatcher {
return true
}
guard let (rnpStart, rnpEnd) = findDI2RegisterNotifFunc(),
- let f1 = findUniqueFieldLoad(funcStart: rnpStart, funcEnd: rnpEnd, mnemonic: "ldrh", disp: 0xD8, requireWDest: false),
- let f2 = findUniqueFieldLoad(funcStart: rnpStart, funcEnd: rnpEnd, mnemonic: "ldr", disp: 0xE8, requireWDest: true)
+ let f1 = findUniqueFieldLoad(
+ funcStart: rnpStart,
+ funcEnd: rnpEnd,
+ mnemonic: "ldrh",
+ disp: 0xD8,
+ requireWDest: false
+ ),
+ let f2 = findUniqueFieldLoad(
+ funcStart: rnpStart,
+ funcEnd: rnpEnd,
+ mnemonic: "ldr",
+ disp: 0xE8,
+ requireWDest: true
+ )
else {
log(" [~] notification-port bound-check loads not both present — skipping GATE2 (all-or-nothing)")
return true
diff --git a/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift b/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift
index 89c86124..9e69b7b0 100644
--- a/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift
+++ b/sources/FirmwarePatcher/Manifest/ManifestHashPatcher.swift
@@ -110,7 +110,8 @@ public final class ManifestHashPatcher: Patcher {
// while SHA384 walked it; mapping means the kernel pages it in
// ahead of the hash and evicts behind it.
let componentData = try Data(
- contentsOf: restoreDir.appendingPathComponent(path), options: .mappedIfSafe,
+ contentsOf: restoreDir.appendingPathComponent(path),
+ options: .mappedIfSafe,
)
let finalData = try patchIm4pTypeTag(comp, info["Img4PayloadType"] as? String, componentData)
let shaHash = SHA384.hash(data: finalData)
diff --git a/sources/MobileRestoreCore/vphone_restore_bridge.c b/sources/MobileRestoreCore/vphone_restore_bridge.c
index a57697a9..18339e2a 100644
--- a/sources/MobileRestoreCore/vphone_restore_bridge.c
+++ b/sources/MobileRestoreCore/vphone_restore_bridge.c
@@ -144,11 +144,17 @@ static void vphone_emit(int level, const char *message)
* &client->tss_recoveryos_root_ticket instead, so comparing the out-parameter
* against &client->tss separates them exactly.
*/
-int vphone_offline_tss_lookup(struct idevicerestore_client_t *client,
- plist_t build_identity, plist_t *tss);
-
-int vphone_offline_tss_lookup(struct idevicerestore_client_t *client,
- plist_t build_identity, plist_t *tss)
+int vphone_offline_tss_lookup(
+ struct idevicerestore_client_t *client,
+ plist_t build_identity,
+ plist_t *tss
+);
+
+int vphone_offline_tss_lookup(
+ struct idevicerestore_client_t *client,
+ plist_t build_identity,
+ plist_t *tss
+)
{
(void)build_identity;
@@ -646,8 +652,12 @@ int vphone_restore_run(const struct vphone_restore_options *options)
goto done;
}
if (stat(options->restore_dir, &st) != 0) {
- logger(LL_ERROR, "Cannot use '%s' as a restore directory: %s\n",
- options->restore_dir, strerror(errno));
+ logger(
+ LL_ERROR,
+ "Cannot use '%s' as a restore directory: %s\n",
+ options->restore_dir,
+ strerror(errno)
+ );
result = VPHONE_RESTORE_E_NO_RESTORE_DIR;
goto done;
}
@@ -665,8 +675,11 @@ int vphone_restore_run(const struct vphone_restore_options *options)
result = VPHONE_RESTORE_E_TICKET;
goto done;
}
- logger(LL_INFO, "Restoring offline with the TSS response at '%s'\n",
- options->ticket_path);
+ logger(
+ LL_INFO,
+ "Restoring offline with the TSS response at '%s'\n",
+ options->ticket_path
+ );
}
result = vphone_drive_idevicerestore(options);
diff --git a/sources/MobileRestoreCore/vphone_zip_stub.c b/sources/MobileRestoreCore/vphone_zip_stub.c
index 18d97c70..3016ba52 100644
--- a/sources/MobileRestoreCore/vphone_zip_stub.c
+++ b/sources/MobileRestoreCore/vphone_zip_stub.c
@@ -50,8 +50,12 @@ zip_t *zip_open(const char *path, int flags, int *errorp)
if (errorp) {
*errorp = 21; /* ZIP_ER_OPNOTSUPP */
}
- logger(LL_ERROR, "Cannot open '%s' as a zip archive: %s.\n",
- path ? path : "(null)", VPHONE_ZIP_REASON);
+ logger(
+ LL_ERROR,
+ "Cannot open '%s' as a zip archive: %s.\n",
+ path ? path : "(null)",
+ VPHONE_ZIP_REASON
+ );
return NULL;
}
@@ -64,10 +68,13 @@ zip_t *zip_open(const char *path, int flags, int *errorp)
*/
static void vphone_zip_unreachable(const char *fn)
{
- logger(LL_ERROR,
- "internal error: %s() was called on a zip handle that cannot "
- "exist (%s)\n",
- fn, VPHONE_ZIP_REASON);
+ logger(
+ LL_ERROR,
+ "internal error: %s() was called on a zip handle that cannot "
+ "exist (%s)\n",
+ fn,
+ VPHONE_ZIP_REASON
+ );
}
int zip_close(zip_t *archive)
@@ -158,9 +165,13 @@ int zip_stat_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags, zip_st
return -1;
}
-int zip_file_get_external_attributes(zip_t *archive, zip_uint64_t index,
- zip_flags_t flags, zip_uint8_t *opsys,
- zip_uint32_t *attributes)
+int zip_file_get_external_attributes(
+ zip_t *archive,
+ zip_uint64_t index,
+ zip_flags_t flags,
+ zip_uint8_t *opsys,
+ zip_uint32_t *attributes
+)
{
(void)archive;
(void)index;
diff --git a/sources/MobileRestoreCore/zip.h b/sources/MobileRestoreCore/zip.h
index 6111cc6a..a24a7f11 100644
--- a/sources/MobileRestoreCore/zip.h
+++ b/sources/MobileRestoreCore/zip.h
@@ -120,9 +120,13 @@ int zip_delete(zip_t *archive, zip_uint64_t index);
void zip_stat_init(zip_stat_t *st);
int zip_stat(zip_t *archive, const char *fname, zip_flags_t flags, zip_stat_t *st);
int zip_stat_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags, zip_stat_t *st);
-int zip_file_get_external_attributes(zip_t *archive, zip_uint64_t index,
- zip_flags_t flags, zip_uint8_t *opsys,
- zip_uint32_t *attributes);
+int zip_file_get_external_attributes(
+ zip_t *archive,
+ zip_uint64_t index,
+ zip_flags_t flags,
+ zip_uint8_t *opsys,
+ zip_uint32_t *attributes
+);
zip_file_t *zip_fopen_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags);
int zip_fclose(zip_file_t *file);
diff --git a/sources/VPhoneAPIKit/VPhoneAPIClient.swift b/sources/VPhoneAPIKit/VPhoneAPIClient.swift
index 32b751c8..d95bdbb4 100644
--- a/sources/VPhoneAPIKit/VPhoneAPIClient.swift
+++ b/sources/VPhoneAPIKit/VPhoneAPIClient.swift
@@ -111,8 +111,11 @@ public struct VPhoneAPIClient: Sendable {
/// Runs any icli subcommand inside the guest. Arguments are passed as an
/// array to the pinned icli executable, without a shell. The result holds
/// its exit code, decoded JSON output (or text), and stderr.
- public func runIcli(_ arguments: [String], stdin: String? = nil,
- stdinData: Data? = nil) async throws -> VPhoneJSONValue {
+ public func runIcli(
+ _ arguments: [String],
+ stdin: String? = nil,
+ stdinData: Data? = nil
+ ) async throws -> VPhoneJSONValue {
guard stdin == nil || stdinData == nil else {
throw VPhoneAPIError(code: "input", message: "Pass either stdin or stdinData")
}
@@ -138,8 +141,11 @@ public struct VPhoneAPIClient: Sendable {
/// Sends a host file to an absolute guest path without loading it into
/// memory. The guest stages it beside the destination and renames it.
- public func uploadFile(from localURL: URL, toGuestPath guestPath: String,
- permissions: String = "644") async throws -> VPhoneJSONValue {
+ public func uploadFile(
+ from localURL: URL,
+ toGuestPath guestPath: String,
+ permissions: String = "644"
+ ) async throws -> VPhoneJSONValue {
var request = URLRequest(url: try fileURL(guestPath, mode: permissions))
request.httpMethod = "PUT"
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
diff --git a/sources/VPhoneArchive/VPhoneArchiveExtractor.swift b/sources/VPhoneArchive/VPhoneArchiveExtractor.swift
index 14ab75d5..b4e97bc3 100644
--- a/sources/VPhoneArchive/VPhoneArchiveExtractor.swift
+++ b/sources/VPhoneArchive/VPhoneArchiveExtractor.swift
@@ -50,7 +50,8 @@ public enum VPhoneArchiveExtractor {
guard archive_read_open_filename(reader, archive.path, blockSize) == ARCHIVE_OK else {
throw VPhoneArchiveError.cannotOpen(
- path: archive.path, reason: archiveErrorString(reader),
+ path: archive.path,
+ reason: archiveErrorString(reader),
)
}
@@ -80,7 +81,8 @@ public enum VPhoneArchiveExtractor {
}
guard status == ARCHIVE_OK || status == ARCHIVE_WARN, let entry else {
throw VPhoneArchiveError.readFailed(
- path: archive.path, reason: archiveErrorString(reader),
+ path: archive.path,
+ reason: archiveErrorString(reader),
)
}
@@ -100,7 +102,8 @@ public enum VPhoneArchiveExtractor {
let targetPath = target.standardized.path
guard targetPath == destinationPath || targetPath.hasPrefix(destinationPath + "/") else {
throw VPhoneArchiveError.pathEscapesDestination(
- member: memberPath, destination: destinationPath,
+ member: memberPath,
+ destination: destinationPath,
)
}
archive_entry_set_pathname(entry, targetPath)
@@ -120,7 +123,8 @@ public enum VPhoneArchiveExtractor {
let resolvedLink = linkTarget.standardized.path
guard resolvedLink.hasPrefix(destinationPath + "/") else {
throw VPhoneArchiveError.pathEscapesDestination(
- member: linkPath, destination: destinationPath,
+ member: linkPath,
+ destination: destinationPath,
)
}
archive_entry_set_hardlink(entry, resolvedLink)
@@ -135,13 +139,16 @@ public enum VPhoneArchiveExtractor {
guard archive_write_header(writer, entry) == ARCHIVE_OK else {
throw VPhoneArchiveError.writeFailed(
- path: target.path, reason: archiveErrorString(writer),
+ path: target.path,
+ reason: archiveErrorString(writer),
)
}
if archive_entry_size(entry) > 0 {
bytes += try copyData(
- from: reader, to: writer, isCancelled: isCancelled,
+ from: reader,
+ to: writer,
+ isCancelled: isCancelled,
onBlock: bytesRead.map { report in
{ report(archive_filter_bytes(reader, -1)) }
},
@@ -150,7 +157,8 @@ public enum VPhoneArchiveExtractor {
guard archive_write_finish_entry(writer) == ARCHIVE_OK else {
throw VPhoneArchiveError.writeFailed(
- path: target.path, reason: archiveErrorString(writer),
+ path: target.path,
+ reason: archiveErrorString(writer),
)
}
@@ -232,13 +240,15 @@ public enum VPhoneArchiveExtractor {
}
guard status == ARCHIVE_OK || status == ARCHIVE_WARN else {
throw VPhoneArchiveError.readFailed(
- path: "<member data>", reason: archiveErrorString(reader),
+ path: "<member data>",
+ reason: archiveErrorString(reader),
)
}
guard archive_write_data_block(writer, buffer, size, offset) >= ARCHIVE_OK else {
throw VPhoneArchiveError.writeFailed(
- path: "<member data>", reason: archiveErrorString(writer),
+ path: "<member data>",
+ reason: archiveErrorString(writer),
)
}
total += Int64(size)
diff --git a/sources/VPhoneArchive/VPhoneArchivePaths.swift b/sources/VPhoneArchive/VPhoneArchivePaths.swift
index ddf381af..8067556c 100644
--- a/sources/VPhoneArchive/VPhoneArchivePaths.swift
+++ b/sources/VPhoneArchive/VPhoneArchivePaths.swift
@@ -18,7 +18,8 @@ enum VPhoneArchivePaths {
static func resolved(_ url: URL) throws -> URL {
guard let resolved = realpath(url.path, nil) else {
throw VPhoneArchiveError.cannotOpen(
- path: url.path, reason: String(cString: strerror(errno)),
+ path: url.path,
+ reason: String(cString: strerror(errno)),
)
}
defer { free(resolved) }
diff --git a/sources/VPhoneArchive/VPhoneArchiveReader.swift b/sources/VPhoneArchive/VPhoneArchiveReader.swift
index e7041058..3caae0b3 100644
--- a/sources/VPhoneArchive/VPhoneArchiveReader.swift
+++ b/sources/VPhoneArchive/VPhoneArchiveReader.swift
@@ -64,7 +64,8 @@ public enum VPhoneArchiveReader {
}
guard read > 0 else {
throw VPhoneArchiveError.readFailed(
- path: archive.path, reason: archiveErrorString(reader),
+ path: archive.path,
+ reason: archiveErrorString(reader),
)
}
data.append(contentsOf: buffer[0 ..< Int(read)])
@@ -99,7 +100,8 @@ public enum VPhoneArchiveReader {
guard archive_read_open_filename(reader, archive.path, blockSize) == ARCHIVE_OK else {
throw VPhoneArchiveError.cannotOpen(
- path: archive.path, reason: archiveErrorString(reader),
+ path: archive.path,
+ reason: archiveErrorString(reader),
)
}
return try body(reader)
@@ -116,7 +118,8 @@ public enum VPhoneArchiveReader {
}
guard status == ARCHIVE_OK || status == ARCHIVE_WARN else {
throw VPhoneArchiveError.readFailed(
- path: archive.path, reason: archiveErrorString(reader),
+ path: archive.path,
+ reason: archiveErrorString(reader),
)
}
return entry
diff --git a/sources/VPhoneArchive/VPhoneArchiveWriter.swift b/sources/VPhoneArchive/VPhoneArchiveWriter.swift
index cd943173..5459c4c5 100644
--- a/sources/VPhoneArchive/VPhoneArchiveWriter.swift
+++ b/sources/VPhoneArchive/VPhoneArchiveWriter.swift
@@ -73,7 +73,8 @@ public enum VPhoneArchiveWriter {
guard archive_write_open_filename(writer, archive.path) == ARCHIVE_OK else {
throw VPhoneArchiveError.cannotOpen(
- path: archive.path, reason: archiveErrorString(writer),
+ path: archive.path,
+ reason: archiveErrorString(writer),
)
}
defer { archive_write_close(writer) }
@@ -107,7 +108,8 @@ public enum VPhoneArchiveWriter {
let resolvedRoot = try VPhoneArchivePaths.resolved(root)
guard archive_read_disk_open(disk, resolvedRoot.path) == ARCHIVE_OK else {
throw VPhoneArchiveError.cannotOpen(
- path: resolvedRoot.path, reason: archiveErrorString(disk),
+ path: resolvedRoot.path,
+ reason: archiveErrorString(disk),
)
}
@@ -144,7 +146,8 @@ public enum VPhoneArchiveWriter {
}
guard status == ARCHIVE_OK || status == ARCHIVE_WARN else {
throw VPhoneArchiveError.readFailed(
- path: root.path, reason: archiveErrorString(disk),
+ path: root.path,
+ reason: archiveErrorString(disk),
)
}
@@ -175,7 +178,8 @@ public enum VPhoneArchiveWriter {
guard archive_write_header(writer, resolved) == ARCHIVE_OK else {
throw VPhoneArchiveError.writeFailed(
- path: stored, reason: archiveErrorString(writer),
+ path: stored,
+ reason: archiveErrorString(writer),
)
}
@@ -210,14 +214,16 @@ public enum VPhoneArchiveWriter {
guard archive_read_open_filename(reader, input.path, 10240) == ARCHIVE_OK else {
throw VPhoneArchiveError.cannotOpen(
- path: input.path, reason: archiveErrorString(reader),
+ path: input.path,
+ reason: archiveErrorString(reader),
)
}
var entry: OpaquePointer?
guard archive_read_next_header(reader, &entry) == ARCHIVE_OK else {
throw VPhoneArchiveError.readFailed(
- path: input.path, reason: archiveErrorString(reader),
+ path: input.path,
+ reason: archiveErrorString(reader),
)
}
@@ -237,7 +243,8 @@ public enum VPhoneArchiveWriter {
}
guard read > 0 else {
throw VPhoneArchiveError.readFailed(
- path: input.path, reason: archiveErrorString(reader),
+ path: input.path,
+ reason: archiveErrorString(reader),
)
}
try handle.write(contentsOf: buffer[0 ..< Int(read)])
@@ -254,7 +261,8 @@ public enum VPhoneArchiveWriter {
) throws {
guard archive_write_set_filter_option(writer, filter, key, value) == ARCHIVE_OK else {
throw VPhoneArchiveError.writeFailed(
- path: "<filter \(filter)>", reason: archiveErrorString(writer),
+ path: "<filter \(filter)>",
+ reason: archiveErrorString(writer),
)
}
}
@@ -291,7 +299,8 @@ public enum VPhoneArchiveWriter {
}
guard sent > 0 else {
throw VPhoneArchiveError.writeFailed(
- path: path, reason: archiveErrorString(writer),
+ path: path,
+ reason: archiveErrorString(writer),
)
}
onBytes(Int64(sent))
diff --git a/sources/VPhoneArchive/VPhoneIPSWCache.swift b/sources/VPhoneArchive/VPhoneIPSWCache.swift
index 5d1f0c8e..fee48603 100644
--- a/sources/VPhoneArchive/VPhoneIPSWCache.swift
+++ b/sources/VPhoneArchive/VPhoneIPSWCache.swift
@@ -65,7 +65,9 @@ public enum VPhoneIPSWCache {
let size = try Int64(fm.attributesOfItem(atPath: downloaded.path)[.size] as? UInt64 ?? 0)
if response.expectedContentLength > 0, size != response.expectedContentLength {
throw Error.incompleteDownload(
- url, expected: response.expectedContentLength, actual: size,
+ url,
+ expected: response.expectedContentLength,
+ actual: size,
)
}
diff --git a/sources/VPhoneCore/VPhoneAEA.swift b/sources/VPhoneCore/VPhoneAEA.swift
index 2475d5ea..58be71ba 100644
--- a/sources/VPhoneCore/VPhoneAEA.swift
+++ b/sources/VPhoneCore/VPhoneAEA.swift
@@ -129,7 +129,9 @@ public enum VPhoneAEA {
var recipient = try HPKE.Recipient(
privateKey: privateKey,
ciphersuite: HPKE.Ciphersuite(
- kem: .P256_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256,
+ kem: .P256_HKDF_SHA256,
+ kdf: .HKDF_SHA256,
+ aead: .AES_GCM_256,
),
info: Data(),
encapsulatedKey: encapsulated,
diff --git a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift b/sources/VPhoneCore/VPhoneAPFSSnapshot.swift
index ef0d484e..6d080d00 100644
--- a/sources/VPhoneCore/VPhoneAPFSSnapshot.swift
+++ b/sources/VPhoneCore/VPhoneAPFSSnapshot.swift
@@ -196,7 +196,8 @@ public enum VPhoneAPFSSnapshot {
let newPrefixBytes = Array(newPrefix.utf8)
guard newPrefixBytes.count == oldPrefix.count else {
throw VPhoneAPFSSnapshotError.prefixLengthMismatch(
- given: newPrefixBytes.count, required: oldPrefix.count,
+ given: newPrefixBytes.count,
+ required: oldPrefix.count,
)
}
diff --git a/sources/VPhoneCore/VPhoneFirmwareIndex.swift b/sources/VPhoneCore/VPhoneFirmwareIndex.swift
index 9f7db458..f8604683 100644
--- a/sources/VPhoneCore/VPhoneFirmwareIndex.swift
+++ b/sources/VPhoneCore/VPhoneFirmwareIndex.swift
@@ -176,7 +176,8 @@ public enum VPhoneFirmwareIndex {
let json = try decompressXZ(compressed)
try? FileManager.default.createDirectory(
- at: cache.deletingLastPathComponent(), withIntermediateDirectories: true,
+ at: cache.deletingLastPathComponent(),
+ withIntermediateDirectories: true,
)
try? json.write(to: cache)
return json
@@ -190,8 +191,11 @@ public enum VPhoneFirmwareIndex {
/// advance and is two orders of magnitude larger than the input.
static func decompressXZ(_ input: Data) throws -> Data {
var stream = compression_stream(
- dst_ptr: UnsafeMutablePointer<UInt8>(bitPattern: 1)!, dst_size: 0,
- src_ptr: UnsafePointer<UInt8>(bitPattern: 1)!, src_size: 0, state: nil,
+ dst_ptr: UnsafeMutablePointer<UInt8>(bitPattern: 1)!,
+ dst_size: 0,
+ src_ptr: UnsafePointer<UInt8>(bitPattern: 1)!,
+ src_size: 0,
+ state: nil,
)
guard compression_stream_init(&stream, COMPRESSION_STREAM_DECODE, COMPRESSION_LZMA)
== COMPRESSION_STATUS_OK
diff --git a/sources/VPhoneCore/VPhoneGuestLauncher.swift b/sources/VPhoneCore/VPhoneGuestLauncher.swift
index 088acda8..d9647105 100644
--- a/sources/VPhoneCore/VPhoneGuestLauncher.swift
+++ b/sources/VPhoneCore/VPhoneGuestLauncher.swift
@@ -129,7 +129,8 @@ public struct VPhoneGuestLaunchPlanner: Sendable {
)
guard result.succeeded,
let plist = try? PropertyListSerialization.propertyList(
- from: Data(result.stdout.utf8), format: nil,
+ from: Data(result.stdout.utf8),
+ format: nil,
) as? [String: Any]
else { return false }
return plist["com.apple.private.virtualization"] as? Bool == true &&
diff --git a/sources/VPhoneCore/VPhonePCCGPUDriver.swift b/sources/VPhoneCore/VPhonePCCGPUDriver.swift
index 8d9e65ea..2e320681 100644
--- a/sources/VPhoneCore/VPhonePCCGPUDriver.swift
+++ b/sources/VPhoneCore/VPhonePCCGPUDriver.swift
@@ -66,7 +66,9 @@ public enum VPhonePCCGPUDriver {
let actual = properties["DTPlatformVersion"] as? String ?? "unknown"
guard actual == expectedPlatformVersion else {
throw Error.wrongPlatformVersion(
- source, expected: expectedPlatformVersion, actual: actual,
+ source,
+ expected: expectedPlatformVersion,
+ actual: actual,
)
}
}
diff --git a/sources/VPhoneCore/VPhoneRemoteZip.swift b/sources/VPhoneCore/VPhoneRemoteZip.swift
index a493b2f0..1a9de186 100644
--- a/sources/VPhoneCore/VPhoneRemoteZip.swift
+++ b/sources/VPhoneCore/VPhoneRemoteZip.swift
@@ -96,7 +96,8 @@ public struct VPhoneRemoteZip: Sendable {
let directory = try await range(of: url, from: directoryOffset, count: directorySize)
return try VPhoneRemoteZip(
- url: url, entries: parseCentralDirectory(directory, expected: entryCount),
+ url: url,
+ entries: parseCentralDirectory(directory, expected: entryCount),
)
}
diff --git a/sources/VPhoneSign/VPhoneCodeSignature.swift b/sources/VPhoneSign/VPhoneCodeSignature.swift
index ac298438..4bef172e 100644
--- a/sources/VPhoneSign/VPhoneCodeSignature.swift
+++ b/sources/VPhoneSign/VPhoneCodeSignature.swift
@@ -121,7 +121,11 @@ struct VPhoneCodeSignature {
var directories: [Data] = []
for (index, digest) in digests.enumerated() {
let directory = directory(
- digest: digest, code: code, codeLimit: codeLimit, executable: executable, blobs: blobs,
+ digest: digest,
+ code: code,
+ codeLimit: codeLimit,
+ executable: executable,
+ blobs: blobs,
)
directories.append(directory)
blobs.append((index == 0 ? 0 : 0x1000 + UInt32(index) - 1, directory))
diff --git a/sources/VPhoneSign/VPhoneMachOImage.swift b/sources/VPhoneSign/VPhoneMachOImage.swift
index 048283ac..10f9de95 100644
--- a/sources/VPhoneSign/VPhoneMachOImage.swift
+++ b/sources/VPhoneSign/VPhoneMachOImage.swift
@@ -204,7 +204,10 @@ struct VPhoneMachOImage {
/// number of CodeDirectories has a different CDHash. So it is
/// reproduced, not corrected.
private static func digests(
- in image: Data, command: UInt32, at start: Int, size: Int,
+ in image: Data,
+ command: UInt32,
+ at start: Int,
+ size: Int,
) throws -> [VPhoneCodeSignature.Digest]? {
/// A packed version: patch, minor, then major in the high 16 bits.
func version(_ value: UInt32) -> (major: UInt32, minor: UInt32) {
@@ -337,13 +340,19 @@ struct VPhoneMachOImage {
+ (segment.sections.isEmpty && segment.fileSize > 0 ? [segment.fileOffset] : [])
}
let firstContent = content.filter { $0 > 0 }.min() ?? 0
- guard UInt64(Self.headerSize + max(rebuilt, commandsSize)) <= firstContent, firstContent <= UInt64(codeEnd) else {
- throw VPhoneSignError.noRoom("content starts at \(firstContent), \(Self.headerSize + rebuilt) bytes of commands")
+ guard UInt64(Self.headerSize + max(rebuilt, commandsSize)) <= firstContent,
+ firstContent <= UInt64(codeEnd)
+ else {
+ throw VPhoneSignError.noRoom(
+ "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)
+ var bytes = image.subdata(
+ 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 {
let start: UInt64 = bytes.littleEndianValue(at: 40)
diff --git a/sources/VPhoneSign/VPhoneSignDER.swift b/sources/VPhoneSign/VPhoneSignDER.swift
index e99e436e..60965e23 100644
--- a/sources/VPhoneSign/VPhoneSignDER.swift
+++ b/sources/VPhoneSign/VPhoneSignDER.swift
@@ -174,7 +174,12 @@ enum VPhoneDER {
let parts = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let text = String(
format: "%02d%02d%02d%02d%02d%02dZ",
- parts.year! % 100, parts.month!, parts.day!, parts.hour!, parts.minute!, parts.second!,
+ parts.year! % 100,
+ parts.month!,
+ parts.day!,
+ parts.hour!,
+ parts.minute!,
+ parts.second!,
)
return encode(0x17, Data(text.utf8))
}
diff --git a/sources/VPhoneSign/VPhoneSignEntitlements.swift b/sources/VPhoneSign/VPhoneSignEntitlements.swift
index 1f99407f..ee1e3647 100644
--- a/sources/VPhoneSign/VPhoneSignEntitlements.swift
+++ b/sources/VPhoneSign/VPhoneSignEntitlements.swift
@@ -100,7 +100,9 @@ struct VPhoneSignEntitlements: Equatable {
("com.apple.private.amfi.can-load-cdhash", 0x100), ("com.apple.private.amfi.can-execute-cdhash", 0x100),
]
return flags.reduce(mainBinary ? 1 : 0) { result, flag in
- entries.first { $0.key.utf8.elementsEqual(flag.key.utf8) }?.value == .boolean(true) ? result | flag.bit : result
+ entries.first { $0.key.utf8.elementsEqual(flag.key.utf8) }?.value == .boolean(true)
+ ? result | flag.bit
+ : result
}
}
@@ -114,7 +116,9 @@ struct VPhoneSignEntitlements: Equatable {
/// refused rather than signed.
func xml() throws -> Data {
let foundation = try? PropertyListSerialization.data(
- fromPropertyList: Self.foundation(.dictionary(entries)), format: .xml, options: 0,
+ fromPropertyList: Self.foundation(.dictionary(entries)),
+ format: .xml,
+ options: 0,
)
guard Self.document(.dictionary(entries), sorted: true) == foundation else {
throw VPhoneSignError.unsupportedEntitlements("Foundation and libplist would write this list differently")
@@ -213,7 +217,9 @@ struct VPhoneSignEntitlements: Equatable {
return
}
out += "<dict>\n".utf8
- for entry in sorted ? entries.sorted(by: { $0.key.utf16.lexicographicallyPrecedes($1.key.utf16) }) : entries {
+ for entry in sorted
+ ? entries.sorted(by: { $0.key.utf16.lexicographicallyPrecedes($1.key.utf16) })
+ : entries {
out += indent + [0x09]
text("key", entry.key)
write(entry.value, depth: depth + 1, sorted: sorted, into: &out)
diff --git a/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift b/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift
index 00648534..742ca710 100644
--- a/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift
+++ b/sources/VPhoneSign/VPhoneSignEntitlementsReader.swift
@@ -105,7 +105,11 @@ extension VPhoneSignEntitlements {
try open(dictionary: name == "dict")
}
case "/dict", "/array":
- guard !empty, let frame = stack.popLast(), frame.isDictionary == (name == "/dict"), frame.key == nil else {
+ guard !empty,
+ let frame = stack.popLast(),
+ frame.isDictionary == (name == "/dict"),
+ frame.key == nil
+ else {
throw Self.refuse("<\(name)> closes a container that is not open, or a key without a value")
}
guard !stack.isEmpty else {
@@ -128,7 +132,8 @@ extension VPhoneSignEntitlements {
// libplist's decoder skips what it does not know; base64
// that reads back the same is what the two agree on
let encoded = try empty ? "" : String(
- decoding: text(closing: name, skippingSpace: true).filter { !Self.isSpace($0) }, as: UTF8.self,
+ decoding: text(closing: name, skippingSpace: true).filter { !Self.isSpace($0) },
+ as: UTF8.self,
)
guard let value = Data(base64Encoded: encoded), value.base64EncodedString() == encoded else {
throw Self.refuse("a <data> whose base64 does not read back the same")
@@ -186,7 +191,9 @@ extension VPhoneSignEntitlements {
}
var name = bytes[start ..< at]
if at < bytes.count, bytes[at] != UInt8(ascii: ">") {
- guard name.elementsEqual("plist".utf8) else { throw Self.refuse("attributes on <\(String(decoding: name, as: UTF8.self))>") }
+ guard name.elementsEqual("plist".utf8) else {
+ throw Self.refuse("attributes on <\(String(decoding: name, as: UTF8.self))>")
+ }
while at < bytes.count, bytes[at] != UInt8(ascii: "<"), bytes[at] != UInt8(ascii: ">") {
if bytes[at] == UInt8(ascii: "\"") {
at = try closingQuote()
@@ -209,7 +216,9 @@ extension VPhoneSignEntitlements {
if skippingSpace {
skipSpace()
}
- guard let end = bytes[at...].firstIndex(of: UInt8(ascii: "<")) else { throw Self.refuse("<\(name)> is never closed") }
+ guard let end = bytes[at...].firstIndex(of: UInt8(ascii: "<")) else {
+ throw Self.refuse("<\(name)> is never closed")
+ }
let text = bytes[at ..< end]
at = end + 1
try expect("/" + name)
@@ -353,7 +362,9 @@ extension VPhoneSignEntitlements {
at += 1
continue
}
- guard let end = text[at...].firstIndex(of: UInt8(ascii: ";")) else { throw refuse("an entity that is never closed") }
+ guard let end = text[at...].firstIndex(of: UInt8(ascii: ";")) else {
+ throw refuse("an entity that is never closed")
+ }
let name = text[(at + 1) ..< end]
switch String(decoding: name, as: UTF8.self) {
case "amp": bytes.append(UInt8(ascii: "&"))
@@ -365,7 +376,10 @@ extension VPhoneSignEntitlements {
let hex = name.dropFirst().first.map { $0 | 0x20 == UInt8(ascii: "x") } == true
let digits = name.dropFirst(hex ? 2 : 1)
guard name.first == UInt8(ascii: "#"), name.count <= 8, !digits.isEmpty,
- digits.allSatisfy({ (0x30 ... 0x39).contains($0) || hex && (0x61 ... 0x66).contains($0 | 0x20) }),
+ digits.allSatisfy({
+ (0x30 ... 0x39).contains($0)
+ || hex && (0x61 ... 0x66).contains($0 | 0x20)
+ }),
let value = UInt32(String(decoding: digits, as: UTF8.self), radix: hex ? 16 : 10), value != 0,
let scalar = Unicode.Scalar(value)
else { throw refuse("an entity libplist matches by its first letters") }
diff --git a/sources/VPhoneSign/VPhoneSignIdentity.swift b/sources/VPhoneSign/VPhoneSignIdentity.swift
index 4cfff862..b487b5c9 100644
--- a/sources/VPhoneSign/VPhoneSignIdentity.swift
+++ b/sources/VPhoneSign/VPhoneSignIdentity.swift
@@ -76,7 +76,9 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {
// 1.2.840.113635.100.9.1: a plist of every cdhash, truncated to 20
// bytes, which is the form the older attribute carries.
if let plist = try? PropertyListSerialization.data(
- fromPropertyList: ["cdhashes": cdHashes.map { $0.prefix(20) }], format: .xml, options: 0,
+ fromPropertyList: ["cdhashes": cdHashes.map { $0.prefix(20) }],
+ format: .xml,
+ options: 0,
) {
attributes.append(attribute(VPhoneDER.OID.hashAgility, [VPhoneDER.octetString(plist)]))
}
@@ -127,7 +129,10 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {
private func sign(_ content: Data) throws -> Data {
var error: Unmanaged<CFError>?
guard let signature = SecKeyCreateSignature(
- key, .rsaSignatureMessagePKCS1v15SHA256, content as CFData, &error,
+ key,
+ .rsaSignatureMessagePKCS1v15SHA256,
+ content as CFData,
+ &error,
) as Data? else {
throw VPhoneSignError.signingFailed(
(error?.takeRetainedValue()).map { "\($0)" } ?? "SecKeyCreateSignature gave no signature",
@@ -143,7 +148,9 @@ public struct VPhoneSignIdentity: VPhoneSigningIdentity, @unchecked Sendable {
// MARK: Reading the certificate
private static func certificateFields(_ certificate: Data) throws -> (
- issuer: Data, subject: Data, serialNumber: Data,
+ issuer: Data,
+ subject: Data,
+ serialNumber: Data,
) {
let tbs = try VPhoneDER.children(of: VPhoneDER.element(in: certificate, at: 0).content)
guard let first = tbs.first else { throw VPhoneSignError.identityUnreadable("an empty certificate") }
diff --git a/sources/VPhoneSign/VPhoneSignPKCS12.swift b/sources/VPhoneSign/VPhoneSignPKCS12.swift
index f653a77a..023c3273 100644
--- a/sources/VPhoneSign/VPhoneSignPKCS12.swift
+++ b/sources/VPhoneSign/VPhoneSignPKCS12.swift
@@ -72,9 +72,13 @@ struct VPhoneSignPKCS12 {
return try VPhoneDER.element(in: fields[1].content, at: 0).content
case VPhoneDER.OID.encryptedData:
let encrypted = try VPhoneDER.children(of: VPhoneDER.element(in: fields[1].content, at: 0).content)
- guard encrypted.count >= 2 else { throw VPhoneSignError.identityUnreadable("an EncryptedData without content") }
+ guard encrypted.count >= 2 else {
+ throw VPhoneSignError.identityUnreadable("an EncryptedData without content")
+ }
let info = try VPhoneDER.children(of: encrypted[1].content)
- guard info.count >= 3 else { throw VPhoneSignError.identityUnreadable("an EncryptedContentInfo without content") }
+ guard info.count >= 3 else {
+ throw VPhoneSignError.identityUnreadable("an EncryptedContentInfo without content")
+ }
// [0] IMPLICIT OCTET STRING: the content is the value itself
return try decrypt(info[2].content, algorithm: info[1], password: password)
default:
@@ -87,7 +91,9 @@ struct VPhoneSignPKCS12 {
/// An EncryptedPrivateKeyInfo.
private static func decryptPrivateKey(_ encoded: Data, password: String) throws -> Data {
let fields = try VPhoneDER.children(of: VPhoneDER.element(in: encoded, at: 0).content)
- guard fields.count >= 2 else { throw VPhoneSignError.identityUnreadable("an EncryptedPrivateKeyInfo without content") }
+ guard fields.count >= 2 else {
+ throw VPhoneSignError.identityUnreadable("an EncryptedPrivateKeyInfo without content")
+ }
return try decrypt(fields[1].content, algorithm: fields[0], password: password)
}
@@ -170,10 +176,14 @@ struct VPhoneSignPKCS12 {
// an empty password is a real password here: the pointer
// may be null, which CCKeyDerivationPBKDF accepts with a
// length of zero
- bytes.baseAddress.map { UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self) }, bytes.count,
- salt.baseAddress, salt.count,
- prf, UInt32(iterations),
- &key, key.count,
+ bytes.baseAddress.map { UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self) },
+ bytes.count,
+ salt.baseAddress,
+ salt.count,
+ prf,
+ UInt32(iterations),
+ &key,
+ key.count,
)
}
}
@@ -186,10 +196,17 @@ struct VPhoneSignPKCS12 {
let status = [UInt8](ciphertext).withUnsafeBufferPointer { input in
[UInt8](iv).withUnsafeBufferPointer { iv in
CCCrypt(
- CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding),
- key, key.count, iv.baseAddress,
- input.baseAddress, input.count,
- &plaintext, plaintext.count, &written,
+ CCOperation(kCCDecrypt),
+ CCAlgorithm(kCCAlgorithmAES),
+ CCOptions(kCCOptionPKCS7Padding),
+ key,
+ key.count,
+ iv.baseAddress,
+ input.baseAddress,
+ input.count,
+ &plaintext,
+ plaintext.count,
+ &written,
)
}
}
diff --git a/sources/VPhoneSign/VPhoneSigner.swift b/sources/VPhoneSign/VPhoneSigner.swift
index 20c3312e..3493a1d4 100644
--- a/sources/VPhoneSign/VPhoneSigner.swift
+++ b/sources/VPhoneSign/VPhoneSigner.swift
@@ -124,7 +124,10 @@ public enum VPhoneSigner {
for (index, slice) in file.slices.enumerated() {
let alignment = file.architectures.map { Int($0[index].alignment) } ?? slice.linkeditAlignment
let signature = try signature(
- for: slice, identifier: identifier, digests: digests, options: options,
+ for: slice,
+ identifier: identifier,
+ digests: digests,
+ options: options,
)
let executable = slice.executableSegment
try images.append(slice.signed(
@@ -170,7 +173,8 @@ public enum VPhoneSigner {
case .ldid:
signature.teamIdentifier = options.identity?.teamIdentifier ?? ""
signature.requirementsBlob = VPhoneCodeSignature.requirements(
- identifier: identifier, commonName: options.identity?.commonName ?? "",
+ identifier: identifier,
+ commonName: options.identity?.commonName ?? "",
)
signature.cmsReservation = options.identity == nil ? nil : cmsReservation
case .appleAdHoc:
diff --git a/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift b/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift
index e03f87f2..ff3c5f8b 100644
--- a/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift
+++ b/sources/VPhoneVirtualMachineKit/GuestCommunication/VPhoneGuestControl.swift
@@ -223,8 +223,12 @@ 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), body: data,
- contentType: "application/octet-stream")
+ let response = try await http(
+ method: "PUT",
+ path: try filePath(path, mode: permissions),
+ body: data,
+ contentType: "application/octet-stream"
+ )
guard response.status == 200 else { throw try httpError(response) }
}
@@ -252,9 +256,13 @@ final class VPhoneGuestControl {
func clipboardGet() async throws -> ClipboardContent {
let (info, image) = try await sendRequest(["t": "clipboard_get"])
- return ClipboardContent(text: info["text"] as? String, types: info["types"] as? [String] ?? [],
- hasImage: info["has_image"] as? Bool ?? false,
- changeCount: info["change_count"] as? Int ?? 0, imageData: image)
+ return ClipboardContent(
+ text: info["text"] as? String,
+ types: info["types"] as? [String] ?? [],
+ hasImage: info["has_image"] as? Bool ?? false,
+ changeCount: info["change_count"] as? Int ?? 0,
+ imageData: image
+ )
}
func clipboardSet(text: String) async throws {
@@ -262,14 +270,24 @@ final class VPhoneGuestControl {
}
func clipboardSet(imageData: Data) async throws {
- let response = try await http(method: "PUT", path: "/v1/clipboard/image", body: imageData,
- contentType: "application/octet-stream")
+ let response = try await http(
+ method: "PUT",
+ path: "/v1/clipboard/image",
+ body: imageData,
+ contentType: "application/octet-stream"
+ )
guard response.status == 200 else { throw try httpError(response) }
}
- func sendLocation(latitude: Double, longitude: Double, altitude: Double,
- horizontalAccuracy: Double, verticalAccuracy: Double,
- speed: Double, course: Double) {
+ func sendLocation(
+ latitude: Double,
+ longitude: Double,
+ altitude: Double,
+ horizontalAccuracy: Double,
+ verticalAccuracy: Double,
+ speed: Double,
+ course: Double
+ ) {
Task {
do { _ = try await call("location.set", params: [
"latitude": latitude, "longitude": longitude, "altitude": altitude,
@@ -301,16 +319,25 @@ final class VPhoneGuestControl {
return .guestError(error?["message"] as? String ?? "HTTP \(response.status)")
}
- private func http(method: String, path: String, body: Data = Data(),
- contentType: String = "application/json") async throws -> VPhoneHTTPResponse {
+ private func http(
+ method: String,
+ path: String,
+ body: Data = Data(),
+ contentType: String = "application/json"
+ ) async throws -> VPhoneHTTPResponse {
guard let device else { throw ControlError.notConnected }
let socket = await withCheckedContinuation {
(continuation: CheckedContinuation<VPhoneSocketResult, Never>) in
device.connect(toPort: 1339) { continuation.resume(returning: VPhoneSocketResult($0)) }
}
let connection = try socket.result.get()
- let transaction = VPhoneHTTPTransaction(connection: connection, method: method, path: path,
- body: body, contentType: contentType)
+ let transaction = VPhoneHTTPTransaction(
+ connection: connection,
+ method: method,
+ path: path,
+ body: body,
+ contentType: contentType
+ )
return try await withCheckedThrowingContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
do { continuation.resume(returning: try transaction.run()) }
@@ -337,8 +364,13 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
let body: Data
let contentType: String
- init(connection: VZVirtioSocketConnection, method: String, path: String,
- body: Data, contentType: String) {
+ init(
+ connection: VZVirtioSocketConnection,
+ method: String,
+ path: String,
+ body: Data,
+ contentType: String
+ ) {
self.connection = connection
self.method = method
self.path = path
@@ -365,7 +397,9 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {
var received = Data()
let marker = Data("\r\n\r\n".utf8)
while received.range(of: marker) == nil {
- guard received.count < 64 * 1024 else { throw VPhoneGuestControl.ControlError.protocolError("HTTP headers too large") }
+ guard received.count < 64 * 1024 else {
+ throw VPhoneGuestControl.ControlError.protocolError("HTTP headers too large")
+ }
try readMore(fd, into: &received)
}
let boundary = received.range(of: marker)!
diff --git a/sources/vphone-amfi-allow/vphone-amfi-allow.c b/sources/vphone-amfi-allow/vphone-amfi-allow.c
index bae8664d..a143c553 100644
--- a/sources/vphone-amfi-allow/vphone-amfi-allow.c
+++ b/sources/vphone-amfi-allow/vphone-amfi-allow.c
@@ -133,8 +133,11 @@ static Class manager_class(void) {
}
cls = objc_getClass(MANAGER_CLASS);
if (!cls) {
- fprintf(stderr, "error: class %s not found — this macOS build is not supported\n",
- MANAGER_CLASS);
+ fprintf(
+ stderr,
+ "error: class %s not found — this macOS build is not supported\n",
+ MANAGER_CLASS
+ );
exit(1);
}
return cls;
@@ -143,8 +146,12 @@ static Class manager_class(void) {
static ptrdiff_t ivar_offset(const char *name) {
Ivar iv = class_getInstanceVariable(manager_class(), name);
if (!iv) {
- fprintf(stderr, "error: ivar %s not found on %s — this macOS build is not supported\n",
- name, MANAGER_CLASS);
+ fprintf(
+ stderr,
+ "error: ivar %s not found on %s — this macOS build is not supported\n",
+ name,
+ MANAGER_CLASS
+ );
exit(1);
}
return ivar_getOffset(iv);
@@ -253,11 +260,14 @@ static int attach_amfid(const char *self_path) {
}
kern_return_t kr = task_for_pid(mach_task_self(), g_amfid, &g_task);
if (kr != KERN_SUCCESS) {
- fprintf(stderr,
- "error: task_for_pid(%d): %s\n"
- " needs root and SIP debugging restrictions off "
- "(csrutil enable --without debug)\n",
- g_amfid, mach_error_string(kr));
+ fprintf(
+ stderr,
+ "error: task_for_pid(%d): %s\n"
+ " needs root and SIP debugging restrictions off "
+ "(csrutil enable --without debug)\n",
+ g_amfid,
+ mach_error_string(kr)
+ );
return 0;
}
return 1;
@@ -267,8 +277,12 @@ static int read_amfid(mach_vm_address_t addr, void *buf, size_t len) {
mach_vm_size_t got = 0;
kern_return_t kr = mach_vm_read_overwrite(g_task, addr, len, (mach_vm_address_t)buf, &got);
if (kr != KERN_SUCCESS) {
- fprintf(stderr, "error: read %#llx from amfid: %s\n", (unsigned long long)addr,
- mach_error_string(kr));
+ fprintf(
+ stderr,
+ "error: read %#llx from amfid: %s\n",
+ (unsigned long long)addr,
+ mach_error_string(kr)
+ );
return 0;
}
return got == len;
@@ -282,8 +296,12 @@ static int write_amfid_byte(mach_vm_address_t addr, uint8_t value) {
if (current == value) return 1; // never write what is already there
kern_return_t kr = mach_vm_write(g_task, addr, (vm_offset_t)&value, 1);
if (kr != KERN_SUCCESS) {
- fprintf(stderr, "error: write %#llx in amfid: %s\n", (unsigned long long)addr,
- mach_error_string(kr));
+ fprintf(
+ stderr,
+ "error: write %#llx in amfid: %s\n",
+ (unsigned long long)addr,
+ mach_error_string(kr)
+ );
return 0;
}
uint8_t back = 0;
@@ -316,8 +334,13 @@ static mach_vm_address_t amfid_manager(const char *self_path) {
uintptr_t remote_isa = 0, local_isa = (uintptr_t)manager_class();
if (!read_amfid((mach_vm_address_t)remote, &remote_isa, sizeof(remote_isa))) return 0;
if ((remote_isa & kISAClassBits) != (local_isa & kISAClassBits)) {
- fprintf(stderr, "error: %#lx in amfid is not an %s (isa %#lx)\n", (unsigned long)remote,
- MANAGER_CLASS, (unsigned long)remote_isa);
+ fprintf(
+ stderr,
+ "error: %#lx in amfid is not an %s (isa %#lx)\n",
+ (unsigned long)remote,
+ MANAGER_CLASS,
+ (unsigned long)remote_isa
+ );
return 0;
}
@@ -329,8 +352,13 @@ static mach_vm_address_t amfid_manager(const char *self_path) {
1))
return 0;
if (flags[0] > 1 || flags[1] > 1) {
- fprintf(stderr, "error: %s ivars do not read as booleans (%u, %u)\n", MANAGER_CLASS,
- flags[0], flags[1]);
+ fprintf(
+ stderr,
+ "error: %s ivars do not read as booleans (%u, %u)\n",
+ MANAGER_CLASS,
+ flags[0],
+ flags[1]
+ );
return 0;
}
return (mach_vm_address_t)remote;
@@ -349,7 +377,9 @@ static CFStringRef stock_requirement(void) {
Class cls = manager_class();
id mgr = ((id(*)(id, SEL))objc_msgSend)((id)cls, sel_registerName("sharedManager"));
SecRequirementRef stock = ((SecRequirementRef(*)(id, SEL))objc_msgSend)(
- mgr, sel_registerName("restrictedRequirement"));
+ mgr,
+ sel_registerName("restrictedRequirement")
+ );
CFStringRef text = NULL;
if (!stock || SecRequirementCopyString(stock, kSecCSDefaultFlags, &text) != errSecSuccess ||
!text) {
@@ -368,7 +398,11 @@ static CFStringRef requirement_for(int count, char **paths) {
for (int i = 0; i < count; i++) {
CFURLRef url = CFURLCreateFromFileSystemRepresentation(
- NULL, (const UInt8 *)paths[i], (CFIndex)strlen(paths[i]), false);
+ NULL,
+ (const UInt8 *)paths[i],
+ (CFIndex)strlen(paths[i]),
+ false
+ );
SecStaticCodeRef code = NULL;
OSStatus st = SecStaticCodeCreateWithPath(url, kSecCSDefaultFlags, &code);
CFRelease(url);
@@ -384,8 +418,12 @@ static CFStringRef requirement_for(int count, char **paths) {
st = SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info);
CFRelease(code);
if (st != errSecSuccess) {
- fprintf(stderr, "error: %s: cannot read signing information (%d)\n", paths[i],
- (int)st);
+ fprintf(
+ stderr,
+ "error: %s: cannot read signing information (%d)\n",
+ paths[i],
+ (int)st
+ );
exit(1);
}
@@ -419,8 +457,12 @@ static CFStringRef requirement_for(int count, char **paths) {
}
static int write_prefs(CFStringRef requirement) {
- CFMutableDictionaryRef d = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
+ CFMutableDictionaryRef d = CFDictionaryCreateMutable(
+ NULL,
+ 0,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks
+ );
CFDictionarySetValue(d, CFSTR("Entitlements"), requirement);
// Setting Entitlements alone also turns _allowUnsafeDynamicLinking on
// (checkCodeRequirementsPreferenceUnsynchronized, 0x23cea5758), which would
@@ -465,8 +507,11 @@ static int sysctl_int(const char *name) {
static void report(const char *self_path) {
printf("host\n");
- printf(" vm.cs_system_enforcement %d%s\n", sysctl_int("vm.cs_system_enforcement"),
- sysctl_int("vm.cs_system_enforcement") == 1 ? " (code patching is fatal here)" : "");
+ printf(
+ " vm.cs_system_enforcement %d%s\n",
+ sysctl_int("vm.cs_system_enforcement"),
+ sysctl_int("vm.cs_system_enforcement") == 1 ? " (code patching is fatal here)" : ""
+ );
printf(" preference file %s\n",
access(PREFS_PATH, R_OK) == 0 ? PREFS_PATH : PREFS_PATH " (absent)");
@@ -492,8 +537,11 @@ static void report(const char *self_path) {
printf(" %s %#llx\n", MANAGER_CLASS, (unsigned long long)mgr);
printf(" _isRunningInternalBuild %u%s\n", internal, internal ? " (preference honoured)" : "");
printf(" _allowUnsafeDynamicLinking %u\n", unsafe_linking);
- printf(" _restrictedRequirement %#lx%s\n", (unsigned long)restricted,
- restricted ? "" : " (nothing would be allowed)");
+ printf(
+ " _restrictedRequirement %#lx%s\n",
+ (unsigned long)restricted,
+ restricted ? "" : " (nothing would be allowed)"
+ );
}
// --------------------------------------------------------------------------
@@ -530,8 +578,11 @@ static int cmd_allow(const char *self_path, int count, char **paths, int hold_se
uintptr_t restricted = 0;
if (read_amfid(mgr + req_off, &restricted, sizeof(restricted)) && restricted &&
restricted != before) {
- printf("amfid adopted the requirement (_restrictedRequirement %#lx -> %#lx)\n",
- (unsigned long)before, (unsigned long)restricted);
+ printf(
+ "amfid adopted the requirement (_restrictedRequirement %#lx -> %#lx)\n",
+ (unsigned long)before,
+ (unsigned long)restricted
+ );
goto live;
}
usleep(100 * 1000);
diff --git a/sources/vphone-archive/main.swift b/sources/vphone-archive/main.swift
index 877de2ce..c820ffeb 100644
--- a/sources/vphone-archive/main.swift
+++ b/sources/vphone-archive/main.swift
@@ -38,24 +38,36 @@ struct Extract: ParsableCommand {
abstract: "Unpack an archive into a directory",
)
- @Option(name: [.customShort("f"), .long], help: "Archive to read",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("f"), .long],
+ help: "Archive to read",
+ transform: URL.init(fileURLWithPath:)
+ )
var file: URL
- @Option(name: [.customShort("C"), .customLong("directory")],
- help: "Where to unpack it", transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("C"), .customLong("directory")],
+ help: "Where to unpack it",
+ 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")
+ @Flag(
+ name: [.customShort("p"), .customLong("preserve-permissions")],
+ 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")
+ @Flag(
+ name: .customLong("no-overwrite-dir"),
+ 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")
+ @Flag(
+ name: .customLong("numeric-owner"),
+ help: "Accepted for compatibility; ownership is always restored by number"
+ )
var numericOwner = false
@Flag(name: [.customShort("v"), .long], help: "Print each member as it is written")
@@ -73,7 +85,9 @@ struct Extract: ParsableCommand {
options.noOverwriteDir = noOverwriteDir
let written = try VPhoneArchiveExtractor.extract(
- file, into: destination, options: options,
+ file,
+ into: destination,
+ options: options,
progress: verbose ? { print($0.currentPath) } : nil,
)
if !verbose {
@@ -90,12 +104,18 @@ struct Create: ParsableCommand {
abstract: "Pack a directory into an archive",
)
- @Option(name: [.customShort("f"), .long], help: "Archive to write",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("f"), .long],
+ help: "Archive to write",
+ transform: URL.init(fileURLWithPath:)
+ )
var file: URL
- @Option(name: [.customShort("C"), .customLong("directory")],
- help: "Directory to pack", transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("C"), .customLong("directory")],
+ help: "Directory to pack",
+ transform: URL.init(fileURLWithPath:)
+ )
var source: URL = .init(fileURLWithPath: ".")
@Option(help: "tar dialect: gnutar, pax or ustar")
@@ -141,8 +161,11 @@ struct Create: ParsableCommand {
}
let written = try VPhoneArchiveWriter.create(
- archive: file, from: source,
- format: tarFormat, compression: compression, excluding: exclude,
+ archive: file,
+ from: source,
+ format: tarFormat,
+ compression: compression,
+ excluding: exclude,
progress: verbose ? { print($0.currentPath) } : nil,
)
if !verbose {
@@ -163,12 +186,18 @@ struct Decompress: ParsableCommand {
""",
)
- @Option(name: [.customShort("f"), .long], help: "File to decompress",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("f"), .long],
+ help: "File to decompress",
+ transform: URL.init(fileURLWithPath:)
+ )
var file: URL
- @Option(name: [.customShort("o"), .long], help: "Where to write the result",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("o"), .long],
+ help: "Where to write the result",
+ transform: URL.init(fileURLWithPath:)
+ )
var output: URL
func run() throws {
@@ -181,11 +210,15 @@ struct Decompress: ParsableCommand {
struct List: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "list", abstract: "List an archive's members",
+ commandName: "list",
+ abstract: "List an archive's members",
)
- @Option(name: [.customShort("f"), .long], help: "Archive to read",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("f"), .long],
+ help: "Archive to read",
+ transform: URL.init(fileURLWithPath:)
+ )
var file: URL
@Flag(name: [.customShort("v"), .long], help: "Include mode, owner and size")
@@ -212,8 +245,11 @@ struct Cat: ParsableCommand {
abstract: "Write one member to stdout without unpacking the archive",
)
- @Option(name: [.customShort("f"), .long], help: "Archive to read",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: [.customShort("f"), .long],
+ help: "Archive to read",
+ transform: URL.init(fileURLWithPath:)
+ )
var file: URL
@Argument(help: "Member path inside the archive")
@@ -246,12 +282,16 @@ struct Fingerprint: ParsableCommand {
@Argument(help: "Tree to describe", transform: URL.init(fileURLWithPath:))
var tree: URL
- @Argument(help: "Second tree; given, the two are compared",
- transform: URL.init(fileURLWithPath:))
+ @Argument(
+ help: "Second tree; given, the two are compared",
+ transform: URL.init(fileURLWithPath:)
+ )
var other: URL?
- @Flag(name: .customLong("no-content-hashes"),
- help: "Skip file digests — much faster, and enough to compare metadata")
+ @Flag(
+ name: .customLong("no-content-hashes"),
+ help: "Skip file digests — much faster, and enough to compare metadata"
+ )
var noContentHashes = false
func run() throws {
@@ -265,7 +305,8 @@ struct Fingerprint: ParsableCommand {
}
let second = try VPhoneTreeFingerprint.capture(
- other, includeContentHashes: !noContentHashes,
+ other,
+ includeContentHashes: !noContentHashes,
)
let differences = first.differences(from: second)
guard differences.isEmpty else {
diff --git a/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift b/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift
index 9385324a..655a6ce3 100644
--- a/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift
+++ b/sources/vphone-cli/VPhoneCustomFirmwareInstaller.swift
@@ -34,8 +34,11 @@ struct VPhoneCustomFirmwareInstaller {
args.append("--force-dsc-maxslide")
}
if geteuid() == 0 {
- try VPhoneCustomFirmwareInstaller(bundle: bundle, resources: resources,
- forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide).run()
+ try VPhoneCustomFirmwareInstaller(
+ bundle: bundle,
+ resources: resources,
+ forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide
+ ).run()
return 0
}
if rootPopup {
@@ -43,7 +46,10 @@ struct VPhoneCustomFirmwareInstaller {
env["SUDO_USER"] = NSUserName()
env["SUDO_UID"] = String(getuid())
return try VPhoneProcessRunner.runWithAdminPrivileges(
- exe, args, env: env, echo: verbose,
+ exe,
+ args,
+ env: env,
+ echo: verbose,
)
}
var env = ProcessInfo.processInfo.environment
@@ -53,7 +59,10 @@ struct VPhoneCustomFirmwareInstaller {
args.insert("-A", at: 0)
}
return try VPhoneProcessRunner.runForeground(
- URL(fileURLWithPath: "/usr/bin/sudo"), args, env: env, echo: verbose,
+ URL(fileURLWithPath: "/usr/bin/sudo"),
+ args,
+ env: env,
+ echo: verbose,
)
}
@@ -88,7 +97,8 @@ struct VPhoneCustomFirmwareInstaller {
let info = try tool("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"], quiet: true)
guard let plist = try PropertyListSerialization.propertyList(
- from: Data(info.utf8), format: nil,
+ from: Data(info.utf8),
+ format: nil,
) as? [String: Any],
let container = plist["APFSContainerReference"] as? String,
container.hasPrefix("disk")
@@ -145,11 +155,21 @@ struct VPhoneCustomFirmwareInstaller {
} else if forceDyldSharedCacheMaxSlide {
try patch("patch-dsc-maxslide", [dsc.path, "--force"])
}
- try patchMachO(system: system, work: work,
- path: "usr/libexec/seputil", verb: "patch-seputil", identifier: "com.apple.seputil")
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/seputil",
+ verb: "patch-seputil",
+ identifier: "com.apple.seputil"
+ )
if version.hasPrefix("27.") {
- try patchMachO(system: system, work: work,
- path: "usr/libexec/diskimagesiod", verb: "patch-diskimagesiod", preserveEntitlements: true)
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/diskimagesiod",
+ verb: "patch-diskimagesiod",
+ preserveEntitlements: true
+ )
}
try renameGigalocker(data: data)
let gpuSource = VPhonePCCGPUDriver.stagedBundle(in: restore)
@@ -179,14 +199,27 @@ struct VPhoneCustomFirmwareInstaller {
{
try fm.setAttributes([.posixPermissions: NSNumber(value: 0o644)], ofItemAtPath: file.path)
}
- try patchMachO(system: system, work: work,
- path: "usr/libexec/launchd_cache_loader", verb: "patch-launchd-cache-loader",
- identifier: "com.apple.launchd_cache_loader")
- try patchMachO(system: system, work: work,
- path: "usr/libexec/mobileactivationd", verb: "patch-mobileactivationd")
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/launchd_cache_loader",
+ verb: "patch-launchd-cache-loader",
+ identifier: "com.apple.launchd_cache_loader"
+ )
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/mobileactivationd",
+ verb: "patch-mobileactivationd"
+ )
try installVphoned(system: system, work: work)
- try patchMachO(system: system, work: work,
- path: "sbin/launchd", verb: "patch-launchd-jetsam", preserveEntitlements: true)
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "sbin/launchd",
+ verb: "patch-launchd-jetsam",
+ preserveEntitlements: true
+ )
try patchDebugserver(system: system, work: work)
if version.hasPrefix("27.") {
try patchCampo(system: system, work: work)
@@ -205,17 +238,30 @@ struct VPhoneCustomFirmwareInstaller {
let encrypted = restore.appendingPathComponent(paths.systemOS)
let plain = work.appendingPathComponent("SystemOS.dmg")
let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: encrypted) }
- try tool("/usr/bin/aea", ["decrypt", "-i", encrypted.path,
- "-o", plain.path, "-key-value", key], quiet: true)
+ try tool(
+ "/usr/bin/aea",
+ ["decrypt", "-i", encrypted.path,
+ "-o", plain.path, "-key-value", key],
+ quiet: true
+ )
let osMount = work.appendingPathComponent("mnt-os")
let appMount = work.appendingPathComponent("mnt-app")
try fm.createDirectory(at: osMount, withIntermediateDirectories: true)
try fm.createDirectory(at: appMount, withIntermediateDirectories: true)
- try tool("/usr/bin/hdiutil", ["attach", "-mountpoint", osMount.path,
- plain.path, "-nobrowse", "-owners", "off"], quiet: true)
+ try tool(
+ "/usr/bin/hdiutil",
+ ["attach", "-mountpoint", osMount.path,
+ plain.path, "-nobrowse", "-owners", "off"],
+ quiet: true
+ )
defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", osMount.path], quiet: true) }
- try tool("/usr/bin/hdiutil", ["attach", "-mountpoint", appMount.path,
- restore.appendingPathComponent(paths.appOS).path, "-nobrowse", "-owners", "off"], quiet: true)
+ try tool(
+ "/usr/bin/hdiutil",
+ ["attach", "-mountpoint", appMount.path,
+ restore.appendingPathComponent(paths.appOS).path,
+ "-nobrowse", "-owners", "off"],
+ quiet: true
+ )
defer { _ = try? tool("/usr/bin/hdiutil", ["detach", "-force", appMount.path], quiet: true) }
for (source, destination) in [(osMount, os), (appMount, app)] {
// The restored rootfs has dangling Cryptex symlinks. fileExists
@@ -266,8 +312,14 @@ struct VPhoneCustomFirmwareInstaller {
try replace(temp, at: launchd, mode: 0o644)
}
- private func patchMachO(system: URL, work: URL, path: String, verb: String,
- identifier: String? = nil, preserveEntitlements: Bool = false) throws
+ private func patchMachO(
+ system: URL,
+ work: URL,
+ path: String,
+ verb: String,
+ identifier: String? = nil,
+ preserveEntitlements: Bool = false
+ ) throws
{
let target = system.appendingPathComponent(path)
let backup = target.appendingPathExtension("bak")
@@ -331,8 +383,13 @@ struct VPhoneCustomFirmwareInstaller {
try patch("patch-campo-entitlements", [ent.path])
let staged = work.appendingPathComponent("Campo")
try fm.copyItem(at: target, to: staged)
- try VPhoneSigner.sign(fileAt: staged,
- options: .init(entitlements: Data(contentsOf: ent, options: .mappedIfSafe), mergesExisting: true))
+ try VPhoneSigner.sign(
+ fileAt: staged,
+ options: .init(
+ entitlements: Data(contentsOf: ent, options: .mappedIfSafe),
+ mergesExisting: true
+ )
+ )
try replace(staged, at: target, mode: 0o755)
}
@@ -355,7 +412,8 @@ struct VPhoneCustomFirmwareInstaller {
"System/Library/CoreServices/SystemVersion.plist",
)
guard let value = try PropertyListSerialization.propertyList(
- from: Data(contentsOf: plist, options: .mappedIfSafe), format: nil,
+ from: Data(contentsOf: plist, options: .mappedIfSafe),
+ format: nil,
) as? [String: Any],
let version = value["ProductVersion"] as? String
else {
@@ -365,7 +423,9 @@ struct VPhoneCustomFirmwareInstaller {
}
private func symlink(_ destination: String, at path: URL) throws {
- if fm.fileExists(atPath: path.path) || (try? path.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true {
+ if fm.fileExists(atPath: path.path)
+ || (try? path.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true
+ {
try fm.removeItem(at: path)
}
try fm.createSymbolicLink(atPath: path.path, withDestinationPath: destination)
diff --git a/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift b/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift
index d5166828..e66ec54a 100644
--- a/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift
+++ b/sources/vphone-cli/VPhoneCustomFirmwarePatchCLI.swift
@@ -165,7 +165,12 @@ struct VPhoneCustomFirmwareInjectDylibCommand: ParsableCommand {
var dylibPath: String
func run() throws {
- let injections = try CustomFirmwareInjectDylib.inject(dylibPath: dylibPath, into: binary, weak: true, policy: .strip)
+ let injections = try CustomFirmwareInjectDylib.inject(
+ dylibPath: dylibPath,
+ into: binary,
+ weak: true,
+ policy: .strip
+ )
for injection in injections {
let stripped = injection.removedCodeSignature ? ", signature stripped" : ""
print(" [+] LC_LOAD_WEAK_DYLIB \(dylibPath) -> \(binary.lastPathComponent) "
diff --git a/sources/vphone-cli/VPhoneFirmwareAEACLI.swift b/sources/vphone-cli/VPhoneFirmwareAEACLI.swift
index e6f4e565..027e7aee 100644
--- a/sources/vphone-cli/VPhoneFirmwareAEACLI.swift
+++ b/sources/vphone-cli/VPhoneFirmwareAEACLI.swift
@@ -73,7 +73,8 @@ struct VPhoneFirmwareIM4PCreateCommand: ParsableCommand {
func run() throws {
let im4p = try IM4P(
- fourcc: fourcc, description: version,
+ fourcc: fourcc,
+ description: version,
payload: Data(contentsOf: file, options: .mappedIfSafe),
)
try im4p.data.write(to: output)
@@ -89,8 +90,11 @@ struct VPhoneFirmwareIM4PExtractCommand: ParsableCommand {
@Argument(help: "The IM4P container", transform: URL.init(fileURLWithPath:))
var file: URL
- @Option(name: .customLong("output"), help: "Where to write the payload",
- transform: URL.init(fileURLWithPath:))
+ @Option(
+ name: .customLong("output"),
+ help: "Where to write the payload",
+ transform: URL.init(fileURLWithPath:)
+ )
var output: URL
func run() throws {
diff --git a/sources/vphone-cli/VPhoneFirmwareCLI.swift b/sources/vphone-cli/VPhoneFirmwareCLI.swift
index d7337275..bd318f71 100644
--- a/sources/vphone-cli/VPhoneFirmwareCLI.swift
+++ b/sources/vphone-cli/VPhoneFirmwareCLI.swift
@@ -224,7 +224,9 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
if list {
let code = VPhoneFirmwareMatrixCommandLine.list(
- device: "iPhone17,3", readmePath: readme, downloadURLs: urls,
+ device: "iPhone17,3",
+ readmePath: readme,
+ downloadURLs: urls,
)
if code != 0 {
throw ExitCode(code)
@@ -238,7 +240,9 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
throw ValidationError("Use either --iphone-source or --iphone-version/--iphone-build.")
}
let selection = VPhoneFirmwareMatrix.selection(
- device: "iPhone17,3", version: iphoneVersion ?? "", build: iphoneBuild ?? "",
+ device: "iPhone17,3",
+ version: iphoneVersion ?? "",
+ build: iphoneBuild ?? "",
readme: try? String(contentsOfFile: readme, encoding: .utf8),
downloadURLs: urls,
style: .forStream(FileHandle.standardError.fileDescriptor),
@@ -257,9 +261,11 @@ struct VPhoneFirmwarePrepareCommand: ParsableCommand {
let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)
let bundle = try lib.library.bundle(named: name)
try VPhoneFirmwarePreparer.prepare(
- iPhoneSource: phone, cloudOSSource: cloud,
+ iPhoneSource: phone,
+ cloudOSSource: cloud,
gpuDriverBundle: gpuDriverBundle.map { URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath) },
- bundle: bundle, resources: resources,
+ bundle: bundle,
+ resources: resources,
)
}
}
diff --git a/sources/vphone-cli/VPhoneFirmwareDownloadCLI.swift b/sources/vphone-cli/VPhoneFirmwareDownloadCLI.swift
index cdb6addf..e981347d 100644
--- a/sources/vphone-cli/VPhoneFirmwareDownloadCLI.swift
+++ b/sources/vphone-cli/VPhoneFirmwareDownloadCLI.swift
@@ -112,7 +112,8 @@ struct VPhoneFirmwareSealToolCommand: ParsableCommand {
let manifestData = try await zip.read(manifestEntry)
guard let manifest = try PropertyListSerialization.propertyList(
- from: manifestData, format: nil,
+ from: manifestData,
+ format: nil,
) as? [String: Any],
let identities = manifest["BuildIdentities"] as? [[String: Any]]
else {
@@ -147,7 +148,8 @@ struct VPhoneFirmwareSealToolCommand: ParsableCommand {
let attached = try run("/usr/bin/hdiutil",
["attach", "-readonly", "-nobrowse", "-plist", dmg.path])
guard let plist = try PropertyListSerialization.propertyList(
- from: Data(attached.utf8), format: nil,
+ from: Data(attached.utf8),
+ format: nil,
) as? [String: Any],
let entities = plist["system-entities"] as? [[String: Any]],
let mount = entities.compactMap({ $0["mount-point"] as? String }).first
diff --git a/sources/vphone-cli/VPhoneFirmwarePreparer.swift b/sources/vphone-cli/VPhoneFirmwarePreparer.swift
index b5c97abb..c3dadf8f 100644
--- a/sources/vphone-cli/VPhoneFirmwarePreparer.swift
+++ b/sources/vphone-cli/VPhoneFirmwarePreparer.swift
@@ -35,7 +35,8 @@ enum VPhoneFirmwarePreparer {
) throws {
let fm = FileManager.default
let existing = try fm.contentsOfDirectory(
- at: bundle.url, includingPropertiesForKeys: [.isDirectoryKey],
+ at: bundle.url,
+ includingPropertiesForKeys: [.isDirectoryKey],
)
for candidate in existing where candidate.lastPathComponent.contains("Restore") {
if try candidate.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true {
@@ -76,13 +77,15 @@ enum VPhoneFirmwarePreparer {
if let gpuDriverBundle {
print("[*] Staging GPU driver from local bundle...")
try VPhonePCCGPUDriver.stage(
- from: gpuDriverBundle, into: phoneTree,
+ from: gpuDriverBundle,
+ into: phoneTree,
expectedPlatformVersion: cloud.version,
)
} else {
print("[*] Restoring cloudOS in a temporary vphone VM to extract its GPU driver...")
try VPhonePCCGPURecovery.stage(
- cloudOSDirectory: cloudTree, into: phoneTree,
+ cloudOSDirectory: cloudTree,
+ into: phoneTree,
expectedPlatformVersion: cloud.version,
)
}
@@ -177,7 +180,8 @@ enum VPhoneFirmwarePreparer {
private static func makeUserWritable(_ directory: URL) throws {
let fm = FileManager.default
guard let entries = fm.enumerator(
- at: directory, includingPropertiesForKeys: [.isSymbolicLinkKey],
+ at: directory,
+ includingPropertiesForKeys: [.isSymbolicLinkKey],
) else { return }
for case let file as URL in entries {
let values = try file.resourceValues(forKeys: [.isSymbolicLinkKey])
@@ -187,7 +191,8 @@ enum VPhoneFirmwarePreparer {
let attributes = try fm.attributesOfItem(atPath: file.path)
let mode = (attributes[.posixPermissions] as? NSNumber)?.uint16Value ?? 0o644
try fm.setAttributes(
- [.posixPermissions: NSNumber(value: mode | 0o200)], ofItemAtPath: file.path,
+ [.posixPermissions: NSNumber(value: mode | 0o200)],
+ ofItemAtPath: file.path,
)
}
}
diff --git a/sources/vphone-cli/VPhoneHostPreflight.swift b/sources/vphone-cli/VPhoneHostPreflight.swift
index d496c427..614b2b38 100644
--- a/sources/vphone-cli/VPhoneHostPreflight.swift
+++ b/sources/vphone-cli/VPhoneHostPreflight.swift
@@ -21,7 +21,8 @@ enum VPhoneHostPreflight {
struct VPhoneHostCommand: ParsableCommand {
static let configuration = CommandConfiguration(
- commandName: "host", subcommands: [VPhoneHostPreflightCommand.self],
+ commandName: "host",
+ subcommands: [VPhoneHostPreflightCommand.self],
)
}
diff --git a/sources/vphone-cli/VPhonePCCGPURecovery.swift b/sources/vphone-cli/VPhonePCCGPURecovery.swift
index 3e2a2588..6f6ae011 100644
--- a/sources/vphone-cli/VPhonePCCGPURecovery.swift
+++ b/sources/vphone-cli/VPhonePCCGPURecovery.swift
@@ -33,7 +33,10 @@ enum VPhonePCCGPURecovery {
let library = VPhoneLibrary(root: temporaryLibrary)
let name = "pcc-\(UUID().uuidString.lowercased())"
let vm = try VPhoneBundleOperations.create(.init(
- name: name, cpuCount: 8, memoryMB: 8192, diskSizeGB: 64,
+ name: name,
+ cpuCount: 8,
+ memoryMB: 8192,
+ diskSizeGB: 64,
romSource: VPhoneBundleOperations.defaultROMSource(),
sepromSource: VPhoneBundleOperations.defaultSEPROMSource(),
), in: library)
@@ -74,8 +77,11 @@ enum VPhonePCCGPURecovery {
print("[*] Restoring cloudOS to temporary vphone VM (ECID 0x\(VPhoneRestoreIdentity.formatECID(ecid)))...")
try VPhoneRestoreService.restore(
- vmDir: vm.url, ecid: ecid, udid: VPhoneRestoreOperations.resolveUDID(bundle: vm),
- erase: true, ticketPath: nil,
+ vmDir: vm.url,
+ ecid: ecid,
+ udid: VPhoneRestoreOperations.resolveUDID(bundle: vm),
+ erase: true,
+ ticketPath: nil,
onEvent: VPhoneRestoreConsole.handler(level: .info),
)
dfu.terminate()
@@ -105,7 +111,8 @@ enum VPhonePCCGPURecovery {
let info = try run("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"])
guard let plist = try PropertyListSerialization.propertyList(
- from: Data(info.utf8), format: nil,
+ from: Data(info.utf8),
+ format: nil,
) as? [String: Any],
let container = plist["APFSContainerReference"] as? String,
container.hasPrefix("disk")
@@ -122,7 +129,8 @@ enum VPhonePCCGPURecovery {
path: "System/Library/Extensions/\(VPhonePCCGPUDriver.name)",
)
try VPhonePCCGPUDriver.stage(
- from: source, into: restoreDirectory,
+ from: source,
+ into: restoreDirectory,
expectedPlatformVersion: expectedPlatformVersion,
)
print("[+] GPU driver staged from cloudOS restored by vphone-cli")
diff --git a/sources/vphone-cli/VPhoneRestoreCLI.swift b/sources/vphone-cli/VPhoneRestoreCLI.swift
index 98fac57e..e3ea5fa7 100644
--- a/sources/vphone-cli/VPhoneRestoreCLI.swift
+++ b/sources/vphone-cli/VPhoneRestoreCLI.swift
@@ -253,8 +253,10 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {
let resources = projectRoot.map { VPhoneResources(base: URL(fileURLWithPath: $0)) } ?? .resolve()
let code = try VPhoneCustomFirmwareInstaller.elevate(
- bundle: bundle.url, resources: resources,
- forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide, rootPopup: rootPopup,
+ bundle: bundle.url,
+ resources: resources,
+ forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,
+ rootPopup: rootPopup,
verbose: v.showsToolDetail,
)
if code == 0 {
diff --git a/sources/vphone-cli/VPhoneSignCLI.swift b/sources/vphone-cli/VPhoneSignCLI.swift
index fe957c56..12009f89 100644
--- a/sources/vphone-cli/VPhoneSignCLI.swift
+++ b/sources/vphone-cli/VPhoneSignCLI.swift
@@ -96,7 +96,8 @@ struct VPhoneSignCommand: ParsableCommand {
options.style = appleAdHoc ? .appleAdHoc : .ldid
if let pkcs12 {
options.identity = try VPhoneSignIdentity(
- pkcs12: Data(contentsOf: pkcs12, options: .mappedIfSafe), password: "",
+ pkcs12: Data(contentsOf: pkcs12, options: .mappedIfSafe),
+ password: "",
)
}
try VPhoneSigner.sign(fileAt: file, options: options)
diff --git a/sources/vphone-cli/VPhoneVirtualMachineCreator.swift b/sources/vphone-cli/VPhoneVirtualMachineCreator.swift
index 48ba1c34..1f127e90 100644
--- a/sources/vphone-cli/VPhoneVirtualMachineCreator.swift
+++ b/sources/vphone-cli/VPhoneVirtualMachineCreator.swift
@@ -165,7 +165,11 @@ public struct VPhoneVirtualMachineCreator {
print("[*] Waiting 5s for cleanup before CFW install...")
Thread.sleep(forTimeInterval: 5)
print("\n=== CFW install (host-mount) ===")
- try runCustomFirmwareInstall(options: options, bundleURL: bundleURL, sudoEnvironmentExtras: sudoEnvironmentExtras)
+ try runCustomFirmwareInstall(
+ options: options,
+ bundleURL: bundleURL,
+ sudoEnvironmentExtras: sudoEnvironmentExtras
+ )
// CFW install is the last consumer of the built restore tree (it copies
// the SystemOS/AppOS cryptexes from it onto Disk.img); reclaim it now.
@@ -417,7 +421,11 @@ public struct VPhoneVirtualMachineCreator {
// MARK: - CFW install
- private func runCustomFirmwareInstall(options: Options, bundleURL: URL, sudoEnvironmentExtras: [String: String]) throws {
+ private func runCustomFirmwareInstall(
+ options: Options,
+ bundleURL: URL,
+ sudoEnvironmentExtras: [String: String]
+ ) throws {
let v = options.verbosity
// --sudo-password (askpass) wins over --root-popup.
let usePopup = options.rootPopup && sudoEnvironmentExtras["SUDO_ASKPASS"] == nil
diff --git a/tests/FirmwarePatcherTests/ARM64EncoderTests.swift b/tests/FirmwarePatcherTests/ARM64EncoderTests.swift
index e5d62db7..2414905e 100644
--- a/tests/FirmwarePatcherTests/ARM64EncoderTests.swift
+++ b/tests/FirmwarePatcherTests/ARM64EncoderTests.swift
@@ -64,81 +64,95 @@ struct ARM64EncoderKeystoneParityTests {
static let asmCallSiteCases: [ARM64EncodingCase] = [
// asm("mov w0, #0\nret") — force the camera check to return 0
ARM64EncodingCase(
- source: "mov w0, #0", keystone: 0x5280_0000,
+ source: "mov w0, #0",
+ keystone: 0x5280_0000,
encoded: ARM64Encoder.encodeMovzW(rd: 0, imm16: 0),
origin: #"camera_dsc asm("mov w0, #0\nret")"#,
),
// asm("mov w0, #3\nret")
ARM64EncodingCase(
- source: "mov w0, #3", keystone: 0x5280_0060,
+ source: "mov w0, #3",
+ keystone: 0x5280_0060,
encoded: ARM64Encoder.encodeMovzW(rd: 0, imm16: 3),
origin: #"camera_dsc asm("mov w0, #3\nret")"#,
),
// asm_at(f"b #{kern_va}", pub_va) — redirect the public stub at its own address
ARM64EncodingCase(
- source: "b #0x1010 @0x1000", keystone: 0x1400_0004,
+ source: "b #0x1010 @0x1000",
+ keystone: 0x1400_0004,
encoded: ARM64Encoder.encodeB(from: 0x1000, to: 0x1010),
origin: #"iomfb_force_kern asm_at("b #{kern_va}", pub_va)"#,
),
// asm_at(f"b #0x{patch_target:X}", patch_off) — the same shape, backwards
ARM64EncodingCase(
- source: "b #0x1000 @0x2000", keystone: 0x17FF_FC00,
+ source: "b #0x1000 @0x2000",
+ keystone: 0x17FF_FC00,
encoded: ARM64Encoder.encodeB(from: 0x2000, to: 0x1000),
origin: #"jetsam asm_at("b #{patch_target}", patch_off)"#,
),
// asm(f"mov w3, #{target_size}"), where TARGET_SIZE == 0x588
ARM64EncodingCase(
- source: "mov w3, #0x588", keystone: 0x5280_B103,
+ source: "mov w3, #0x588",
+ keystone: 0x5280_B103,
encoded: ARM64Encoder.encodeMovzW(rd: 3, imm16: 0x588),
origin: #"iomfb_swapend asm("mov w3, #{target_size}")"#,
),
// The next seven build the SwapEnd call-setup sequence in _self_test().
ARM64EncodingCase(
- source: "ldr w0, [x0, #0x14]", keystone: 0xB940_1400,
+ source: "ldr w0, [x0, #0x14]",
+ keystone: 0xB940_1400,
encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 0, rn: 0, offset: 0x14),
origin: #"iomfb_swapend asm("ldr w0, [x0, #0x14]")"#,
),
ARM64EncodingCase(
- source: "add x2, x19, #0x18", keystone: 0x9100_6262,
+ source: "add x2, x19, #0x18",
+ keystone: 0x9100_6262,
encoded: ARM64Encoder.encodeAddImm12(rd: 2, rn: 19, imm12: 0x18),
origin: #"iomfb_swapend asm("add x2, x19, #0x18")"#,
),
ARM64EncodingCase(
- source: "mov w1, #5", keystone: 0x5280_00A1,
+ source: "mov w1, #5",
+ keystone: 0x5280_00A1,
encoded: ARM64Encoder.encodeMovzW(rd: 1, imm16: 5),
origin: #"iomfb_swapend asm("mov w1, #5")"#,
),
ARM64EncodingCase(
- source: "mov w3, #0x548", keystone: 0x5280_A903,
+ source: "mov w3, #0x548",
+ keystone: 0x5280_A903,
encoded: ARM64Encoder.encodeMovzW(rd: 3, imm16: 0x548),
origin: #"iomfb_swapend asm("mov w3, #0x548")"#,
),
ARM64EncodingCase(
- source: "mov x4, #0", keystone: 0xD280_0004,
+ source: "mov x4, #0",
+ keystone: 0xD280_0004,
encoded: ARM64Encoder.encodeMovzX(rd: 4, imm16: 0),
origin: #"iomfb_swapend asm("mov x4, #0")"#,
),
ARM64EncodingCase(
- source: "mov x5, #0", keystone: 0xD280_0005,
+ source: "mov x5, #0",
+ keystone: 0xD280_0005,
encoded: ARM64Encoder.encodeMovzX(rd: 5, imm16: 0),
origin: #"iomfb_swapend asm("mov x5, #0")"#,
),
// asm("bl #0x40") — plain asm(), so keystone assembles it at address 0.
ARM64EncodingCase(
- source: "bl #0x40 @0x0", keystone: 0x9400_0010,
+ source: "bl #0x40 @0x0",
+ keystone: 0x9400_0010,
encoded: ARM64Encoder.encodeBL(from: 0, to: 0x40),
origin: #"iomfb_swapend asm("bl #0x40")"#,
),
// asm(f"mov {m['cset_reg']}, #1") — cset_reg is always a W register; the
// matcher rejects any destination that does not start with "w".
ARM64EncodingCase(
- source: "mov w8, #1", keystone: 0x5280_0028,
+ source: "mov w8, #1",
+ keystone: 0x5280_0028,
encoded: ARM64Encoder.encodeMovzW(rd: 8, imm16: 1),
origin: #"watchdogd asm("mov {cset_reg}, #1")"#,
),
// asm("cset w0, eq") — the one instruction with no encoder before this change
ARM64EncodingCase(
- source: "cset w0, eq", keystone: 0x1A9F_17E0,
+ source: "cset w0, eq",
+ keystone: 0x1A9F_17E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .eq),
origin: #"xpc_lwcr asm("cset w0, eq")"#,
),
@@ -149,205 +163,265 @@ struct ARM64EncoderKeystoneParityTests {
static let operandCoverageCases: [ARM64EncodingCase] = [
// --- encodeB: both signs, and both ends of the imm26 range -------
ARM64EncodingCase(
- source: "b #0x7FFFFFC @0x0", keystone: 0x15FF_FFFF,
+ source: "b #0x7FFFFFC @0x0",
+ keystone: 0x15FF_FFFF,
encoded: ARM64Encoder.encodeB(from: 0, to: 0x7FFFFFC),
origin: "B max forward",
),
ARM64EncodingCase(
- source: "b #0x0 @0x8000000", keystone: 0x1600_0000,
+ source: "b #0x0 @0x8000000",
+ keystone: 0x1600_0000,
encoded: ARM64Encoder.encodeB(from: 0x8000000, to: 0),
origin: "B max backward",
),
// --- encodeBL ----------------------------------------------------
ARM64EncodingCase(
- source: "bl #0x1100 @0x1000", keystone: 0x9400_0040,
+ source: "bl #0x1100 @0x1000",
+ keystone: 0x9400_0040,
encoded: ARM64Encoder.encodeBL(from: 0x1000, to: 0x1100),
origin: "BL forward",
),
ARM64EncodingCase(
- source: "bl #0x2000 @0x3000", keystone: 0x97FF_FC00,
+ source: "bl #0x2000 @0x3000",
+ keystone: 0x97FF_FC00,
encoded: ARM64Encoder.encodeBL(from: 0x3000, to: 0x2000),
origin: "BL backward",
),
// --- encodeTestBitBranch: b5 both ways, TBZ and TBNZ, both signs --
ARM64EncodingCase(
- source: "tbz w8, #0xb, #0x14", keystone: 0x3658_00A8,
+ source: "tbz w8, #0xb, #0x14",
+ keystone: 0x3658_00A8,
encoded: ARM64Encoder.encodeTestBitBranch(
- nonzero: false, register: 8, bit: 11, from: 0, to: 0x14,
+ nonzero: false,
+ register: 8,
+ bit: 11,
+ from: 0,
+ to: 0x14,
),
origin: "TBZ W, bit<32",
),
ARM64EncodingCase(
- source: "tbz w8, #0xa, #0x14", keystone: 0x3650_00A8,
+ source: "tbz w8, #0xa, #0x14",
+ keystone: 0x3650_00A8,
encoded: ARM64Encoder.encodeTestBitBranch(
- nonzero: false, register: 8, bit: 10, from: 0, to: 0x14,
+ nonzero: false,
+ register: 8,
+ bit: 10,
+ from: 0,
+ to: 0x14,
),
origin: "TBZ W, bit<32",
),
ARM64EncodingCase(
- source: "tbnz w0, #0, #0x8", keystone: 0x3700_0040,
+ source: "tbnz w0, #0, #0x8",
+ keystone: 0x3700_0040,
encoded: ARM64Encoder.encodeTestBitBranch(
- nonzero: true, register: 0, bit: 0, from: 0, to: 8,
+ nonzero: true,
+ register: 0,
+ bit: 0,
+ from: 0,
+ to: 8,
),
origin: "TBNZ bit 0",
),
ARM64EncodingCase(
- source: "tbz x9, #32, #0x40", keystone: 0xB600_0209,
+ source: "tbz x9, #32, #0x40",
+ keystone: 0xB600_0209,
encoded: ARM64Encoder.encodeTestBitBranch(
- nonzero: false, register: 9, bit: 32, from: 0, to: 0x40,
+ nonzero: false,
+ register: 9,
+ bit: 32,
+ from: 0,
+ to: 0x40,
),
origin: "TBZ X, b5 set",
),
ARM64EncodingCase(
- source: "tbnz x3, #63, #0x0 @0x100", keystone: 0xB7FF_F803,
+ source: "tbnz x3, #63, #0x0 @0x100",
+ keystone: 0xB7FF_F803,
encoded: ARM64Encoder.encodeTestBitBranch(
- nonzero: true, register: 3, bit: 63, from: 0x100, to: 0,
+ nonzero: true,
+ register: 3,
+ bit: 63,
+ from: 0x100,
+ to: 0,
),
origin: "TBNZ bit 63, backward",
),
// --- encodeADRP: forward, backward, and same page ----------------
ARM64EncodingCase(
- source: "adrp x2, #0x5000 @0x1000", keystone: 0x9000_0022,
+ source: "adrp x2, #0x5000 @0x1000",
+ keystone: 0x9000_0022,
encoded: ARM64Encoder.encodeADRP(rd: 2, pc: 0x1000, target: 0x5000),
origin: "ADRP forward",
),
ARM64EncodingCase(
- source: "adrp x0, #0x1000 @0x9000", keystone: 0x90FF_FFC0,
+ source: "adrp x0, #0x1000 @0x9000",
+ keystone: 0x90FF_FFC0,
encoded: ARM64Encoder.encodeADRP(rd: 0, pc: 0x9000, target: 0x1000),
origin: "ADRP backward",
),
ARM64EncodingCase(
- source: "adrp x17, #0x1000 @0x1FFF", keystone: 0x9000_0011,
+ source: "adrp x17, #0x1000 @0x1FFF",
+ keystone: 0x9000_0011,
encoded: ARM64Encoder.encodeADRP(rd: 17, pc: 0x1FFF, target: 0x1000),
origin: "ADRP same page, unaligned PC",
),
// --- encodeAddImm12 ----------------------------------------------
ARM64EncodingCase(
- source: "add x2, x2, #0xabc", keystone: 0x912A_F042,
+ source: "add x2, x2, #0xabc",
+ keystone: 0x912A_F042,
encoded: ARM64Encoder.encodeAddImm12(rd: 2, rn: 2, imm12: 0xABC),
origin: "ADD imm12",
),
ARM64EncodingCase(
- source: "add x0, x0, #0", keystone: 0x9100_0000,
+ source: "add x0, x0, #0",
+ keystone: 0x9100_0000,
encoded: ARM64Encoder.encodeAddImm12(rd: 0, rn: 0, imm12: 0),
origin: "ADD imm12 = 0",
),
// --- encodeMovzW / encodeMovzX: every legal hw --------------------
ARM64EncodingCase(
- source: "movz w5, #0x1234, lsl #16", keystone: 0x52A2_4685,
+ source: "movz w5, #0x1234, lsl #16",
+ keystone: 0x52A2_4685,
encoded: ARM64Encoder.encodeMovzW(rd: 5, imm16: 0x1234, shift: 16),
origin: "MOVZ W hw=1",
),
ARM64EncodingCase(
- source: "movz x3, #0x4000", keystone: 0xD288_0003,
+ source: "movz x3, #0x4000",
+ keystone: 0xD288_0003,
encoded: ARM64Encoder.encodeMovzX(rd: 3, imm16: 0x4000, shift: 0),
origin: "MOVZ X hw=0",
),
ARM64EncodingCase(
- source: "movz x9, #0xbeef, lsl #32", keystone: 0xD2D7_DDE9,
+ source: "movz x9, #0xbeef, lsl #32",
+ keystone: 0xD2D7_DDE9,
encoded: ARM64Encoder.encodeMovzX(rd: 9, imm16: 0xBEEF, shift: 32),
origin: "MOVZ X hw=2",
),
ARM64EncodingCase(
- source: "movz x1, #0xdead, lsl #48", keystone: 0xD2FB_D5A1,
+ source: "movz x1, #0xdead, lsl #48",
+ keystone: 0xD2FB_D5A1,
encoded: ARM64Encoder.encodeMovzX(rd: 1, imm16: 0xDEAD, shift: 48),
origin: "MOVZ X hw=3",
),
// --- encodeMovX ---------------------------------------------------
ARM64EncodingCase(
- source: "mov x0, x20", keystone: 0xAA14_03E0,
+ source: "mov x0, x20",
+ keystone: 0xAA14_03E0,
encoded: ARM64Encoder.encodeMovX(rd: 0, rm: 20),
origin: "MOV X reg",
),
ARM64EncodingCase(
- source: "mov x9, xzr", keystone: 0xAA1F_03E9,
+ source: "mov x9, xzr",
+ keystone: 0xAA1F_03E9,
encoded: ARM64Encoder.encodeMovX(rd: 9, rm: 31),
origin: "MOV X from XZR",
),
ARM64EncodingCase(
- source: "mov x30, x1", keystone: 0xAA01_03FE,
+ source: "mov x30, x1",
+ keystone: 0xAA01_03FE,
encoded: ARM64Encoder.encodeMovX(rd: 30, rm: 1),
origin: "MOV X high Rd",
),
// --- encodeCsetW: all 14 conditions, plus other destinations ------
ARM64EncodingCase(
- source: "cset w0, ne", keystone: 0x1A9F_07E0,
+ source: "cset w0, ne",
+ keystone: 0x1A9F_07E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ne), origin: "CSET ne",
),
ARM64EncodingCase(
- source: "cset w0, hs", keystone: 0x1A9F_37E0,
+ source: "cset w0, hs",
+ keystone: 0x1A9F_37E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .hs), origin: "CSET hs",
),
ARM64EncodingCase(
- source: "cset w0, lo", keystone: 0x1A9F_27E0,
+ source: "cset w0, lo",
+ keystone: 0x1A9F_27E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .lo), origin: "CSET lo",
),
ARM64EncodingCase(
- source: "cset w0, mi", keystone: 0x1A9F_57E0,
+ source: "cset w0, mi",
+ keystone: 0x1A9F_57E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .mi), origin: "CSET mi",
),
ARM64EncodingCase(
- source: "cset w0, pl", keystone: 0x1A9F_47E0,
+ source: "cset w0, pl",
+ keystone: 0x1A9F_47E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .pl), origin: "CSET pl",
),
ARM64EncodingCase(
- source: "cset w0, vs", keystone: 0x1A9F_77E0,
+ source: "cset w0, vs",
+ keystone: 0x1A9F_77E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .vs), origin: "CSET vs",
),
ARM64EncodingCase(
- source: "cset w0, vc", keystone: 0x1A9F_67E0,
+ source: "cset w0, vc",
+ keystone: 0x1A9F_67E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .vc), origin: "CSET vc",
),
ARM64EncodingCase(
- source: "cset w0, hi", keystone: 0x1A9F_97E0,
+ source: "cset w0, hi",
+ keystone: 0x1A9F_97E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .hi), origin: "CSET hi",
),
ARM64EncodingCase(
- source: "cset w0, ls", keystone: 0x1A9F_87E0,
+ source: "cset w0, ls",
+ keystone: 0x1A9F_87E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ls), origin: "CSET ls",
),
ARM64EncodingCase(
- source: "cset w0, ge", keystone: 0x1A9F_B7E0,
+ source: "cset w0, ge",
+ keystone: 0x1A9F_B7E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .ge), origin: "CSET ge",
),
ARM64EncodingCase(
- source: "cset w0, lt", keystone: 0x1A9F_A7E0,
+ source: "cset w0, lt",
+ keystone: 0x1A9F_A7E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .lt), origin: "CSET lt",
),
ARM64EncodingCase(
- source: "cset w0, gt", keystone: 0x1A9F_D7E0,
+ source: "cset w0, gt",
+ keystone: 0x1A9F_D7E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .gt), origin: "CSET gt",
),
ARM64EncodingCase(
- source: "cset w0, le", keystone: 0x1A9F_C7E0,
+ source: "cset w0, le",
+ keystone: 0x1A9F_C7E0,
encoded: ARM64Encoder.encodeCsetW(rd: 0, condition: .le), origin: "CSET le",
),
ARM64EncodingCase(
- source: "cset w8, ne", keystone: 0x1A9F_07E8,
+ source: "cset w8, ne",
+ keystone: 0x1A9F_07E8,
encoded: ARM64Encoder.encodeCsetW(rd: 8, condition: .ne), origin: "CSET Rd=8",
),
ARM64EncodingCase(
- source: "cset w19, eq", keystone: 0x1A9F_17F3,
+ source: "cset w19, eq",
+ keystone: 0x1A9F_17F3,
encoded: ARM64Encoder.encodeCsetW(rd: 19, condition: .eq), origin: "CSET Rd=19",
),
// --- encodeLdrWUnsignedOffset: zero, SP base, both imm12 ends -----
ARM64EncodingCase(
- source: "ldr w7, [x19]", keystone: 0xB940_0267,
+ source: "ldr w7, [x19]",
+ keystone: 0xB940_0267,
encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 7, rn: 19, offset: 0),
origin: "LDR W offset 0",
),
ARM64EncodingCase(
- source: "ldr w8, [sp, #0xcc]", keystone: 0xB940_CFE8,
+ source: "ldr w8, [sp, #0xcc]",
+ keystone: 0xB940_CFE8,
encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 8, rn: 31, offset: 0xCC),
origin: "LDR W base = SP",
),
ARM64EncodingCase(
- source: "ldr w8, [x0, #0x454]", keystone: 0xB944_5408,
+ source: "ldr w8, [x0, #0x454]",
+ keystone: 0xB944_5408,
encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 8, rn: 0, offset: 0x454),
origin: "LDR W mid offset",
),
ARM64EncodingCase(
- source: "ldr w30, [x29, #0x3ffc]", keystone: 0xB97F_FFBE,
+ source: "ldr w30, [x29, #0x3ffc]",
+ keystone: 0xB97F_FFBE,
encoded: ARM64Encoder.encodeLdrWUnsignedOffset(rt: 30, rn: 29, offset: 0x3FFC),
origin: "LDR W max imm12",
),
diff --git a/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift b/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift
index 7c9457cb..d1a55a19 100644
--- a/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift
+++ b/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift
@@ -273,7 +273,8 @@ struct CryptexFileOpsTests {
@Test func `a plist without A max key is an error`() {
let withoutMax = Self.sizesPlist.replacingOccurrences(
- of: "<key>max</key>", with: "<key>maximum</key>",
+ of: "<key>max</key>",
+ with: "<key>maximum</key>",
)
#expect(throws: ProcessError.self) {
try CryptexFilesystemPatcher.maxResizeSize(fromDiskutilPlist: withoutMax)
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareCacheloaderTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareCacheloaderTests.swift
index a5a99f7f..8e9ed71d 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareCacheloaderTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareCacheloaderTests.swift
@@ -269,10 +269,14 @@ struct CustomFirmwareCacheLoaderGateTests {
// Recomputed here from the two instructions, independently of how the
// patcher found them: page(ADRP) + imm(ADD) has to be the literal.
let adrp = try #require(disassembler.disassembleOne(
- in: data, at: anchor.referenceFileOffset, address: anchor.referenceVMA,
+ in: data,
+ at: anchor.referenceFileOffset,
+ address: anchor.referenceVMA,
))
let add = try #require(disassembler.disassembleOne(
- in: data, at: anchor.referenceFileOffset + 4, address: anchor.referenceVMA + 4,
+ in: data,
+ at: anchor.referenceFileOffset + 4,
+ address: anchor.referenceVMA + 4,
))
#expect(adrp.mnemonic == "adrp")
#expect(add.mnemonic == "add")
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift
index 197ed283..890cfd7b 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareDaemonsTests.swift
@@ -185,7 +185,10 @@ struct CustomFirmwareDaemonsTests {
let arguments = daemon["ProgramArguments"] as? [Any] ?? []
let strings = arguments.compactMap { $0 as? String }
#expect(!strings.contains("-R"))
- #expect(Array(strings.suffix(CustomFirmwareDaemons.dropbearKeyArguments.count)) == CustomFirmwareDaemons.dropbearKeyArguments)
+ #expect(
+ Array(strings.suffix(CustomFirmwareDaemons.dropbearKeyArguments.count))
+ == CustomFirmwareDaemons.dropbearKeyArguments
+ )
}
@Test
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareJetsamTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareJetsamTests.swift
index fb14fa58..669c0178 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareJetsamTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareJetsamTests.swift
@@ -561,7 +561,11 @@ struct CustomFirmwareJetsamDecodeTests {
// tbz w8, #1, #8 — three operands, target last, from the encoder.
let tbz = try #require(ARM64Encoder.encodeTestBitBranch(
- nonzero: false, register: 8, bit: 1, from: 0, to: 8,
+ nonzero: false,
+ register: 8,
+ bit: 1,
+ from: 0,
+ to: 8,
))
let tbzInsn = try #require(disassembler.disassembleOne(tbz, at: 0))
#expect(tbzInsn.mnemonic == "tbz")
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift
index a8b4eae7..b8347ab2 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareMachOTests.swift
@@ -121,7 +121,8 @@ enum MachOFixture {
// The fixture is 0755 already; this is only so a reference tree
// someone made read-only does not turn into a failing patch test.
try FileManager.default.setAttributes(
- [.posixPermissions: 0o755], ofItemAtPath: destination.path,
+ [.posixPermissions: 0o755],
+ ofItemAtPath: destination.path,
)
return destination
}
@@ -226,18 +227,32 @@ struct CustomFirmwareMachOCodeSignatureTests {
/// pinned directly.
@Test func `slot ranges follow code limit alignment`() {
let aligned = CustomFirmwareCodeDirectory(
- slotType: 0, offset: 0, length: 0, hashOffset: 0, hashSize: 32,
- hashType: 2, pageSize: 4096, pageSizeLog2: 12,
- codeSlotCount: 2, codeLimit: 8192,
+ slotType: 0,
+ offset: 0,
+ length: 0,
+ hashOffset: 0,
+ hashSize: 32,
+ hashType: 2,
+ pageSize: 4096,
+ pageSizeLog2: 12,
+ codeSlotCount: 2,
+ codeLimit: 8192,
)
#expect(aligned.slotRange(0) == 0 ..< 4096)
#expect(aligned.slotRange(1) == 4096 ..< 8192)
#expect(aligned.slotRange(2) == nil)
let short = CustomFirmwareCodeDirectory(
- slotType: 0, offset: 0, length: 0, hashOffset: 0, hashSize: 32,
- hashType: 2, pageSize: 4096, pageSizeLog2: 12,
- codeSlotCount: 2, codeLimit: 5000,
+ slotType: 0,
+ offset: 0,
+ length: 0,
+ hashOffset: 0,
+ hashSize: 32,
+ hashType: 2,
+ pageSize: 4096,
+ pageSizeLog2: 12,
+ codeSlotCount: 2,
+ codeLimit: 5000,
)
#expect(short.slotRange(0) == 0 ..< 4096)
#expect(short.slotRange(1) == 4096 ..< 5000)
diff --git a/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift b/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift
index 11a2c7a6..914b1387 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwarePlistPatchTests.swift
@@ -392,7 +392,10 @@ struct CustomFirmwareBuildVersionTests {
// the Cryptex copy on a device can be binary.
for format in ["xml1", "binary1"] {
let swiftOutput = directory.appending(path: "swift-\(format).plist")
- try CustomFirmwarePatchFixtures.copyContents(of: CustomFirmwarePatchFixtures.systemVersionPlist, to: swiftOutput)
+ try CustomFirmwarePatchFixtures.copyContents(
+ of: CustomFirmwarePatchFixtures.systemVersionPlist,
+ to: swiftOutput
+ )
try CustomFirmwarePatchFixtures.run("/usr/bin/plutil", ["-convert", format, swiftOutput.path])
let before = try #require(try PlistComparison.load(swiftOutput) as? [String: Any])
diff --git a/tests/FirmwarePatcherTests/CustomFirmwareWatchdogdTests.swift b/tests/FirmwarePatcherTests/CustomFirmwareWatchdogdTests.swift
index 94220d9f..0cd189c8 100644
--- a/tests/FirmwarePatcherTests/CustomFirmwareWatchdogdTests.swift
+++ b/tests/FirmwarePatcherTests/CustomFirmwareWatchdogdTests.swift
@@ -114,7 +114,8 @@ enum WatchdogdFixture {
where instruction.mnemonic == "bl"
{
guard let target = ARM64Encoder.decodeBranchTarget(
- insn: CustomFirmwareWatchdogd.word(of: instruction), pc: instruction.address,
+ insn: CustomFirmwareWatchdogd.word(of: instruction),
+ pc: instruction.address,
) else { continue }
if symbols.name(forBranchTarget: target) == "_sysctlbyname" {
found.append(instruction.address)
@@ -270,19 +271,31 @@ struct CustomFirmwareWatchdogdAnchorTests {
// add x9, … ; mov x0, x9 ; bl — the literal is the call's argument.
#expect(try CustomFirmwareWatchdogd.passesLiteral(
- inRegister: "x9", from: 1, toCallAt: 3, in: stream(movingInto: 0),
+ inRegister: "x9",
+ from: 1,
+ toCallAt: 3,
+ in: stream(movingInto: 0),
))
// The same shape moving into x1 is some other call's argument.
#expect(try !CustomFirmwareWatchdogd.passesLiteral(
- inRegister: "x9", from: 1, toCallAt: 3, in: stream(movingInto: 1),
+ inRegister: "x9",
+ from: 1,
+ toCallAt: 3,
+ in: stream(movingInto: 1),
))
// No move at all, and the pointer never reaches x0.
#expect(try !CustomFirmwareWatchdogd.passesLiteral(
- inRegister: "x9", from: 1, toCallAt: 3, in: stream(movingInto: nil),
+ inRegister: "x9",
+ from: 1,
+ toCallAt: 3,
+ in: stream(movingInto: nil),
))
// The direct form the shipped binary uses needs no move.
#expect(try CustomFirmwareWatchdogd.passesLiteral(
- inRegister: "x0", from: 1, toCallAt: 3, in: stream(movingInto: nil),
+ inRegister: "x0",
+ from: 1,
+ toCallAt: 3,
+ in: stream(movingInto: nil),
))
}
@@ -481,7 +494,8 @@ struct CustomFirmwareWatchdogdReferenceTests {
@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))
func `agrees with the frozen reference on an already patched binary`() throws {
let file = try WatchdogdFixture.scratchCopy(
- of: WatchdogdFixture.watchdogd, named: "watchdogd-twice",
+ of: WatchdogdFixture.watchdogd,
+ named: "watchdogd-twice",
)
defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }
@@ -503,7 +517,8 @@ struct CustomFirmwareWatchdogdReferenceTests {
@Test(.enabled(if: WatchdogdFixture.hasCodesign))
func `patched binary still verifies under codesign`() throws {
let file = try WatchdogdFixture.scratchCopy(
- of: WatchdogdFixture.watchdogd, named: "watchdogd-signed",
+ of: WatchdogdFixture.watchdogd,
+ named: "watchdogd-signed",
)
defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }
diff --git a/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift b/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift
index 9f6ec5c6..03e42cb2 100644
--- a/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift
+++ b/tests/FirmwarePatcherTests/DyldSharedCacheCameraPatcherTests.swift
@@ -61,18 +61,42 @@ private enum FrozenReference {
/// then `[2/2] +[AVCaptureDevice authorizationStatusForMediaType:] →
/// return Authorized`. Six sites, in the order the reference listed them.
static let sites: [Site] = [
- Site(symbol: "+[_NUStyleTransferApplyProcessor processWithInputs:arguments:output:error:]",
- vma: 0x1_BF43_0C04, before: "7f2303d5ef3bb66d", after: "00008052c0035fd6"),
- Site(symbol: "+[_NUStyleTransferInterpolateProcessor processWithInputs:arguments:output:error:]",
- vma: 0x1_BF43_A3A8, before: "7f2303d5ff0303d1", after: "00008052c0035fd6"),
- Site(symbol: "+[_NUStyleTransferLearnProcessor processWithInputs:arguments:output:error:]",
- vma: 0x1_BF42_EC54, before: "7f2303d5ff0304d1", after: "00008052c0035fd6"),
- Site(symbol: "+[_NUStyleTransferProcessor processWithInputs:arguments:output:error:]",
- vma: 0x1_BF43_3BD0, before: "7f2303d5ffc306d1", after: "00008052c0035fd6"),
- Site(symbol: "+[_NUStyleTransferThumbnailProcessor processWithInputs:arguments:output:error:]",
- vma: 0x1_BF43_5DB4, before: "7f2303d5ff8303d1", after: "00008052c0035fd6"),
- Site(symbol: "+[AVCaptureDevice authorizationStatusForMediaType:]",
- vma: 0x1_AD8A_12D8, before: "7f2303d5ffc301d1", after: "60008052c0035fd6"),
+ Site(
+ symbol: "+[_NUStyleTransferApplyProcessor processWithInputs:arguments:output:error:]",
+ vma: 0x1_BF43_0C04,
+ before: "7f2303d5ef3bb66d",
+ after: "00008052c0035fd6"
+ ),
+ Site(
+ symbol: "+[_NUStyleTransferInterpolateProcessor processWithInputs:arguments:output:error:]",
+ vma: 0x1_BF43_A3A8,
+ before: "7f2303d5ff0303d1",
+ after: "00008052c0035fd6"
+ ),
+ Site(
+ symbol: "+[_NUStyleTransferLearnProcessor processWithInputs:arguments:output:error:]",
+ vma: 0x1_BF42_EC54,
+ before: "7f2303d5ff0304d1",
+ after: "00008052c0035fd6"
+ ),
+ Site(
+ symbol: "+[_NUStyleTransferProcessor processWithInputs:arguments:output:error:]",
+ vma: 0x1_BF43_3BD0,
+ before: "7f2303d5ffc306d1",
+ after: "00008052c0035fd6"
+ ),
+ Site(
+ symbol: "+[_NUStyleTransferThumbnailProcessor processWithInputs:arguments:output:error:]",
+ vma: 0x1_BF43_5DB4,
+ before: "7f2303d5ff8303d1",
+ after: "00008052c0035fd6"
+ ),
+ Site(
+ symbol: "+[AVCaptureDevice authorizationStatusForMediaType:]",
+ vma: 0x1_AD8A_12D8,
+ before: "7f2303d5ffc301d1",
+ after: "60008052c0035fd6"
+ ),
]
static var sitesBySymbol: [String: Site] {
diff --git a/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift b/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift
index 68ba6361..324fa89f 100644
--- a/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift
+++ b/tests/FirmwarePatcherTests/DyldSharedCacheIOMFBForceKernTests.swift
@@ -55,100 +55,192 @@ private enum FrozenReference {
/// giving the public entry point, its address, the kern sibling it would
/// branch to and that sibling's address.
static let forcedPairs: [Pair] = [
- Pair(publicName: "_IOMobileFramebufferSwapBegin",
- publicAddress: 0x2_2AC0_C1B0,
- kernName: "_kern_SwapBegin", kernAddress: 0x2_2AC0_C1CC),
- Pair(publicName: "_IOMobileFramebufferSwapCancel",
- publicAddress: 0x2_2AC1_23C8,
- kernName: "_kern_SwapCancel", kernAddress: 0x2_2AC3_D4AC),
- Pair(publicName: "_IOMobileFramebufferSwapCancelAll",
- publicAddress: 0x2_2AC1_24F4,
- kernName: "_kern_SwapCancelAll", kernAddress: 0x2_2AC1_2510),
- Pair(publicName: "_IOMobileFramebufferSwapCancelAllGetCurrent",
- publicAddress: 0x2_2AC1_2468,
- kernName: "_kern_SwapCancelAllGetCurrent", kernAddress: 0x2_2AC1_2484),
- Pair(publicName: "_IOMobileFramebufferSwapDebugInfo",
- publicAddress: 0x2_2AC0_C734,
- kernName: "_kern_SwapDebugInfo", kernAddress: 0x2_2AC0_C328),
- Pair(publicName: "_IOMobileFramebufferSwapEnd",
- publicAddress: 0x2_2AC0_C750,
- kernName: "_kern_SwapEnd", kernAddress: 0x2_2AC0_C334),
- Pair(publicName: "_IOMobileFramebufferSwapGetCurrent",
- publicAddress: 0x2_2AC3_A85C,
- kernName: "_kern_SwapGetCurrent", kernAddress: 0x2_2AC3_D518),
- Pair(publicName: "_IOMobileFramebufferSwapSecureLayer",
- publicAddress: 0x2_2AC3_A528,
- kernName: "_kern_SwapSecureLayer", kernAddress: 0x2_2AC3_CB9C),
- Pair(publicName: "_IOMobileFramebufferSwapSetAmbientLux",
- publicAddress: 0x2_2AC0_D0F4,
- kernName: "_kern_SwapSetAmbientLux", kernAddress: 0x2_2AC0_D110),
- Pair(publicName: "_IOMobileFramebufferSwapSetBrightness",
- publicAddress: 0x2_2AC0_D214,
- kernName: "_kern_SwapSetBrightness", kernAddress: 0x2_2AC0_D230),
- Pair(publicName: "_IOMobileFramebufferSwapSetBrightnessLimit",
- publicAddress: 0x2_2AC1_25B0,
- kernName: "_kern_SwapSetBrightnessLimit", kernAddress: 0x2_2AC1_25CC),
- Pair(publicName: "_IOMobileFramebufferSwapSetColorMatrix",
- publicAddress: 0x2_2AC3_A800,
- kernName: "_kern_SwapSetColorMatrix", kernAddress: 0x2_2AC3_D2E0),
- Pair(publicName: "_IOMobileFramebufferSwapSetDisplayEdr",
- publicAddress: 0x2_2AC1_2634,
- kernName: "_kern_SwapSetDisplayEdr", kernAddress: 0x2_2AC1_2650),
- Pair(publicName: "_IOMobileFramebufferSwapSetDisplayEdrHeadroom",
- publicAddress: 0x2_2AC1_278C,
- kernName: "_kern_SwapSetDisplayEdrHeadroom", kernAddress: 0x2_2AC1_2724),
- Pair(publicName: "_IOMobileFramebufferSwapSetEventSignal",
- publicAddress: 0x2_2AC0_BE50,
- kernName: "_kern_SwapSetEventSignal", kernAddress: 0x2_2AC0_CEBC),
- Pair(publicName: "_IOMobileFramebufferSwapSetEventSignalOnGlass",
- publicAddress: 0x2_2AC3_A560,
- kernName: "_kern_SwapSetEventSignalOnGlass", kernAddress: 0x2_2AC3_CDB0),
- Pair(publicName: "_IOMobileFramebufferSwapSetEventWait",
- publicAddress: 0x2_2AC0_BE6C,
- kernName: "_kern_SwapSetEventWait", kernAddress: 0x2_2AC0_BF58),
- Pair(publicName: "_IOMobileFramebufferSwapSetIndicatorBrightnessLimit",
- publicAddress: 0x2_2AC1_2594,
- kernName: "_kern_SwapSetIndicatorBrightnessLimit", kernAddress: 0x2_2AC1_26B8),
- Pair(publicName: "_IOMobileFramebufferSwapSetLFCTimestamps",
- publicAddress: 0x2_2AC3_A7AC,
- kernName: "_kern_SwapSetLFCTimestamps", kernAddress: 0x2_2AC3_DA6C),
- Pair(publicName: "_IOMobileFramebufferSwapSetLayer",
- publicAddress: 0x2_2AC0_CEA0,
- kernName: "_kern_SwapSetLayer", kernAddress: 0x2_2AC0_C8F4),
- Pair(publicName: "_IOMobileFramebufferSwapSetLayerEDRCompensation",
- publicAddress: 0x2_2AC0_C194,
- kernName: "_kern_SwapSetLayerEDRCompensation", kernAddress: 0x2_2AC0_BE88),
- Pair(publicName: "_IOMobileFramebufferSwapSetPostBlendLayer",
- publicAddress: 0x2_2AC3_A544,
- kernName: "_kern_SwapSetPostBlendLayer", kernAddress: 0x2_2AC3_CC3C),
- Pair(publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventSignal",
- publicAddress: 0x2_2AC3_A5B4,
- kernName: "_kern_SwapSetPostBlendLayerEventSignal", kernAddress: 0x2_2AC3_CE98),
- Pair(publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventSignalOnGlass",
- publicAddress: 0x2_2AC3_A598,
- kernName: "_kern_SwapSetPostBlendLayerEventSignalOnGlass",
- kernAddress: 0x2_2AC3_CE58),
- Pair(publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventWait",
- publicAddress: 0x2_2AC3_A57C,
- kernName: "_kern_SwapSetPostBlendLayerEventWait", kernAddress: 0x2_2AC3_CDE8),
- Pair(publicName: "_IOMobileFramebufferSwapSetPulseWidthMaximization",
- publicAddress: 0x2_2AC4_1AC0,
- kernName: "_kern_SwapSetPulseWidthMaximization", kernAddress: 0x2_2AC3_D1F4),
- Pair(publicName: "_IOMobileFramebufferSwapSetResTransitionStrength",
- publicAddress: 0x2_2AC4_1ADC,
- kernName: "_kern_SwapSetResTransitionStrength", kernAddress: 0x2_2AC3_D238),
- Pair(publicName: "_IOMobileFramebufferSwapSetSecureAnimation",
- publicAddress: 0x2_2AC0_F354,
- kernName: "_kern_SwapSetSecureAnimation", kernAddress: 0x2_2AC0_F370),
- Pair(publicName: "_IOMobileFramebufferSwapSubtitleRegion",
- publicAddress: 0x2_2AC3_A720,
- kernName: "_kern_SwapSubtitleRegion", kernAddress: 0x2_2AC3_CF08),
- Pair(publicName: "_IOMobileFramebufferSwapWait",
- publicAddress: 0x2_2AC0_C298,
- kernName: "_kern_SwapWait", kernAddress: 0x2_2AC0_C2B4),
- Pair(publicName: "_IOMobileFramebufferSwapWaitWithTimeout",
- publicAddress: 0x2_2AC3_A840,
- kernName: "_kern_SwapWaitWithTimeout", kernAddress: 0x2_2AC3_D420),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapBegin",
+ publicAddress: 0x2_2AC0_C1B0,
+ kernName: "_kern_SwapBegin",
+ kernAddress: 0x2_2AC0_C1CC
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapCancel",
+ publicAddress: 0x2_2AC1_23C8,
+ kernName: "_kern_SwapCancel",
+ kernAddress: 0x2_2AC3_D4AC
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapCancelAll",
+ publicAddress: 0x2_2AC1_24F4,
+ kernName: "_kern_SwapCancelAll",
+ kernAddress: 0x2_2AC1_2510
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapCancelAllGetCurrent",
+ publicAddress: 0x2_2AC1_2468,
+ kernName: "_kern_SwapCancelAllGetCurrent",
+ kernAddress: 0x2_2AC1_2484
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapDebugInfo",
+ publicAddress: 0x2_2AC0_C734,
+ kernName: "_kern_SwapDebugInfo",
+ kernAddress: 0x2_2AC0_C328
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapEnd",
+ publicAddress: 0x2_2AC0_C750,
+ kernName: "_kern_SwapEnd",
+ kernAddress: 0x2_2AC0_C334
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapGetCurrent",
+ publicAddress: 0x2_2AC3_A85C,
+ kernName: "_kern_SwapGetCurrent",
+ kernAddress: 0x2_2AC3_D518
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSecureLayer",
+ publicAddress: 0x2_2AC3_A528,
+ kernName: "_kern_SwapSecureLayer",
+ kernAddress: 0x2_2AC3_CB9C
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetAmbientLux",
+ publicAddress: 0x2_2AC0_D0F4,
+ kernName: "_kern_SwapSetAmbientLux",
+ kernAddress: 0x2_2AC0_D110
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetBrightness",
+ publicAddress: 0x2_2AC0_D214,
+ kernName: "_kern_SwapSetBrightness",
+ kernAddress: 0x2_2AC0_D230
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetBrightnessLimit",
+ publicAddress: 0x2_2AC1_25B0,
+ kernName: "_kern_SwapSetBrightnessLimit",
+ kernAddress: 0x2_2AC1_25CC
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetColorMatrix",
+ publicAddress: 0x2_2AC3_A800,
+ kernName: "_kern_SwapSetColorMatrix",
+ kernAddress: 0x2_2AC3_D2E0
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetDisplayEdr",
+ publicAddress: 0x2_2AC1_2634,
+ kernName: "_kern_SwapSetDisplayEdr",
+ kernAddress: 0x2_2AC1_2650
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetDisplayEdrHeadroom",
+ publicAddress: 0x2_2AC1_278C,
+ kernName: "_kern_SwapSetDisplayEdrHeadroom",
+ kernAddress: 0x2_2AC1_2724
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetEventSignal",
+ publicAddress: 0x2_2AC0_BE50,
+ kernName: "_kern_SwapSetEventSignal",
+ kernAddress: 0x2_2AC0_CEBC
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetEventSignalOnGlass",
+ publicAddress: 0x2_2AC3_A560,
+ kernName: "_kern_SwapSetEventSignalOnGlass",
+ kernAddress: 0x2_2AC3_CDB0
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetEventWait",
+ publicAddress: 0x2_2AC0_BE6C,
+ kernName: "_kern_SwapSetEventWait",
+ kernAddress: 0x2_2AC0_BF58
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetIndicatorBrightnessLimit",
+ publicAddress: 0x2_2AC1_2594,
+ kernName: "_kern_SwapSetIndicatorBrightnessLimit",
+ kernAddress: 0x2_2AC1_26B8
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetLFCTimestamps",
+ publicAddress: 0x2_2AC3_A7AC,
+ kernName: "_kern_SwapSetLFCTimestamps",
+ kernAddress: 0x2_2AC3_DA6C
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetLayer",
+ publicAddress: 0x2_2AC0_CEA0,
+ kernName: "_kern_SwapSetLayer",
+ kernAddress: 0x2_2AC0_C8F4
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetLayerEDRCompensation",
+ publicAddress: 0x2_2AC0_C194,
+ kernName: "_kern_SwapSetLayerEDRCompensation",
+ kernAddress: 0x2_2AC0_BE88
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetPostBlendLayer",
+ publicAddress: 0x2_2AC3_A544,
+ kernName: "_kern_SwapSetPostBlendLayer",
+ kernAddress: 0x2_2AC3_CC3C
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventSignal",
+ publicAddress: 0x2_2AC3_A5B4,
+ kernName: "_kern_SwapSetPostBlendLayerEventSignal",
+ kernAddress: 0x2_2AC3_CE98
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventSignalOnGlass",
+ publicAddress: 0x2_2AC3_A598,
+ kernName: "_kern_SwapSetPostBlendLayerEventSignalOnGlass",
+ kernAddress: 0x2_2AC3_CE58
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetPostBlendLayerEventWait",
+ publicAddress: 0x2_2AC3_A57C,
+ kernName: "_kern_SwapSetPostBlendLayerEventWait",
+ kernAddress: 0x2_2AC3_CDE8
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetPulseWidthMaximization",
+ publicAddress: 0x2_2AC4_1AC0,
+ kernName: "_kern_SwapSetPulseWidthMaximization",
+ kernAddress: 0x2_2AC3_D1F4
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetResTransitionStrength",
+ publicAddress: 0x2_2AC4_1ADC,
+ kernName: "_kern_SwapSetResTransitionStrength",
+ kernAddress: 0x2_2AC3_D238
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSetSecureAnimation",
+ publicAddress: 0x2_2AC0_F354,
+ kernName: "_kern_SwapSetSecureAnimation",
+ kernAddress: 0x2_2AC0_F370
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapSubtitleRegion",
+ publicAddress: 0x2_2AC3_A720,
+ kernName: "_kern_SwapSubtitleRegion",
+ kernAddress: 0x2_2AC3_CF08
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapWait",
+ publicAddress: 0x2_2AC0_C298,
+ kernName: "_kern_SwapWait",
+ kernAddress: 0x2_2AC0_C2B4
+ ),
+ Pair(
+ publicName: "_IOMobileFramebufferSwapWaitWithTimeout",
+ publicAddress: 0x2_2AC3_A840,
+ kernName: "_kern_SwapWaitWithTimeout",
+ kernAddress: 0x2_2AC3_D420
+ ),
]
/// The four `[=] … not a thin trampoline; leaving on virt path` lines. The
diff --git a/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift b/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift
index 637ab1cd..4766176f 100644
--- a/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift
+++ b/tests/FirmwarePatcherTests/FirmwareManifestSelectionTests.swift
@@ -100,7 +100,8 @@ struct FirmwareManifestSelectionTests {
Self.identity(deviceClass: "vresearch101ap", variant: "Research Erase Install"),
]
let (release, research) = try FirmwareManifest.findCloudOS(
- identities, deviceClass: "vresearch101ap",
+ identities,
+ deviceClass: "vresearch101ap",
)
#expect(release == 2)
#expect(research == 3) // the first research one, not the last
diff --git a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift
index 3dc9a952..63169007 100644
--- a/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift
+++ b/tests/FirmwarePatcherTests/FirmwarePatcherTests.swift
@@ -161,7 +161,11 @@ struct ARM64EncoderTests {
// The vm_map_delete --frida patch retargets `tbz/tbnz w8,#9` to bit 13
// (current-protection.X → max_protection.X), preserving sense and target.
let tbz = try #require(ARM64Encoder.encodeTestBitBranch(
- nonzero: false, register: 8, bit: 13, from: 0x1000, to: 0x1020,
+ nonzero: false,
+ register: 8,
+ bit: 13,
+ from: 0x1000,
+ to: 0x1020,
))
let tbzI = try #require(disasm.disassembleOne(tbz, at: 0x1000))
#expect(tbzI.mnemonic == "tbz")
@@ -170,7 +174,11 @@ struct ARM64EncoderTests {
#expect(tbzI.operandString.contains("0x1020"))
let tbnz = try #require(ARM64Encoder.encodeTestBitBranch(
- nonzero: true, register: 8, bit: 13, from: 0x2000, to: 0x1F00,
+ nonzero: true,
+ register: 8,
+ bit: 13,
+ from: 0x2000,
+ to: 0x1F00,
))
let tbnzI = try #require(disasm.disassembleOne(tbnz, at: 0x2000))
#expect(tbnzI.mnemonic == "tbnz")
diff --git a/tests/VPhoneArchiveTests/BundleTransferTests.swift b/tests/VPhoneArchiveTests/BundleTransferTests.swift
index 69344cb6..f52d5ac4 100644
--- a/tests/VPhoneArchiveTests/BundleTransferTests.swift
+++ b/tests/VPhoneArchiveTests/BundleTransferTests.swift
@@ -187,7 +187,9 @@ struct BundleTransferTests {
#expect(throws: VPhoneBundleTransferError.self) {
_ = try VPhoneBundleTransfer.importArchive(
- from: archive, name: nil, in: VPhoneLibrary(root: root.appendingPathComponent("library")),
+ from: archive,
+ name: nil,
+ in: VPhoneLibrary(root: root.appendingPathComponent("library")),
)
}
}
@@ -206,7 +208,10 @@ struct BundleTransferTests {
func pack() throws {
try? fm.removeItem(at: archive)
try VPhoneArchiveWriter.create(
- archive: archive, from: bundleDir, topLevel: "original", compression: .gzip(level: 1),
+ archive: archive,
+ from: bundleDir,
+ topLevel: "original",
+ compression: .gzip(level: 1),
)
}
try pack()
@@ -217,7 +222,9 @@ struct BundleTransferTests {
#expect(try fm.contentsOfDirectory(atPath: lib.root.path).isEmpty)
let manifest = VPhoneVirtualMachineManifest(
- cpuCount: 2, memorySize: 2048 * 1024 * 1024, romImages: nil,
+ cpuCount: 2,
+ memorySize: 2048 * 1024 * 1024,
+ romImages: nil,
)
try manifest.write(to: config)
try pack()
@@ -268,7 +275,9 @@ struct BundleTransferTests {
let dstRoot = try makeRoot()
defer { try? FileManager.default.removeItem(at: dstRoot) }
let imported = try VPhoneBundleTransfer.importArchive(
- from: archive, name: "copy", in: VPhoneLibrary(root: dstRoot),
+ from: archive,
+ name: "copy",
+ in: VPhoneLibrary(root: dstRoot),
)
try body(archive, imported)
}
@@ -369,7 +378,9 @@ struct BundleTransferTests {
let dstRoot = try makeRoot()
defer { try? FileManager.default.removeItem(at: dstRoot) }
_ = try VPhoneBundleTransfer.importArchive(
- from: archive, name: "copy", in: VPhoneLibrary(root: dstRoot),
+ from: archive,
+ name: "copy",
+ in: VPhoneLibrary(root: dstRoot),
) {
imp.add($0, $1)
}
@@ -408,7 +419,8 @@ struct BundleTransferTests {
try Data(repeating: 0x7A, count: 100 * 1024).write(to: payload)
for alias in ["linked_b.bin", "linked_c.bin"] {
try FileManager.default.linkItem(
- at: payload, to: bundle.url.appendingPathComponent(alias),
+ at: payload,
+ to: bundle.url.appendingPathComponent(alias),
)
}
@@ -481,7 +493,9 @@ struct BundleTransferTests {
let dstRoot = try makeRoot()
defer { try? FileManager.default.removeItem(at: dstRoot) }
let imported = try VPhoneBundleTransfer.importArchive(
- from: archive, name: "fromlegacy", in: VPhoneLibrary(root: dstRoot),
+ from: archive,
+ name: "fromlegacy",
+ in: VPhoneLibrary(root: dstRoot),
)
#expect(imported.name == "fromlegacy")
#expect(imported.manifest.cpuCount == 6)
diff --git a/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift b/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift
index 0c188b19..1b8ef3cc 100644
--- a/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift
+++ b/tests/VPhoneArchiveTests/ExtractPermissionsTests.swift
@@ -48,7 +48,8 @@ struct ExtractPermissionsTests {
try fm.createDirectory(at: source, withIntermediateDirectories: true)
try Data("#!/bin/sh\n".utf8).write(to: source.appendingPathComponent(setuidFile))
try fm.createDirectory(
- at: source.appendingPathComponent(wideDirectory), withIntermediateDirectories: true,
+ at: source.appendingPathComponent(wideDirectory),
+ withIntermediateDirectories: true,
)
try Data("owo\n".utf8).write(to: source.appendingPathComponent(worldWritableFile))
// chmod after the writes: creating a file resets its mode.
@@ -141,7 +142,9 @@ struct ExtractPermissionsTests {
} }
try VPhoneArchiveExtractor.extract(
- fixture.archive, into: ours, options: .intoHostDirectory,
+ fixture.archive,
+ into: ours,
+ options: .intoHostDirectory,
)
let untarred = try VPhoneProcessRunner.runCapturing(
URL(fileURLWithPath: "/usr/bin/tar"),
@@ -170,7 +173,9 @@ struct ExtractPermissionsTests {
defer { try? fm.removeItem(at: destination) }
try VPhoneArchiveExtractor.extract(
- fixture.archive, into: destination, options: .intoHostDirectory,
+ fixture.archive,
+ into: destination,
+ options: .intoHostDirectory,
)
for name in Fixture.archivedModes.keys.sorted() {
diff --git a/tests/VPhoneArchiveTests/IPSWCacheTests.swift b/tests/VPhoneArchiveTests/IPSWCacheTests.swift
index f800d21e..d2e69170 100644
--- a/tests/VPhoneArchiveTests/IPSWCacheTests.swift
+++ b/tests/VPhoneArchiveTests/IPSWCacheTests.swift
@@ -16,7 +16,9 @@ private final class IPSWStubProtocol: URLProtocol {
override func startLoading() {
let response = HTTPURLResponse(
- url: request.url!, statusCode: Self.status, httpVersion: "HTTP/1.1",
+ url: request.url!,
+ statusCode: Self.status,
+ httpVersion: "HTTP/1.1",
headerFields: ["Content-Length": String(Self.payload.count)],
)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
@@ -36,7 +38,9 @@ struct IPSWCacheTests {
"ProductVersion": "26.6.2", "ProductBuildVersion": "23G90",
]
let data = try PropertyListSerialization.data(
- fromPropertyList: manifest, format: .xml, options: 0,
+ fromPropertyList: manifest,
+ format: .xml,
+ options: 0,
)
try data.write(to: files.appendingPathComponent("BuildManifest.plist"))
let archive = root.appendingPathComponent("input.ipsw")
@@ -50,7 +54,8 @@ struct IPSWCacheTests {
defer { try? FileManager.default.removeItem(at: root) }
let source = try fixture(in: root)
let result = try await VPhoneIPSWCache.resolve(
- source.path, in: root.appendingPathComponent("cache"),
+ source.path,
+ in: root.appendingPathComponent("cache"),
)
#expect(result.file == source)
#expect(result.version == "26.6.2")
@@ -77,7 +82,9 @@ struct IPSWCacheTests {
try Data("damaged".utf8).write(to: cached)
let result = try await VPhoneIPSWCache.resolve(
- url.absoluteString, in: cacheDir, session: session,
+ url.absoluteString,
+ in: cacheDir,
+ session: session,
)
#expect(result.file == cached)
#expect(result.build == "23G90")
@@ -85,7 +92,9 @@ struct IPSWCacheTests {
IPSWStubProtocol.status = 503
let reused = try await VPhoneIPSWCache.resolve(
- url.absoluteString, in: cacheDir, session: session,
+ url.absoluteString,
+ in: cacheDir,
+ session: session,
)
#expect(reused.file == cached)
}
diff --git a/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift b/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift
index 19367b19..ff0f46a2 100644
--- a/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift
+++ b/tests/VPhoneArchiveTests/NoOverwriteDirTests.swift
@@ -29,7 +29,8 @@ struct NoOverwriteDirTests {
try Data("from archive\n".utf8).write(to: dir.appendingPathComponent("inside.txt"))
try Data("beside\n".utf8).write(to: staging.appendingPathComponent("beside.txt"))
try FileManager.default.setAttributes(
- [.posixPermissions: NSNumber(value: directoryMode)], ofItemAtPath: dir.path,
+ [.posixPermissions: NSNumber(value: directoryMode)],
+ ofItemAtPath: dir.path,
)
let archive = FileManager.default.temporaryDirectory
@@ -88,11 +89,14 @@ struct NoOverwriteDirTests {
let existing = destination.appendingPathComponent("dir")
try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: true)
try FileManager.default.setAttributes(
- [.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: existing.path,
+ [.posixPermissions: NSNumber(value: 0o700)],
+ ofItemAtPath: existing.path,
)
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: Self.installOptions(noOverwriteDir: true),
+ archive,
+ into: destination,
+ options: Self.installOptions(noOverwriteDir: true),
)
#expect(try Self.mode(of: existing) == 0o700)
@@ -110,11 +114,14 @@ struct NoOverwriteDirTests {
let existing = destination.appendingPathComponent("dir")
try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: true)
try FileManager.default.setAttributes(
- [.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: existing.path,
+ [.posixPermissions: NSNumber(value: 0o700)],
+ ofItemAtPath: existing.path,
)
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: Self.installOptions(noOverwriteDir: false),
+ archive,
+ into: destination,
+ options: Self.installOptions(noOverwriteDir: false),
)
// `man 3 archive_write_disk`: "existing directories will have their
@@ -141,7 +148,9 @@ struct NoOverwriteDirTests {
try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: true)
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: Self.installOptions(noOverwriteDir: true),
+ archive,
+ into: destination,
+ options: Self.installOptions(noOverwriteDir: true),
)
// This is the difference from ARCHIVE_EXTRACT_NO_OVERWRITE, which
@@ -164,7 +173,9 @@ struct NoOverwriteDirTests {
try Data("stale\n".utf8).write(to: beside)
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: Self.installOptions(noOverwriteDir: true),
+ archive,
+ into: destination,
+ options: Self.installOptions(noOverwriteDir: true),
)
// The other half of why ARCHIVE_EXTRACT_NO_OVERWRITE is not a
@@ -182,7 +193,9 @@ struct NoOverwriteDirTests {
}
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: Self.installOptions(noOverwriteDir: true),
+ archive,
+ into: destination,
+ options: Self.installOptions(noOverwriteDir: true),
)
let dir = destination.appendingPathComponent("dir")
@@ -204,11 +217,14 @@ struct NoOverwriteDirTests {
let elsewhere = destination.appendingPathComponent("elsewhere")
try FileManager.default.createDirectory(at: elsewhere, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(
- at: destination.appendingPathComponent("dir"), withDestinationURL: elsewhere,
+ at: destination.appendingPathComponent("dir"),
+ withDestinationURL: elsewhere,
)
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: Self.installOptions(noOverwriteDir: true),
+ archive,
+ into: destination,
+ options: Self.installOptions(noOverwriteDir: true),
)
// Two things have to hold, and both do.
diff --git a/tests/VPhoneArchiveTests/RoundTripTests.swift b/tests/VPhoneArchiveTests/RoundTripTests.swift
index 194d92e6..639040e9 100644
--- a/tests/VPhoneArchiveTests/RoundTripTests.swift
+++ b/tests/VPhoneArchiveTests/RoundTripTests.swift
@@ -48,7 +48,9 @@ struct RoundTripTests {
try VPhoneArchiveWriter.create(archive: archive, from: source, compression: compression)
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: .intoHostDirectory,
+ archive,
+ into: destination,
+ options: .intoHostDirectory,
)
#expect(try String(
@@ -173,10 +175,12 @@ struct RoundTripTests {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
try Data("same\n".utf8).write(to: url.appendingPathComponent("f.txt"))
try FileManager.default.setAttributes(
- [.modificationDate: when], ofItemAtPath: url.appendingPathComponent("f.txt").path,
+ [.modificationDate: when],
+ ofItemAtPath: url.appendingPathComponent("f.txt").path,
)
try FileManager.default.setAttributes(
- [.modificationDate: when], ofItemAtPath: url.path,
+ [.modificationDate: when],
+ ofItemAtPath: url.path,
)
}
defer {
@@ -291,7 +295,9 @@ struct RoundTripTests {
defer { try? FileManager.default.removeItem(at: staging) }
try FileManager.default.copyItem(at: tar, to: staging.appendingPathComponent("inner.tar"))
try VPhoneArchiveWriter.create(
- archive: compressed, from: staging, compression: .zstd(level: 3),
+ archive: compressed,
+ from: staging,
+ compression: .zstd(level: 3),
)
// What decompress gives back is the tar.zst's single stream, which
@@ -326,7 +332,9 @@ struct RoundTripTests {
#expect(throws: VPhoneArchiveError.self) {
try VPhoneArchiveExtractor.extract(
- archive, into: destination, options: .intoHostDirectory,
+ archive,
+ into: destination,
+ options: .intoHostDirectory,
)
}
#expect(!FileManager.default.fileExists(
diff --git a/tests/VPhoneCoreTests/FirmwareMatrixTests.swift b/tests/VPhoneCoreTests/FirmwareMatrixTests.swift
index e66bbaf5..0f2c2af2 100644
--- a/tests/VPhoneCoreTests/FirmwareMatrixTests.swift
+++ b/tests/VPhoneCoreTests/FirmwareMatrixTests.swift
@@ -407,7 +407,10 @@ struct FirmwareMatrixRealDataTests {
#expect(releases.count == 31)
#expect(Set(releases.map(\.build)).count == 31)
- let tested = try VPhoneFirmwareMatrix.testedBuilds(readme: RealData.repositoryCompatibilityGuide(), device: Fixture.d)
+ let tested = try VPhoneFirmwareMatrix.testedBuilds(
+ readme: RealData.repositoryCompatibilityGuide(),
+ device: Fixture.d
+ )
var supported = 0, notTested = 0
for release in releases {
let id = VPhoneFirmwareBuildID(version: release.version, build: release.build)
diff --git a/tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift b/tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift
index fdd2b6b8..58f8efc9 100644
--- a/tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift
+++ b/tests/VPhoneCoreTests/NewVirtualMachineManifestTests.swift
@@ -57,7 +57,8 @@ struct NewVirtualMachineManifestTests {
try VPhoneVirtualMachineManifest.newVM().write(to: url)
let parsed = try PropertyListSerialization.propertyList(
- from: Data(contentsOf: url), format: nil,
+ from: Data(contentsOf: url),
+ format: nil,
) as? [String: Any]
// Absent, not null: the host OS decides when the key is missing.
@@ -73,7 +74,8 @@ struct NewVirtualMachineManifestTests {
try VPhoneVirtualMachineManifest.newVM(platformFusing: .dev).write(to: url)
let parsed = try PropertyListSerialization.propertyList(
- from: Data(contentsOf: url), format: nil,
+ from: Data(contentsOf: url),
+ format: nil,
) as? [String: Any]
#expect(parsed?["platformFusing"] as? String == "dev")
@@ -87,7 +89,8 @@ struct NewVirtualMachineManifestTests {
try VPhoneVirtualMachineManifest.newVM().write(to: url)
let parsed = try #require(PropertyListSerialization.propertyList(
- from: Data(contentsOf: url), format: nil,
+ from: Data(contentsOf: url),
+ format: nil,
) as? [String: Any])
#expect(parsed.keys.sorted() == [
@@ -121,7 +124,8 @@ struct NewVirtualMachineManifestTests {
try VPhoneVirtualMachineManifest.newVM().write(to: url)
let parsed = try #require(PropertyListSerialization.propertyList(
- from: Data(contentsOf: url), format: nil,
+ from: Data(contentsOf: url),
+ format: nil,
) as? [String: Any])
// A number that becomes "8" parses fine and fails much later.
diff --git a/tests/VPhoneCoreTests/PCCGPUDriverTests.swift b/tests/VPhoneCoreTests/PCCGPUDriverTests.swift
index 1cecb659..337cae80 100644
--- a/tests/VPhoneCoreTests/PCCGPUDriverTests.swift
+++ b/tests/VPhoneCoreTests/PCCGPUDriverTests.swift
@@ -9,7 +9,8 @@ struct PCCGPUDriverTests {
defer { try? FileManager.default.removeItem(at: root) }
let source = root.appendingPathComponent(VPhonePCCGPUDriver.name)
try FileManager.default.createDirectory(
- at: source.appendingPathComponent("_CodeSignature"), withIntermediateDirectories: true,
+ at: source.appendingPathComponent("_CodeSignature"),
+ withIntermediateDirectories: true,
)
for file in ["AppleParavirtGPUMetalIOGPUFamily",
"_CodeSignature/CodeResources"]
@@ -37,7 +38,8 @@ struct PCCGPUDriverTests {
#expect(throws: VPhonePCCGPUDriver.Error.self) {
try VPhonePCCGPUDriver.stage(
- from: source, into: restore,
+ from: source,
+ into: restore,
expectedPlatformVersion: "26.1",
)
}
@@ -45,7 +47,9 @@ struct PCCGPUDriverTests {
try FileManager.default.removeItem(at: source.appendingPathComponent("_CodeSignature/CodeResources"))
#expect(throws: VPhonePCCGPUDriver.Error.self) {
try VPhonePCCGPUDriver.stage(
- from: source, into: restore, expectedPlatformVersion: "26.4",
+ from: source,
+ into: restore,
+ expectedPlatformVersion: "26.4",
)
}
}
diff --git a/tests/VPhoneCoreTests/PlistEquivalence.swift b/tests/VPhoneCoreTests/PlistEquivalence.swift
index 257f5534..b59e95f5 100644
--- a/tests/VPhoneCoreTests/PlistEquivalence.swift
+++ b/tests/VPhoneCoreTests/PlistEquivalence.swift
@@ -52,7 +52,8 @@ enum PlistEquivalence {
}
for key in Set(l.keys).intersection(r.keys).sorted() {
found += differences(
- between: l[key]!, and: r[key]!,
+ between: l[key]!,
+ and: r[key]!,
at: path.isEmpty ? key : "\(path).\(key)",
)
}
@@ -110,10 +111,12 @@ enum PlistEquivalence {
/// Parse two plist files and report every semantic difference.
static func differences(betweenFileAt lhs: URL, andFileAt rhs: URL) throws -> [Difference] {
let left = try PropertyListSerialization.propertyList(
- from: Data(contentsOf: lhs), format: nil,
+ from: Data(contentsOf: lhs),
+ format: nil,
)
let right = try PropertyListSerialization.propertyList(
- from: Data(contentsOf: rhs), format: nil,
+ from: Data(contentsOf: rhs),
+ format: nil,
)
return differences(between: left, and: right)
}
diff --git a/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift b/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift
index cb1a15bd..c6cdb263 100644
--- a/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift
+++ b/tests/VPhoneSignTests/VPhoneSignEntitlementsTests.swift
@@ -39,7 +39,9 @@ struct VPhoneSignEntitlementsTests {
defer { try? FileManager.default.removeItem(at: directory) }
let plist = VPhoneSignParityTests.sampleEntitlements
let file = try VPhoneSignFixtures.sign(
- VPhoneSignFixtures.url("hello-arm64"), in: directory, entitlements: plist,
+ VPhoneSignFixtures.url("hello-arm64"),
+ in: directory,
+ entitlements: plist,
)
let read = try VPhoneSigner.entitlements(ofFileAt: file)
@@ -251,7 +253,9 @@ struct VPhoneSignEntitlementsTests {
@Test
func `a binary plist is refused rather than read as XML`() throws {
let binary = try PropertyListSerialization.data(
- fromPropertyList: ["k": true], format: .binary, options: 0,
+ fromPropertyList: ["k": true],
+ format: .binary,
+ options: 0,
)
#expect(throws: VPhoneSignError.self) {
_ = try VPhoneSignEntitlements(xml: binary)
diff --git a/tests/VPhoneSignTests/VPhoneSignParityTests.swift b/tests/VPhoneSignTests/VPhoneSignParityTests.swift
index 5f9d3a0a..05863710 100644
--- a/tests/VPhoneSignTests/VPhoneSignParityTests.swift
+++ b/tests/VPhoneSignTests/VPhoneSignParityTests.swift
@@ -51,7 +51,9 @@ struct VPhoneSignParityTests {
let name = source.lastPathComponent
let ours = try VPhoneSignFixtures.sign(
- source, in: directory, entitlements: Self.sampleEntitlements,
+ source,
+ in: directory,
+ entitlements: Self.sampleEntitlements,
)
try VPhoneSignFixtures.expect("\(name).entitlements", matches: Data(contentsOf: ours))
}
@@ -78,7 +80,10 @@ struct VPhoneSignParityTests {
}
let ours = try VPhoneSignFixtures.sign(
- source, in: directory, entitlements: Self.sampleEntitlements, mergesExisting: true,
+ source,
+ in: directory,
+ entitlements: Self.sampleEntitlements,
+ mergesExisting: true,
)
try VPhoneSignFixtures.expect("\(name).mergeSample", matches: Data(contentsOf: ours))
}
@@ -159,7 +164,10 @@ struct VPhoneSignParityTests {
)
let ours = try VPhoneSignFixtures.sign(
- source, in: directory, entitlements: Self.sampleEntitlements, mergesExisting: true,
+ source,
+ in: directory,
+ entitlements: Self.sampleEntitlements,
+ mergesExisting: true,
)
try VPhoneSignFixtures.expect("\(name).mergeSample", matches: Data(contentsOf: ours))
@@ -206,7 +214,9 @@ struct VPhoneSignParityTests {
// reads the name off the file it was handed
let name = "named-for-this-test"
let file = try VPhoneSignFixtures.copy(
- VPhoneSignFixtures.url("hello-arm64"), into: directory, as: name,
+ VPhoneSignFixtures.url("hello-arm64"),
+ into: directory,
+ as: name,
)
try VPhoneSigner.sign(fileAt: file)
diff --git a/tests/VPhoneSignTests/VPhoneSignStyleTests.swift b/tests/VPhoneSignTests/VPhoneSignStyleTests.swift
index 1f45d2e3..360398ef 100644
--- a/tests/VPhoneSignTests/VPhoneSignStyleTests.swift
+++ b/tests/VPhoneSignTests/VPhoneSignStyleTests.swift
@@ -30,7 +30,9 @@ struct VPhoneSignStyleTests {
let directory = try VPhoneSignFixtures.temporaryDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
let file = try VPhoneSignFixtures.sign(
- VPhoneSignFixtures.url("hello-arm64"), in: directory, style: .appleAdHoc,
+ VPhoneSignFixtures.url("hello-arm64"),
+ in: directory,
+ style: .appleAdHoc,
)
for slice in try VPhoneSignBlobs(fileAt: file).slices {
@@ -125,7 +127,9 @@ struct VPhoneSignStyleTests {
// not through the shared helper: the mode has to be set between the
// copy and the signature
let file = try VPhoneSignFixtures.copy(
- VPhoneSignFixtures.url("hello-arm64"), into: directory, as: "binary",
+ VPhoneSignFixtures.url("hello-arm64"),
+ into: directory,
+ as: "binary",
)
try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: file.path)