peachsim 0.1.1881 → 0.1.1886

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/cli/commands/control.ts +11 -10
  2. package/cli/commands/reset.ts +1 -1
  3. package/cli/outbound-endpoints.ts +1 -1
  4. package/detox/index.ts +62 -1
  5. package/dist-lib/agent-daemon-client.cjs +1 -1
  6. package/dist-lib/agent-events.cjs +1 -1
  7. package/dist-lib/attached-projects.cjs +1 -1
  8. package/dist-lib/auth/shared-session.cjs +1 -1
  9. package/dist-lib/backend-origin.cjs +1 -1
  10. package/dist-lib/beta.cjs +1 -1
  11. package/dist-lib/beta.mjs +1 -1
  12. package/dist-lib/bridge-constants.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.mjs +1 -1
  15. package/dist-lib/bridge-contract.cjs +1 -1
  16. package/dist-lib/bridge-contract.mjs +1 -1
  17. package/dist-lib/bundle-channel.cjs +8914 -4264
  18. package/dist-lib/capture-contract.cjs +1 -1
  19. package/dist-lib/capture-contract.mjs +1 -1
  20. package/dist-lib/cloud-contract.cjs +1 -1
  21. package/dist-lib/cloud-contract.mjs +1 -1
  22. package/dist-lib/cloud-test-args.cjs +1 -1
  23. package/dist-lib/cloud-test-args.mjs +1 -1
  24. package/dist-lib/cloud.cjs +1 -1
  25. package/dist-lib/cloud.mjs +1 -1
  26. package/dist-lib/config.cjs +1 -1
  27. package/dist-lib/config.mjs +1 -1
  28. package/dist-lib/detox/index.cjs +35 -2
  29. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  30. package/dist-lib/expo-swift-bundle.cjs +8494 -3955
  31. package/dist-lib/expo-swift-metadata.cjs +5 -1
  32. package/dist-lib/expo-swift-metadata.mjs +5 -1
  33. package/dist-lib/home-paths.cjs +1 -1
  34. package/dist-lib/host/bridge-host.cjs +9679 -5057
  35. package/dist-lib/host/fetch-proxy-handler.cjs +93 -13
  36. package/dist-lib/host/fetch-proxy-overrides.cjs +10 -2
  37. package/dist-lib/host/fetch-proxy-overrides.mjs +8 -2
  38. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  39. package/dist-lib/host/websocket-proxy.cjs +1 -1
  40. package/dist-lib/index.cjs +525 -120
  41. package/dist-lib/jump-to-source-babel.cjs +1 -1
  42. package/dist-lib/jump-to-source-native.cjs +1 -1
  43. package/dist-lib/kotlin-host.cjs +1 -1
  44. package/dist-lib/menu.cjs +1 -1
  45. package/dist-lib/menu.mjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  48. package/dist-lib/metro-production-bundle.cjs +1 -1
  49. package/dist-lib/metro-production-bundle.mjs +1 -1
  50. package/dist-lib/metro.cjs +523 -118
  51. package/dist-lib/native-app-identity-project.cjs +395 -72
  52. package/dist-lib/native-app-identity-project.mjs +720 -375
  53. package/dist-lib/native-app-identity.cjs +37 -1
  54. package/dist-lib/native-app-identity.mjs +36 -1
  55. package/dist-lib/native-firebase-metadata.cjs +1 -1
  56. package/dist-lib/native-firebase-metadata.mjs +1 -1
  57. package/dist-lib/pdfium-raster.cjs +1 -1
  58. package/dist-lib/pdfium-raster.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +1 -1
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/public-origins-lib-esm.json +58 -28
  64. package/dist-lib/public-origins-lib.json +233 -92
  65. package/dist-lib/react-native-host-modules.cjs +1 -1
  66. package/dist-lib/react-native-host-modules.mjs +1 -1
  67. package/dist-lib/reap-browser.cjs +1 -1
  68. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  69. package/dist-lib/sdk.cjs +1 -1
  70. package/dist-lib/sdk.mjs +1 -1
  71. package/dist-lib/skills.cjs +30711 -25956
  72. package/dist-lib/swift-compile.cjs +6782 -2533
  73. package/dist-lib/swift-compile.mjs +6112 -1864
  74. package/dist-lib/swift-package.cjs +20 -3
  75. package/dist-lib/swift-package.mjs +20 -3
  76. package/dist-lib/swift-submit.cjs +2 -2
  77. package/dist-lib/swift-submit.mjs +2 -2
  78. package/dist-lib/swift-toolchain.cjs +19 -1
  79. package/dist-lib/swift.cjs +1 -1
  80. package/dist-lib/vite-swift.cjs +8640 -4109
  81. package/dist-lib/vite.cjs +93 -13
  82. package/dist-lib/worklet-executable.cjs +1 -1
  83. package/dist-lib/worklet-executable.mjs +1 -1
  84. package/dist-types/packages/peach-engine/src/engine/canvaskit-api.d.ts +1 -1
  85. package/dist-types/packages/peach-engine/src/engine/fontDataContract.d.ts +2 -0
  86. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  87. package/dist-types/packages/peach-engine/src/render-worker/native-ui-protocol.d.ts +1 -0
  88. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +11 -1
  89. package/dist-types/packages/peach-engine/src/render-worker/shell-tree-wire.d.ts +2 -1
  90. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  91. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +10 -1
  92. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  93. package/dist-types/packages/peach-kit/src/ui/popover-placement.d.ts +1 -1
  94. package/dist-types/packages/sootsim-swift/src/securityHostContract.d.ts +10 -0
  95. package/package.json +1 -1
  96. package/runtime-companion.json +1 -1
  97. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHost.h +555 -0
  98. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +1 -0
  99. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes +6 -0
  100. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSURLProtocol.h +0 -1
  101. package/sdk/ios/System/Library/Frameworks/QuartzCore.framework/Modules/module.modulemap +6 -0
  102. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarButtonItemBadge.h +1 -1
  103. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarMinimization.h +1 -1
  104. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIScrollView.h +1 -1
  105. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UISearchTab.h +1 -1
  106. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITab.h +1 -1
  107. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITabAccessory.h +2 -2
  108. package/sdk/ios/usr/include/os/activity.h +534 -0
  109. package/sdk/ios/usr/include/os.modulemap +15 -0
  110. package/sdk/ios/wasm/include/fcntl.h +16 -0
  111. package/sdk/ios/wasm/include/string.h +5 -0
  112. package/sdk/native-hashes.json +1 -1
  113. package/src/dns-over-https.ts +61 -9
  114. package/src/expo-swift-host.ts +11 -3
  115. package/src/host/fetch-proxy-handler.ts +51 -2
  116. package/src/host/fetch-proxy-overrides.ts +4 -0
  117. package/src/host/hostname-resolver.ts +9 -5
  118. package/src/native-app-identity-project.ts +13 -2
  119. package/src/native-app-identity.ts +47 -0
  120. package/src/nitro-adapter.lock.json +260 -260
  121. package/src/nitro-superset.lock.json +4 -4
  122. package/src/storageSnapshotContract.ts +20 -1
  123. package/src/swift-compile.ts +399 -72
  124. package/src/swift-compiler-digest.ts +15 -0
  125. package/src/swift-coverage/xcode-packages.ts +3 -2
  126. package/src/swift-distribution.lock.json +12 -12
  127. package/src/swift-guest-archive.ts +153 -0
  128. package/src/swift-guest-compile.ts +449 -0
  129. package/src/swift-guest-image-ledger.ts +656 -0
  130. package/src/swift-guest-link-plan.ts +52 -0
  131. package/src/swift-guest-link.ts +1414 -0
  132. package/src/swift-guest-linked-spans.ts +338 -0
  133. package/src/swift-guest-manifest.ts +141 -0
  134. package/src/swift-guest-projection-storage.ts +310 -0
  135. package/src/swift-guest-projection.ts +252 -0
  136. package/src/swift-guest-runtime-plan.ts +834 -0
  137. package/src/swift-guest-source-inputs.ts +427 -0
  138. package/src/swift-guest-source-plan.ts +279 -0
  139. package/src/swift-host.ts +125 -17
  140. package/src/swift-link-roots.ts +27 -50
  141. package/src/swift-package-manifest.ts +34 -18
  142. package/src/swift-package.ts +32 -2
  143. package/src/swift-packages.ts +138 -17
  144. package/src/swift-runtime-products.ts +73 -0
  145. package/src/swift-shared-sdk.ts +1 -1
  146. package/src/swift-submit.ts +13 -3
  147. package/src/swift-toolchain.ts +18 -0
  148. package/src/swift-wasm-prune.ts +313 -14
  149. package/src/swiftContract.ts +83 -0
  150. package/src/swiftRuntimeProductContract.ts +85 -45
  151. package/src/turbo-runtime.lock.json +23 -23
  152. package/src/wasm-optimize.ts +16 -4
  153. package/src/xcode-project.ts +142 -14
@@ -0,0 +1,1414 @@
1
+ // perform a source-owned link with a caller-scoped guest symbol ledger.
2
+ // the discovery link records wasm-ld's selected objects and archive members;
3
+ // the final link rewrites those objects without editing their sources.
4
+ import { execFileSync } from 'node:child_process'
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { StringDecoder } from 'node:string_decoder'
8
+ import {
9
+ aliasGuestArchive,
10
+ aliasGuestLinkIdentities,
11
+ originalGuestArchiveSelections,
12
+ type AliasedGuestArchive,
13
+ } from './swift-guest-archive'
14
+ import { createGuestImageLedger, type GuestImageObject } from './swift-guest-image-ledger'
15
+ import {
16
+ selectedGuestInputImage,
17
+ type GuestLinkArtifact,
18
+ type GuestLinkPlan,
19
+ type GuestLinkSelection,
20
+ } from './swift-guest-link-plan'
21
+ import {
22
+ createGuestImageManifest,
23
+ selectedGuestManifestInputs,
24
+ } from './swift-guest-manifest'
25
+ import {
26
+ guestProjectionRegionCapacity,
27
+ reserveGuestProjectionStorage,
28
+ type ReservedGuestProjectionStorage,
29
+ } from './swift-guest-projection-storage'
30
+ import {
31
+ guestFrameworkLinkArtifacts,
32
+ guestSdkProductLinkArtifacts,
33
+ guestSdkProductImages,
34
+ guestRuntimeProductsForInputs,
35
+ guestAliasedSdkArchiveArtifacts,
36
+ } from './swift-guest-runtime-plan'
37
+ import { frameworkRuntimeProductId } from './swift-runtime-products'
38
+ import {
39
+ pruneSwiftWasmLink,
40
+ readArMembers,
41
+ guestWasmSymbols,
42
+ type SwiftPrunedSdkInputs,
43
+ } from './swift-wasm-prune'
44
+ import type { SwiftGuestImageManifest } from './swiftGuestImageContract'
45
+ import type {
46
+ SwiftFrameworkProduct,
47
+ SwiftSdkProduct,
48
+ } from './swiftRuntimeProductContract'
49
+
50
+ export interface GuestLinkOptions {
51
+ readonly plan: GuestLinkPlan
52
+ readonly args: readonly string[]
53
+ readonly directory: string
54
+ readonly wasmLd: string
55
+ readonly clang: string
56
+ readonly llvmAr: string
57
+ /** source product that owns the generated shared lookup tables. */
58
+ readonly ledgerDataImage: number
59
+ /** final linker-map names for the selected, rewritten owned objects. */
60
+ readonly onLinkedOwners?: (owners: ReadonlyMap<string, number>) => void
61
+ /** caller-owned sections in the generated ledger object. */
62
+ readonly onLinkedSections?: (owners: ReadonlyMap<string, number>) => void
63
+ readonly projection?: GuestLinkProjection
64
+ /** Resolve scopes from the actual selected inputs before generating the ledger. */
65
+ readonly resolvePlan?: (
66
+ selection: readonly GuestLinkSelection[],
67
+ plan: GuestLinkPlan,
68
+ ) => GuestLinkPlan
69
+ }
70
+
71
+ /** The planner supplies source metadata, never post-link region shapes. */
72
+ export interface GuestLinkProjection {
73
+ readonly image: number
74
+ readonly identities: ReadonlyMap<string, string>
75
+ readonly linkOptions: readonly string[]
76
+ readonly images: readonly {
77
+ readonly image: number
78
+ readonly id: string
79
+ readonly installName: string
80
+ readonly fileType: SwiftGuestImageManifest['fileType']
81
+ readonly buildVersion: SwiftGuestImageManifest['buildVersion']
82
+ }[]
83
+ readonly memoryProtection: { readonly initial: number; readonly maximum: number }
84
+ readonly tableProtection: { readonly initial: number; readonly maximum: number }
85
+ readonly clangOptions: readonly string[]
86
+ readonly onReserved: (storage: ReservedGuestProjectionStorage, object: string) => void
87
+ }
88
+
89
+ interface InputOccurrence {
90
+ readonly artifact: GuestLinkArtifact
91
+ readonly token: string
92
+ readonly lazy: boolean
93
+ readonly whole: boolean
94
+ }
95
+
96
+ export function remapGuestLinkPlan(
97
+ plan: GuestLinkPlan,
98
+ rewritten: ReadonlyMap<string, string>,
99
+ ): GuestLinkPlan {
100
+ return {
101
+ ...plan,
102
+ artifacts: plan.artifacts.map((artifact) => ({
103
+ ...artifact,
104
+ path: rewritten.get(artifact.path) ?? artifact.path,
105
+ })),
106
+ }
107
+ }
108
+
109
+ /** Resolve actual object and archive paths using the linker's search order. */
110
+ export function guestLinkInputFiles(args: readonly string[]): string[] {
111
+ const dirs: string[] = []
112
+ for (let i = 0; i < args.length; i++) {
113
+ const arg = args[i]!
114
+ if (arg === '-L' || arg === '--library-path') dirs.push(args[++i]!)
115
+ else if (arg.startsWith('-L')) dirs.push(arg.slice(2))
116
+ else if (arg.startsWith('--library-path=')) dirs.push(arg.slice(15))
117
+ }
118
+ const inputs = new Set<string>()
119
+ for (let i = 0; i < args.length; i++) {
120
+ const arg = args[i]!
121
+ if (arg === '-L' || arg === '--library-path' || arg === '-o' || arg === '--output') {
122
+ i++
123
+ continue
124
+ }
125
+ if (arg.startsWith('@')) throw new Error(`nested linker response file ${arg}`)
126
+ let file: string | undefined
127
+ if (
128
+ arg === '-l' ||
129
+ arg === '--library' ||
130
+ arg.startsWith('--library=') ||
131
+ (arg.startsWith('-l') && arg.length > 2)
132
+ ) {
133
+ const name =
134
+ arg === '-l' || arg === '--library'
135
+ ? args[++i]!
136
+ : arg.startsWith('--library=')
137
+ ? arg.slice(10)
138
+ : arg.slice(2)
139
+ const archive = name.startsWith(':') ? name.slice(1) : `lib${name}.a`
140
+ file = dirs
141
+ .map((dir) => path.join(dir, archive))
142
+ .find((item) => fs.existsSync(item))
143
+ if (!file) throw new Error(`unresolved guest link library ${name}`)
144
+ } else if (!arg.startsWith('-') && fs.existsSync(arg) && fs.statSync(arg).isFile()) {
145
+ const fd = fs.openSync(arg, 'r')
146
+ const magic = Buffer.alloc(8)
147
+ try {
148
+ fs.readSync(fd, magic, 0, magic.length, 0)
149
+ } finally {
150
+ fs.closeSync(fd)
151
+ }
152
+ if (
153
+ magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) ||
154
+ magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) ||
155
+ magic.toString('ascii') === '!<arch>\n' ||
156
+ magic.toString('ascii') === '!<thin>\n'
157
+ )
158
+ file = arg
159
+ }
160
+ if (file) inputs.add(path.resolve(file))
161
+ }
162
+ return [...inputs]
163
+ }
164
+
165
+ /** Actual object and archive inputs that have not been assigned to an image. */
166
+ export function unownedGuestLinkInputs(
167
+ plan: GuestLinkPlan,
168
+ args: readonly string[],
169
+ ): string[] {
170
+ const owned = new Set(plan.artifacts.map((artifact) => path.resolve(artifact.path)))
171
+ return guestLinkInputFiles(args).filter((file) => !owned.has(file))
172
+ }
173
+
174
+ function occurrences(plan: GuestLinkPlan, args: readonly string[]): InputOccurrence[] {
175
+ const dirs: string[] = []
176
+ for (let i = 0; i < args.length; i++) {
177
+ const arg = args[i]!
178
+ if (arg === '-L') dirs.push(args[++i]!)
179
+ else if (arg.startsWith('-L')) dirs.push(arg.slice(2))
180
+ }
181
+ const owned = new Map(
182
+ plan.artifacts.map((artifact) => [path.resolve(artifact.path), artifact]),
183
+ )
184
+ if (owned.size !== plan.artifacts.length)
185
+ throw new Error('duplicate guest link artifact')
186
+ const found: InputOccurrence[] = []
187
+ const seen = new Map<string, InputOccurrence>()
188
+ let lazy = false
189
+ let whole = false
190
+ for (const token of args) {
191
+ if (token === '--start-lib') {
192
+ lazy = true
193
+ continue
194
+ }
195
+ if (token === '--end-lib') {
196
+ lazy = false
197
+ continue
198
+ }
199
+ if (token === '--whole-archive') {
200
+ whole = true
201
+ continue
202
+ }
203
+ if (token === '--no-whole-archive') {
204
+ whole = false
205
+ continue
206
+ }
207
+ let filename = token
208
+ if (token.startsWith('-l') && token.length > 2) {
209
+ const library = token.slice(2)
210
+ filename =
211
+ dirs
212
+ .map((dir) =>
213
+ path.join(
214
+ dir,
215
+ library.startsWith(':') ? library.slice(1) : `lib${library}.a`,
216
+ ),
217
+ )
218
+ .find((file) => fs.existsSync(file)) ?? token
219
+ }
220
+ const artifact = owned.get(path.resolve(filename))
221
+ if (artifact) {
222
+ const prior = seen.get(artifact.path)
223
+ if (prior) {
224
+ if (prior.lazy !== lazy || prior.whole !== whole)
225
+ throw new Error(
226
+ `guest link input has conflicting occurrence modes: ${artifact.path}`,
227
+ )
228
+ continue
229
+ }
230
+ const occurrence = { artifact, token, lazy, whole }
231
+ seen.set(artifact.path, occurrence)
232
+ found.push(occurrence)
233
+ }
234
+ }
235
+ if (found.length !== plan.artifacts.length)
236
+ throw new Error('guest plan does not match linker inputs')
237
+ return found
238
+ }
239
+
240
+ export function selectedGuestLinkInputs(
241
+ plan: GuestLinkPlan,
242
+ args: readonly string[],
243
+ whyExtract: string,
244
+ linkTrace: string,
245
+ ): GuestLinkSelection[] {
246
+ const rows = whyExtract.trimEnd().split('\n')
247
+ if (rows.shift() !== 'reference\textracted\tsymbol')
248
+ throw new Error('invalid wasm-ld extraction report')
249
+ const extracted = new Set(
250
+ rows.map((row) => {
251
+ const fields = row.split('\t')
252
+ if (fields.length !== 3) throw new Error('invalid wasm-ld extraction row')
253
+ return fields[1]!
254
+ }),
255
+ )
256
+ const traced = new Set(linkTrace.split('\n').filter(Boolean))
257
+ for (const file of extracted)
258
+ if (!traced.has(file))
259
+ throw new Error(`extracted guest input is absent from link trace ${file}`)
260
+ const result: GuestLinkSelection[] = []
261
+ for (const { artifact, lazy, whole } of occurrences(plan, args)) {
262
+ if (artifact.kind === 'object') {
263
+ if (!lazy && !traced.has(artifact.path))
264
+ throw new Error(`eager guest input is absent from link trace ${artifact.path}`)
265
+ if (traced.has(artifact.path))
266
+ result.push({ artifact: artifact.path, member: null })
267
+ continue
268
+ }
269
+ const prefix = `${artifact.path}(`
270
+ const names = [...traced]
271
+ .filter((item) => item.startsWith(prefix) && item.endsWith(')'))
272
+ .map((item) => item.slice(prefix.length, -1))
273
+ const members = readArMembers(fs.readFileSync(artifact.path))
274
+ for (const member of members) {
275
+ if (whole || names.includes(member.name))
276
+ result.push({ artifact: artifact.path, member: member.name })
277
+ }
278
+ for (const name of names)
279
+ if (members.filter((member) => member.name === name).length !== 1)
280
+ throw new Error(
281
+ `ambiguous or unsupported archive member ${artifact.path}(${name})`,
282
+ )
283
+ }
284
+ return result
285
+ }
286
+
287
+ function outputPath(args: readonly string[]): string {
288
+ let output = ''
289
+ for (let i = 0; i < args.length; i++) {
290
+ const arg = args[i]!
291
+ if (arg === '-o' || arg === '--output') output = args[++i]!
292
+ else if (arg.startsWith('--output=')) output = arg.slice('--output='.length)
293
+ }
294
+ if (!output) throw new Error('guest link has no output path')
295
+ return output
296
+ }
297
+
298
+ function withOutput(
299
+ args: readonly string[],
300
+ output: string,
301
+ discovery: boolean,
302
+ ): string[] {
303
+ const result: string[] = []
304
+ for (let i = 0; i < args.length; i++) {
305
+ const arg = args[i]!
306
+ if (arg === '-o' || arg === '--output') {
307
+ i++
308
+ continue
309
+ }
310
+ if (arg.startsWith('--output=')) continue
311
+ if (discovery && (arg.startsWith('--why-extract=') || arg.startsWith('--Map=')))
312
+ continue
313
+ result.push(arg)
314
+ }
315
+ result.push('-o', output)
316
+ return result
317
+ }
318
+
319
+ export function linkGuestImages(
320
+ options: GuestLinkOptions,
321
+ ): readonly GuestLinkSelection[] {
322
+ const { args, directory, wasmLd, clang, llvmAr } = options
323
+ let plan = options.plan
324
+ if (!plan.images.some((image) => image.id === options.ledgerDataImage))
325
+ throw new Error(`unknown ledger data image ${options.ledgerDataImage}`)
326
+ fs.mkdirSync(directory, { recursive: true })
327
+ const discovery = path.join(directory, 'discovery.wasm')
328
+ const whyPath = path.join(directory, 'why-extract.txt')
329
+ const mapPath = path.join(directory, 'discovery.map')
330
+ const runLink = (name: string, arguments_: readonly string[]) => {
331
+ const response = path.join(directory, `${name}.rsp`)
332
+ const trace = path.join(directory, `${name}-inputs.txt`)
333
+ fs.writeFileSync(
334
+ response,
335
+ [...arguments_, '--trace'].map((argument) => JSON.stringify(argument)).join(' '),
336
+ )
337
+ const output = fs.openSync(trace, 'w')
338
+ try {
339
+ execFileSync(wasmLd, [`@${response}`], { stdio: ['ignore', output, 'inherit'] })
340
+ } finally {
341
+ fs.closeSync(output)
342
+ }
343
+ return fs.readFileSync(trace, 'utf8')
344
+ }
345
+ let discoveryProjection: string | undefined
346
+ if (options.projection) {
347
+ const source = path.join(directory, 'projection-discovery.c')
348
+ discoveryProjection = path.join(directory, 'projection-discovery.o')
349
+ fs.writeFileSync(
350
+ source,
351
+ '#include "guest-image-projection.h"\n' +
352
+ 'const struct peach_guest_image __peach_guest_images[] = {{0}};\n' +
353
+ 'const uint32_t __peach_guest_image_count = 0;\n',
354
+ )
355
+ execFileSync(
356
+ clang,
357
+ [...options.projection.clangOptions, '-c', source, '-o', discoveryProjection],
358
+ { stdio: 'pipe' },
359
+ )
360
+ }
361
+ const archives = new Map<string, ReturnType<typeof readArMembers>>()
362
+ const prepare = (provider: boolean) => {
363
+ const trace = runLink('discovery', [
364
+ ...withOutput(args, discovery, true),
365
+ ...(discoveryProjection ? [discoveryProjection] : []),
366
+ ...(provider ? ['--undefined=__peach_dlsym_from_image'] : []),
367
+ `--why-extract=${whyPath}`,
368
+ `--Map=${mapPath}`,
369
+ ])
370
+ const selected = selectedGuestLinkInputs(
371
+ plan,
372
+ args,
373
+ fs.readFileSync(whyPath, 'utf8'),
374
+ trace,
375
+ )
376
+ if (options.resolvePlan) {
377
+ const identity = (value: GuestLinkPlan) =>
378
+ JSON.stringify([
379
+ value.images.map(({ id, name }) => [id, name]),
380
+ value.artifacts.map(
381
+ ({
382
+ path: file,
383
+ kind,
384
+ image,
385
+ memberImages,
386
+ memberOrigins,
387
+ instrumentDynamicLookups,
388
+ }) => [
389
+ file,
390
+ kind,
391
+ image,
392
+ memberImages ? [...memberImages] : null,
393
+ memberOrigins ? [...memberOrigins] : null,
394
+ instrumentDynamicLookups,
395
+ ],
396
+ ),
397
+ ])
398
+ const originalOwnership = identity(plan)
399
+ const resolved = options.resolvePlan(selected, plan)
400
+ if (identity(resolved) !== originalOwnership)
401
+ throw new Error('resolved guest scopes changed input ownership')
402
+ plan = resolved
403
+ }
404
+ const objectsByImage = new Map<number, GuestImageObject[]>()
405
+ for (const image of plan.images) objectsByImage.set(image.id, [])
406
+ for (const item of selected) {
407
+ const artifact = plan.artifacts.find(
408
+ (candidate) => candidate.path === item.artifact,
409
+ )!
410
+ const image = selectedGuestInputImage(artifact, item.member)
411
+ let bytes: Uint8Array
412
+ if (item.member === null) bytes = fs.readFileSync(item.artifact)
413
+ else {
414
+ let members = archives.get(item.artifact)
415
+ if (!members) {
416
+ members = readArMembers(fs.readFileSync(item.artifact))
417
+ archives.set(item.artifact, members)
418
+ }
419
+ bytes = members.find((member) => member.name === item.member)!.bytes
420
+ }
421
+ const objects = objectsByImage.get(image)
422
+ if (!objects) throw new Error(`unknown image ${image}`)
423
+ objects.push({
424
+ path: item.member === null ? item.artifact : `${item.artifact}(${item.member})`,
425
+ bytes,
426
+ // the actual loader delegates non-ledger lookups to libc; wrapping its
427
+ // own dlsym call would recurse back into the loader.
428
+ instrumentDynamicLookups:
429
+ artifact.instrumentDynamicLookups &&
430
+ !guestWasmSymbols(bytes).defined.includes('__peach_dlsym_from_image'),
431
+ })
432
+ }
433
+ const ledger = createGuestImageLedger({
434
+ images: plan.images.map((image) => ({
435
+ ...image,
436
+ objects: objectsByImage.get(image.id)!,
437
+ })),
438
+ callers: plan.callers,
439
+ symbols: plan.symbols,
440
+ liveSymbols: linkedMapSymbols(fs.readFileSync(mapPath, 'utf8')),
441
+ commandLineSymbols: commandLineSymbols(args),
442
+ directBindings: plan.directBindings,
443
+ })
444
+ return { selected, ledger }
445
+ }
446
+ let prepared = prepare(false)
447
+ const provider = prepared.ledger.callerWrappers.length > 0
448
+ // a generated caller wrapper introduces this provider reference. include it
449
+ // in discovery before deciding which archive members the ledger owns.
450
+ if (provider) prepared = prepare(true)
451
+ const { selected, ledger } = prepared
452
+ const replacements = new Map<string, string>()
453
+ const linkedOwners = new Map<string, number>()
454
+ for (const [index, artifact] of plan.artifacts.entries()) {
455
+ const prefix = `${artifact.path}(`
456
+ if (artifact.kind === 'object') {
457
+ const object = ledger.objects.find((item) => item.path === artifact.path)
458
+ if (!object) continue
459
+ const output = path.join(directory, `object-${index}.o`)
460
+ fs.writeFileSync(output, object.bytes)
461
+ replacements.set(artifact.path, output)
462
+ linkedOwners.set(output, selectedGuestInputImage(artifact, null))
463
+ continue
464
+ }
465
+ const members = archives.get(artifact.path)
466
+ if (!members) continue
467
+ const listed = execFileSync(llvmAr, ['t', artifact.path], { encoding: 'utf8' })
468
+ .trimEnd()
469
+ .split('\n')
470
+ if (
471
+ listed.length !== members.length ||
472
+ new Set(listed).size !== listed.length ||
473
+ members.some(
474
+ (member, i) =>
475
+ listed[i] !== member.name || path.basename(member.name) !== member.name,
476
+ )
477
+ )
478
+ throw new Error(`unsupported archive layout ${artifact.path}`)
479
+ const memberDir = path.join(directory, `archive-${index}`)
480
+ fs.mkdirSync(memberDir, { recursive: true })
481
+ const output = path.join(directory, `archive-${index}.a`)
482
+ const inputs = members.map((member) => {
483
+ const memberOutput = path.join(memberDir, member.name)
484
+ const rewritten = ledger.objects.find(
485
+ (item) => item.path === `${prefix}${member.name})`,
486
+ )
487
+ fs.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes)
488
+ if (rewritten) {
489
+ linkedOwners.set(
490
+ `${output}(${member.name})`,
491
+ selectedGuestInputImage(artifact, member.name),
492
+ )
493
+ }
494
+ return memberOutput
495
+ })
496
+ fs.rmSync(output, { force: true })
497
+ const response = path.join(memberDir, 'members.rsp')
498
+ fs.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(' '))
499
+ execFileSync(llvmAr, ['rcs', output, `@${response}`], { stdio: 'pipe' })
500
+ replacements.set(artifact.path, output)
501
+ }
502
+ const irPath = path.join(directory, 'ledger.ll')
503
+ const ledgerObject = path.join(directory, 'ledger.o')
504
+ fs.writeFileSync(irPath, ledger.llvmIR)
505
+ execFileSync(
506
+ clang,
507
+ ['--target=wasm32-unknown-wasip1', '-c', irPath, '-o', ledgerObject],
508
+ { stdio: 'pipe' },
509
+ )
510
+ linkedOwners.set(ledgerObject, options.ledgerDataImage)
511
+ let projectionObject: string | undefined
512
+ let projectionStorage: ReservedGuestProjectionStorage | undefined
513
+ if (options.projection) {
514
+ const projection = options.projection
515
+ if (!plan.images.some((image) => image.id === projection.image))
516
+ throw new Error('guest projection has no source image')
517
+ if (
518
+ projection.images.length !== plan.images.length ||
519
+ projection.images.some(
520
+ (image, index) => image.image !== index || plan.images[index]?.id !== index,
521
+ )
522
+ )
523
+ throw new Error('guest projection image order differs from link plan')
524
+ const selectedInputs = selectedGuestManifestInputs(
525
+ plan,
526
+ selected,
527
+ projection.identities,
528
+ )
529
+ const images = projection.images.map((image) =>
530
+ createGuestImageManifest({
531
+ ...image,
532
+ inputs: selectedInputs.get(image.image) ?? [],
533
+ linkOptions: projection.linkOptions,
534
+ regions: [],
535
+ }),
536
+ )
537
+ const generated = fs.readFileSync(ledgerObject)
538
+ const capacities = ledger.images.map((image) => ({
539
+ regions: guestProjectionRegionCapacity(
540
+ [...image.objects.map((object) => object.bytes), generated],
541
+ images.length + 2,
542
+ ),
543
+ memoryProtection: projection.memoryProtection,
544
+ tableProtection: projection.tableProtection,
545
+ }))
546
+ projectionStorage = reserveGuestProjectionStorage(images, capacities)
547
+ const projectionSource = path.join(directory, 'projection.c')
548
+ projectionObject = path.join(directory, 'projection.o')
549
+ fs.writeFileSync(projectionSource, projectionStorage.source)
550
+ execFileSync(
551
+ clang,
552
+ [...projection.clangOptions, '-c', projectionSource, '-o', projectionObject],
553
+ {
554
+ stdio: 'pipe',
555
+ },
556
+ )
557
+ linkedOwners.set(projectionObject, projection.image)
558
+ }
559
+ const byToken = new Map(
560
+ occurrences(plan, args).map(({ artifact, token }) => [
561
+ token,
562
+ replacements.get(artifact.path),
563
+ ]),
564
+ )
565
+ // the same input named twice (a product link line repeats shared objects)
566
+ // is one file for the linker; rewritten copies would otherwise load twice.
567
+ const placed = new Set<string>()
568
+ const finalArgs = args
569
+ .map((arg) => byToken.get(arg) ?? arg)
570
+ .filter((arg) => {
571
+ if (!arg.endsWith('.o') && !arg.endsWith('.a')) return true
572
+ if (placed.has(arg)) return false
573
+ placed.add(arg)
574
+ return true
575
+ })
576
+ const finalOutput = path.join(directory, 'final.wasm')
577
+ const finalWhy = path.join(directory, 'final-why-extract.txt')
578
+ const finalTrace = runLink('final', [
579
+ ...withOutput(finalArgs, finalOutput, false),
580
+ ledgerObject,
581
+ ...(projectionObject ? [projectionObject] : []),
582
+ ...(provider ? ['--undefined=__peach_dlsym_from_image'] : []),
583
+ `--why-extract=${finalWhy}`,
584
+ ])
585
+ // the ledger and rewritten references can change archive extraction. every
586
+ // selected member must have participated in ledger construction, so do not
587
+ // publish a link whose final inputs differ from the discovery link.
588
+ const finalSelection = selectedGuestLinkInputs(
589
+ remapGuestLinkPlan(plan, replacements),
590
+ finalArgs,
591
+ fs.readFileSync(finalWhy, 'utf8'),
592
+ finalTrace,
593
+ )
594
+ const original = new Map([...replacements].map(([before, after]) => [after, before]))
595
+ const key = (item: GuestLinkSelection) =>
596
+ JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member])
597
+ const before = new Set(selected.map(key))
598
+ const after = new Set(finalSelection.map(key))
599
+ const changed = [...before].filter((item) => !after.has(item))
600
+ changed.push(...[...after].filter((item) => !before.has(item)))
601
+ if (changed.length)
602
+ throw new Error(
603
+ `guest link selected different inputs after rewriting:\n${changed.join('\n')}`,
604
+ )
605
+ fs.renameSync(finalOutput, outputPath(args))
606
+ if (projectionStorage && projectionObject)
607
+ options.projection!.onReserved(projectionStorage, projectionObject)
608
+ options.onLinkedOwners?.(linkedOwners)
609
+ options.onLinkedSections?.(
610
+ new Map(
611
+ ledger.callerWrappers.map(({ symbol, image }) => [
612
+ `${ledgerObject}:(${symbol})`,
613
+ image,
614
+ ]),
615
+ ),
616
+ )
617
+ return selected
618
+ }
619
+
620
+ // every symbol name a linker map lists, which is what the link kept.
621
+ function linkedMapSymbols(map: string): Set<string> {
622
+ const names = new Set<string>()
623
+ for (const match of map.matchAll(/^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/gm))
624
+ names.add(match[1]!)
625
+ return names
626
+ }
627
+
628
+ // symbols the linker command line names directly, besides object references.
629
+ function commandLineSymbols(args: readonly string[]): string[] {
630
+ const names: string[] = []
631
+ for (const [i, arg] of args.entries()) {
632
+ if (arg === '--entry' || arg === '-e' || arg === '-u') names.push(args[i + 1]!)
633
+ else
634
+ for (const flag of [
635
+ '--entry=',
636
+ '--undefined=',
637
+ '--export=',
638
+ '--export-if-defined=',
639
+ ])
640
+ if (arg.startsWith(flag)) names.push(arg.slice(flag.length))
641
+ }
642
+ return names
643
+ }
644
+
645
+ /** Link only after every input has an explicit source-image owner. */
646
+ function normalizedGuestLinkArgs(input: readonly string[]): string[] {
647
+ const args: string[] = []
648
+ for (let i = 0; i < input.length; i++) {
649
+ const arg = input[i]!
650
+ if (arg === '-l' || arg === '--library') args.push(`-l${input[++i]!}`)
651
+ else if (arg === '-L' || arg === '--library-path') args.push(`-L${input[++i]!}`)
652
+ else if (arg.startsWith('--library=')) args.push(`-l${arg.slice(10)}`)
653
+ else if (arg.startsWith('--library-path=')) args.push(`-L${arg.slice(15)}`)
654
+ else args.push(arg)
655
+ }
656
+ return args
657
+ }
658
+
659
+ /** Replace only exact source archives, preserving their position in link order. */
660
+ export function aliasGuestLinkArguments(
661
+ input: readonly string[],
662
+ archives: readonly AliasedGuestArchive[],
663
+ ): string[] {
664
+ const args = normalizedGuestLinkArgs(input)
665
+ const directories = args
666
+ .filter((arg) => arg.startsWith('-L'))
667
+ .map((arg) => arg.slice(2))
668
+ const aliases = new Map(
669
+ archives.map((archive) => [path.resolve(archive.source), archive.archive]),
670
+ )
671
+ if (aliases.size !== archives.length)
672
+ throw new Error('duplicate original guest archive')
673
+ const used = new Set<string>()
674
+ const result = args.map((arg) => {
675
+ let file = arg
676
+ if (arg.startsWith('-l') && arg.length > 2) {
677
+ const name = arg.slice(2)
678
+ const library = name.startsWith(':') ? name.slice(1) : `lib${name}.a`
679
+ file =
680
+ directories
681
+ .map((directory) => path.join(directory, library))
682
+ .find((candidate) => fs.existsSync(candidate)) ?? arg
683
+ }
684
+ if (file.startsWith('-')) return arg
685
+ const source = path.resolve(file)
686
+ const alias = aliases.get(source)
687
+ if (alias === undefined) return arg
688
+ used.add(source)
689
+ return alias
690
+ })
691
+ if (used.size !== aliases.size)
692
+ throw new Error('aliased guest archive is not a link input')
693
+ return result
694
+ }
695
+
696
+ /** Reject selected inputs without an explicit source-image owner. */
697
+ export function linkCompleteGuestImages(
698
+ options: GuestLinkOptions,
699
+ ): readonly GuestLinkSelection[] {
700
+ const args = normalizedGuestLinkArgs(options.args)
701
+ const unowned = unownedGuestLinkInputs(options.plan, args)
702
+ const candidates = unowned.map((file): GuestLinkArtifact => {
703
+ const descriptor = fs.openSync(file, 'r')
704
+ const magic = Buffer.alloc(8)
705
+ try {
706
+ fs.readSync(descriptor, magic, 0, magic.length, 0)
707
+ } finally {
708
+ fs.closeSync(descriptor)
709
+ }
710
+ return {
711
+ path: file,
712
+ kind: magic.toString('ascii') === '!<arch>\n' ? 'archive' : 'object',
713
+ image: null,
714
+ instrumentDynamicLookups: false,
715
+ }
716
+ })
717
+ return linkGuestImages({
718
+ ...options,
719
+ args,
720
+ plan: { ...options.plan, artifacts: [...options.plan.artifacts, ...candidates] },
721
+ })
722
+ }
723
+
724
+ /** Obtain selected input identities before constructing source-owned image scopes. */
725
+ export function discoverGuestLinkInputs(options: {
726
+ readonly args: readonly string[]
727
+ readonly directory: string
728
+ readonly wasmLd: string
729
+ /** Additional discovery-only objects required by the final link. */
730
+ readonly objects: readonly string[]
731
+ }): GuestLinkSelection[] {
732
+ const args = normalizedGuestLinkArgs(options.args)
733
+ const artifacts = guestLinkInputFiles(args).map((file): GuestLinkArtifact => {
734
+ const descriptor = fs.openSync(file, 'r')
735
+ const magic = Buffer.alloc(8)
736
+ try {
737
+ fs.readSync(descriptor, magic, 0, magic.length, 0)
738
+ } finally {
739
+ fs.closeSync(descriptor)
740
+ }
741
+ const kind = magic.toString('ascii') === '!<arch>\n' ? 'archive' : 'object'
742
+ return { path: file, kind, image: 0, instrumentDynamicLookups: false }
743
+ })
744
+ const plan: GuestLinkPlan = { images: [], callers: [], artifacts, symbols: [] }
745
+ fs.mkdirSync(options.directory, { recursive: true })
746
+ const why = path.join(options.directory, 'preselection-why.txt')
747
+ const response = path.join(options.directory, 'preselection.rsp')
748
+ const output = path.join(options.directory, 'preselection.wasm')
749
+ const flags = [
750
+ ...withOutput(args, output, true),
751
+ ...options.objects,
752
+ // the loader runtime backs every image's lookup wrappers, so it belongs to
753
+ // the selection that assigns member owners.
754
+ '--undefined=__peach_dlsym_from_image',
755
+ `--why-extract=${why}`,
756
+ '--trace',
757
+ ]
758
+ fs.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(' '))
759
+ const trace = path.join(options.directory, 'preselection-inputs.txt')
760
+ const traceOutput = fs.openSync(trace, 'w')
761
+ try {
762
+ execFileSync(options.wasmLd, [`@${response}`], {
763
+ stdio: ['ignore', traceOutput, 'inherit'],
764
+ })
765
+ } finally {
766
+ fs.closeSync(traceOutput)
767
+ }
768
+ return selectedGuestLinkInputs(
769
+ plan,
770
+ args,
771
+ fs.readFileSync(why, 'utf8'),
772
+ fs.readFileSync(trace, 'utf8'),
773
+ )
774
+ }
775
+
776
+ /** Discover selected SDK members before assigning runtime product images. */
777
+ export function prepareGuestRuntimeInputs(options: {
778
+ readonly args: readonly string[]
779
+ readonly directory: string
780
+ readonly wasmLd: string
781
+ readonly llvmAr: string
782
+ readonly discoveryObjects: readonly string[]
783
+ readonly products: readonly {
784
+ readonly product: SwiftSdkProduct
785
+ readonly root: string
786
+ }[]
787
+ readonly rewritten: ReadonlyMap<string, string>
788
+ readonly sdk: SwiftPrunedSdkInputs
789
+ readonly firstImage: number
790
+ readonly containingImage?: number
791
+ readonly framework?: {
792
+ readonly product: SwiftFrameworkProduct
793
+ readonly root: string
794
+ }
795
+ }): {
796
+ readonly args: readonly string[]
797
+ readonly selected: readonly GuestLinkSelection[]
798
+ readonly archives: readonly AliasedGuestArchive[]
799
+ readonly sdkProducts: GuestSdkLinkProducts
800
+ readonly archiveArtifacts: readonly GuestLinkArtifact[]
801
+ } {
802
+ const originals = new Map(
803
+ [...options.rewritten].map(([before, after]) => [
804
+ path.resolve(after),
805
+ path.resolve(before),
806
+ ]),
807
+ )
808
+ if (originals.size !== options.rewritten.size)
809
+ throw new Error('ambiguous rewritten runtime input')
810
+ const recordedArchives = new Set(
811
+ options.products.flatMap(({ product, root }) =>
812
+ product.artifacts.flatMap((artifact) =>
813
+ artifact.kind === 'archive' ? [path.resolve(root, artifact.path)] : [],
814
+ ),
815
+ ),
816
+ )
817
+ const archives: AliasedGuestArchive[] = []
818
+ for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
819
+ const original = originals.get(file) ?? file
820
+ if (!recordedArchives.has(original)) continue
821
+ const members = readArMembers(fs.readFileSync(file))
822
+ if (new Set(members.map((member) => member.name)).size === members.length) continue
823
+ archives.push(
824
+ aliasGuestArchive({
825
+ archive: file,
826
+ directory: path.join(options.directory, `archive-${archives.length}`),
827
+ llvmAr: options.llvmAr,
828
+ }),
829
+ )
830
+ }
831
+ const args = aliasGuestLinkArguments(options.args, archives)
832
+ const selected = discoverGuestLinkInputs({
833
+ args,
834
+ directory: options.directory,
835
+ wasmLd: options.wasmLd,
836
+ objects: options.discoveryObjects,
837
+ })
838
+ const closure = guestRuntimeProductsForInputs({
839
+ products: options.products,
840
+ selected: originalGuestArchiveSelections(selected, archives),
841
+ rewritten: options.rewritten,
842
+ sdk: options.sdk,
843
+ firstImage: options.firstImage,
844
+ containingImage: options.containingImage,
845
+ framework: options.framework,
846
+ })
847
+ const aliasSources = new Set(
848
+ archives.map(
849
+ (archive) =>
850
+ originals.get(path.resolve(archive.source)) ?? path.resolve(archive.source),
851
+ ),
852
+ )
853
+ const sdkProducts = {
854
+ products: options.products,
855
+ images: closure.images,
856
+ containingImages: closure.containingImages,
857
+ linkedArchives: closure.linkedArchives.filter(
858
+ (archive) => !aliasSources.has(path.resolve(archive)),
859
+ ),
860
+ }
861
+ const archiveArtifacts = guestAliasedSdkArchiveArtifacts({
862
+ products: options.products,
863
+ archives,
864
+ selected,
865
+ rewritten: options.rewritten,
866
+ images: new Map([...closure.images, ...closure.containingImages]),
867
+ })
868
+ return { args, selected, archives, sdkProducts, archiveArtifacts }
869
+ }
870
+
871
+ /** Collect undefined references and exact owners from selected original objects. */
872
+ export function selectedGuestSymbolInputs(
873
+ plan: GuestLinkPlan,
874
+ selected: readonly GuestLinkSelection[],
875
+ ): {
876
+ readonly symbols: readonly string[]
877
+ readonly definitions: readonly string[]
878
+ readonly hostImports: ReadonlySet<string>
879
+ readonly owners: ReadonlyMap<string, number>
880
+ readonly weakReferences: ReadonlyMap<string, ReadonlySet<string>>
881
+ readonly weakDefinitions: ReadonlyMap<string, ReadonlySet<string>>
882
+ readonly definitionObjects: ReadonlyMap<string, ReadonlySet<string>>
883
+ } {
884
+ const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]))
885
+ const archives = new Map<string, ReturnType<typeof readArMembers>>()
886
+ const symbols = new Set<string>()
887
+ const hostImports = new Set<string>()
888
+ const tags = new Set<string>()
889
+ const definitions = new Set<string>()
890
+ const owners = new Map<string, number>()
891
+ const weakReferences = new Map<string, ReadonlySet<string>>()
892
+ const weakDefinitions = new Map<string, ReadonlySet<string>>()
893
+ const definitionObjects = new Map<string, Set<string>>()
894
+ for (const item of selected) {
895
+ const artifact = artifacts.get(item.artifact)
896
+ if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`)
897
+ let bytes: Uint8Array
898
+ let name = item.artifact
899
+ if (item.member === null) bytes = fs.readFileSync(item.artifact)
900
+ else {
901
+ let members = archives.get(item.artifact)
902
+ if (!members) {
903
+ members = readArMembers(fs.readFileSync(item.artifact))
904
+ archives.set(item.artifact, members)
905
+ }
906
+ const matching = members.filter((member) => member.name === item.member)
907
+ if (matching.length !== 1)
908
+ throw new Error(
909
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`,
910
+ )
911
+ bytes = matching[0]!.bytes
912
+ name += `(${item.member})`
913
+ }
914
+ if (owners.has(name)) throw new Error(`duplicate selected symbol input ${name}`)
915
+ owners.set(name, selectedGuestInputImage(artifact, item.member))
916
+ const names = guestWasmSymbols(bytes)
917
+ weakReferences.set(name, new Set(names.weakUndefined))
918
+ weakDefinitions.set(name, new Set(names.weakDefined))
919
+ for (const symbol of names.undefined) symbols.add(symbol)
920
+ for (const symbol of names.hostImports) hostImports.add(symbol)
921
+ for (const symbol of names.tags) tags.add(symbol)
922
+ for (const symbol of names.defined) {
923
+ definitions.add(symbol)
924
+ const objects = definitionObjects.get(symbol) ?? new Set<string>()
925
+ objects.add(name)
926
+ definitionObjects.set(symbol, objects)
927
+ }
928
+ }
929
+ return {
930
+ symbols: [...symbols].filter((symbol) => !tags.has(symbol)),
931
+ definitions: [...definitions].filter((symbol) => !tags.has(symbol)),
932
+ hostImports,
933
+ owners,
934
+ weakReferences,
935
+ weakDefinitions,
936
+ definitionObjects,
937
+ }
938
+ }
939
+
940
+ /** Verify cross-image bindings from the actual linker's symbol trace. */
941
+ export function verifyGuestSymbolScopes(options: {
942
+ readonly args: readonly string[]
943
+ readonly directory: string
944
+ readonly wasmLd: string
945
+ readonly objects: readonly string[]
946
+ readonly symbols: readonly string[]
947
+ readonly owners: ReadonlyMap<string, number>
948
+ readonly callers: GuestLinkPlan['callers']
949
+ readonly startupObjects: ReadonlySet<string>
950
+ readonly weakReferences: ReadonlyMap<string, ReadonlySet<string>>
951
+ readonly weakDefinitions: ReadonlyMap<string, ReadonlySet<string>>
952
+ readonly definitionObjects: ReadonlyMap<string, ReadonlySet<string>>
953
+ /** Candidate provider objects from this source object's declared framework requests. */
954
+ readonly frameworkProviders: ReadonlyMap<string, ReadonlySet<string>>
955
+ /**
956
+ * Members of the system C library every image implicitly links, as native
957
+ * images link libSystem. It is statically owned by the containing image, so
958
+ * no other image's dependency scope reaches it.
959
+ */
960
+ readonly systemProviders: ReadonlySet<string>
961
+ /** Unresolved imports supplied by the host, not by another guest image. */
962
+ readonly hostImports: ReadonlySet<string>
963
+ }): {
964
+ bindings: readonly {
965
+ readonly symbol: string
966
+ readonly caller: number
967
+ readonly provider:
968
+ | { readonly kind: 'image'; readonly image: number }
969
+ | { readonly kind: 'physical-module' }
970
+ }[]
971
+ directBindings: NonNullable<GuestLinkPlan['directBindings']>
972
+ } {
973
+ const symbols = [...new Set(options.symbols)]
974
+ const requested = new Set(symbols)
975
+ if (symbols.some((symbol) => !symbol || symbol.includes('\0') || symbol.includes('\n')))
976
+ throw new Error('invalid traced guest symbol')
977
+ if (!symbols.length) return { bindings: [], directBindings: [] }
978
+ fs.mkdirSync(options.directory, { recursive: true })
979
+ const response = path.join(options.directory, 'scope-trace.rsp')
980
+ const output = path.join(options.directory, 'scope-trace.wasm')
981
+ const args = [
982
+ ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
983
+ ...options.objects,
984
+ ...symbols.map((symbol) => `--trace-symbol=${symbol}`),
985
+ ]
986
+ fs.writeFileSync(response, args.map((arg) => JSON.stringify(arg)).join(' '))
987
+ const tracePath = path.join(options.directory, 'scope-trace.txt')
988
+ const traceOutput = fs.openSync(tracePath, 'w')
989
+ try {
990
+ execFileSync(options.wasmLd, [`@${response}`], {
991
+ stdio: ['ignore', traceOutput, 'inherit'],
992
+ })
993
+ } finally {
994
+ fs.closeSync(traceOutput)
995
+ }
996
+ const records = new Map<
997
+ string,
998
+ {
999
+ references: Map<string, number>
1000
+ providers: Map<string, number>
1001
+ physicalModule: boolean
1002
+ }
1003
+ >()
1004
+ const consume = (line: string) => {
1005
+ const match = /^(.*): (reference to|definition of) (.*)$/.exec(line)
1006
+ if (!match) return
1007
+ const [, object, kind, symbol] = match
1008
+ if (!requested.has(symbol!)) return
1009
+ if (options.hostImports.has(symbol!)) return
1010
+ const record = records.get(symbol!) ?? {
1011
+ references: new Map<string, number>(),
1012
+ providers: new Map<string, number>(),
1013
+ physicalModule: false,
1014
+ }
1015
+ if (object === '<internal>' && kind === 'definition of') {
1016
+ record.physicalModule = true
1017
+ } else {
1018
+ const image = options.owners.get(object!)
1019
+ if (image === undefined)
1020
+ throw new Error(`traced guest object has no owner ${object}`)
1021
+ ;(kind === 'reference to' ? record.references : record.providers).set(
1022
+ object!,
1023
+ image,
1024
+ )
1025
+ }
1026
+ records.set(symbol!, record)
1027
+ }
1028
+ const traceInput = fs.openSync(tracePath, 'r')
1029
+ try {
1030
+ const decoder = new StringDecoder('utf8')
1031
+ const buffer = Buffer.allocUnsafe(64 * 1024)
1032
+ let pending = ''
1033
+ let count: number
1034
+ while ((count = fs.readSync(traceInput, buffer, 0, buffer.length, null)) > 0) {
1035
+ pending += decoder.write(buffer.subarray(0, count))
1036
+ let end: number
1037
+ while ((end = pending.indexOf('\n')) !== -1) {
1038
+ consume(pending.slice(0, end))
1039
+ pending = pending.slice(end + 1)
1040
+ }
1041
+ }
1042
+ consume(pending + decoder.end())
1043
+ } finally {
1044
+ fs.closeSync(traceInput)
1045
+ }
1046
+ const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]))
1047
+ const result: {
1048
+ symbol: string
1049
+ caller: number
1050
+ provider: { kind: 'image'; image: number } | { kind: 'physical-module' }
1051
+ }[] = []
1052
+ const directBindings: NonNullable<GuestLinkPlan['directBindings']>[number][] = []
1053
+ for (const symbol of symbols) {
1054
+ const record = records.get(symbol)
1055
+ if (!record || !record.references.size) continue
1056
+ if (!record.providers.size && options.hostImports.has(symbol)) continue
1057
+ const startupReferences = [...record.references].filter(
1058
+ ([object]) =>
1059
+ options.startupObjects.has(object) &&
1060
+ options.weakReferences.get(object)?.has(symbol),
1061
+ )
1062
+ const otherReferences = [...record.references].filter(
1063
+ ([object]) => !startupReferences.some(([startup]) => startup === object),
1064
+ )
1065
+ for (const [, caller] of startupReferences)
1066
+ if (!callers.has(caller))
1067
+ throw new Error(`guest image has no caller scope ${caller}`)
1068
+ if (startupReferences.length && !record.physicalModule) {
1069
+ const candidates = options.definitionObjects.get(symbol) ?? new Set<string>()
1070
+ if (candidates.size > 1 || record.providers.size > 1)
1071
+ throw new Error(`ambiguous startup provider ${symbol}`)
1072
+ if (
1073
+ candidates.size !== record.providers.size ||
1074
+ [...record.providers.keys()].some((object) => !candidates.has(object))
1075
+ )
1076
+ throw new Error(`unproven startup provider ${symbol}`)
1077
+ if (record.providers.size === 1) {
1078
+ const [providerObject, providerImage] = [...record.providers][0]!
1079
+ if (options.weakDefinitions.get(providerObject)?.has(symbol))
1080
+ throw new Error(`weak startup provider ${symbol}`)
1081
+ for (const [object] of startupReferences)
1082
+ directBindings.push({ object, symbol, providerObject, providerImage })
1083
+ }
1084
+ if (!otherReferences.length) continue
1085
+ }
1086
+ // an unresolved weak import stays absent, as in dyld; wasm-ld reports it
1087
+ // as an internal undefined_weak definition.
1088
+ if (
1089
+ !record.providers.size &&
1090
+ !record.physicalModule &&
1091
+ [...record.references.keys()].every((object) =>
1092
+ options.weakReferences.get(object)?.has(symbol),
1093
+ )
1094
+ )
1095
+ continue
1096
+ const providerImages = new Set(record.providers.values())
1097
+ // weak copies beside at most one strong definition are not ambiguous:
1098
+ // each caller binds the first definition in its own lookup order, as in
1099
+ // dyld, and a caller whose scope holds none binds the strong one.
1100
+ // the trace names only the copy wasm-ld kept, so every definition counts.
1101
+ const copies = [...(options.definitionObjects.get(symbol) ?? [])].flatMap(
1102
+ (object) => {
1103
+ const image = options.owners.get(object)
1104
+ return image === undefined
1105
+ ? []
1106
+ : [{ image, weak: !!options.weakDefinitions.get(object)?.has(symbol) }]
1107
+ },
1108
+ )
1109
+ const copyImages = new Set(copies.map((copy) => copy.image))
1110
+ const strongImages = new Set(
1111
+ copies.filter((copy) => !copy.weak).map((copy) => copy.image),
1112
+ )
1113
+ const interposed =
1114
+ !record.physicalModule && copyImages.size > 1 && strongImages.size <= 1
1115
+ const providerCount = interposed
1116
+ ? 1
1117
+ : providerImages.size + Number(record.physicalModule)
1118
+ // wasm-ld reports an undefined symbol only when live code uses it, so a
1119
+ // missing provider is the final link's to report.
1120
+ if (!providerCount) continue
1121
+ if (providerCount !== 1)
1122
+ throw new Error(`guest symbol has ambiguous provider ${symbol}`)
1123
+ const scopedReferences = record.physicalModule
1124
+ ? [...record.references]
1125
+ : otherReferences
1126
+ for (const [object, caller] of scopedReferences) {
1127
+ const scope = callers.get(caller)
1128
+ if (!scope) throw new Error(`guest image has no caller scope ${caller}`)
1129
+ if (record.physicalModule) {
1130
+ result.push({ symbol, caller, provider: { kind: 'physical-module' } })
1131
+ continue
1132
+ }
1133
+ const provider = interposed
1134
+ ? ([caller, ...scope].find((image) => copyImages.has(image)) ??
1135
+ [...strongImages][0] ??
1136
+ [...providerImages][0])
1137
+ : [...providerImages][0]!
1138
+ if (provider === undefined)
1139
+ throw new Error(`guest scope ${caller} omits every provider of ${symbol}`)
1140
+ if (caller === provider) continue
1141
+ // every image carries its own copy of a weak definition, so a caller
1142
+ // whose image defines one binds to it and needs no other provider.
1143
+ if (
1144
+ [...(options.definitionObjects.get(symbol) ?? [])].some(
1145
+ (definer) =>
1146
+ options.owners.get(definer) === caller &&
1147
+ options.weakDefinitions.get(definer)?.has(symbol),
1148
+ )
1149
+ )
1150
+ continue
1151
+ if (!scope.includes(provider)) {
1152
+ const candidates = options.definitionObjects.get(symbol) ?? new Set<string>()
1153
+ const providers = [...record.providers.keys()]
1154
+ // a weak import binds only inside the image's own dependency scope, so
1155
+ // a provider outside it leaves the import absent, as in dyld.
1156
+ if (
1157
+ options.weakReferences.get(object)?.has(symbol) &&
1158
+ !providers.some((provider) => options.systemProviders.has(provider))
1159
+ )
1160
+ continue
1161
+ // weak definitions of one symbol are copies of the same code, so a
1162
+ // strong reference may bind to whichever copy the link traced
1163
+ const equivalentCopies =
1164
+ providers.length === 1 &&
1165
+ candidates.has(providers[0]!) &&
1166
+ [...candidates].every((definer) =>
1167
+ options.weakDefinitions.get(definer)?.has(symbol),
1168
+ )
1169
+ if (
1170
+ !equivalentCopies &&
1171
+ (candidates.size !== 1 ||
1172
+ providers.length !== 1 ||
1173
+ !candidates.has(providers[0]!) ||
1174
+ !(
1175
+ options.systemProviders.has(providers[0]!) ||
1176
+ // a strong undefined reference binds through the process global
1177
+ // scope, the root image and its dependency closure, as in elf.
1178
+ provider === 0 ||
1179
+ callers.get(0)?.includes(provider) ||
1180
+ (!options.weakReferences.get(object)?.has(symbol) &&
1181
+ options.frameworkProviders.get(object)?.has(providers[0]!))
1182
+ ))
1183
+ )
1184
+ throw new Error(
1185
+ `guest scope ${caller} omits traced provider ${provider} for ${symbol}`,
1186
+ )
1187
+ directBindings.push({
1188
+ object,
1189
+ symbol,
1190
+ providerObject: providers[0]!,
1191
+ providerImage: provider,
1192
+ })
1193
+ continue
1194
+ }
1195
+ result.push({ symbol, caller, provider: { kind: 'image', image: provider } })
1196
+ }
1197
+ }
1198
+ return { bindings: result, directBindings }
1199
+ }
1200
+
1201
+ export interface GuestSdkLinkProducts {
1202
+ readonly products: readonly {
1203
+ readonly product: SwiftSdkProduct
1204
+ readonly root: string
1205
+ }[]
1206
+ readonly images: ReadonlyMap<string, number>
1207
+ readonly containingImages: ReadonlyMap<string, number>
1208
+ readonly linkedArchives: readonly string[]
1209
+ }
1210
+
1211
+ export interface PrunedGuestLinkOptions {
1212
+ readonly buildDirectory: string
1213
+ readonly toolchainBin: string
1214
+ readonly moduleRoot: string
1215
+ readonly staticClangTargets: readonly string[]
1216
+ readonly linkDirectory: string
1217
+ readonly mapPath: string
1218
+ /** source product that owns the generated shared lookup tables. */
1219
+ readonly ledgerDataImage: number
1220
+ /** the evaluated framework source product and its resolved logical image. */
1221
+ readonly framework: {
1222
+ readonly product: SwiftFrameworkProduct
1223
+ readonly root: string
1224
+ } | null
1225
+ /** source-produced SDK records and the image assigned to each product. */
1226
+ readonly sdkProducts:
1227
+ | GuestSdkLinkProducts
1228
+ | ((
1229
+ args: readonly string[],
1230
+ rewritten: ReadonlyMap<string, string>,
1231
+ sdk: SwiftPrunedSdkInputs,
1232
+ ) => GuestSdkLinkProducts)
1233
+ | null
1234
+ /** Select actual SDK members and aliases before assigning product images. */
1235
+ readonly prepareRuntime?: (
1236
+ args: readonly string[],
1237
+ rewritten: ReadonlyMap<string, string>,
1238
+ sdk: SwiftPrunedSdkInputs,
1239
+ ) => ReturnType<typeof prepareGuestRuntimeInputs>
1240
+ readonly projection?:
1241
+ | GuestLinkProjection
1242
+ | ((
1243
+ args: readonly string[],
1244
+ rewritten: ReadonlyMap<string, string>,
1245
+ sdk: SwiftPrunedSdkInputs,
1246
+ products: GuestSdkLinkProducts | null,
1247
+ plan: GuestLinkPlan,
1248
+ ) => GuestLinkProjection)
1249
+ readonly resolvePlan?: GuestLinkOptions['resolvePlan']
1250
+ /** Return original input paths; the prune step supplies the exact rewrites. */
1251
+ readonly plan: (
1252
+ args: readonly string[],
1253
+ rewritten: ReadonlyMap<string, string>,
1254
+ sdk: SwiftPrunedSdkInputs,
1255
+ sdkProducts: GuestSdkLinkProducts | null,
1256
+ ) => GuestLinkPlan
1257
+ }
1258
+
1259
+ export interface PrunedGuestLinkResult {
1260
+ readonly selected: readonly GuestLinkSelection[]
1261
+ readonly owners: ReadonlyMap<string, number>
1262
+ readonly generatedSectionOwners: ReadonlyMap<string, number>
1263
+ readonly sdk: SwiftPrunedSdkInputs
1264
+ readonly mapPath: string
1265
+ /** Linker-generated wrappers require separate per-caller attribution. */
1266
+ readonly generatedLedgerObject: string
1267
+ }
1268
+
1269
+ /** Run the normal pruner and use its selected, owned inputs for the guest link. */
1270
+ export function linkPrunedGuestImages(
1271
+ options: PrunedGuestLinkOptions,
1272
+ ): PrunedGuestLinkResult {
1273
+ let result: PrunedGuestLinkResult | undefined
1274
+ pruneSwiftWasmLink(
1275
+ options.buildDirectory,
1276
+ options.toolchainBin,
1277
+ options.moduleRoot,
1278
+ options.staticClangTargets,
1279
+ undefined,
1280
+ (args, rewritten, sdk) => {
1281
+ if (args.some((arg) => arg === '--Map' || arg.startsWith('--Map=')))
1282
+ throw new Error('guest link already has a linker map')
1283
+ const framework = options.framework
1284
+ const prepared = options.prepareRuntime?.(args, rewritten, sdk)
1285
+ if (prepared && options.sdkProducts !== null)
1286
+ throw new Error('guest runtime products supplied twice')
1287
+ const linkedArgs = prepared?.args ?? args
1288
+ const sdkProducts =
1289
+ prepared?.sdkProducts ??
1290
+ (typeof options.sdkProducts === 'function'
1291
+ ? options.sdkProducts(args, rewritten, sdk)
1292
+ : options.sdkProducts)
1293
+ const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts)
1294
+ let frameworkArtifacts: GuestLinkArtifact[] = []
1295
+ const selectedObjects =
1296
+ prepared &&
1297
+ new Set(
1298
+ prepared.selected
1299
+ .filter((item) => item.member === null)
1300
+ .map((item) => path.resolve(item.artifact)),
1301
+ )
1302
+ const selectedFramework =
1303
+ framework &&
1304
+ (!prepared ||
1305
+ framework.product.objects.some((object) => {
1306
+ const original = path.resolve(framework.root, object.path)
1307
+ const linked = path.resolve(rewritten.get(original) ?? original)
1308
+ return selectedObjects?.has(linked) ?? false
1309
+ }))
1310
+ if (framework && selectedFramework) {
1311
+ const image = sdkProducts?.images.get(
1312
+ frameworkRuntimeProductId(framework.product),
1313
+ )
1314
+ if (image === undefined)
1315
+ throw new Error(
1316
+ 'framework objects require their declared compiler runtime image',
1317
+ )
1318
+ frameworkArtifacts = guestFrameworkLinkArtifacts(
1319
+ framework.product,
1320
+ framework.root,
1321
+ linkedArgs,
1322
+ rewritten,
1323
+ image,
1324
+ )
1325
+ }
1326
+ if (sdkProducts) {
1327
+ for (const image of guestSdkProductImages(
1328
+ sdkProducts.products.map((entry) => entry.product),
1329
+ sdkProducts.images,
1330
+ )) {
1331
+ const planned = sourcePlan.images.find((entry) => entry.id === image.id)
1332
+ if (
1333
+ !planned ||
1334
+ planned.name !== image.name ||
1335
+ planned.dependencies.length !== image.dependencies.length ||
1336
+ planned.dependencies.some(
1337
+ (dependency, index) => dependency !== image.dependencies[index],
1338
+ )
1339
+ )
1340
+ throw new Error(`SDK image scope differs from source product ${image.name}`)
1341
+ }
1342
+ }
1343
+ const plan = remapGuestLinkPlan(
1344
+ {
1345
+ ...sourcePlan,
1346
+ artifacts: [
1347
+ ...sourcePlan.artifacts,
1348
+ ...frameworkArtifacts,
1349
+ ...(sdkProducts
1350
+ ? guestSdkProductLinkArtifacts(
1351
+ sdkProducts.products,
1352
+ sdk,
1353
+ linkedArgs,
1354
+ sdkProducts.linkedArchives,
1355
+ rewritten,
1356
+ new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
1357
+ prepared?.selected,
1358
+ )
1359
+ : []),
1360
+ ...(prepared?.archiveArtifacts ?? []),
1361
+ ],
1362
+ },
1363
+ rewritten,
1364
+ )
1365
+ let owners: ReadonlyMap<string, number> = new Map()
1366
+ let generatedSectionOwners: ReadonlyMap<string, number> = new Map()
1367
+ let projection =
1368
+ typeof options.projection === 'function'
1369
+ ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan)
1370
+ : options.projection
1371
+ if (projection && prepared) {
1372
+ const identities = new Map(projection.identities)
1373
+ for (const [before, after] of rewritten) {
1374
+ const identity = identities.get(before)
1375
+ const existing = identities.get(after)
1376
+ if (identity !== undefined && existing !== undefined && existing !== identity)
1377
+ throw new Error(`rewritten guest input has conflicting identity ${after}`)
1378
+ if (identity !== undefined) identities.set(after, identity)
1379
+ }
1380
+ projection = {
1381
+ ...projection,
1382
+ identities: aliasGuestLinkIdentities(identities, prepared.archives),
1383
+ }
1384
+ }
1385
+ const selected = linkCompleteGuestImages({
1386
+ plan,
1387
+ args: [...linkedArgs, `--Map=${options.mapPath}`],
1388
+ directory: options.linkDirectory,
1389
+ wasmLd: path.join(options.toolchainBin, 'wasm-ld'),
1390
+ clang: path.join(options.toolchainBin, 'clang'),
1391
+ llvmAr: path.join(options.toolchainBin, 'llvm-ar'),
1392
+ ledgerDataImage: options.ledgerDataImage,
1393
+ projection,
1394
+ resolvePlan: options.resolvePlan,
1395
+ onLinkedOwners: (value) => {
1396
+ owners = value
1397
+ },
1398
+ onLinkedSections: (value) => {
1399
+ generatedSectionOwners = value
1400
+ },
1401
+ })
1402
+ result = {
1403
+ selected,
1404
+ owners,
1405
+ generatedSectionOwners,
1406
+ sdk,
1407
+ mapPath: options.mapPath,
1408
+ generatedLedgerObject: path.join(options.linkDirectory, 'ledger.o'),
1409
+ }
1410
+ },
1411
+ )
1412
+ if (!result) throw new Error('guest link did not receive pruned inputs')
1413
+ return result
1414
+ }