Skip to content

Commit 313f1c6

Browse files
authored
feat(ios): run iOS apps on an Apple silicon Mac with --device mac (#6205)
1 parent ab19351 commit 313f1c6

26 files changed

Lines changed: 1238 additions & 21 deletions

‎lib/common/bootstrap.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,10 @@ injector.require(
200200
"iOSSimulatorDiscovery",
201201
"./mobile/mobile-core/ios-simulator-discovery",
202202
);
203+
injector.require(
204+
"iOSMacDeviceDiscovery",
205+
"./mobile/mobile-core/ios-mac-device-discovery",
206+
);
203207
injector.require(
204208
"androidDeviceDiscovery",
205209
"./mobile/mobile-core/android-device-discovery",

‎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.
Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
import * as crypto from "crypto";
2+
import * as path from "path";
3+
import { ApplicationManagerBase } from "../../application-manager-base";
4+
import { hook, sleep } from "../../../helpers";
5+
import { cache } from "../../../decorators";
6+
import { IOS_LOG_PREDICATE } from "../../../constants";
7+
import {
8+
IChildProcess,
9+
IDictionary,
10+
IFileSystem,
11+
IHooksService,
12+
IPlistParser,
13+
} from "../../../declarations";
14+
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";
19+
20+
interface IIOSMacApplicationHost extends Mobile.IiOSDevice {
21+
readonly wrapperPath: string;
22+
readonly applicationBundlePath: string;
23+
readonly executableName: string;
24+
}
25+
26+
export class IOSMacApplicationManager extends ApplicationManagerBase {
27+
constructor(
28+
private device: IIOSMacApplicationHost,
29+
private $childProcess: IChildProcess,
30+
private $fs: IFileSystem,
31+
private $options: IOptions,
32+
private $plistParser: IPlistParser,
33+
private $tempService: ITempService,
34+
protected $deviceLogProvider: Mobile.IDeviceLogProvider,
35+
$logger: ILogger,
36+
$hooksService: IHooksService,
37+
) {
38+
super($logger, $hooksService, $deviceLogProvider);
39+
}
40+
41+
public async getInstalledApplications(): Promise<string[]> {
42+
const infoPlistPath = path.join(
43+
this.device.applicationBundlePath,
44+
"Info.plist",
45+
);
46+
if (!this.$fs.exists(infoPlistPath)) {
47+
return [];
48+
}
49+
50+
const infoPlist = await this.$plistParser.parseFile(infoPlistPath);
51+
return infoPlist?.CFBundleIdentifier ? [infoPlist.CFBundleIdentifier] : [];
52+
}
53+
54+
@hook("install")
55+
public async installApplication(packageFilePath: string): Promise<void> {
56+
const wrapperPath = this.device.wrapperPath;
57+
this.$fs.deleteDirectory(wrapperPath);
58+
this.$fs.ensureDirectoryExists(path.join(wrapperPath, "Wrapper"));
59+
// ditto keeps the bundle's symlinks and extended attributes, which its
60+
// code signature covers.
61+
await this.$childProcess.spawnFromEvent(
62+
"ditto",
63+
[packageFilePath, this.device.applicationBundlePath],
64+
"close",
65+
);
66+
this.$fs.symlink(
67+
path.join("Wrapper", path.basename(this.device.applicationBundlePath)),
68+
path.join(wrapperPath, "WrappedBundle"),
69+
);
70+
}
71+
72+
public async uninstallApplication(appIdentifier: string): Promise<void> {
73+
await this.stopApplication({
74+
appId: appIdentifier,
75+
projectName: null,
76+
projectDir: null,
77+
});
78+
this.$fs.deleteDirectory(this.device.wrapperPath);
79+
}
80+
81+
public async startApplication(
82+
appData: Mobile.IStartApplicationData,
83+
): Promise<void> {
84+
await this.setDeviceLogData(appData);
85+
await this.restoreCodeSignature();
86+
await this.registerWithLaunchServices();
87+
88+
const args = ["-n", this.device.wrapperPath];
89+
if (appData.waitForDebugger) {
90+
args.push("--args", "--nativescript-debug-brk");
91+
}
92+
await this.$childProcess.spawnFromEvent("open", args, "close");
93+
94+
const [pid] = await this.getRunningPids(appData.appId);
95+
if (pid) {
96+
this.$deviceLogProvider.setApplicationPidForDevice(
97+
this.device.deviceInfo.identifier,
98+
pid,
99+
);
100+
}
101+
}
102+
103+
public async stopApplication(
104+
appData: Mobile.IApplicationData,
105+
): Promise<void> {
106+
await this.device.destroyDebugSocket(appData.appId);
107+
108+
for (const signal of ["TERM", "KILL"]) {
109+
const pids = await this.getRunningPids(appData.appId);
110+
if (!pids.length) {
111+
return;
112+
}
113+
114+
await this.$childProcess
115+
.spawnFromEvent("kill", [`-${signal}`, ...pids], "close")
116+
.catch((err) => this.$logger.trace(err));
117+
118+
// `open -n` while the old instance is still exiting starts a second copy.
119+
for (let attempt = 0; attempt < 40; attempt++) {
120+
if (!(await this.getRunningPids(appData.appId)).length) {
121+
return;
122+
}
123+
await sleep(50);
124+
}
125+
}
126+
}
127+
128+
public async getDebuggableApps(): Promise<
129+
Mobile.IDeviceApplicationInformation[]
130+
> {
131+
return [];
132+
}
133+
134+
public async getDebuggableAppViews(
135+
appIdentifiers: string[],
136+
): Promise<IDictionary<Mobile.IDebugWebViewInfo[]>> {
137+
return null;
138+
}
139+
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+
220+
/**
221+
* macOS runs the app from a copy of the wrapper under /private/var/folders,
222+
* 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.
225+
*/
226+
private async getRunningPids(appId: string): Promise<string[]> {
227+
const name = this.device.executableName.replace(
228+
/[.*+?^${}()|[\]\\]/g,
229+
"\\$&",
230+
);
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> {
259+
try {
260+
const infoPlist = await this.$plistParser.parseFile(
261+
path.join(bundlePath, "Info.plist"),
262+
);
263+
return infoPlist?.CFBundleIdentifier === appId;
264+
} catch (err) {
265+
this.$logger.trace(`Unable to read the Info.plist of ${bundlePath}`, err);
266+
return false;
267+
}
268+
}
269+
270+
private async setDeviceLogData(
271+
appData: Mobile.IApplicationData,
272+
): Promise<void> {
273+
this.$deviceLogProvider.setProjectNameForDevice(
274+
this.device.deviceInfo.identifier,
275+
appData.projectName,
276+
);
277+
this.$deviceLogProvider.setProjectDirForDevice(
278+
this.device.deviceInfo.identifier,
279+
appData.projectDir,
280+
);
281+
282+
if (!this.$options.justlaunch) {
283+
await this.startDeviceLog();
284+
}
285+
}
286+
287+
@cache()
288+
private startDeviceLog(): Promise<void> {
289+
return this.device.openDeviceLogStream({ predicate: IOS_LOG_PREDICATE });
290+
}
291+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import * as semver from "semver";
2+
3+
/**
4+
* `--device mac` selects this Mac; it is also the device's imageIdentifier.
5+
*/
6+
export const IOS_MAC_DEVICE_ALIAS = "mac";
7+
8+
export const IOS_MAC_DEVICE_DISPLAY_NAME = "My Mac (Designed for iPad)";
9+
10+
/**
11+
* Mac builds get their own folder under DerivedData's Build/Products. They use
12+
* the iphoneos SDK like phone builds, and .nsbuildinfo only records prepare
13+
* time, so a shared <Config>-iphoneos folder would let switching between a
14+
* phone and the Mac skip the build and install the other target's app.
15+
*/
16+
export const IOS_MAC_BUILD_DIR_NAME = "mac";
17+
18+
export function isIOSMacDevice(device: Mobile.IDevice): boolean {
19+
return device?.deviceInfo?.imageIdentifier === IOS_MAC_DEVICE_ALIAS;
20+
}
21+
22+
/**
23+
* Whether this @nativescript/ios version loads UIKit from /System/iOSSupport
24+
* on a Mac (NativeScript/ios#551). Older runtimes stop at launch with
25+
* "UIApplicationDidFinishLaunchingNotification is not defined".
26+
* Returns true for versions it can't parse, so only a known-bad one warns.
27+
*/
28+
export function iOSRuntimeCanRunOnMac(version: string): boolean {
29+
const next = /^\d+\.\d+\.\d+-next\.(\d{4}-\d{2}-\d{2})-(\d+)$/.exec(
30+
version ?? "",
31+
);
32+
if (next) {
33+
const [, date, runId] = next;
34+
const firstDate = "2026-11-11";
35+
const firstRunId = 43080423883;
36+
return date > firstDate || (date === firstDate && +runId >= firstRunId);
37+
}
38+
39+
if (!semver.valid(version)) {
40+
return true;
41+
}
42+
43+
return semver.gte(version, "9.1.1");
44+
}

0 commit comments

Comments
 (0)