Skip to content

Commit f38f45a

Browse files
committed
fix(ios): keep Mac relaunches working after a sync
Syncing writes into the signed bundle, which breaks its seal, and macOS won't launch it. Before each launch the CLI now runs `codesign --verify --strict` and, if that fails, re-signs the bundle with the leaf certificate from its own embedded signature, keeping the identifier, entitlements, flags and runtime. macOS also only launches an iOS app whose code matches the CDHashes LaunchServices recorded for it. A launch right after the bundle changes can race LaunchServices' re-registration, use the stale record and fail with "Launch Constraint Violation" (POSIX 162), so the wrapper is registered with `lsregister -f` before every launch. Also: - Only stop processes whose Info.plist names this app, so other iPad apps with the same executable name are left alone. - Read `log stream` output line by line, so the debugger port line is never split across chunks. - `ns device list-files` prints the Mac's entries. - Mac discovery honours the `deviceId` passed to DevicesService. - Warn that --i-cloud-container-environment has no effect on a Mac build, which isn't archived and exported.
1 parent 7b46221 commit f38f45a

10 files changed

Lines changed: 362 additions & 26 deletions

File tree

‎lib/common/definitions/mobile.d.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1212,6 +1212,10 @@ declare global {
12121212
shouldReturnImmediateResult: boolean;
12131213
platform: string;
12141214
fullDiscovery?: boolean;
1215+
/**
1216+
* The device requested by index, identifier or name, if any.
1217+
*/
1218+
deviceId?: string;
12151219
/**
12161220
* Ends the wait for physical devices once the device requested on the
12171221
* command line has been found by any discovery.

‎lib/common/mobile/ios/mac/ios-mac-application-manager.ts‎

Lines changed: 127 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as crypto from "crypto";
12
import * as path from "path";
23
import { ApplicationManagerBase } from "../../application-manager-base";
34
import { hook, sleep } from "../../../helpers";
@@ -11,6 +12,10 @@ import {
1112
IPlistParser,
1213
} from "../../../declarations";
1314
import { IOptions } from "../../../../declarations";
15+
import { ITempService } from "../../../../definitions/temp-service";
16+
17+
const LSREGISTER_PATH =
18+
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
1419

1520
interface IIOSMacApplicationHost extends Mobile.IiOSDevice {
1621
readonly wrapperPath: string;
@@ -25,6 +30,7 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
2530
private $fs: IFileSystem,
2631
private $options: IOptions,
2732
private $plistParser: IPlistParser,
33+
private $tempService: ITempService,
2834
protected $deviceLogProvider: Mobile.IDeviceLogProvider,
2935
$logger: ILogger,
3036
$hooksService: IHooksService,
@@ -76,14 +82,16 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
7682
appData: Mobile.IStartApplicationData,
7783
): Promise<void> {
7884
await this.setDeviceLogData(appData);
85+
await this.restoreCodeSignature();
86+
await this.registerWithLaunchServices();
7987

8088
const args = ["-n", this.device.wrapperPath];
8189
if (appData.waitForDebugger) {
8290
args.push("--args", "--nativescript-debug-brk");
8391
}
8492
await this.$childProcess.spawnFromEvent("open", args, "close");
8593

86-
const [pid] = await this.getRunningPids();
94+
const [pid] = await this.getRunningPids(appData.appId);
8795
if (pid) {
8896
this.$deviceLogProvider.setApplicationPidForDevice(
8997
this.device.deviceInfo.identifier,
@@ -98,7 +106,7 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
98106
await this.device.destroyDebugSocket(appData.appId);
99107

100108
for (const signal of ["TERM", "KILL"]) {
101-
const pids = await this.getRunningPids();
109+
const pids = await this.getRunningPids(appData.appId);
102110
if (!pids.length) {
103111
return;
104112
}
@@ -109,7 +117,7 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
109117

110118
// `open -n` while the old instance is still exiting starts a second copy.
111119
for (let attempt = 0; attempt < 40; attempt++) {
112-
if (!(await this.getRunningPids()).length) {
120+
if (!(await this.getRunningPids(appData.appId)).length) {
113121
return;
114122
}
115123
await sleep(50);
@@ -129,25 +137,133 @@ export class IOSMacApplicationManager extends ApplicationManagerBase {
129137
return null;
130138
}
131139

140+
/**
141+
* Syncing writes into the signed bundle and breaks its seal, and macOS won't
142+
* launch a bundle whose seal is broken. The signature embedded in the
143+
* executable survives the sync, so its leaf certificate names the identity
144+
* to re-sign with.
145+
*/
146+
private async restoreCodeSignature(): Promise<void> {
147+
const bundlePath = this.device.applicationBundlePath;
148+
const verify = await this.$childProcess.spawnFromEvent(
149+
"codesign",
150+
["--verify", "--strict", bundlePath],
151+
"close",
152+
{},
153+
{ throwError: false },
154+
);
155+
if (verify.exitCode === 0) {
156+
return;
157+
}
158+
159+
try {
160+
const certificatesPrefix = path.join(
161+
await this.$tempService.mkdirSync("ios-mac-codesign"),
162+
"certificate",
163+
);
164+
await this.$childProcess.spawnFromEvent(
165+
"codesign",
166+
["-d", `--extract-certificates=${certificatesPrefix}`, bundlePath],
167+
"close",
168+
);
169+
const leafCertificatePath = `${certificatesPrefix}0`;
170+
if (!this.$fs.exists(leafCertificatePath)) {
171+
this.$logger.warn(
172+
`${bundlePath} has no signing certificate to re-sign it with. Rebuild the app if macOS refuses to launch it.`,
173+
);
174+
return;
175+
}
176+
177+
const identity = crypto
178+
.createHash("sha1")
179+
.update(this.$fs.readFile(leafCertificatePath))
180+
.digest("hex");
181+
await this.$childProcess.spawnFromEvent(
182+
"codesign",
183+
[
184+
"--force",
185+
"--sign",
186+
identity,
187+
"--preserve-metadata=identifier,entitlements,flags,runtime",
188+
bundlePath,
189+
],
190+
"close",
191+
);
192+
} catch (err) {
193+
this.$logger.warn(
194+
`Unable to re-sign ${bundlePath}: ${err.message}. Rebuild the app if macOS refuses to launch it.`,
195+
);
196+
}
197+
}
198+
199+
/**
200+
* macOS only launches an iOS app whose code matches the CDHashes
201+
* LaunchServices recorded for it. Once the bundle changes, the launch can
202+
* race LaunchServices' own re-registration, use the stale record and fail
203+
* with "Launch Constraint Violation", so register it before every launch.
204+
*/
205+
private async registerWithLaunchServices(): Promise<void> {
206+
const result = await this.$childProcess.spawnFromEvent(
207+
LSREGISTER_PATH,
208+
["-f", this.device.wrapperPath],
209+
"close",
210+
{},
211+
{ throwError: false },
212+
);
213+
if (result.exitCode !== 0) {
214+
this.$logger.trace(
215+
`Unable to register ${this.device.wrapperPath} with LaunchServices: ${result.stderr}`,
216+
);
217+
}
218+
}
219+
132220
/**
133221
* macOS runs the app from a copy of the wrapper under /private/var/folders,
134222
* so match the bundle layout rather than the path the CLI installed to.
223+
* Other iPad apps can share the executable name, so each match's
224+
* Info.plist must also name this app.
135225
*/
136-
private async getRunningPids(): Promise<string[]> {
226+
private async getRunningPids(appId: string): Promise<string[]> {
137227
const name = this.device.executableName.replace(
138228
/[.*+?^${}()|[\]\\]/g,
139229
"\\$&",
140230
);
231+
const processPattern = `/Wrapper/${name}\\.app/${name}( |$)`;
232+
const result = await this.$childProcess.spawnFromEvent(
233+
"pgrep",
234+
["-lf", processPattern],
235+
"close",
236+
{},
237+
// pgrep exits with 1 when nothing matches.
238+
{ throwError: false },
239+
);
240+
241+
const bundlePattern = new RegExp(
242+
`^(\\d+) (.*/Wrapper/${name}\\.app)/${name}(?: |$)`,
243+
);
244+
const pids: string[] = [];
245+
for (const line of (result.stdout || "").split("\n")) {
246+
const match = bundlePattern.exec(line);
247+
if (match && (await this.isBundleOf(match[2], appId))) {
248+
pids.push(match[1]);
249+
}
250+
}
251+
252+
return pids;
253+
}
254+
255+
private async isBundleOf(
256+
bundlePath: string,
257+
appId: string,
258+
): Promise<boolean> {
141259
try {
142-
const result = await this.$childProcess.spawnFromEvent(
143-
"pgrep",
144-
["-f", `/Wrapper/${name}\\.app/${name}( |$)`],
145-
"close",
260+
const infoPlist = await this.$plistParser.parseFile(
261+
path.join(bundlePath, "Info.plist"),
146262
);
147-
return result.stdout.split(/\s+/).filter(Boolean);
263+
return infoPlist?.CFBundleIdentifier === appId;
148264
} catch (err) {
149-
// pgrep exits with 1 when nothing matches.
150-
return [];
265+
this.$logger.trace(`Unable to read the Info.plist of ${bundlePath}`, err);
266+
return false;
151267
}
152268
}
153269

‎lib/common/mobile/ios/mac/ios-mac-device.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ChildProcess } from "child_process";
22
import * as net from "net";
33
import * as path from "path";
4+
import * as readline from "readline";
45
import { IOSDeviceBase } from "../ios-device-base";
56
import { IOSMacApplicationManager } from "./ios-mac-application-manager";
67
import { IOSMacFileSystem } from "./ios-mac-file-system";
@@ -129,15 +130,20 @@ export class IOSMacDevice extends IOSDeviceBase {
129130
predicate ? `${processPredicate} AND ${predicate}` : processPredicate,
130131
]);
131132

132-
const action = (data: Buffer | string) => {
133-
this.$deviceLogProvider.logData(
134-
data.toString(),
135-
this.$devicePlatformsConstants.iOS,
136-
this.deviceInfo.identifier,
137-
);
138-
};
139-
this.logProcess.stdout?.on("data", action);
140-
this.logProcess.stderr?.on("data", action);
133+
// The debugger port is parsed from a single log line, so chunks must be
134+
// reassembled into lines first. IOSLogFilter holds back text without a
135+
// trailing newline as a partial line, so the newline is put back.
136+
for (const stream of [this.logProcess.stdout, this.logProcess.stderr]) {
137+
if (stream) {
138+
readline.createInterface({ input: stream }).on("line", (line) =>
139+
this.$deviceLogProvider.logData(
140+
`${line}\n`,
141+
this.$devicePlatformsConstants.iOS,
142+
this.deviceInfo.identifier,
143+
),
144+
);
145+
}
146+
}
141147
this.logProcess.once("error", (err) =>
142148
this.$logger.trace(`Unable to stream the Mac log: ${err.message}`),
143149
);

‎lib/common/mobile/ios/mac/ios-mac-file-system.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import * as fs from "fs";
1+
import { EOL } from "os";
22
import { IOSSimulatorFileSystem } from "../simulator/ios-simulator-file-system";
33
import { IFileSystem } from "../../../declarations";
44

@@ -11,7 +11,8 @@ export class IOSMacFileSystem extends IOSSimulatorFileSystem {
1111
super(null, $fs, $logger);
1212
}
1313

14-
public async listFiles(devicePath: string): Promise<any> {
15-
return fs.readdirSync(devicePath);
14+
public async listFiles(devicePath: string): Promise<void> {
15+
this.$logger.info("Listing %s", devicePath);
16+
this.$logger.info(this.$fs.readDirectory(devicePath).join(EOL));
1617
}
1718
}

‎lib/common/mobile/ios/simulator/ios-simulator-file-system.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import { IFileSystem, IStringDictionary } from "../../../declarations";
66
export class IOSSimulatorFileSystem implements Mobile.IDeviceFileSystem {
77
constructor(
88
private iosSim: any,
9-
private $fs: IFileSystem,
10-
private $logger: ILogger
9+
protected $fs: IFileSystem,
10+
protected $logger: ILogger
1111
) {}
1212

1313
public async listFiles(devicePath: string): Promise<void> {

‎lib/common/mobile/mobile-core/devices-service.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,7 @@ export class DevicesService
944944
shouldReturnImmediateResult: deviceInitOpts.shouldReturnImmediateResult,
945945
detectionInterval: deviceInitOpts.detectionInterval,
946946
fullDiscovery: deviceInitOpts.fullDiscovery,
947+
deviceId: deviceOption,
947948
isRequestedDeviceFound: deviceInitOpts.isRequestedDeviceFound,
948949
};
949950

@@ -1221,6 +1222,7 @@ export class DevicesService
12211222
shouldReturnImmediateResult: !!shouldReturnImmediateResult,
12221223
emulator: !!emulator,
12231224
fullDiscovery: deviceInitOpts.fullDiscovery,
1225+
deviceId: deviceInitOpts.deviceId,
12241226
isRequestedDeviceFound: deviceInitOpts.isRequestedDeviceFound,
12251227
};
12261228
}

‎lib/common/mobile/mobile-core/ios-mac-device-discovery.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export class IOSMacDeviceDiscovery extends DeviceDiscovery {
4949
return;
5050
}
5151

52-
const requested = this.$options.device;
52+
const requested = options?.deviceId ?? this.$options.device;
5353
const isRequested =
5454
requested === IOS_MAC_DEVICE_ALIAS ||
5555
requested === hardware.provisioningUDID;

0 commit comments

Comments
 (0)