From 7b88759d081572b4c2073ff9f1b650ecb64c55ed Mon Sep 17 00:00:00 2001 From: Igor Randjelovic Date: Fri, 30 Oct 2026 23:02:40 +0100 Subject: [PATCH 1/4] fix(ios): keep debug-brk apps alive on devices with a native debugger iOS kills an app that takes about 20 seconds to launch, which is what waiting for or pausing in the JS debugger before UIApplicationMain looks like. The simulator already attaches lldb to prevent that; devices now do too, using the pid ios-device-lib reports. --- .../ios/device/ios-application-manager.ts | 57 ++++++++++- .../mobile/ios-application-manager.ts | 94 +++++++++++++++++++ 2 files changed, 148 insertions(+), 3 deletions(-) create mode 100644 lib/common/test/unit-tests/mobile/ios-application-manager.ts diff --git a/lib/common/mobile/ios/device/ios-application-manager.ts b/lib/common/mobile/ios/device/ios-application-manager.ts index b1199c1d8c..789f64575e 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, @@ -13,6 +15,7 @@ import { export class IOSApplicationManager extends ApplicationManagerBase { private applicationsLiveSyncInfos: Mobile.IApplicationInfo[]; + private lldbProcesses: IDictionary = {}; constructor( protected $logger: ILogger, @@ -22,7 +25,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 +122,7 @@ export class IOSApplicationManager extends ApplicationManagerBase { const { appId } = appData; await this.device.destroyDebugSocket(appId); + this.detachNativeDebugger(appId); const action = () => this.$iosDeviceOperations.stop([ @@ -173,15 +178,61 @@ export class IOSApplicationManager extends ApplicationManagerBase { private async runApplicationCore( appData: Mobile.IStartApplicationData ): Promise { + 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: number = (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. lldb only knows about devices since Xcode 16; without it the wait + // is just limited to those 20 seconds. + private attachNativeDebugger(appId: string, pid: number): void { + this.detachNativeDebugger(appId); + + const lldb = this.$childProcess.spawn("xcrun", ["lldb"]); + this.lldbProcesses[appId] = lldb; + lldb.on("error", (err: Error) => { + this.$logger.trace("Unable to attach lldb to the application", err); + }); + // Attaching stops the app. It can only be continued once that has happened, + // and until then it can't answer the JS debugger's attach request. + let output = ""; + lldb.stdout?.on("data", (data: Buffer) => { + this.$logger.trace(`${data}`); + if (output !== null) { + output += data; + if (/Process \d+ stopped/.test(output)) { + output = null; + lldb.stdin?.write("process continue\n"); + } + } + }); + lldb.stderr?.on("data", (data: Buffer) => this.$logger.trace(`${data}`)); + lldb.stdin?.write( + `device select ${this.device.deviceInfo.identifier}\ndevice process attach -p ${pid}\n` + ); + } + + private detachNativeDebugger(appId: string): void { + const lldb = this.lldbProcesses[appId]; + if (lldb) { + delete this.lldbProcesses[appId]; + lldb.stdin?.write("process detach\nquit\n"); + lldb.stdin?.end(); + } } @cache() 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..bc6d95155a --- /dev/null +++ b/lib/common/test/unit-tests/mobile/ios-application-manager.ts @@ -0,0 +1,94 @@ +import { assert } from "chai"; +import { EventEmitter } from "events"; +import { IOSApplicationManager } from "../../../mobile/ios/device/ios-application-manager"; + +describe("IOSApplicationManager native debugger", () => { + const deviceId = "device"; + const appData = { appId: "org.app", projectName: "app", projectDir: "/app" }; + + const setup = (pid?: number) => { + const lldbInput: string[] = []; + const lldbOutput = new EventEmitter(); + const spawned: string[][] = []; + const manager = new (IOSApplicationManager)( + { trace: () => {}, info: () => {} }, + {}, + { + deviceInfo: { identifier: deviceId }, + destroyDebugSocket: async () => {}, + }, + {}, + {}, + { + start: async () => ({ [deviceId]: [{ deviceId, pid }] }), + stop: async () => ({}), + apps: async () => ({}), + }, + { justlaunch: true }, + new Proxy({}, { get: () => () => {} }), + { + spawn: (command: string, args: string[]) => { + spawned.push([command, ...args]); + return { + on: () => {}, + stdout: lldbOutput, + stdin: { + write: (text: string) => lldbInput.push(text), + end: () => {}, + }, + }; + }, + }, + ); + return { manager, lldbInput, lldbOutput, spawned }; + }; + + it("attaches lldb to an app that waits for the JS debugger", async () => { + const { manager, lldbInput, spawned } = setup(42); + + await manager.restartApplication({ ...appData, waitForDebugger: true }); + + assert.deepEqual(spawned, [["xcrun", "lldb"]]); + assert.include(lldbInput[0], `device select ${deviceId}`); + assert.include(lldbInput[0], "device process attach -p 42"); + }); + + it("continues the app once, after the attach stopped it", async () => { + const { manager, lldbInput, lldbOutput } = setup(42); + + await manager.restartApplication({ ...appData, waitForDebugger: true }); + assert.lengthOf(lldbInput, 1); + + lldbOutput.emit("data", Buffer.from("Process 42 sto")); + assert.lengthOf(lldbInput, 1); + lldbOutput.emit("data", Buffer.from("pped\n")); + lldbOutput.emit("data", Buffer.from("Process 42 stopped\n")); + + assert.deepEqual(lldbInput.slice(1), ["process continue\n"]); + }); + + 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({ ...appData, waitForDebugger: true }); + + assert.deepEqual(spawned, []); + }); + + it("detaches when the app stops", async () => { + const { manager, lldbInput } = setup(42); + + await manager.restartApplication({ ...appData, waitForDebugger: true }); + await manager.stopApplication(appData); + + assert.include(lldbInput[lldbInput.length - 1], "process detach"); + }); +}); From 57088a278b6a4ec4d18212a2e106ab472a72b436 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sun, 15 Nov 2026 19:25:49 -0800 Subject: [PATCH 2/4] refactor(ios): type the pid ios-device-lib reports for a started app ios-device-lib 0.10.0 types the start response with the pid, so the application manager can read it without casting the result to any. --- lib/common/definitions/mobile.d.ts | 2 +- lib/common/mobile/ios/device/ios-application-manager.ts | 2 +- lib/common/mobile/ios/device/ios-device-operations.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) 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 789f64575e..5dcba00ee0 100644 --- a/lib/common/mobile/ios/device/ios-application-manager.ts +++ b/lib/common/mobile/ios/device/ios-application-manager.ts @@ -189,7 +189,7 @@ export class IOSApplicationManager extends ApplicationManagerBase { }, ]); - const pid: number = (result?.[deviceId]?.[0])?.pid; + const pid = result?.[deviceId]?.[0]?.pid; if (appData.waitForDebugger && pid > 0) { this.attachNativeDebugger(appData.appId, pid); } 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, ); From cfe01ccbe0fb060b0a09eaa726c6ba944f2348c9 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sun, 15 Nov 2026 19:25:49 -0800 Subject: [PATCH 3/4] fix(ios): keep the lldb attached for debug-brk from leaving the app stopped The app was only continued after lldb printed "Process N stopped" on stdout, so any other output left it stopped for good while lldb kept the watchdog away. The stop is now also looked for on stderr, and the app is continued after a timeout if it never shows up. lldb ran in the CLI's process group, so Ctrl-C reached it and stopped the app. It now runs detached and still exits when the CLI closes its stdin. Stopping the app no longer races lldb's detach: the CLI waits for lldb to exit (killing it after a short timeout) before stopping or relaunching the app, so lldb can't intercept the termination signal. A launch that doesn't wait for a debugger also detaches an lldb left from an earlier debug-brk launch, and a broken pipe to lldb is only traced. --- .../ios/device/ios-application-manager.ts | 94 +++++-- .../mobile/ios-application-manager.ts | 234 +++++++++++++++--- 2 files changed, 269 insertions(+), 59 deletions(-) diff --git a/lib/common/mobile/ios/device/ios-application-manager.ts b/lib/common/mobile/ios/device/ios-application-manager.ts index 5dcba00ee0..2ae4af5a82 100644 --- a/lib/common/mobile/ios/device/ios-application-manager.ts +++ b/lib/common/mobile/ios/device/ios-application-manager.ts @@ -14,6 +14,9 @@ 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 = {}; @@ -122,7 +125,7 @@ export class IOSApplicationManager extends ApplicationManagerBase { const { appId } = appData; await this.device.destroyDebugSocket(appId); - this.detachNativeDebugger(appId); + await this.detachNativeDebugger(appId); const action = () => this.$iosDeviceOperations.stop([ @@ -178,6 +181,8 @@ 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(); const result = await this.$iosDeviceOperations.start([ @@ -197,41 +202,84 @@ export class IOSApplicationManager extends ApplicationManagerBase { // 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. lldb only knows about devices since Xcode 16; without it the wait - // is just limited to those 20 seconds. + // 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 { - this.detachNativeDebugger(appId); - - const lldb = this.$childProcess.spawn("xcrun", ["lldb"]); + // 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); }); - // Attaching stops the app. It can only be continued once that has happened, - // and until then it can't answer the JS debugger's attach request. - let output = ""; - lldb.stdout?.on("data", (data: Buffer) => { - this.$logger.trace(`${data}`); - if (output !== null) { + 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; - if (/Process \d+ stopped/.test(output)) { - output = null; - lldb.stdin?.write("process continue\n"); + const state = /Process \d+ (stopped|resuming)/.exec(output)?.[1]; + if (state) { + done(); + if (state === "stopped") { + continueApp(); + } } - } - }); - lldb.stderr?.on("data", (data: Buffer) => this.$logger.trace(`${data}`)); + }); + }; + watch(lldb.stdout); + watch(lldb.stderr); + lldb.stdin?.write( `device select ${this.device.deviceInfo.identifier}\ndevice process attach -p ${pid}\n` ); } - private detachNativeDebugger(appId: string): void { + // 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) { - delete this.lldbProcesses[appId]; - lldb.stdin?.write("process detach\nquit\n"); - lldb.stdin?.end(); + if (!lldb) { + return; + } + delete this.lldbProcesses[appId]; + + if (lldb.pid && lldb.exitCode === null && lldb.signalCode === null) { + let timer: NodeJS.Timeout; + await new Promise((resolve) => { + timer = setTimeout(() => { + this.$logger.trace("lldb did not exit in time, killing it"); + lldb.kill(); + resolve(); + }, IOSApplicationManager.LLDB_EXIT_TIMEOUT); + lldb.once("exit", () => resolve()); + lldb.stdin?.end("process detach\nquit\n"); + }); + clearTimeout(timer); } } diff --git a/lib/common/test/unit-tests/mobile/ios-application-manager.ts b/lib/common/test/unit-tests/mobile/ios-application-manager.ts index bc6d95155a..4a596773d4 100644 --- a/lib/common/test/unit-tests/mobile/ios-application-manager.ts +++ b/lib/common/test/unit-tests/mobile/ios-application-manager.ts @@ -1,15 +1,65 @@ 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 killed = false; + 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[], + ) { + super(); + } + + public kill() { + this.killed = true; + 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) => { - const lldbInput: string[] = []; - const lldbOutput = new EventEmitter(); - const spawned: string[][] = []; + const setup = (pid?: number, lldbExitsOnEnd = true) => { + const events: string[] = []; + const lldbs: FakeLldb[] = []; + const spawned: { args: string[]; options: any }[] = []; const manager = new (IOSApplicationManager)( { trace: () => {}, info: () => {} }, {}, @@ -20,51 +70,131 @@ describe("IOSApplicationManager native debugger", () => { {}, {}, { - start: async () => ({ [deviceId]: [{ deviceId, pid }] }), - stop: async () => ({}), - apps: 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[]) => { - spawned.push([command, ...args]); - return { - on: () => {}, - stdout: lldbOutput, - stdin: { - write: (text: string) => lldbInput.push(text), - end: () => {}, - }, - }; + spawn: (command: string, args: string[], options: any) => { + spawned.push({ args: [command, ...args], options }); + const lldb = new FakeLldb(lldbExitsOnEnd, events); + lldbs.push(lldb); + return lldb; }, }, ); - return { manager, lldbInput, lldbOutput, spawned }; + 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, lldbInput, spawned } = setup(42); + const { manager, lldbs, spawned } = setup(42); - await manager.restartApplication({ ...appData, waitForDebugger: true }); + await manager.restartApplication(debugBrk); - assert.deepEqual(spawned, [["xcrun", "lldb"]]); - assert.include(lldbInput[0], `device select ${deviceId}`); - assert.include(lldbInput[0], "device process attach -p 42"); + 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 () => { - const { manager, lldbInput, lldbOutput } = setup(42); + 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({ ...appData, waitForDebugger: true }); - assert.lengthOf(lldbInput, 1); + 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")); - lldbOutput.emit("data", Buffer.from("Process 42 sto")); - assert.lengthOf(lldbInput, 1); - lldbOutput.emit("data", Buffer.from("pped\n")); - lldbOutput.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(lldbInput.slice(1), ["process continue\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 () => { @@ -78,17 +208,49 @@ describe("IOSApplicationManager native debugger", () => { it("doesn't attach without a process id", async () => { const { manager, spawned } = setup(-1); - await manager.restartApplication({ ...appData, waitForDebugger: true }); + await manager.restartApplication(debugBrk); assert.deepEqual(spawned, []); }); - it("detaches when the app stops", async () => { - const { manager, lldbInput } = setup(42); + it("detaches before stopping the app", async () => { + const { manager, lldbs, events } = setup(42); - await manager.restartApplication({ ...appData, waitForDebugger: true }); + await manager.restartApplication(debugBrk); + events.length = 0; await manager.stopApplication(appData); - assert.include(lldbInput[lldbInput.length - 1], "process detach"); + assert.include(lldbs[0].input[lldbs[0].input.length - 1], "process detach"); + assert.deepEqual(events, ["lldb exit", "stop"]); + assert.isFalse(lldbs[0].killed); + }); + + 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.isTrue(lldbs[0].killed); + assert.deepEqual(events, ["lldb exit", "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); }); }); From 89c774f70adea6228e8ca90ba04fe3c75c894f66 Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Sun, 15 Nov 2026 19:38:39 -0800 Subject: [PATCH 4/4] fix(ios): wait for lldb to exit after killing it before stopping the app kill() only sends the signal, so an lldb that outlived its detach could still be attached when the app was stopped, and intercept the stop. The CLI now waits for the exit after SIGTERM too, escalates to SIGKILL, and gives up after a bounded time so a stuck lldb can't block the stop. --- .../ios/device/ios-application-manager.ts | 40 +++++++++++---- .../mobile/ios-application-manager.ts | 50 ++++++++++++++++--- 2 files changed, 71 insertions(+), 19 deletions(-) diff --git a/lib/common/mobile/ios/device/ios-application-manager.ts b/lib/common/mobile/ios/device/ios-application-manager.ts index 2ae4af5a82..6293033b83 100644 --- a/lib/common/mobile/ios/device/ios-application-manager.ts +++ b/lib/common/mobile/ios/device/ios-application-manager.ts @@ -269,20 +269,38 @@ export class IOSApplicationManager extends ApplicationManagerBase { delete this.lldbProcesses[appId]; if (lldb.pid && lldb.exitCode === null && lldb.signalCode === null) { - let timer: NodeJS.Timeout; - await new Promise((resolve) => { - timer = setTimeout(() => { - this.$logger.trace("lldb did not exit in time, killing it"); - lldb.kill(); - resolve(); - }, IOSApplicationManager.LLDB_EXIT_TIMEOUT); - lldb.once("exit", () => resolve()); - lldb.stdin?.end("process detach\nquit\n"); - }); - clearTimeout(timer); + 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() private async startDeviceLog(): Promise { await this.device.openDeviceLogStream(); diff --git a/lib/common/test/unit-tests/mobile/ios-application-manager.ts b/lib/common/test/unit-tests/mobile/ios-application-manager.ts index 4a596773d4..db5e47582c 100644 --- a/lib/common/test/unit-tests/mobile/ios-application-manager.ts +++ b/lib/common/test/unit-tests/mobile/ios-application-manager.ts @@ -8,7 +8,7 @@ class FakeLldb extends EventEmitter { public input: string[] = []; public exitCode: number = null; public signalCode: string = null; - public killed = false; + public signals: string[] = []; public stdout = new EventEmitter(); public stderr = new EventEmitter(); public stdin = Object.assign(new EventEmitter(), { @@ -29,13 +29,16 @@ class FakeLldb extends EventEmitter { constructor( private exitsOnEnd: boolean, private events: string[], + private exitsOnSignals: string[], ) { super(); } - public kill() { - this.killed = true; - this.exit(); + public kill(signal: string) { + this.signals.push(signal); + if (this.exitsOnSignals.includes(signal)) { + setImmediate(() => this.exit()); + } } private exit() { @@ -56,7 +59,11 @@ describe("IOSApplicationManager native debugger", () => { clock = undefined; }); - const setup = (pid?: number, lldbExitsOnEnd = true) => { + const setup = ( + pid?: number, + lldbExitsOnEnd = true, + lldbExitsOnSignals = ["SIGTERM", "SIGKILL"], + ) => { const events: string[] = []; const lldbs: FakeLldb[] = []; const spawned: { args: string[]; options: any }[] = []; @@ -87,7 +94,7 @@ describe("IOSApplicationManager native debugger", () => { { spawn: (command: string, args: string[], options: any) => { spawned.push({ args: [command, ...args], options }); - const lldb = new FakeLldb(lldbExitsOnEnd, events); + const lldb = new FakeLldb(lldbExitsOnEnd, events, lldbExitsOnSignals); lldbs.push(lldb); return lldb; }, @@ -222,7 +229,7 @@ describe("IOSApplicationManager native debugger", () => { assert.include(lldbs[0].input[lldbs[0].input.length - 1], "process detach"); assert.deepEqual(events, ["lldb exit", "stop"]); - assert.isFalse(lldbs[0].killed); + assert.deepEqual(lldbs[0].signals, []); }); it("kills lldb when it doesn't exit after detaching", async () => { @@ -238,10 +245,37 @@ describe("IOSApplicationManager native debugger", () => { await clock.tickAsync(60000); await stopped; - assert.isTrue(lldbs[0].killed); + 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);