Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/common/definitions/mobile.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1359,7 +1359,7 @@ declare global {
start(
startArray: IOSDeviceLib.IIOSApplicationData[],
errorHandler?: DeviceOperationErrorHandler,
): Promise<IOSDeviceResponse>;
): Promise<IDictionary<IOSDeviceLib.IStartApplicationResponse[]>>;

stop(
stopArray: IOSDeviceLib.IIOSApplicationData[],
Expand Down
123 changes: 120 additions & 3 deletions lib/common/mobile/ios/device/ios-application-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,21 @@ 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,
IDictionary,
} 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<ChildProcess> = {};

constructor(
protected $logger: ILogger,
Expand All @@ -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);
}
Expand Down Expand Up @@ -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([
Expand Down Expand Up @@ -173,15 +181,124 @@ export class IOSApplicationManager extends ApplicationManagerBase {
private async runApplicationCore(
appData: Mobile.IStartApplicationData
): Promise<void> {
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<void> {
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<void>((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<void>,
ms: number
): Promise<boolean> {
let timer: NodeJS.Timeout;
const timeout = new Promise<boolean>((resolve) => {
timer = setTimeout(() => resolve(false), ms);
});
const result = await Promise.race([exited.then(() => true), timeout]);
clearTimeout(timer);
return result;
}

@cache()
Expand Down
4 changes: 2 additions & 2 deletions lib/common/mobile/ios/device/ios-device-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ export class IOSDeviceOperations
public async start(
startArray: IOSDeviceLib.IDdiApplicationData[],
errorHandler?: DeviceOperationErrorHandler,
): Promise<IOSDeviceResponse> {
): Promise<IDictionary<IOSDeviceLib.IStartApplicationResponse[]>> {
this.assertIsInitialized();

_.each(startArray, (s) => {
Expand All @@ -236,7 +236,7 @@ export class IOSDeviceOperations
);
});

return this.getMultipleResults<IOSDeviceLib.IDeviceResponse>(
return this.getMultipleResults<IOSDeviceLib.IStartApplicationResponse>(
() => this.deviceLib.start(startArray),
errorHandler,
);
Expand Down
Loading
Loading