diff --git a/companion/Helper/main.swift b/companion/Helper/main.swift index 21e6a199..c5505870 100644 --- a/companion/Helper/main.swift +++ b/companion/Helper/main.swift @@ -81,27 +81,29 @@ final class Launcher: @unchecked Sendable { var registered = embedded != nil, lastRegister = Date.distantPast while true { Thread.sleep(forTimeInterval: 1) - lock.lock(); let open = wanted; lock.unlock() - if !registered { - if installed() { - registered = true - log("app registered with iPadOS") - } else if FileManager.default.fileExists(atPath: appPath + "/OrchardCompanion"), - Date().timeIntervalSince(lastRegister) > 3 { - lastRegister = Date() - log("registering the app: uicache exit \(spawn([uicache, "-p", appPath]))") + autoreleasepool { + lock.lock(); let open = wanted; lock.unlock() + if !registered { + if installed() { + registered = true + log("app registered with iPadOS") + } else if FileManager.default.fileExists(atPath: appPath + "/OrchardCompanion"), + Date().timeIntervalSince(lastRegister) > 3 { + lastRegister = Date() + log("registering the app: uicache exit \(spawn([uicache, "-p", appPath]))") + } + return } - continue - } - guard open else { continue } - if oc_running(process) != 0 { - log("app running") - lock.lock(); wanted = false; lock.unlock() - continue + guard open else { return } + if oc_running(process) != 0 { + log("app running") + lock.lock(); wanted = false; lock.unlock() + return + } + let viaLS = openWithLaunchServices() + let viaSB = viaLS ? 0 : oc_springboard_launch(bundleID) + log("opening the app: LaunchServices \(viaLS), SpringBoard \(viaSB)") } - let viaLS = openWithLaunchServices() - let viaSB = viaLS ? 0 : oc_springboard_launch(bundleID) - log("opening the app: LaunchServices \(viaLS), SpringBoard \(viaSB)") } } } @@ -264,7 +266,9 @@ final class Server: @unchecked Sendable { launcher.run() Thread.detachNewThread { [status] in while true { - status.rewrite() + autoreleasepool { + status.rewrite() + } Thread.sleep(forTimeInterval: 1) } } @@ -272,10 +276,12 @@ final class Server: @unchecked Sendable { // engine is synchronous and lock-guarded, iOS 12 has no async). Thread.detachNewThread { [self] in while true { - engine.refresh() - let snapshot = try? engine.snapshot() - publish(snapshot) - status.update(snapshot) + autoreleasepool { + engine.refresh() + let snapshot = try? engine.snapshot() + publish(snapshot) + status.update(snapshot) + } Thread.sleep(forTimeInterval: 1) } } @@ -346,58 +352,62 @@ final class Server: @unchecked Sendable { var buffer = Data() var authenticated = false while let line = readLine(fd, &buffer) { - guard let object = try? JSONSerialization.jsonObject(with: line) as? [String: Any], - object.count == 1, let (name, body) = object.first else { return } - let args = body as? [String: Any] ?? [:] - if !authenticated { - guard name == "hello", let given = args["token"] as? String, - constantTimeEqual(given.lowercased(), token) else { return } - authenticated = true - adopt(fd) + let keepOpen: Bool = autoreleasepool { + guard let object = try? JSONSerialization.jsonObject(with: line) as? [String: Any], + object.count == 1, let (name, body) = object.first else { return false } + let args = body as? [String: Any] ?? [:] + if !authenticated { + guard name == "hello", let given = args["token"] as? String, + constantTimeEqual(given.lowercased(), token) else { return false } + authenticated = true + adopt(fd) + status.pinged() + // The app shows the computer as connected right away. + status.rewrite() + log("the computer connected") + launcher.want() + reply(fd, ok: ["protocol": protocolVersion, "ecid": ecid() as Any? ?? NSNull(), "machine": machine()]) + return true + } status.pinged() - // The app shows the computer as connected right away. - status.rewrite() - log("the computer connected") - launcher.want() - reply(fd, ok: ["protocol": protocolVersion, "ecid": ecid() as Any? ?? NSNull(), "machine": machine()]) - continue - } - status.pinged() - do { - switch name { - case "ping": reply(fd, ok: [:]) - case "restart": - // The installer quit: back to normal iPadOS. - guard engine.idleForRestart else { throw ResizeError("The storage is being split; restart later.") } - reply(fd, ok: [:]) - log("restarting for the installer") - Thread.detachNewThread { - Thread.sleep(forTimeInterval: 0.5) - // The kernel's own restart (no tool needed: works on any route). - log("restart: \(oc_restart())") + do { + switch name { + case "ping": reply(fd, ok: [:]) + case "restart": + // The installer quit: back to normal iPadOS. + guard engine.idleForRestart else { throw ResizeError("The storage is being split; restart later.") } + reply(fd, ok: [:]) + log("restarting for the installer") + Thread.detachNewThread { + Thread.sleep(forTimeInterval: 0.5) + // The kernel's own restart (no tool needed: works on any route). + log("restart: \(oc_restart())") + } + case "log": + // The helper's own log (timings from boot to the app), its last 64 KiB. + let data = FileManager.default.contents(atPath: logPath) ?? Data() + reply(fd, ok: ["text": String(decoding: data.suffix(65536), as: UTF8.self)]) + case "snapshot": try reply(fd, okJSON: latestSnapshot()) + case "split": + guard let bytes = (args["apfs_bytes"] as? NSNumber)?.int64Value, + let revisionText = args["revision"] as? String, let revision = UUID(uuidString: revisionText) + else { throw ResizeError("A split needs apfs_bytes and the layout's revision.") } + // Partitions after APFS the user approved erasing, when the size needs their space. + let replacing = (args["replacing"] as? [String] ?? []).compactMap(UUID.init(uuidString:)) + guard replacing.count == (args["replacing"] as? [String] ?? []).count else { throw ResizeError("replacing holds an invalid partition id.") } + let plan = try engine.plan(PlanRequest(revision: revision, requestedBytes: bytes, createLinux: false, replacing: replacing)) + let data = try JSONEncoder().encode(engine.start(StartRequest(planID: plan.id, requestID: UUID()))) + try reply(fd, okJSON: data) + // The copy shows the running split from now on. + publish(try? engine.snapshot()) + default: throw ResizeError("Unknown request.") } - case "log": - // The helper's own log (timings from boot to the app), its last 64 KiB. - let data = FileManager.default.contents(atPath: logPath) ?? Data() - reply(fd, ok: ["text": String(decoding: data.suffix(65536), as: UTF8.self)]) - case "snapshot": try reply(fd, okJSON: latestSnapshot()) - case "split": - guard let bytes = (args["apfs_bytes"] as? NSNumber)?.int64Value, - let revisionText = args["revision"] as? String, let revision = UUID(uuidString: revisionText) - else { throw ResizeError("A split needs apfs_bytes and the layout's revision.") } - // Partitions after APFS the user approved erasing, when the size needs their space. - let replacing = (args["replacing"] as? [String] ?? []).compactMap(UUID.init(uuidString:)) - guard replacing.count == (args["replacing"] as? [String] ?? []).count else { throw ResizeError("replacing holds an invalid partition id.") } - let plan = try engine.plan(PlanRequest(revision: revision, requestedBytes: bytes, createLinux: false, replacing: replacing)) - let data = try JSONEncoder().encode(engine.start(StartRequest(planID: plan.id, requestID: UUID()))) - try reply(fd, okJSON: data) - // The copy shows the running split from now on. - publish(try? engine.snapshot()) - default: throw ResizeError("Unknown request.") + } catch { + reply(fd, error: error.localizedDescription) } - } catch { - reply(fd, error: error.localizedDescription) + return true } + if !keepOpen { return } } } diff --git a/crates/runtime/src/overlay.rs b/crates/runtime/src/overlay.rs index b71a2176..0545d7cc 100644 --- a/crates/runtime/src/overlay.rs +++ b/crates/runtime/src/overlay.rs @@ -274,6 +274,12 @@ fn job() -> Value { d.insert("AbandonProcessGroup".into(), true.into()); d.insert("StandardOutPath".into(), "/cores/orchard-companion.log".into()); d.insert("StandardErrorPath".into(), "/cores/orchard-companion.err".into()); + // Match resize-apfs's helper plist so iPadOS Jetsam does not kill the + // daemon at its default unlisted-daemon cap (~18 MB) during long shrinks. + let mut jetsam = plist::Dictionary::new(); + jetsam.insert("JetsamPriority".into(), 160.into()); + jetsam.insert("JetsamMemoryLimit".into(), 256.into()); + d.insert("JetsamProperties".into(), Value::Dictionary(jetsam)); Value::Dictionary(d) } @@ -466,4 +472,12 @@ mod tests { bad.app.push(("../escape".into(), vec![], 0o644)); assert!(build(&palera1n, &bad, &Identity::random()).is_err()); } + + #[test] + fn the_helper_job_sets_jetsam_properties() { + let dict = job().into_dictionary().expect("job plist dictionary"); + let jetsam = dict.get("JetsamProperties").and_then(Value::as_dictionary).expect("JetsamProperties"); + assert_eq!(jetsam.get("JetsamPriority").and_then(Value::as_signed_integer), Some(160)); + assert_eq!(jetsam.get("JetsamMemoryLimit").and_then(Value::as_signed_integer), Some(256)); + } } diff --git a/ios-installer/Helper/main.swift b/ios-installer/Helper/main.swift index 88df3570..0f465ae0 100644 --- a/ios-installer/Helper/main.swift +++ b/ios-installer/Helper/main.swift @@ -64,8 +64,10 @@ final class Resizer: @unchecked Sendable { func run() { Thread.detachNewThread { [self] in while true { - engine.refresh() - report() + autoreleasepool { + engine.refresh() + report() + } Thread.sleep(forTimeInterval: 1) } } @@ -174,21 +176,25 @@ final class Server: @unchecked Sendable { guard raf_peer_uid(fd, &uid) == 0, uid == mobileUID || uid == 0, uid == 0 || appExecutable.map({ raf_peer_is_executable(fd, $0) == 1 }) == true else { return } while let frame = try? LocalFrames.read(from: fd) { - let refused = { (message: String) in - (try? JSONSerialization.data(withJSONObject: ["error": ["message": message]])) ?? Data() - } - guard let object = try? JSONSerialization.jsonObject(with: frame) as? [String: Any], - let given = object["token"] as? String, constantTimeEqual(given, token) else { - try? LocalFrames.write(refused("Invalid helper credentials."), to: fd) - return - } - served.lock(); wasServed = true; served.unlock() - let answer: Data = String(decoding: frame, as: UTF8.self).withCString { request in - guard let raw = oi_request(request) else { return refused("The installer did not answer.") } - defer { oi_free(raw) } - return Data(String(cString: raw).utf8) + let keepOpen: Bool = autoreleasepool { + let refused = { (message: String) in + (try? JSONSerialization.data(withJSONObject: ["error": ["message": message]])) ?? Data() + } + guard let object = try? JSONSerialization.jsonObject(with: frame) as? [String: Any], + let given = object["token"] as? String, constantTimeEqual(given, token) else { + try? LocalFrames.write(refused("Invalid helper credentials."), to: fd) + return false + } + served.lock(); wasServed = true; served.unlock() + let answer: Data = String(decoding: frame, as: UTF8.self).withCString { request in + guard let raw = oi_request(request) else { return refused("The installer did not answer.") } + defer { oi_free(raw) } + return Data(String(cString: raw).utf8) + } + do { try LocalFrames.write(answer, to: fd) } catch { return false } + return true } - do { try LocalFrames.write(answer, to: fd) } catch { return } + if !keepOpen { return } } } }