Skip to content

Commit 8f14569

Browse files
committed
fix(ios): budget the xcrun shim probe like other cold toolchain probes and type why a shim is armed
- The probe spends COLD_TOOLCHAIN_PROBE_TIMEOUT_MS, the budget sized for the first-exec xcrun stall, instead of its own 2 s, and it follows the request's abort signal, so a canceled build or session gives the device-set lock back as a cancellation. - XCRUN_TOOLS carries a firstLaunchShim trait per tool; only simctl and devicectl are probed. - Each armed entry in details.xcrunShims carries armedBy (version_mismatch, version_unreadable, shim_unreadable, shim_not_located, probe_out_of_budget, probe_canceled), and the message follows it. - One shared fake-shim fixture, built on the captured Xcode 26.2 simctl shim, serves the core and runner tests and the startup-failure fixture table.
1 parent 957bb81 commit 8f14569

18 files changed

Lines changed: 551 additions & 455 deletions
Lines changed: 151 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import assert from 'node:assert/strict';
2-
import fs from 'node:fs';
32
import path from 'node:path';
43
import { afterEach, test, vi } from 'vitest';
5-
import type { ExecResult } from '@agent-device/host-kit/command';
4+
import type { ExecResult, ExecOptions } from '@agent-device/host-kit/command';
5+
import { COLD_TOOLCHAIN_PROBE_TIMEOUT_MS } from '../../runner/apple-runner-platform.ts';
6+
import { createLocalAppleToolProvider, withAppleToolProvider } from '../tool-provider.ts';
67
import {
7-
createLocalAppleToolProvider,
8-
withAppleToolProvider,
9-
XCRUN_TOOL_NAMES,
10-
type AppleToolCommandExecutor,
11-
} from '../tool-provider.ts';
12-
import { probeXcrunShimFirstLaunchHooks } from '../xcrun-shim-first-launch.ts';
8+
probeXcrunShimFirstLaunchHooks,
9+
XCRUN_SHIM_TOOL_NAMES,
10+
} from '../xcrun-shim-first-launch.ts';
1311
import { mkdtempForTest } from '../../__tests__/tmp-dir.ts';
12+
import {
13+
fakeFrameworkInfoPlistPath,
14+
hookedShimText,
15+
withFakeXcrunHost,
16+
writeFakeXcrunShims,
17+
} from './xcrun-shim-fixtures.ts';
1418

1519
afterEach(() => {
1620
vi.restoreAllMocks();
@@ -20,152 +24,180 @@ async function tempRoot(): Promise<string> {
2024
return await mkdtempForTest('xcrun-shim-first-launch-');
2125
}
2226

23-
function writeFile(root: string, name: string, text: string | Buffer): string {
24-
const filePath = path.join(root, name);
25-
fs.writeFileSync(filePath, text);
26-
return filePath;
27-
}
28-
29-
function hookedShim(expectedVersion: string, infoPlistPath: string): string {
30-
return [
31-
'#!/bin/bash',
32-
`EXPECTED_VERSION="${expectedVersion}"`,
33-
`CURRENT_VERSION="$(/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "${infoPlistPath}" 2>&1)"`,
34-
'if [[ "${EXPECTED_VERSION}" != "${CURRENT_VERSION}" ]]; then',
35-
' "${DEVELOPER_DIR}/usr/bin/xcodebuild" -runFirstLaunch >&2',
36-
'fi',
37-
'',
38-
].join('\n');
39-
}
40-
41-
async function withFakeXcrun<T>(
42-
runCommand: AppleToolCommandExecutor,
43-
plistVersions: Record<string, string>,
44-
task: () => Promise<T>,
45-
): Promise<T> {
46-
const provider = createLocalAppleToolProvider({
47-
runCommand,
48-
plist: {
49-
readJson: async (plistPath) =>
50-
plistPath in plistVersions ? { CFBundleVersion: plistVersions[plistPath] } : null,
51-
},
52-
});
53-
return await withAppleToolProvider(provider, task);
54-
}
55-
56-
function xcrunFind(found: Partial<Record<string, string>>): {
57-
runCommand: AppleToolCommandExecutor;
58-
calls: Array<[string, string[]]>;
59-
} {
60-
const calls: Array<[string, string[]]> = [];
61-
const runCommand: AppleToolCommandExecutor = async (cmd, args): Promise<ExecResult> => {
62-
calls.push([cmd, args]);
63-
const tool = args[1] ?? '';
64-
const shimPath = found[tool];
65-
return shimPath
66-
? { exitCode: 0, stdout: `${shimPath}\n`, stderr: '' }
67-
: { exitCode: 1, stdout: '', stderr: `xcrun: error: unable to find utility "${tool}"` };
68-
};
69-
return { runCommand, calls };
70-
}
71-
72-
test('the probe locates every declared xcrun tool through xcrun --find', async () => {
73-
const { runCommand, calls } = xcrunFind({});
27+
test('only the tools Xcode ships as first-launch shims are probed', async () => {
28+
const host = writeFakeXcrunShims(await tempRoot(), {});
7429

75-
const shims = await withFakeXcrun(runCommand, {}, () => probeXcrunShimFirstLaunchHooks());
30+
const shims = await withFakeXcrunHost(host, () => probeXcrunShimFirstLaunchHooks());
7631

77-
assert.deepEqual(
78-
calls.map(([cmd, args]) => [cmd, ...args]),
79-
XCRUN_TOOL_NAMES.map((tool) => ['xcrun', '--find', tool]),
80-
);
81-
assert.deepEqual(
82-
shims.map((shim) => shim.tool),
83-
[...XCRUN_TOOL_NAMES],
84-
);
32+
assert.deepEqual(XCRUN_SHIM_TOOL_NAMES, ['simctl', 'devicectl']);
33+
assert.deepEqual(host.finds, XCRUN_SHIM_TOOL_NAMES);
8534
for (const shim of shims) {
86-
assert.equal(shim.hook, 'armed', `${shim.tool} was not found, so it cannot be called safe`);
87-
assert.equal(shim.shimPath, null);
35+
assert.deepEqual(
36+
{ hook: shim.hook, shimPath: shim.shimPath },
37+
{ hook: 'armed', shimPath: null },
38+
`${shim.tool} was not found, so it cannot be called safe`,
39+
);
40+
assert.equal(shim.hook === 'armed' && shim.armedBy, 'shim_not_located');
8841
}
8942
});
9043

9144
test('a hooked shim found by xcrun --find is read against the plist its own text names', async () => {
9245
const root = await tempRoot();
9346
const otherPlist = path.join(root, 'Other.framework', 'Info.plist');
94-
const simctl = writeFile(root, 'simctl', hookedShim('1051.17.7', otherPlist));
9547
const machO = Buffer.concat([
9648
Buffer.from([0xcf, 0xfa, 0xed, 0xfe]),
9749
Buffer.from(' -runFirstLaunch'),
9850
]);
99-
const binary = writeFile(root, 'xctrace', machO);
100-
const readJson = vi.fn(async (plistPath: string) =>
101-
plistPath === otherPlist ? { CFBundleVersion: '1155.4' } : null,
102-
);
103-
const { runCommand } = xcrunFind({
104-
simctl,
105-
devicectl: binary,
106-
xcdevice: binary,
107-
xctrace: binary,
51+
const host = writeFakeXcrunShims(root, {
52+
simctl: { text: hookedShimText('1051.17.7', otherPlist) },
53+
devicectl: { text: machO },
10854
});
55+
host.installedVersions.set(otherPlist, '1155.4');
10956

110-
const shims = await withAppleToolProvider(
111-
createLocalAppleToolProvider({ runCommand, plist: { readJson } }),
112-
() => probeXcrunShimFirstLaunchHooks(),
113-
);
57+
const [simctl, devicectl] = await withFakeXcrunHost(host, () => probeXcrunShimFirstLaunchHooks());
11458

115-
assert.deepEqual(
116-
readJson.mock.calls.map(([plistPath]) => plistPath),
117-
[otherPlist],
118-
);
119-
assert.deepEqual(shims[0], {
59+
assert.deepEqual(host.plistReads, [otherPlist]);
60+
assert.deepEqual(simctl, {
12061
tool: 'simctl',
121-
shimPath: simctl,
62+
shimPath: host.xcrunShimPaths.simctl,
12263
hook: 'armed',
64+
armedBy: 'version_mismatch',
12365
expectedVersion: '1051.17.7',
12466
frameworkInfoPlistPath: otherPlist,
12567
installedVersion: '1155.4',
12668
});
127-
for (const shim of shims.slice(1)) {
128-
assert.deepEqual(shim, { tool: shim.tool, shimPath: binary, hook: 'none' });
129-
}
69+
assert.deepEqual(devicectl, {
70+
tool: 'devicectl',
71+
shimPath: host.xcrunShimPaths.devicectl,
72+
hook: 'none',
73+
});
13074
});
13175

13276
test('equal versions disarm a hooked shim', async () => {
133-
const root = await tempRoot();
134-
const plist = path.join(root, 'CoreDevice.framework', 'Info.plist');
135-
const devicectl = writeFile(root, 'devicectl', hookedShim('629.3', plist));
136-
const shimPaths = Object.fromEntries(XCRUN_TOOL_NAMES.map((tool) => [tool, devicectl]));
77+
const host = writeFakeXcrunShims(await tempRoot(), {
78+
simctl: { expectedVersion: '1155.4', installedVersion: '1155.4' },
79+
devicectl: { expectedVersion: '629.3', installedVersion: '629.3' },
80+
});
13781

138-
const shims = await withFakeXcrun(xcrunFind({}).runCommand, { [plist]: '629.3' }, () =>
139-
probeXcrunShimFirstLaunchHooks({ xcrunShimPaths: shimPaths }),
82+
const shims = await withFakeXcrunHost(host, () =>
83+
probeXcrunShimFirstLaunchHooks({ xcrunShimPaths: host.xcrunShimPaths }),
14084
);
14185

142-
for (const shim of shims) {
143-
assert.deepEqual(shim, {
144-
tool: shim.tool,
145-
shimPath: devicectl,
146-
hook: 'disarmed',
147-
expectedVersion: '629.3',
148-
frameworkInfoPlistPath: plist,
149-
installedVersion: '629.3',
150-
});
151-
}
86+
assert.deepEqual(
87+
shims.map((shim) => [shim.tool, shim.hook]),
88+
[
89+
['simctl', 'disarmed'],
90+
['devicectl', 'disarmed'],
91+
],
92+
);
93+
});
94+
95+
test('a shim xcrun found but that cannot be read counts as armed', async () => {
96+
const root = await tempRoot();
97+
const host = writeFakeXcrunShims(root, {
98+
devicectl: { expectedVersion: '629.3', installedVersion: '629.3' },
99+
});
100+
const missing = path.join(root, 'xcrun-shims', 'simctl-removed');
101+
host.xcrunShimPaths.simctl = missing;
102+
103+
const [simctl] = await withFakeXcrunHost(host, () => probeXcrunShimFirstLaunchHooks());
104+
105+
assert.deepEqual(simctl, {
106+
tool: 'simctl',
107+
shimPath: missing,
108+
hook: 'armed',
109+
armedBy: 'shim_unreadable',
110+
expectedVersion: null,
111+
frameworkInfoPlistPath: null,
112+
installedVersion: null,
113+
});
152114
});
153115

154-
test('a probe that outlives its budget reads every unanswered shim as armed', async () => {
116+
// Each shape breaks one value and keeps the rest readable and equal, so the verdict is that value's.
117+
const UNREADABLE_VERSION_SHAPES: Record<string, (plistPath: string) => string> = {
118+
'no EXPECTED_VERSION': (plistPath) =>
119+
hookedShimText('1', plistPath).replace('EXPECTED_VERSION="1"', 'EXPECTED_VERSION='),
120+
'no Info.plist path on the CURRENT_VERSION line': (plistPath) =>
121+
hookedShimText('1', plistPath).replace(`"${plistPath}"`, '"$PLIST"'),
122+
'an unreadable framework Info.plist': (plistPath) => hookedShimText('1', `${plistPath}.missing`),
123+
};
124+
125+
for (const [shape, text] of Object.entries(UNREADABLE_VERSION_SHAPES)) {
126+
test(`a hooked shim with ${shape} fails closed`, async () => {
127+
const root = await tempRoot();
128+
const plistPath = fakeFrameworkInfoPlistPath(root, 'devicectl');
129+
const host = writeFakeXcrunShims(root, { devicectl: { text: text(plistPath) } });
130+
host.installedVersions.set(plistPath, '1');
131+
132+
const [, devicectl] = await withFakeXcrunHost(host, () => probeXcrunShimFirstLaunchHooks());
133+
134+
assert.equal(devicectl?.hook === 'armed' && devicectl.armedBy, 'version_unreadable');
135+
});
136+
}
137+
138+
function hangingXcrun(onStart: (options: ExecOptions | undefined) => void) {
139+
return createLocalAppleToolProvider({
140+
runCommand: async (_cmd, _args, options): Promise<ExecResult> => {
141+
onStart(options);
142+
return await new Promise<ExecResult>(() => {});
143+
},
144+
});
145+
}
146+
147+
test('the probe spends the cold-toolchain budget on each xcrun --find and reads a timeout as armed', async () => {
155148
const budget = new AbortController();
156-
vi.spyOn(AbortSignal, 'timeout').mockReturnValue(budget.signal);
157-
const pending = new Promise<ExecResult>(() => {});
149+
const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(budget.signal);
150+
const findTimeoutsMs: Array<number | undefined> = [];
151+
const provider = hangingXcrun((options) => {
152+
findTimeoutsMs.push(options?.timeoutMs);
153+
if (findTimeoutsMs.length === XCRUN_SHIM_TOOL_NAMES.length) budget.abort();
154+
});
155+
156+
const shims = await withAppleToolProvider(provider, () => probeXcrunShimFirstLaunchHooks());
157+
158+
assert.deepEqual(timeout.mock.calls, [[COLD_TOOLCHAIN_PROBE_TIMEOUT_MS]]);
159+
assert.deepEqual(
160+
findTimeoutsMs,
161+
XCRUN_SHIM_TOOL_NAMES.map(() => COLD_TOOLCHAIN_PROBE_TIMEOUT_MS),
162+
);
163+
assert.deepEqual(
164+
shims.map((shim) => [shim.tool, shim.hook, shim.hook === 'armed' && shim.armedBy]),
165+
XCRUN_SHIM_TOOL_NAMES.map((tool) => [tool, 'armed', 'probe_out_of_budget']),
166+
);
167+
});
168+
169+
test('a request canceled mid-probe stops every unanswered shim as canceled', async () => {
170+
const request = new AbortController();
158171
let started = 0;
159-
const runCommand: AppleToolCommandExecutor = async () => {
172+
const provider = hangingXcrun((options) => {
160173
started += 1;
161-
if (started === XCRUN_TOOL_NAMES.length) budget.abort();
162-
return await pending;
163-
};
174+
assert.equal(options?.signal?.aborted, false);
175+
if (started === XCRUN_SHIM_TOOL_NAMES.length) request.abort();
176+
});
177+
178+
const shims = await withAppleToolProvider(provider, () =>
179+
probeXcrunShimFirstLaunchHooks({ signal: request.signal }),
180+
);
164181

165-
const shims = await withFakeXcrun(runCommand, {}, () => probeXcrunShimFirstLaunchHooks());
182+
assert.deepEqual(
183+
shims.map((shim) => shim.hook === 'armed' && shim.armedBy),
184+
XCRUN_SHIM_TOOL_NAMES.map(() => 'probe_canceled'),
185+
);
186+
});
187+
188+
test('an already-canceled request spawns no xcrun at all', async () => {
189+
const host = writeFakeXcrunShims(await tempRoot(), {
190+
simctl: { expectedVersion: '1155.4', installedVersion: '1155.4' },
191+
devicectl: { expectedVersion: '629.3', installedVersion: '629.3' },
192+
});
193+
194+
const shims = await withFakeXcrunHost(host, () =>
195+
probeXcrunShimFirstLaunchHooks({ signal: AbortSignal.abort() }),
196+
);
166197

198+
assert.deepEqual(host.finds, []);
167199
assert.deepEqual(
168-
shims.map((shim) => [shim.tool, shim.hook, shim.shimPath]),
169-
XCRUN_TOOL_NAMES.map((tool) => [tool, 'armed', null]),
200+
shims.map((shim) => shim.hook === 'armed' && shim.armedBy),
201+
XCRUN_SHIM_TOOL_NAMES.map(() => 'probe_canceled'),
170202
);
171203
});

0 commit comments

Comments
 (0)