diff --git a/lib/common/definitions/mobile.d.ts b/lib/common/definitions/mobile.d.ts index bb522079fa..293bd4ebdb 100644 --- a/lib/common/definitions/mobile.d.ts +++ b/lib/common/definitions/mobile.d.ts @@ -1359,7 +1359,7 @@ declare global { start( startArray: IOSDeviceLib.IIOSApplicationData[], errorHandler?: DeviceOperationErrorHandler, - ): Promise; + ): Promise>; stop( stopArray: IOSDeviceLib.IIOSApplicationData[], diff --git a/lib/common/mobile/ios/device/ios-application-manager.ts b/lib/common/mobile/ios/device/ios-application-manager.ts index b1199c1d8c..6293033b83 100644 --- a/lib/common/mobile/ios/device/ios-application-manager.ts +++ b/lib/common/mobile/ios/device/ios-application-manager.ts @@ -4,7 +4,9 @@ import { hook } from "../../../helpers"; import { ApplicationManagerBase } from "../../application-manager-base"; import { cache } from "../../../decorators"; import { IOptions } from "../../../../declarations"; +import { ChildProcess } from "child_process"; import { + IChildProcess, IHooksService, IErrors, IiOSNotificationService, @@ -12,7 +14,11 @@ import { } from "../../../declarations"; export class IOSApplicationManager extends ApplicationManagerBase { + private static readonly LLDB_CONTINUE_TIMEOUT = 10000; + private static readonly LLDB_EXIT_TIMEOUT = 3000; + private applicationsLiveSyncInfos: Mobile.IApplicationInfo[]; + private lldbProcesses: IDictionary = {}; constructor( protected $logger: ILogger, @@ -22,7 +28,8 @@ export class IOSApplicationManager extends ApplicationManagerBase { private $iOSNotificationService: IiOSNotificationService, private $iosDeviceOperations: IIOSDeviceOperations, private $options: IOptions, - protected $deviceLogProvider: Mobile.IDeviceLogProvider + protected $deviceLogProvider: Mobile.IDeviceLogProvider, + private $childProcess: IChildProcess ) { super($logger, $hooksService, $deviceLogProvider); } @@ -118,6 +125,7 @@ export class IOSApplicationManager extends ApplicationManagerBase { const { appId } = appData; await this.device.destroyDebugSocket(appId); + await this.detachNativeDebugger(appId); const action = () => this.$iosDeviceOperations.stop([ @@ -173,15 +181,124 @@ export class IOSApplicationManager extends ApplicationManagerBase { private async runApplicationCore( appData: Mobile.IStartApplicationData ): Promise { + await this.detachNativeDebugger(appData.appId); + + const deviceId = this.device.deviceInfo.identifier; const waitForDebugger = (!!appData.waitForDebugger).toString(); - await this.$iosDeviceOperations.start([ + const result = await this.$iosDeviceOperations.start([ { - deviceId: this.device.deviceInfo.identifier, + deviceId, appId: appData.appId, ddi: this.$options.ddi, waitForDebugger, }, ]); + + const pid = result?.[deviceId]?.[0]?.pid; + if (appData.waitForDebugger && pid > 0) { + this.attachNativeDebugger(appData.appId, pid); + } + } + + // iOS kills an app that takes about 20 seconds to launch, which is what waiting + // for or pausing in the JS debugger looks like, unless a native debugger is + // attached. An lldb without the `device` commands (believed to need Xcode 16) + // can't attach, which limits the wait to those 20 seconds. + private attachNativeDebugger(appId: string, pid: number): void { + // Its own process group keeps Ctrl-C from reaching lldb, which would stop + // the app. lldb still exits when the CLI does, as its stdin closes. + const lldb = this.$childProcess.spawn("xcrun", ["lldb"], { + detached: true, + }); + this.lldbProcesses[appId] = lldb; + lldb.on("error", (err: Error) => { + this.$logger.trace("Unable to attach lldb to the application", err); + }); + lldb.stdin?.on("error", (err: Error) => { + this.$logger.trace("Unable to write to lldb", err); + }); + + // Attaching stops the app, and until it continues it can't answer the JS + // debugger's attach request. The continue is sent once lldb reports the + // stop, or after a timeout in case that report never shows up. + let settled = false; + const continueApp = () => lldb.stdin?.write("process continue\n"); + const fallback = setTimeout( + continueApp, + IOSApplicationManager.LLDB_CONTINUE_TIMEOUT + ); + const done = () => { + settled = true; + clearTimeout(fallback); + }; + lldb.on("close", done); + lldb.on("error", done); + + const watch = (stream: NodeJS.ReadableStream) => { + let output = ""; + stream?.on("data", (data: Buffer) => { + this.$logger.trace(`${data}`); + if (settled) { + return; + } + output += data; + const state = /Process \d+ (stopped|resuming)/.exec(output)?.[1]; + if (state) { + done(); + if (state === "stopped") { + continueApp(); + } + } + }); + }; + watch(lldb.stdout); + watch(lldb.stderr); + + lldb.stdin?.write( + `device select ${this.device.deviceInfo.identifier}\ndevice process attach -p ${pid}\n` + ); + } + + // Stop the app only once lldb is gone, or lldb intercepts the termination + // signal and leaves the app suspended. + private async detachNativeDebugger(appId: string): Promise { + const lldb = this.lldbProcesses[appId]; + if (!lldb) { + return; + } + delete this.lldbProcesses[appId]; + + if (lldb.pid && lldb.exitCode === null && lldb.signalCode === null) { + const exited = new Promise((resolve) => + lldb.once("exit", () => resolve()) + ); + lldb.stdin?.end("process detach\nquit\n"); + for (const signal of [null, "SIGTERM", "SIGKILL"] as const) { + if (signal) { + this.$logger.trace( + `lldb did not exit in time, sending ${signal}` + ); + lldb.kill(signal); + } + const timeout = IOSApplicationManager.LLDB_EXIT_TIMEOUT; + if (await this.exitsWithin(exited, timeout)) { + break; + } + } + } + } + + private async exitsWithin( + exited: Promise, + ms: number + ): Promise { + let timer: NodeJS.Timeout; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), ms); + }); + const result = await Promise.race([exited.then(() => true), timeout]); + clearTimeout(timer); + return result; } @cache() diff --git a/lib/common/mobile/ios/device/ios-device-operations.ts b/lib/common/mobile/ios/device/ios-device-operations.ts index e0675096c7..222298a376 100644 --- a/lib/common/mobile/ios/device/ios-device-operations.ts +++ b/lib/common/mobile/ios/device/ios-device-operations.ts @@ -227,7 +227,7 @@ export class IOSDeviceOperations public async start( startArray: IOSDeviceLib.IDdiApplicationData[], errorHandler?: DeviceOperationErrorHandler, - ): Promise { + ): Promise> { this.assertIsInitialized(); _.each(startArray, (s) => { @@ -236,7 +236,7 @@ export class IOSDeviceOperations ); }); - return this.getMultipleResults( + return this.getMultipleResults( () => this.deviceLib.start(startArray), errorHandler, ); diff --git a/lib/common/test/unit-tests/mobile/ios-application-manager.ts b/lib/common/test/unit-tests/mobile/ios-application-manager.ts new file mode 100644 index 0000000000..db5e47582c --- /dev/null +++ b/lib/common/test/unit-tests/mobile/ios-application-manager.ts @@ -0,0 +1,290 @@ +import { assert } from "chai"; +import { EventEmitter } from "events"; +import * as sinon from "sinon"; +import { IOSApplicationManager } from "../../../mobile/ios/device/ios-application-manager"; + +class FakeLldb extends EventEmitter { + public pid = 1; + public input: string[] = []; + public exitCode: number = null; + public signalCode: string = null; + public signals: string[] = []; + public stdout = new EventEmitter(); + public stderr = new EventEmitter(); + public stdin = Object.assign(new EventEmitter(), { + write: (text: string) => { + this.input.push(text); + return true; + }, + end: (text?: string) => { + if (text) { + this.input.push(text); + } + if (this.exitsOnEnd) { + setImmediate(() => this.exit()); + } + }, + }); + + constructor( + private exitsOnEnd: boolean, + private events: string[], + private exitsOnSignals: string[], + ) { + super(); + } + + public kill(signal: string) { + this.signals.push(signal); + if (this.exitsOnSignals.includes(signal)) { + setImmediate(() => this.exit()); + } + } + + private exit() { + this.exitCode = 0; + this.events.push("lldb exit"); + this.emit("exit", 0, null); + this.emit("close", 0, null); + } +} + +describe("IOSApplicationManager native debugger", () => { + const deviceId = "device"; + const appData = { appId: "org.app", projectName: "app", projectDir: "/app" }; + let clock: sinon.SinonFakeTimers; + + afterEach(() => { + clock?.restore(); + clock = undefined; + }); + + const setup = ( + pid?: number, + lldbExitsOnEnd = true, + lldbExitsOnSignals = ["SIGTERM", "SIGKILL"], + ) => { + const events: string[] = []; + const lldbs: FakeLldb[] = []; + const spawned: { args: string[]; options: any }[] = []; + const manager = new (IOSApplicationManager)( + { trace: () => {}, info: () => {} }, + {}, + { + deviceInfo: { identifier: deviceId }, + destroyDebugSocket: async () => {}, + }, + {}, + {}, + { + start: async () => { + events.push("start"); + return { [deviceId]: [{ deviceId, pid }] }; + }, + stop: async () => { + events.push("stop"); + return {}; + }, + apps: async () => ({ + [deviceId]: [{ response: [{ CFBundleIdentifier: appData.appId }] }], + }), + }, + { justlaunch: true }, + new Proxy({}, { get: () => () => {} }), + { + spawn: (command: string, args: string[], options: any) => { + spawned.push({ args: [command, ...args], options }); + const lldb = new FakeLldb(lldbExitsOnEnd, events, lldbExitsOnSignals); + lldbs.push(lldb); + return lldb; + }, + }, + ); + return { manager, lldbs, spawned, events }; + }; + + const debugBrk = { ...appData, waitForDebugger: true }; + + it("attaches lldb to an app that waits for the JS debugger", async () => { + const { manager, lldbs, spawned } = setup(42); + + await manager.restartApplication(debugBrk); + + assert.deepEqual( + spawned.map((s) => s.args), + [["xcrun", "lldb"]], + ); + assert.include(lldbs[0].input[0], `device select ${deviceId}`); + assert.include(lldbs[0].input[0], "device process attach -p 42"); + }); + + it("runs lldb outside the CLI's process group", async () => { + const { manager, spawned } = setup(42); + + await manager.restartApplication(debugBrk); + + assert.isTrue(spawned[0].options?.detached); + }); + + it("continues the app once, after the attach stopped it", async () => { + clock = sinon.useFakeTimers(); + const { manager, lldbs } = setup(42); + + await manager.restartApplication(debugBrk); + const [lldb] = lldbs; + assert.lengthOf(lldb.input, 1); + + lldb.stdout.emit("data", Buffer.from("Process 42 sto")); + assert.lengthOf(lldb.input, 1); + lldb.stdout.emit("data", Buffer.from("pped\n")); + lldb.stdout.emit("data", Buffer.from("Process 42 stopped\n")); + await clock.tickAsync(60000); + + assert.deepEqual(lldb.input.slice(1), ["process continue\n"]); + }); + + it("continues the app when lldb reports the stop on stderr", async () => { + const { manager, lldbs } = setup(42); + + await manager.restartApplication(debugBrk); + lldbs[0].stderr.emit("data", Buffer.from("Process 42 stopped\n")); + + assert.deepEqual(lldbs[0].input.slice(1), ["process continue\n"]); + }); + + it("continues the app when lldb never reports the stop", async () => { + clock = sinon.useFakeTimers(); + const { manager, lldbs } = setup(42); + + await manager.restartApplication(debugBrk); + const [lldb] = lldbs; + await clock.tickAsync(1000); + assert.lengthOf(lldb.input, 1); + + await clock.tickAsync(60000); + assert.deepEqual(lldb.input.slice(1), ["process continue\n"]); + }); + + it("continues the app on a stop reported after the timeout", async () => { + clock = sinon.useFakeTimers(); + const { manager, lldbs } = setup(42); + + await manager.restartApplication(debugBrk); + const [lldb] = lldbs; + await clock.tickAsync(60000); + lldb.stdout.emit("data", Buffer.from("Process 42 stopped\n")); + lldb.stdout.emit("data", Buffer.from("Process 42 stopped\n")); + + assert.deepEqual(lldb.input.slice(1), [ + "process continue\n", + "process continue\n", + ]); + }); + + it("doesn't continue the app again once lldb resumed it", async () => { + clock = sinon.useFakeTimers(); + const { manager, lldbs } = setup(42); + + await manager.restartApplication(debugBrk); + const [lldb] = lldbs; + await clock.tickAsync(60000); + lldb.stdout.emit("data", Buffer.from("Process 42 resuming\n")); + lldb.stdout.emit("data", Buffer.from("Process 42 stopped\n")); + + assert.deepEqual(lldb.input.slice(1), ["process continue\n"]); + }); + + it("survives a broken pipe to lldb", async () => { + const { manager, lldbs } = setup(42); + + await manager.restartApplication(debugBrk); + + assert.doesNotThrow(() => + lldbs[0].stdin.emit("error", new Error("write EPIPE")), + ); + }); + + it("doesn't attach to an app that doesn't wait", async () => { + const { manager, spawned } = setup(42); + + await manager.restartApplication(appData); + + assert.deepEqual(spawned, []); + }); + + it("doesn't attach without a process id", async () => { + const { manager, spawned } = setup(-1); + + await manager.restartApplication(debugBrk); + + assert.deepEqual(spawned, []); + }); + + it("detaches before stopping the app", async () => { + const { manager, lldbs, events } = setup(42); + + await manager.restartApplication(debugBrk); + events.length = 0; + await manager.stopApplication(appData); + + assert.include(lldbs[0].input[lldbs[0].input.length - 1], "process detach"); + assert.deepEqual(events, ["lldb exit", "stop"]); + assert.deepEqual(lldbs[0].signals, []); + }); + + it("kills lldb when it doesn't exit after detaching", async () => { + clock = sinon.useFakeTimers(); + const { manager, lldbs, events } = setup(42, false); + + await manager.restartApplication(debugBrk); + events.length = 0; + const stopped = manager.stopApplication(appData); + await clock.tickAsync(1000); + assert.deepEqual(events, []); + + await clock.tickAsync(60000); + await stopped; + + assert.deepEqual(lldbs[0].signals, ["SIGTERM"]); + assert.deepEqual(events, ["lldb exit", "stop"]); + }); + + it("force-kills lldb when it ignores SIGTERM", async () => { + clock = sinon.useFakeTimers(); + const { manager, lldbs, events } = setup(42, false, ["SIGKILL"]); + + await manager.restartApplication(debugBrk); + events.length = 0; + const stopped = manager.stopApplication(appData); + await clock.tickAsync(60000); + await stopped; + + assert.deepEqual(lldbs[0].signals, ["SIGTERM", "SIGKILL"]); + assert.deepEqual(events, ["lldb exit", "stop"]); + }); + + it("stops the app even when lldb never exits", async () => { + clock = sinon.useFakeTimers(); + const { manager, events } = setup(42, false, []); + + await manager.restartApplication(debugBrk); + events.length = 0; + const stopped = manager.stopApplication(appData); + await clock.tickAsync(60000); + await stopped; + + assert.deepEqual(events, ["stop"]); + }); + + it("detaches before launching the app without waiting for the debugger", async () => { + const { manager, lldbs, events, spawned } = setup(42); + + await manager.startApplication(debugBrk); + events.length = 0; + await manager.startApplication(appData); + + assert.include(lldbs[0].input[lldbs[0].input.length - 1], "process detach"); + assert.deepEqual(events, ["lldb exit", "start"]); + assert.lengthOf(spawned, 1); + }); +});