peachsim 0.1.2599 → 0.1.2601

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 (133) hide show
  1. package/cli/commands/detect.ts +16 -10
  2. package/dist-lib/agent-daemon-client.cjs +1 -1
  3. package/dist-lib/agent-events.cjs +1 -1
  4. package/dist-lib/attached-projects.cjs +1 -1
  5. package/dist-lib/auth/shared-session.cjs +1 -1
  6. package/dist-lib/backend-origin.cjs +1 -1
  7. package/dist-lib/beta.cjs +1 -1
  8. package/dist-lib/beta.mjs +2 -2
  9. package/dist-lib/bridge-constants.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.mjs +5 -5
  12. package/dist-lib/bridge-contract.cjs +1 -1
  13. package/dist-lib/bridge-contract.mjs +3 -3
  14. package/dist-lib/bundle-channel.cjs +11432 -11074
  15. package/dist-lib/capture-contract.cjs +1 -1
  16. package/dist-lib/capture-contract.mjs +3 -3
  17. package/dist-lib/cloud-contract.cjs +1 -1
  18. package/dist-lib/cloud-contract.mjs +3 -3
  19. package/dist-lib/cloud-test-args.cjs +1 -1
  20. package/dist-lib/cloud-test-args.mjs +2 -2
  21. package/dist-lib/cloud.cjs +1 -1
  22. package/dist-lib/cloud.mjs +7 -7
  23. package/dist-lib/config.cjs +1 -1
  24. package/dist-lib/config.mjs +5 -5
  25. package/dist-lib/detox/index.cjs +11 -2276
  26. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  27. package/dist-lib/esm-chunks/{acorn-KSGHEC5L.mjs → acorn-QZ2CUPHM.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-CK4NJNKN.mjs → chunk-36UH63MB.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-HDVUUMWS.mjs → chunk-3XOVNNLW.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-IFVAWDHV.mjs → chunk-4DSC65OJ.mjs} +5 -5
  31. package/dist-lib/esm-chunks/{chunk-KYAFF2Q6.mjs → chunk-5SWBLCBW.mjs} +5 -5
  32. package/dist-lib/esm-chunks/{chunk-JDBFQAWY.mjs → chunk-6YPM2YPR.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-CQ4RWCRW.mjs → chunk-7NCBX65P.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-BWGJ6NXY.mjs → chunk-AJARDL5C.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-7AHYPBWO.mjs → chunk-CK3Z4ICA.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-VQUR3L3X.mjs → chunk-E26HGQSD.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-WIT6VFZO.mjs → chunk-EWL5AKTY.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-F5HRYLB4.mjs → chunk-EZ4QHTFM.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-MPWL7GEG.mjs → chunk-K7OOJRZB.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-WTHOPBFM.mjs → chunk-N4YUQWGP.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-P4IK6BSJ.mjs → chunk-OSRDW3DT.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-E2OVC7ZZ.mjs → chunk-PE2YXAKR.mjs} +3 -3
  43. package/dist-lib/esm-chunks/{chunk-PC5C5JIJ.mjs → chunk-Q37TTP7V.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-7WHQG7AP.mjs → chunk-RL5UG2KA.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-V6QNDMVW.mjs → chunk-SGLGSFK7.mjs} +2 -2
  46. package/dist-lib/esm-chunks/{chunk-35Z53AZY.mjs → chunk-SYLKF7NM.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-4D3WJ4I7.mjs → chunk-VZZ4446Y.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-YJOP3ITO.mjs → chunk-Y4RGOFWV.mjs} +4 -4
  49. package/dist-lib/esm-chunks/{chunk-S6JNYU27.mjs → chunk-ZGZPGLDT.mjs} +1024 -653
  50. package/dist-lib/esm-chunks/{metro-layout-parser-PPZSA2LY.mjs → metro-layout-parser-GIQWWTMJ.mjs} +3 -3
  51. package/dist-lib/esm-chunks/{swift-package-prebuilt-L7A7TT6Q.mjs → swift-package-prebuilt-XEZH6YEY.mjs} +10 -10
  52. package/dist-lib/esm-chunks/{swift-sdk-app-module-B63EAEQ5.mjs → swift-sdk-app-module-COF7L4HK.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-QQQA3AAT.mjs → swift-sdk-image-AQCBWHPL.mjs} +14 -14
  54. package/dist-lib/esm-chunks/{swift-sdk-image-producer-QP6XD5O7.mjs → swift-sdk-image-producer-5L5LD4VP.mjs} +4 -4
  55. package/dist-lib/expo-swift-bundle.cjs +12833 -12475
  56. package/dist-lib/expo-swift-metadata.cjs +1 -1
  57. package/dist-lib/expo-swift-metadata.mjs +7 -7
  58. package/dist-lib/home-paths.cjs +1 -1
  59. package/dist-lib/host/bridge-host.cjs +12809 -12451
  60. package/dist-lib/host/fetch-proxy-handler.cjs +5434 -5422
  61. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  62. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  63. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  64. package/dist-lib/host/websocket-proxy.cjs +1 -1
  65. package/dist-lib/index.cjs +10 -2275
  66. package/dist-lib/kotlin-host.cjs +1 -1
  67. package/dist-lib/menu.cjs +1 -1
  68. package/dist-lib/menu.mjs +3 -3
  69. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  70. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  71. package/dist-lib/metro-production-bundle.cjs +1 -1
  72. package/dist-lib/metro-production-bundle.mjs +4 -4
  73. package/dist-lib/native-app-identity-project.cjs +23 -11
  74. package/dist-lib/native-app-identity-project.mjs +16 -16
  75. package/dist-lib/native-app-identity.cjs +1 -1
  76. package/dist-lib/native-app-identity.mjs +6 -6
  77. package/dist-lib/native-firebase-metadata.cjs +1 -1
  78. package/dist-lib/native-firebase-metadata.mjs +3 -3
  79. package/dist-lib/pdfium-raster.cjs +1 -1
  80. package/dist-lib/pdfium-raster.mjs +2 -2
  81. package/dist-lib/plist.cjs +1 -1
  82. package/dist-lib/plist.mjs +3 -3
  83. package/dist-lib/profiles.cjs +1 -1
  84. package/dist-lib/public-brand.cjs +1 -1
  85. package/dist-lib/public-origins-lib-esm.json +82 -81
  86. package/dist-lib/public-origins-lib.json +372 -435
  87. package/dist-lib/react-native-host-modules.cjs +1 -1
  88. package/dist-lib/react-native-host-modules.mjs +2 -2
  89. package/dist-lib/reap-browser.cjs +1 -1
  90. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  91. package/dist-lib/sdk.cjs +1 -1
  92. package/dist-lib/sdk.mjs +8 -8
  93. package/dist-lib/skills.cjs +1107 -745
  94. package/dist-lib/swift-compile.cjs +1029 -652
  95. package/dist-lib/swift-compile.mjs +10 -10
  96. package/dist-lib/swift-package.cjs +1 -1
  97. package/dist-lib/swift-package.mjs +3 -3
  98. package/dist-lib/swift-submit.cjs +1 -1
  99. package/dist-lib/swift-submit.mjs +6 -6
  100. package/dist-lib/swift-svg-raster.cjs +1 -1
  101. package/dist-lib/swift-svg-raster.mjs +2 -2
  102. package/dist-lib/swift-toolchain.cjs +1 -1
  103. package/dist-lib/swift.cjs +1 -1
  104. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  107. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  110. package/dist-lib/vendor/ignore.cjs +1 -1
  111. package/dist-lib/vendor/magic-string.cjs +1 -1
  112. package/dist-lib/vendor/plist.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/package.json +1 -3
  126. package/src/device-catalog.ts +4 -5
  127. package/src/ios-version.ts +8 -0
  128. package/src/kotlin-version-catalog.ts +6 -4
  129. package/src/swift-guest-compile.ts +5 -3
  130. package/src/swift-guest-image-ledger.ts +563 -264
  131. package/src/swift-guest-link.ts +628 -468
  132. package/src/wasm-binary-sections.ts +1 -1
  133. package/dist-lib/vendor/smol-toml.cjs +0 -768
@@ -1,9 +1,11 @@
1
1
  // perform a source-owned link with a caller-scoped guest symbol ledger.
2
2
  // the discovery link records wasm-ld's selected objects and archive members;
3
3
  // the final link rewrites those objects without editing their sources.
4
- import { execFileSync } from 'node:child_process'
4
+ import { execFile, execFileSync } from 'node:child_process'
5
5
  import fs from 'node:fs'
6
6
  import path from 'node:path'
7
+ import { promisify } from 'node:util'
8
+ import { mapLimit } from '../../../src/helpers/mapLimit'
7
9
  import {
8
10
  aliasGuestArchive,
9
11
  aliasGuestLinkIdentities,
@@ -61,6 +63,16 @@ import type {
61
63
  SwiftSdkProduct,
62
64
  } from './swiftRuntimeProductContract'
63
65
 
66
+ const execFileAsync = promisify(execFile)
67
+
68
+ export interface PreselectedGuestDiscovery {
69
+ readonly wasm: string
70
+ readonly map: string
71
+ readonly why: string
72
+ readonly trace: string
73
+ readonly projectionObject: string
74
+ }
75
+
64
76
  export interface GuestLinkOptions {
65
77
  readonly plan: GuestLinkPlan
66
78
  readonly args: readonly string[]
@@ -75,6 +87,7 @@ export interface GuestLinkOptions {
75
87
  /** caller-owned sections in the generated ledger object. */
76
88
  readonly onLinkedSections?: (owners: ReadonlyMap<string, number>) => void
77
89
  readonly projection?: GuestLinkProjection
90
+ readonly preselectionDiscovery?: PreselectedGuestDiscovery
78
91
  readonly sharedSdk?: {
79
92
  readonly callers: Readonly<Record<string, number>>
80
93
  readonly hasContainingObject: (identity: string) => boolean
@@ -146,8 +159,12 @@ export function remapGuestLinkPlan(
146
159
  }
147
160
  }
148
161
 
149
- /** Resolve actual object and archive paths using the linker's search order. */
150
- export function guestLinkInputFiles(args: readonly string[]): string[] {
162
+ const WASM_MAGIC = Buffer.from([0, 97, 115, 109])
163
+ const BITCODE_MAGIC = Buffer.from([66, 67, 192, 222])
164
+
165
+ function guestLinkInputFilesWithKind(
166
+ args: readonly string[],
167
+ ): { readonly path: string; readonly kind: 'archive' | 'object' }[] {
151
168
  const dirs: string[] = []
152
169
  for (let i = 0; i < args.length; i++) {
153
170
  const arg = args[i]!
@@ -155,7 +172,8 @@ export function guestLinkInputFiles(args: readonly string[]): string[] {
155
172
  else if (arg.startsWith('-L')) dirs.push(arg.slice(2))
156
173
  else if (arg.startsWith('--library-path=')) dirs.push(arg.slice(15))
157
174
  }
158
- const inputs = new Set<string>()
175
+ const magic = Buffer.allocUnsafe(8)
176
+ const inputs = new Map<string, 'archive' | 'object'>()
159
177
  for (let i = 0; i < args.length; i++) {
160
178
  const arg = args[i]!
161
179
  if (arg === '-L' || arg === '--library-path' || arg === '-o' || arg === '--output') {
@@ -164,6 +182,7 @@ export function guestLinkInputFiles(args: readonly string[]): string[] {
164
182
  }
165
183
  if (arg.startsWith('@')) throw new Error(`nested linker response file ${arg}`)
166
184
  let file: string | undefined
185
+ let kind: 'archive' | 'object' | undefined
167
186
  if (
168
187
  arg === '-l' ||
169
188
  arg === '--library' ||
@@ -181,25 +200,58 @@ export function guestLinkInputFiles(args: readonly string[]): string[] {
181
200
  .map((dir) => path.join(dir, archive))
182
201
  .find((item) => fs.existsSync(item))
183
202
  if (!file) throw new Error(`unresolved guest link library ${name}`)
184
- } else if (!arg.startsWith('-') && fs.existsSync(arg) && fs.statSync(arg).isFile()) {
185
- const fd = fs.openSync(arg, 'r')
186
- const magic = Buffer.alloc(8)
187
- try {
188
- fs.readSync(fd, magic, 0, magic.length, 0)
189
- } finally {
190
- fs.closeSync(fd)
203
+ } else if (!arg.startsWith('-')) {
204
+ const resolved = path.resolve(arg)
205
+ if (inputs.has(resolved)) continue
206
+ const stat = fs.statSync(arg, { throwIfNoEntry: false })
207
+ if (stat?.isFile()) {
208
+ const fd = fs.openSync(arg, 'r')
209
+ let read = 0
210
+ try {
211
+ read = fs.readSync(fd, magic, 0, 8, 0)
212
+ } finally {
213
+ fs.closeSync(fd)
214
+ }
215
+ if (read >= 4) {
216
+ if (
217
+ read >= 8 &&
218
+ (magic.toString('ascii') === '!<arch>\n' ||
219
+ magic.toString('ascii') === '!<thin>\n')
220
+ ) {
221
+ file = arg
222
+ kind = 'archive'
223
+ } else if (
224
+ magic.subarray(0, 4).equals(WASM_MAGIC) ||
225
+ magic.subarray(0, 4).equals(BITCODE_MAGIC)
226
+ ) {
227
+ file = arg
228
+ kind = 'object'
229
+ }
230
+ }
231
+ }
232
+ }
233
+ if (file) {
234
+ const resolved = path.resolve(file)
235
+ if (!inputs.has(resolved)) {
236
+ if (!kind) {
237
+ const fd = fs.openSync(resolved, 'r')
238
+ try {
239
+ fs.readSync(fd, magic, 0, 8, 0)
240
+ } finally {
241
+ fs.closeSync(fd)
242
+ }
243
+ kind = magic.toString('ascii') === '!<arch>\n' ? 'archive' : 'object'
244
+ }
245
+ inputs.set(resolved, kind)
191
246
  }
192
- if (
193
- magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) ||
194
- magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) ||
195
- magic.toString('ascii') === '!<arch>\n' ||
196
- magic.toString('ascii') === '!<thin>\n'
197
- )
198
- file = arg
199
247
  }
200
- if (file) inputs.add(path.resolve(file))
201
248
  }
202
- return [...inputs]
249
+ return [...inputs].map(([filePath, kind]) => ({ path: filePath, kind }))
250
+ }
251
+
252
+ /** Resolve actual object and archive paths using the linker's search order. */
253
+ export function guestLinkInputFiles(args: readonly string[]): string[] {
254
+ return guestLinkInputFilesWithKind(args).map((item) => item.path)
203
255
  }
204
256
 
205
257
  /** Actual object and archive inputs that have not been assigned to an image. */
@@ -393,17 +445,17 @@ function withOutput(
393
445
  return result
394
446
  }
395
447
 
396
- export function linkGuestImages(
448
+ export async function linkGuestImages(
397
449
  options: GuestLinkOptions,
398
- ): readonly GuestLinkSelection[] {
450
+ ): Promise<readonly GuestLinkSelection[]> {
399
451
  const { args, directory, wasmLd, clang, llvmAr } = options
400
452
  let plan = options.plan
401
453
  if (!plan.images.some((image) => image.id === options.ledgerDataImage))
402
454
  throw new Error(`unknown ledger data image ${options.ledgerDataImage}`)
403
455
  fs.mkdirSync(directory, { recursive: true })
404
- const discovery = path.join(directory, 'discovery.wasm')
456
+ let discovery = path.join(directory, 'discovery.wasm')
405
457
  const whyPath = path.join(directory, 'why-extract.txt')
406
- const mapPath = path.join(directory, 'discovery.map')
458
+ let mapPath = path.join(directory, 'discovery.map')
407
459
  const runLink = (name: string, arguments_: readonly string[]) => {
408
460
  const response = path.join(directory, `${name}.rsp`)
409
461
  const trace = path.join(directory, `${name}-inputs.txt`)
@@ -422,21 +474,29 @@ export function linkGuestImages(
422
474
  }
423
475
  return fs.readFileSync(trace, 'utf8')
424
476
  }
477
+ const preselection =
478
+ options.projection && options.preselectionDiscovery
479
+ ? options.preselectionDiscovery
480
+ : undefined
425
481
  let discoveryProjection: string | undefined
426
482
  if (options.projection) {
427
- const source = path.join(directory, 'projection-discovery.c')
428
- discoveryProjection = path.join(directory, 'projection-discovery.o')
429
- fs.writeFileSync(
430
- source,
431
- '#include "guest-image-projection.h"\n' +
432
- 'const struct peach_guest_image __peach_guest_images[] = {{0}};\n' +
433
- 'const uint32_t __peach_guest_image_count = 0;\n',
434
- )
435
- execFileSync(
436
- clang,
437
- [...options.projection.clangOptions, '-c', source, '-o', discoveryProjection],
438
- { stdio: 'pipe' },
439
- )
483
+ if (preselection) {
484
+ discoveryProjection = preselection.projectionObject
485
+ } else {
486
+ const source = path.join(directory, 'projection-discovery.c')
487
+ discoveryProjection = path.join(directory, 'projection-discovery.o')
488
+ fs.writeFileSync(
489
+ source,
490
+ '#include "guest-image-projection.h"\n' +
491
+ 'const struct peach_guest_image __peach_guest_images[] = {{0}};\n' +
492
+ 'const uint32_t __peach_guest_image_count = 0;\n',
493
+ )
494
+ execFileSync(
495
+ clang,
496
+ [...options.projection.clangOptions, '-c', source, '-o', discoveryProjection],
497
+ { stdio: 'pipe' },
498
+ )
499
+ }
440
500
  }
441
501
  const archives = new Map<string, ReturnType<typeof readArMembers>>()
442
502
  const memberBytes = new Map<string, Map<string, Buffer>>()
@@ -474,6 +534,17 @@ export function linkGuestImages(
474
534
  }
475
535
  return byName.get(item.member)!
476
536
  }
537
+ const reusePreselection = () => {
538
+ discovery = preselection!.wasm
539
+ mapPath = preselection!.map
540
+ return selectedGuestLinkInputs(
541
+ plan,
542
+ args,
543
+ fs.readFileSync(preselection!.why, 'utf8'),
544
+ fs.readFileSync(preselection!.trace, 'utf8'),
545
+ archives,
546
+ )
547
+ }
477
548
  const discover = (provider: boolean) => {
478
549
  const trace = runLink('discovery', [
479
550
  ...withOutput(args, discovery, true),
@@ -506,11 +577,13 @@ export function linkGuestImages(
506
577
  const eagerProvider = [...eagerObjects].some((artifact) =>
507
578
  needsProvider({ artifact, member: null }),
508
579
  )
509
- let selected = discover(eagerProvider)
580
+ let selected =
581
+ eagerProvider && preselection ? reusePreselection() : discover(eagerProvider)
510
582
  const provider =
511
583
  eagerProvider ||
512
584
  selected.some((item) => !eagerObjects.has(item.artifact) && needsProvider(item))
513
- if (provider && !eagerProvider) selected = discover(true)
585
+ if (provider && !eagerProvider)
586
+ selected = preselection ? reusePreselection() : discover(true)
514
587
  if (options.resolvePlan) {
515
588
  const identity = (value: GuestLinkPlan) =>
516
589
  JSON.stringify([
@@ -634,84 +707,11 @@ export function linkGuestImages(
634
707
  ),
635
708
  sdkCallerImages,
636
709
  })
637
- const replacements = new Map<string, string>()
638
- const linkedOwners = new Map<string, number>()
639
- const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]))
640
- const appObjects = new Map<string, number>()
641
- const sdkObjects = new Map<
642
- string,
643
- { image: number; product: string; identity: string }
644
- >()
645
- const finalArchives = new Map<string, ReturnType<typeof readArMembers>>()
646
- for (const [index, artifact] of plan.artifacts.entries()) {
647
- const prefix = `${artifact.path}(`
648
- if (artifact.kind === 'object') {
649
- const object = ledgerObjects.get(artifact.path)
650
- if (!object) continue
651
- const output = path.join(directory, `object-${index}.o`)
652
- fs.writeFileSync(output, object.bytes)
653
- replacements.set(artifact.path, output)
654
- linkedOwners.set(output, selectedGuestInputImage(artifact, null))
655
- const image = selectedGuestInputImage(artifact, null)
656
- if (object.sdkProduct === undefined) appObjects.set(output, image)
657
- else
658
- sdkObjects.set(output, {
659
- image,
660
- product: object.sdkProduct,
661
- identity: sdkIdentities.get(object.path)!,
662
- })
663
- continue
664
- }
665
- const members = archives.get(artifact.path)
666
- if (!members) continue
667
- const listing = execFileSync(llvmAr, ['t', artifact.path], {
668
- encoding: 'utf8',
669
- }).trimEnd()
670
- const listed = listing ? listing.split('\n') : []
671
- if (
672
- listed.length !== members.length ||
673
- new Set(listed).size !== listed.length ||
674
- members.some(
675
- (member, i) =>
676
- listed[i] !== member.name || path.basename(member.name) !== member.name,
677
- )
678
- )
679
- throw new Error(`unsupported archive layout ${artifact.path}`)
680
- const memberDir = path.join(directory, `archive-${index}`)
681
- fs.mkdirSync(memberDir, { recursive: true })
682
- const output = path.join(directory, `archive-${index}.a`)
683
- const inputs = members.map((member) => {
684
- const memberOutput = path.join(memberDir, member.name)
685
- const rewritten = ledgerObjects.get(`${prefix}${member.name})`)
686
- fs.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes)
687
- if (rewritten) {
688
- const image = selectedGuestInputImage(artifact, member.name)
689
- linkedOwners.set(`${output}(${member.name})`, image)
690
- if (rewritten.sdkProduct === undefined) appObjects.set(memberOutput, image)
691
- else
692
- sdkObjects.set(`${output}(${member.name})`, {
693
- image,
694
- product: rewritten.sdkProduct,
695
- identity: sdkIdentities.get(rewritten.path)!,
696
- })
697
- }
698
- return memberOutput
699
- })
700
- fs.rmSync(output, { force: true })
701
- const response = path.join(memberDir, 'members.rsp')
702
- fs.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(' '))
703
- execFileSync(llvmAr, ['rcs', output, `@${response}`], { stdio: 'pipe' })
704
- finalArchives.set(
705
- output,
706
- members.map((member) => ({ name: member.name, bytes: new Uint8Array(0) })),
707
- )
708
- replacements.set(artifact.path, output)
709
- }
710
- const compileLedger = (name: string, source: string) => {
710
+ const compileLedgerAsync = (name: string, source: string): Promise<string> => {
711
711
  const irPath = path.join(directory, `${name}.ll`)
712
712
  const object = path.join(directory, `${name}.o`)
713
713
  fs.writeFileSync(irPath, source)
714
- execFileSync(
714
+ return execFileAsync(
715
715
  clang,
716
716
  [
717
717
  '--target=wasm64-unknown-wasip1-threads',
@@ -721,197 +721,306 @@ export function linkGuestImages(
721
721
  '-o',
722
722
  object,
723
723
  ],
724
- { stdio: 'pipe' },
725
- )
726
- return object
724
+ { maxBuffer: 64 * 1024 * 1024 },
725
+ ).then(() => object)
727
726
  }
728
- const ledgerObject = compileLedger('ledger', ledger.llvmIR)
729
- const lazyExports = path.join(directory, 'lazy-exports.rsp')
730
- fs.writeFileSync(lazyExports, guestLazyExports(ledger.lazyFunctions))
731
- linkedOwners.set(ledgerObject, options.ledgerDataImage)
732
- const sectionOwners = new Map(
733
- ledger.callerWrappers.map(({ symbol, image }) => [
734
- `${ledgerObject}:(${symbol})`,
735
- image,
736
- ]),
737
- )
738
- const byToken = new Map(
739
- occurrences(plan, args).map(({ artifact, token }) => [
740
- token,
741
- replacements.get(artifact.path),
742
- ]),
743
- )
744
- // the same input named twice (a product link line repeats shared objects)
745
- // is one file for the linker; rewritten copies would otherwise load twice.
746
- const placed = new Set<string>()
747
- const finalArgs = args
748
- .map((arg) => byToken.get(arg) ?? arg)
749
- .filter((arg) => {
750
- if (!arg.endsWith('.o') && !arg.endsWith('.a')) return true
751
- if (placed.has(arg)) return false
752
- placed.add(arg)
753
- return true
754
- })
755
- const finalOutput = path.join(directory, 'final.wasm')
756
- const finalWhy = path.join(directory, 'final-why-extract.txt')
757
- const linkFinal = (projectionObject?: string, layoutMap?: string) =>
758
- runLink('final', [
759
- ...withOutput(finalArgs, finalOutput, false),
760
- ledgerObject,
761
- `@${lazyExports}`,
762
- ...(projectionObject ? [projectionObject] : []),
763
- ...(provider ? [`--undefined=${providerSymbol}`] : []),
764
- ...(layoutMap ? [`--Map=${layoutMap}`] : []),
765
- `--why-extract=${finalWhy}`,
766
- ])
767
- let projectionObject: string | undefined
768
- let projectionStorage: ReservedGuestProjectionStorage | undefined
769
- let finalTrace: string
770
- if (options.projection) {
771
- const projection = options.projection
772
- if (!plan.images.some((image) => image.id === projection.image))
773
- throw new Error('guest projection has no source image')
774
- if (
775
- projection.images.length !== plan.images.length ||
776
- projection.images.some(
777
- (image, index) => image.image !== index || plan.images[index]?.id !== index,
727
+ // start compiling both generated ledger objects immediately so clang overlaps
728
+ // with writing rewritten objects, packing archives, and the final link.
729
+ const ledgerObjectPromise = compileLedgerAsync('ledger', ledger.llvmIR)
730
+ const appLedgerObjectPromise =
731
+ options.onSplitInputs && ledger.appLLVMIR
732
+ ? compileLedgerAsync('app-ledger', ledger.appLLVMIR)
733
+ : undefined
734
+ try {
735
+ const replacements = new Map<string, string>()
736
+ const linkedOwners = new Map<string, number>()
737
+ const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]))
738
+ const appObjects = new Map<string, number>()
739
+ const sdkObjects = new Map<
740
+ string,
741
+ { image: number; product: string; identity: string }
742
+ >()
743
+ const finalArchives = new Map<string, ReturnType<typeof readArMembers>>()
744
+ const archiveJobs: {
745
+ readonly artifact: GuestLinkArtifact
746
+ readonly index: number
747
+ readonly members: ReturnType<typeof readArMembers>
748
+ readonly memberDir: string
749
+ readonly output: string
750
+ readonly response: string
751
+ }[] = []
752
+ for (const [index, artifact] of plan.artifacts.entries()) {
753
+ const prefix = `${artifact.path}(`
754
+ if (artifact.kind === 'object') {
755
+ const object = ledgerObjects.get(artifact.path)
756
+ if (!object) continue
757
+ const output = path.join(directory, `object-${index}.o`)
758
+ fs.writeFileSync(output, object.bytes)
759
+ replacements.set(artifact.path, output)
760
+ linkedOwners.set(output, selectedGuestInputImage(artifact, null))
761
+ const image = selectedGuestInputImage(artifact, null)
762
+ if (object.sdkProduct === undefined) appObjects.set(output, image)
763
+ else
764
+ sdkObjects.set(output, {
765
+ image,
766
+ product: object.sdkProduct,
767
+ identity: sdkIdentities.get(object.path)!,
768
+ })
769
+ continue
770
+ }
771
+ const members = archives.get(artifact.path)
772
+ if (!members) continue
773
+ const memberDir = path.join(directory, `archive-${index}`)
774
+ fs.mkdirSync(memberDir, { recursive: true })
775
+ const output = path.join(directory, `archive-${index}.a`)
776
+ const inputs = members.map((member) => {
777
+ const memberOutput = path.join(memberDir, member.name)
778
+ const rewritten = ledgerObjects.get(`${prefix}${member.name})`)
779
+ fs.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes)
780
+ if (rewritten) {
781
+ const image = selectedGuestInputImage(artifact, member.name)
782
+ linkedOwners.set(`${output}(${member.name})`, image)
783
+ if (rewritten.sdkProduct === undefined) appObjects.set(memberOutput, image)
784
+ else
785
+ sdkObjects.set(`${output}(${member.name})`, {
786
+ image,
787
+ product: rewritten.sdkProduct,
788
+ identity: sdkIdentities.get(rewritten.path)!,
789
+ })
790
+ }
791
+ return memberOutput
792
+ })
793
+ fs.rmSync(output, { force: true })
794
+ const response = path.join(memberDir, 'members.rsp')
795
+ fs.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(' '))
796
+ finalArchives.set(
797
+ output,
798
+ members.map((member) => ({ name: member.name, bytes: new Uint8Array(0) })),
778
799
  )
779
- )
780
- throw new Error('guest projection image order differs from link plan')
781
- const selectedInputs = selectedGuestManifestInputs(
782
- plan,
783
- selected,
784
- projection.identities,
785
- readSelected,
786
- )
787
- const images = projection.images.map((image) =>
788
- createGuestImageManifest({
789
- ...image,
790
- inputs: selectedInputs.get(image.image) ?? [],
791
- linkOptions: projection.linkOptions,
792
- regions: [],
800
+ replacements.set(artifact.path, output)
801
+ archiveJobs.push({ artifact, index, members, memberDir, output, response })
802
+ }
803
+ const [ledgerObject] = await Promise.all([
804
+ ledgerObjectPromise,
805
+ mapLimit(archiveJobs, 8, async ({ artifact, members, output, response }) => {
806
+ const { stdout } = await execFileAsync(llvmAr, ['t', artifact.path], {
807
+ encoding: 'utf8',
808
+ maxBuffer: 64 * 1024 * 1024,
809
+ })
810
+ const listing = stdout.trimEnd()
811
+ const listed = listing ? listing.split('\n') : []
812
+ if (
813
+ listed.length !== members.length ||
814
+ new Set(listed).size !== listed.length ||
815
+ members.some(
816
+ (member, i) =>
817
+ listed[i] !== member.name || path.basename(member.name) !== member.name,
818
+ )
819
+ )
820
+ throw new Error(`unsupported archive layout ${artifact.path}`)
821
+ await execFileAsync(llvmAr, ['rcs', output, `@${response}`], {
822
+ maxBuffer: 64 * 1024 * 1024,
823
+ })
793
824
  }),
825
+ ])
826
+ const lazyExports = path.join(directory, 'lazy-exports.rsp')
827
+ fs.writeFileSync(lazyExports, guestLazyExports(ledger.lazyFunctions))
828
+ linkedOwners.set(ledgerObject, options.ledgerDataImage)
829
+ const sectionOwners = new Map(
830
+ ledger.callerWrappers.map(({ symbol, image }) => [
831
+ `${ledgerObject}:(${symbol})`,
832
+ image,
833
+ ]),
794
834
  )
795
- objectBytes.clear()
796
- memberBytes.clear()
797
- archives.clear()
798
- if (!discoveryRegions) throw new Error('guest projection layout object missing')
799
- const regionsBefore = discoveryRegions
800
- // generated pieces belong to one image each: the lookup tables to the ledger data
801
- // image, a caller wrapper to its caller, the projection tables to the projection image.
802
- const ledgerPieces = guestProjectionRegionCapacity([fs.readFileSync(ledgerObject)], 0)
803
- const bundleCount = images.filter(
804
- (image) => image.resourceBundlePath !== undefined,
805
- ).length
806
- const projectionPieces = images.length + 2 + (bundleCount ? bundleCount + 1 : 0)
807
- let capacities: GuestProjectionCapacity[] = ledger.images.map((image) => ({
808
- regions:
809
- regionsBefore[image.id]! +
810
- 1 +
811
- ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length +
812
- (image.id === options.ledgerDataImage ? ledgerPieces : 0) +
813
- (image.id === projection.image ? projectionPieces : 0),
814
- memoryProtection: projection.memoryProtection,
815
- tableProtection: projection.tableProtection,
816
- }))
817
- const projectionSource = path.join(directory, 'projection.c')
818
- projectionObject = path.join(directory, 'projection.o')
819
- const callerMap = args.find((arg) => arg.startsWith('--Map='))?.slice('--Map='.length)
820
- const layoutMap = callerMap ?? path.join(directory, 'projection-layout.map')
821
- for (;;) {
822
- projectionStorage = reserveGuestProjectionStorage(images, capacities)
823
- fs.writeFileSync(projectionSource, projectionStorage.source)
824
- execFileSync(
825
- clang,
826
- [...projection.clangOptions, '-c', projectionSource, '-o', projectionObject],
827
- { stdio: 'pipe' },
835
+ const byToken = new Map(
836
+ occurrences(plan, args).map(({ artifact, token }) => [
837
+ token,
838
+ replacements.get(artifact.path),
839
+ ]),
840
+ )
841
+ // the same input named twice (a product link line repeats shared objects)
842
+ // is one file for the linker; rewritten copies would otherwise load twice.
843
+ const placed = new Set<string>()
844
+ const finalArgs = args
845
+ .map((arg) => byToken.get(arg) ?? arg)
846
+ .filter((arg) => {
847
+ if (!arg.endsWith('.o') && !arg.endsWith('.a')) return true
848
+ if (placed.has(arg)) return false
849
+ placed.add(arg)
850
+ return true
851
+ })
852
+ const finalOutput = path.join(directory, 'final.wasm')
853
+ const finalWhy = path.join(directory, 'final-why-extract.txt')
854
+ const linkFinal = (projectionObject?: string, layoutMap?: string) =>
855
+ runLink('final', [
856
+ ...withOutput(finalArgs, finalOutput, false),
857
+ ledgerObject,
858
+ `@${lazyExports}`,
859
+ ...(projectionObject ? [projectionObject] : []),
860
+ ...(provider ? [`--undefined=${providerSymbol}`] : []),
861
+ ...(layoutMap ? [`--Map=${layoutMap}`] : []),
862
+ `--why-extract=${finalWhy}`,
863
+ ])
864
+ let projectionObject: string | undefined
865
+ let projectionStorage: ReservedGuestProjectionStorage | undefined
866
+ let finalTrace: string
867
+ if (options.projection) {
868
+ const projection = options.projection
869
+ if (!plan.images.some((image) => image.id === projection.image))
870
+ throw new Error('guest projection has no source image')
871
+ if (
872
+ projection.images.length !== plan.images.length ||
873
+ projection.images.some(
874
+ (image, index) => image.image !== index || plan.images[index]?.id !== index,
875
+ )
828
876
  )
829
- finalTrace = linkFinal(projectionObject, callerMap ? undefined : layoutMap)
830
- // sharedSdk builds never finalize final.wasm; app-module reserves and validates
831
- // the combined app + SDK projection storage against app.wasm instead.
832
- if (sharedSdk) break
833
- const wasm = fs.readFileSync(finalOutput)
834
- const actual = guestProjectionRegionCounts(
835
- images.length,
836
- guestLinkedSpans(
837
- guestLinkLines(layoutMap),
838
- wasm,
839
- wasm,
840
- new Map(linkedOwners).set(projectionObject, projection.image),
841
- sectionOwners,
842
- ),
877
+ throw new Error('guest projection image order differs from link plan')
878
+ const selectedInputs = selectedGuestManifestInputs(
879
+ plan,
880
+ selected,
881
+ projection.identities,
882
+ readSelected,
883
+ )
884
+ const images = projection.images.map((image) =>
885
+ createGuestImageManifest({
886
+ ...image,
887
+ inputs: selectedInputs.get(image.image) ?? [],
888
+ linkOptions: projection.linkOptions,
889
+ regions: [],
890
+ }),
843
891
  )
844
- if (actual.every((count, index) => count <= capacities[index]!.regions)) break
845
- capacities = capacities.map((capacity, index) => ({
846
- ...capacity,
847
- regions: Math.max(actual[index]!, capacity.regions),
892
+ objectBytes.clear()
893
+ memberBytes.clear()
894
+ archives.clear()
895
+ if (!discoveryRegions) throw new Error('guest projection layout object missing')
896
+ const regionsBefore = discoveryRegions
897
+ // generated pieces belong to one image each: the lookup tables to the ledger data
898
+ // image, a caller wrapper to its caller, the projection tables to the projection image.
899
+ const ledgerPieces = guestProjectionRegionCapacity(
900
+ [fs.readFileSync(ledgerObject)],
901
+ 0,
902
+ )
903
+ const bundleCount = images.filter(
904
+ (image) => image.resourceBundlePath !== undefined,
905
+ ).length
906
+ const projectionPieces = images.length + 2 + (bundleCount ? bundleCount + 1 : 0)
907
+ let capacities: GuestProjectionCapacity[] = ledger.images.map((image) => ({
908
+ regions:
909
+ regionsBefore[image.id]! +
910
+ 1 +
911
+ ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length +
912
+ (image.id === options.ledgerDataImage ? ledgerPieces : 0) +
913
+ (image.id === projection.image ? projectionPieces : 0),
914
+ memoryProtection: projection.memoryProtection,
915
+ tableProtection: projection.tableProtection,
848
916
  }))
849
- }
850
- linkedOwners.set(projectionObject, projection.image)
851
- } else finalTrace = linkFinal()
852
- // the ledger and rewritten references can change archive extraction. every
853
- // selected member must have participated in ledger construction, so do not
854
- // publish a link whose final inputs differ from the discovery link.
855
- const finalSelection = selectedGuestLinkInputs(
856
- remapGuestLinkPlan(plan, replacements),
857
- finalArgs,
858
- fs.readFileSync(finalWhy, 'utf8'),
859
- finalTrace,
860
- finalArchives,
861
- )
862
- const original = new Map([...replacements].map(([before, after]) => [after, before]))
863
- const key = (item: GuestLinkSelection) =>
864
- JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member])
865
- const before = new Set(selected.map(key))
866
- const after = new Set(finalSelection.map(key))
867
- const changed = [...before].filter((item) => !after.has(item))
868
- changed.push(...[...after].filter((item) => !before.has(item)))
869
- if (changed.length)
870
- throw new Error(
871
- `guest link selected different inputs after rewriting:\n${changed.join('\n')}`,
872
- )
873
- fs.renameSync(finalOutput, outputPath(args))
874
- if (KEEP_WASM_NAMES)
875
- fs.writeFileSync(
876
- outputPath(args),
877
- nameGuestImageAliases(fs.readFileSync(outputPath(args)), plan.symbols),
878
- )
879
- if (projectionStorage && projectionObject)
880
- options.projection!.onReserved(projectionStorage, projectionObject)
881
- options.onLinkedOwners?.(linkedOwners)
882
- options.onLinkedSections?.(sectionOwners)
883
- options.onDyldRows?.(ledger)
884
- if (options.onSplitInputs && ledger.appLLVMIR) {
885
- const appLedgerObject = compileLedger('app-ledger', ledger.appLLVMIR)
886
- const appSections = new Map(
887
- ledger.callerWrappers.map(({ symbol, image }) => [
888
- `${appLedgerObject}:(${symbol})`,
889
- image,
890
- ]),
917
+ const projectionSource = path.join(directory, 'projection.c')
918
+ projectionObject = path.join(directory, 'projection.o')
919
+ const callerMap = args
920
+ .find((arg) => arg.startsWith('--Map='))
921
+ ?.slice('--Map='.length)
922
+ const layoutMap = callerMap ?? path.join(directory, 'projection-layout.map')
923
+ for (;;) {
924
+ projectionStorage = reserveGuestProjectionStorage(images, capacities)
925
+ fs.writeFileSync(projectionSource, projectionStorage.source)
926
+ execFileSync(
927
+ clang,
928
+ [...projection.clangOptions, '-c', projectionSource, '-o', projectionObject],
929
+ { stdio: 'pipe' },
930
+ )
931
+ finalTrace = linkFinal(projectionObject, callerMap ? undefined : layoutMap)
932
+ // sharedSdk builds never finalize final.wasm; app-module reserves and validates
933
+ // the combined app + SDK projection storage against app.wasm instead.
934
+ if (sharedSdk) break
935
+ const wasm = fs.readFileSync(finalOutput)
936
+ const actual = guestProjectionRegionCounts(
937
+ images.length,
938
+ guestLinkedSpans(
939
+ guestLinkLines(layoutMap),
940
+ wasm,
941
+ wasm,
942
+ new Map(linkedOwners).set(projectionObject, projection.image),
943
+ sectionOwners,
944
+ ),
945
+ )
946
+ if (actual.every((count, index) => count <= capacities[index]!.regions)) break
947
+ capacities = capacities.map((capacity, index) => ({
948
+ ...capacity,
949
+ regions: Math.max(actual[index]!, capacity.regions),
950
+ }))
951
+ }
952
+ linkedOwners.set(projectionObject, projection.image)
953
+ } else finalTrace = linkFinal()
954
+ // the ledger and rewritten references can change archive extraction. every
955
+ // selected member must have participated in ledger construction, so do not
956
+ // publish a link whose final inputs differ from the discovery link.
957
+ const finalSelection = selectedGuestLinkInputs(
958
+ remapGuestLinkPlan(plan, replacements),
959
+ finalArgs,
960
+ fs.readFileSync(finalWhy, 'utf8'),
961
+ finalTrace,
962
+ finalArchives,
891
963
  )
892
- appObjects.set(appLedgerObject, options.ledgerDataImage)
893
- let appReferencedSymbols: ReadonlySet<string> | undefined
894
- let appDefinedSymbols: ReadonlySet<string> | undefined
895
- if (ledger.appReferencedSymbols && ledger.appDefinedSymbols) {
896
- const referenced = new Set(ledger.appReferencedSymbols)
897
- const defined = new Set(ledger.appDefinedSymbols)
898
- const ledgerSyms = guestWasmSymbols(fs.readFileSync(appLedgerObject))
899
- for (const name of ledgerSyms.undefined) referenced.add(name)
900
- for (const name of ledgerSyms.defined) defined.add(name)
901
- appReferencedSymbols = referenced
902
- appDefinedSymbols = defined
964
+ const original = new Map([...replacements].map(([before, after]) => [after, before]))
965
+ const key = (item: GuestLinkSelection) =>
966
+ JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member])
967
+ const before = new Set(selected.map(key))
968
+ const after = new Set(finalSelection.map(key))
969
+ const changed = [...before].filter((item) => !after.has(item))
970
+ changed.push(...[...after].filter((item) => !before.has(item)))
971
+ if (changed.length)
972
+ throw new Error(
973
+ `guest link selected different inputs after rewriting:\n${changed.join('\n')}`,
974
+ )
975
+ fs.renameSync(finalOutput, outputPath(args))
976
+ if (KEEP_WASM_NAMES)
977
+ fs.writeFileSync(
978
+ outputPath(args),
979
+ nameGuestImageAliases(fs.readFileSync(outputPath(args)), plan.symbols),
980
+ )
981
+ if (projectionStorage && projectionObject)
982
+ options.projection!.onReserved(projectionStorage, projectionObject)
983
+ options.onLinkedOwners?.(linkedOwners)
984
+ options.onLinkedSections?.(sectionOwners)
985
+ options.onDyldRows?.(ledger)
986
+ if (options.onSplitInputs && appLedgerObjectPromise) {
987
+ const appLedgerObject = await appLedgerObjectPromise
988
+ const appSections = new Map(
989
+ ledger.callerWrappers.map(({ symbol, image }) => [
990
+ `${appLedgerObject}:(${symbol})`,
991
+ image,
992
+ ]),
993
+ )
994
+ appObjects.set(appLedgerObject, options.ledgerDataImage)
995
+ let appReferencedSymbols: ReadonlySet<string> | undefined
996
+ let appDefinedSymbols: ReadonlySet<string> | undefined
997
+ if (ledger.appReferencedSymbols && ledger.appDefinedSymbols) {
998
+ const referenced = new Set(ledger.appReferencedSymbols)
999
+ const defined = new Set(ledger.appDefinedSymbols)
1000
+ const ledgerSyms = guestWasmSymbols(fs.readFileSync(appLedgerObject))
1001
+ for (const name of ledgerSyms.undefined) referenced.add(name)
1002
+ for (const name of ledgerSyms.defined) defined.add(name)
1003
+ appReferencedSymbols = referenced
1004
+ appDefinedSymbols = defined
1005
+ }
1006
+ options.onSplitInputs({
1007
+ appObjects,
1008
+ appSections,
1009
+ sdkObjects,
1010
+ lazyFunctions: ledger.appLazyFunctions ?? [],
1011
+ dyldSymbols: ledger.dyldSymbols,
1012
+ appReferencedSymbols,
1013
+ appDefinedSymbols,
1014
+ })
903
1015
  }
904
- options.onSplitInputs({
905
- appObjects,
906
- appSections,
907
- sdkObjects,
908
- lazyFunctions: ledger.appLazyFunctions ?? [],
909
- dyldSymbols: ledger.dyldSymbols,
910
- appReferencedSymbols,
911
- appDefinedSymbols,
912
- })
1016
+ return selected
1017
+ } catch (error) {
1018
+ await Promise.allSettled([
1019
+ ledgerObjectPromise,
1020
+ ...(appLedgerObjectPromise ? [appLedgerObjectPromise] : []),
1021
+ ])
1022
+ throw error
913
1023
  }
914
- return selected
915
1024
  }
916
1025
 
917
1026
  // every symbol name a linker map lists, which is what the link kept.
@@ -1035,26 +1144,23 @@ export function aliasGuestLinkArguments(
1035
1144
  }
1036
1145
 
1037
1146
  /** Reject selected inputs without an explicit source-image owner. */
1038
- export function linkCompleteGuestImages(
1147
+ export async function linkCompleteGuestImages(
1039
1148
  options: GuestLinkOptions,
1040
- ): readonly GuestLinkSelection[] {
1149
+ ): Promise<readonly GuestLinkSelection[]> {
1041
1150
  const args = normalizedGuestLinkArgs(options.args)
1042
- const unowned = unownedGuestLinkInputs(options.plan, args)
1043
- const candidates = unowned.map((file): GuestLinkArtifact => {
1044
- const descriptor = fs.openSync(file, 'r')
1045
- const magic = Buffer.alloc(8)
1046
- try {
1047
- fs.readSync(descriptor, magic, 0, magic.length, 0)
1048
- } finally {
1049
- fs.closeSync(descriptor)
1050
- }
1051
- return {
1052
- path: file,
1053
- kind: magic.toString('ascii') === '!<arch>\n' ? 'archive' : 'object',
1054
- image: null,
1055
- instrumentDynamicLookups: false,
1056
- }
1057
- })
1151
+ const owned = new Set(
1152
+ options.plan.artifacts.map((artifact) => path.resolve(artifact.path)),
1153
+ )
1154
+ const candidates = guestLinkInputFilesWithKind(args)
1155
+ .filter((item) => !owned.has(item.path))
1156
+ .map(
1157
+ ({ path: file, kind }): GuestLinkArtifact => ({
1158
+ path: file,
1159
+ kind,
1160
+ image: null,
1161
+ instrumentDynamicLookups: false,
1162
+ }),
1163
+ )
1058
1164
  return linkGuestImages({
1059
1165
  ...options,
1060
1166
  args,
@@ -1069,27 +1175,33 @@ export function discoverGuestLinkInputs(options: {
1069
1175
  readonly wasmLd: string
1070
1176
  /** Additional discovery-only objects required by the final link. */
1071
1177
  readonly objects: readonly string[]
1178
+ readonly output?: string
1179
+ readonly mapPath?: string
1180
+ readonly onOutput?: (result: {
1181
+ readonly why: string
1182
+ readonly trace: string
1183
+ readonly output: string
1184
+ readonly mapPath?: string
1185
+ }) => void
1072
1186
  }): GuestLinkSelection[] {
1073
1187
  const args = normalizedGuestLinkArgs(options.args)
1074
- const artifacts = guestLinkInputFiles(args).map((file): GuestLinkArtifact => {
1075
- const descriptor = fs.openSync(file, 'r')
1076
- const magic = Buffer.alloc(8)
1077
- try {
1078
- fs.readSync(descriptor, magic, 0, magic.length, 0)
1079
- } finally {
1080
- fs.closeSync(descriptor)
1081
- }
1082
- const kind = magic.toString('ascii') === '!<arch>\n' ? 'archive' : 'object'
1083
- return { path: file, kind, image: 0, instrumentDynamicLookups: false }
1084
- })
1188
+ const artifacts = guestLinkInputFilesWithKind(args).map(
1189
+ ({ path: file, kind }): GuestLinkArtifact => ({
1190
+ path: file,
1191
+ kind,
1192
+ image: 0,
1193
+ instrumentDynamicLookups: false,
1194
+ }),
1195
+ )
1085
1196
  const plan: GuestLinkPlan = { images: [], callers: [], artifacts, symbols: [] }
1086
1197
  fs.mkdirSync(options.directory, { recursive: true })
1087
1198
  const why = path.join(options.directory, 'preselection-why.txt')
1088
1199
  const response = path.join(options.directory, 'preselection.rsp')
1089
1200
  const output =
1090
- process.platform !== 'win32'
1201
+ options.output ??
1202
+ (process.platform !== 'win32'
1091
1203
  ? '/dev/null'
1092
- : path.join(options.directory, 'preselection.wasm')
1204
+ : path.join(options.directory, 'preselection.wasm'))
1093
1205
  const flags = [
1094
1206
  ...withOutput(args, output, true),
1095
1207
  ...options.objects,
@@ -1097,6 +1209,7 @@ export function discoverGuestLinkInputs(options: {
1097
1209
  // the selection that assigns member owners.
1098
1210
  '--undefined=__peach_dlsym_from_image',
1099
1211
  `--why-extract=${why}`,
1212
+ ...(options.mapPath ? [`--Map=${options.mapPath}`] : []),
1100
1213
  '--trace',
1101
1214
  ]
1102
1215
  fs.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(' '))
@@ -1110,6 +1223,7 @@ export function discoverGuestLinkInputs(options: {
1110
1223
  } finally {
1111
1224
  fs.closeSync(traceOutput)
1112
1225
  }
1226
+ options.onOutput?.({ why, trace, output, mapPath: options.mapPath })
1113
1227
  return selectedGuestLinkInputs(
1114
1228
  plan,
1115
1229
  args,
@@ -1125,6 +1239,8 @@ export function prepareGuestRuntimeInputs(options: {
1125
1239
  readonly wasmLd: string
1126
1240
  readonly llvmAr: string
1127
1241
  readonly discoveryObjects: readonly string[]
1242
+ readonly discoveryOutput?: string
1243
+ readonly discoveryMap?: string
1128
1244
  readonly products: readonly {
1129
1245
  readonly product: SwiftSdkProduct
1130
1246
  readonly root: string
@@ -1144,6 +1260,7 @@ export function prepareGuestRuntimeInputs(options: {
1144
1260
  readonly archives: readonly AliasedGuestArchive[]
1145
1261
  readonly sdkProducts: GuestSdkLinkProducts
1146
1262
  readonly archiveArtifacts: readonly GuestLinkArtifact[]
1263
+ readonly discovery?: PreselectedGuestDiscovery
1147
1264
  } {
1148
1265
  const originals = new Map(
1149
1266
  [...options.rewritten].map(([before, after]) => [
@@ -1161,7 +1278,10 @@ export function prepareGuestRuntimeInputs(options: {
1161
1278
  ),
1162
1279
  )
1163
1280
  const archives: AliasedGuestArchive[] = []
1164
- for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
1281
+ for (const { path: file, kind } of guestLinkInputFilesWithKind(
1282
+ normalizedGuestLinkArgs(options.args),
1283
+ )) {
1284
+ if (kind !== 'archive') continue
1165
1285
  const original = originals.get(file) ?? file
1166
1286
  if (!recordedArchives.has(original) && libraryArchiveTarget(original) === null)
1167
1287
  continue
@@ -1176,11 +1296,28 @@ export function prepareGuestRuntimeInputs(options: {
1176
1296
  )
1177
1297
  }
1178
1298
  const args = aliasGuestLinkArguments(options.args, archives)
1299
+ let discovery: PreselectedGuestDiscovery | undefined
1179
1300
  const selected = discoverGuestLinkInputs({
1180
1301
  args,
1181
1302
  directory: options.directory,
1182
1303
  wasmLd: options.wasmLd,
1183
1304
  objects: options.discoveryObjects,
1305
+ output: options.discoveryOutput,
1306
+ mapPath: options.discoveryMap,
1307
+ onOutput:
1308
+ options.discoveryOutput &&
1309
+ options.discoveryMap &&
1310
+ options.discoveryObjects.length === 1
1311
+ ? ({ why, trace, output, mapPath }) => {
1312
+ discovery = {
1313
+ wasm: output,
1314
+ map: mapPath!,
1315
+ why,
1316
+ trace,
1317
+ projectionObject: options.discoveryObjects[0]!,
1318
+ }
1319
+ }
1320
+ : undefined,
1184
1321
  })
1185
1322
  const originalSelection = originalGuestArchiveSelections(selected, archives)
1186
1323
  const closure = guestRuntimeProductsForInputs({
@@ -1213,7 +1350,15 @@ export function prepareGuestRuntimeInputs(options: {
1213
1350
  rewritten: options.rewritten,
1214
1351
  images: new Map([...closure.images, ...closure.containingImages]),
1215
1352
  })
1216
- return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts }
1353
+ return {
1354
+ args,
1355
+ selected,
1356
+ originalSelection,
1357
+ archives,
1358
+ sdkProducts,
1359
+ archiveArtifacts,
1360
+ discovery,
1361
+ }
1217
1362
  }
1218
1363
 
1219
1364
  /** Collect undefined references and exact owners from selected original objects. */
@@ -1364,10 +1509,21 @@ export function verifyGuestSymbolScopes(options: {
1364
1509
  >()
1365
1510
  for (const line of guestLinkLines(tracePath)) {
1366
1511
  const refSep = line.lastIndexOf(': reference to ')
1367
- const defSep = line.lastIndexOf(': definition of ')
1368
- if (refSep < 0 && defSep < 0) continue
1369
- const isRef = refSep > defSep
1370
- const sep = isRef ? refSep : defSep
1512
+ let isRef = false
1513
+ let sep = -1
1514
+ if (refSep >= 0) {
1515
+ const defAfter = line.indexOf(': definition of ', refSep + 15)
1516
+ if (defAfter >= 0) {
1517
+ sep = line.lastIndexOf(': definition of ')
1518
+ isRef = false
1519
+ } else {
1520
+ sep = refSep
1521
+ isRef = true
1522
+ }
1523
+ } else {
1524
+ sep = line.lastIndexOf(': definition of ')
1525
+ if (sep < 0) continue
1526
+ }
1371
1527
  const symbol = line.slice(sep + (isRef ? 15 : 16))
1372
1528
  if (!requested.has(symbol) || options.hostImports.has(symbol)) continue
1373
1529
  let record = records.get(symbol)
@@ -1650,10 +1806,16 @@ export interface PrunedGuestLinkResult {
1650
1806
  }
1651
1807
 
1652
1808
  /** Run the normal pruner and use its selected, owned inputs for the guest link. */
1653
- export function linkPrunedGuestImages(
1809
+ export async function linkPrunedGuestImages(
1654
1810
  options: PrunedGuestLinkOptions,
1655
- ): PrunedGuestLinkResult {
1656
- let result: PrunedGuestLinkResult | undefined
1811
+ ): Promise<PrunedGuestLinkResult> {
1812
+ let pruned:
1813
+ | {
1814
+ readonly args: readonly string[]
1815
+ readonly rewritten: ReadonlyMap<string, string>
1816
+ readonly sdk: SwiftPrunedSdkInputs
1817
+ }
1818
+ | undefined
1657
1819
  pruneSwiftWasmLink(
1658
1820
  options.buildDirectory,
1659
1821
  options.toolchainBin,
@@ -1661,141 +1823,139 @@ export function linkPrunedGuestImages(
1661
1823
  options.staticClangTargets,
1662
1824
  undefined,
1663
1825
  (args, rewritten, sdk) => {
1664
- if (args.some((arg) => arg === '--Map' || arg.startsWith('--Map=')))
1665
- throw new Error('guest link already has a linker map')
1666
- const framework = options.framework
1667
- const prepared = options.prepareRuntime?.(args, rewritten, sdk)
1668
- if (prepared && options.sdkProducts !== null)
1669
- throw new Error('guest runtime products supplied twice')
1670
- const linkedArgs = prepared?.args ?? args
1671
- const sdkProducts =
1672
- prepared?.sdkProducts ??
1673
- (typeof options.sdkProducts === 'function'
1674
- ? options.sdkProducts(args, rewritten, sdk)
1675
- : options.sdkProducts)
1676
- const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts)
1677
- let frameworkArtifacts: GuestLinkArtifact[] = []
1678
- const selectedObjects =
1679
- prepared &&
1680
- new Set(
1681
- prepared.selected
1682
- .filter((item) => item.member === null)
1683
- .map((item) => path.resolve(item.artifact)),
1684
- )
1685
- const selectedFramework =
1686
- framework &&
1687
- (!prepared ||
1688
- framework.product.objects.some((object) => {
1689
- const original = path.resolve(framework.root, object.path)
1690
- const linked = path.resolve(rewritten.get(original) ?? original)
1691
- return selectedObjects?.has(linked) ?? false
1692
- }))
1693
- if (framework && selectedFramework) {
1694
- const image = sdkProducts?.images.get(
1695
- frameworkRuntimeProductId(framework.product),
1696
- )
1697
- if (image === undefined)
1698
- throw new Error(
1699
- 'framework objects require their declared compiler runtime image',
1700
- )
1701
- frameworkArtifacts = guestFrameworkLinkArtifacts(
1702
- framework.product,
1703
- framework.root,
1704
- linkedArgs,
1705
- rewritten,
1706
- image,
1826
+ pruned = { args, rewritten, sdk }
1827
+ },
1828
+ options.resourceReferences,
1829
+ )
1830
+ if (!pruned) throw new Error('guest link did not receive pruned inputs')
1831
+ const { args, rewritten, sdk } = pruned
1832
+ if (args.some((arg) => arg === '--Map' || arg.startsWith('--Map=')))
1833
+ throw new Error('guest link already has a linker map')
1834
+ const framework = options.framework
1835
+ const prepared = options.prepareRuntime?.(args, rewritten, sdk)
1836
+ if (prepared && options.sdkProducts !== null)
1837
+ throw new Error('guest runtime products supplied twice')
1838
+ const linkedArgs = prepared?.args ?? args
1839
+ const sdkProducts =
1840
+ prepared?.sdkProducts ??
1841
+ (typeof options.sdkProducts === 'function'
1842
+ ? options.sdkProducts(args, rewritten, sdk)
1843
+ : options.sdkProducts)
1844
+ const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts)
1845
+ let frameworkArtifacts: GuestLinkArtifact[] = []
1846
+ const selectedObjects =
1847
+ prepared &&
1848
+ new Set(
1849
+ prepared.selected
1850
+ .filter((item) => item.member === null)
1851
+ .map((item) => path.resolve(item.artifact)),
1852
+ )
1853
+ const selectedFramework =
1854
+ framework &&
1855
+ (!prepared ||
1856
+ framework.product.objects.some((object) => {
1857
+ const original = path.resolve(framework.root, object.path)
1858
+ const linked = path.resolve(rewritten.get(original) ?? original)
1859
+ return selectedObjects?.has(linked) ?? false
1860
+ }))
1861
+ if (framework && selectedFramework) {
1862
+ const image = sdkProducts?.images.get(frameworkRuntimeProductId(framework.product))
1863
+ if (image === undefined)
1864
+ throw new Error('framework objects require their declared compiler runtime image')
1865
+ frameworkArtifacts = guestFrameworkLinkArtifacts(
1866
+ framework.product,
1867
+ framework.root,
1868
+ linkedArgs,
1869
+ rewritten,
1870
+ image,
1871
+ )
1872
+ }
1873
+ if (sdkProducts) {
1874
+ for (const image of guestSdkProductImages(
1875
+ sdkProducts.products.map((entry) => entry.product),
1876
+ sdkProducts.images,
1877
+ )) {
1878
+ const planned = sourcePlan.images.find((entry) => entry.id === image.id)
1879
+ if (
1880
+ !planned ||
1881
+ planned.name !== image.name ||
1882
+ planned.dependencies.length !== image.dependencies.length ||
1883
+ planned.dependencies.some(
1884
+ (dependency, index) => dependency !== image.dependencies[index],
1707
1885
  )
1708
- }
1709
- if (sdkProducts) {
1710
- for (const image of guestSdkProductImages(
1711
- sdkProducts.products.map((entry) => entry.product),
1712
- sdkProducts.images,
1713
- )) {
1714
- const planned = sourcePlan.images.find((entry) => entry.id === image.id)
1715
- if (
1716
- !planned ||
1717
- planned.name !== image.name ||
1718
- planned.dependencies.length !== image.dependencies.length ||
1719
- planned.dependencies.some(
1720
- (dependency, index) => dependency !== image.dependencies[index],
1721
- )
1722
- )
1723
- throw new Error(`SDK image scope differs from source product ${image.name}`)
1724
- }
1725
- }
1726
- const remappedPlan = remapGuestLinkPlan(
1727
- {
1728
- ...sourcePlan,
1729
- artifacts: [
1730
- ...sourcePlan.artifacts,
1731
- ...frameworkArtifacts,
1732
- ...(sdkProducts
1733
- ? guestSdkProductLinkArtifacts(
1734
- sdkProducts.products,
1735
- sdk,
1736
- linkedArgs,
1737
- sdkProducts.linkedArchives,
1738
- rewritten,
1739
- new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
1740
- prepared?.selected,
1741
- )
1742
- : []),
1743
- ...(prepared?.archiveArtifacts ?? []),
1744
- ],
1745
- },
1746
- rewritten,
1747
1886
  )
1748
- const plan = aliasGuestLinkPlan(remappedPlan, prepared?.archives ?? [])
1749
- let owners: ReadonlyMap<string, number> = new Map()
1750
- let generatedSectionOwners: ReadonlyMap<string, number> = new Map()
1751
- let projection =
1752
- typeof options.projection === 'function'
1753
- ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan)
1754
- : options.projection
1755
- if (projection && prepared) {
1756
- const identities = new Map(projection.identities)
1757
- for (const [before, after] of rewritten) {
1758
- const identity = identities.get(before)
1759
- const existing = identities.get(after)
1760
- if (identity !== undefined && existing !== undefined && existing !== identity)
1761
- throw new Error(`rewritten guest input has conflicting identity ${after}`)
1762
- if (identity !== undefined) identities.set(after, identity)
1763
- }
1764
- projection = {
1765
- ...projection,
1766
- identities: aliasGuestLinkIdentities(identities, prepared.archives),
1767
- }
1768
- }
1769
- const selected = linkCompleteGuestImages({
1770
- plan,
1771
- args: [...linkedArgs, `--Map=${options.mapPath}`],
1772
- directory: options.linkDirectory,
1773
- wasmLd: path.join(options.toolchainBin, 'wasm-ld'),
1774
- clang: path.join(options.toolchainBin, 'clang'),
1775
- llvmAr: path.join(options.toolchainBin, 'llvm-ar'),
1776
- ledgerDataImage: options.ledgerDataImage,
1777
- projection,
1778
- resolvePlan: options.resolvePlan,
1779
- sharedSdk: options.sharedSdk,
1780
- onSplitInputs: options.onSplitInputs,
1781
- onDyldRows: options.onDyldRows,
1782
- onLinkedOwners: (value) => {
1783
- owners = value
1784
- },
1785
- onLinkedSections: (value) => {
1786
- generatedSectionOwners = value
1787
- },
1788
- })
1789
- result = {
1790
- selected,
1791
- owners,
1792
- generatedSectionOwners,
1793
- sdk,
1794
- mapPath: options.mapPath,
1795
- }
1887
+ throw new Error(`SDK image scope differs from source product ${image.name}`)
1888
+ }
1889
+ }
1890
+ const remappedPlan = remapGuestLinkPlan(
1891
+ {
1892
+ ...sourcePlan,
1893
+ artifacts: [
1894
+ ...sourcePlan.artifacts,
1895
+ ...frameworkArtifacts,
1896
+ ...(sdkProducts
1897
+ ? guestSdkProductLinkArtifacts(
1898
+ sdkProducts.products,
1899
+ sdk,
1900
+ linkedArgs,
1901
+ sdkProducts.linkedArchives,
1902
+ rewritten,
1903
+ new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
1904
+ prepared?.selected,
1905
+ )
1906
+ : []),
1907
+ ...(prepared?.archiveArtifacts ?? []),
1908
+ ],
1796
1909
  },
1797
- options.resourceReferences,
1910
+ rewritten,
1798
1911
  )
1799
- if (!result) throw new Error('guest link did not receive pruned inputs')
1800
- return result
1912
+ const plan = aliasGuestLinkPlan(remappedPlan, prepared?.archives ?? [])
1913
+ let owners: ReadonlyMap<string, number> = new Map()
1914
+ let generatedSectionOwners: ReadonlyMap<string, number> = new Map()
1915
+ let projection =
1916
+ typeof options.projection === 'function'
1917
+ ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan)
1918
+ : options.projection
1919
+ if (projection && prepared) {
1920
+ const identities = new Map(projection.identities)
1921
+ for (const [before, after] of rewritten) {
1922
+ const identity = identities.get(before)
1923
+ const existing = identities.get(after)
1924
+ if (identity !== undefined && existing !== undefined && existing !== identity)
1925
+ throw new Error(`rewritten guest input has conflicting identity ${after}`)
1926
+ if (identity !== undefined) identities.set(after, identity)
1927
+ }
1928
+ projection = {
1929
+ ...projection,
1930
+ identities: aliasGuestLinkIdentities(identities, prepared.archives),
1931
+ }
1932
+ }
1933
+ const selected = await linkCompleteGuestImages({
1934
+ plan,
1935
+ args: [...linkedArgs, `--Map=${options.mapPath}`],
1936
+ directory: options.linkDirectory,
1937
+ wasmLd: path.join(options.toolchainBin, 'wasm-ld'),
1938
+ clang: path.join(options.toolchainBin, 'clang'),
1939
+ llvmAr: path.join(options.toolchainBin, 'llvm-ar'),
1940
+ ledgerDataImage: options.ledgerDataImage,
1941
+ projection,
1942
+ preselectionDiscovery: prepared?.discovery,
1943
+ resolvePlan: options.resolvePlan,
1944
+ sharedSdk: options.sharedSdk,
1945
+ onSplitInputs: options.onSplitInputs,
1946
+ onDyldRows: options.onDyldRows,
1947
+ onLinkedOwners: (value) => {
1948
+ owners = value
1949
+ },
1950
+ onLinkedSections: (value) => {
1951
+ generatedSectionOwners = value
1952
+ },
1953
+ })
1954
+ return {
1955
+ selected,
1956
+ owners,
1957
+ generatedSectionOwners,
1958
+ sdk,
1959
+ mapPath: options.mapPath,
1960
+ }
1801
1961
  }