peachsim 0.1.2623 → 0.1.2625

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 (140) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +1023 -621
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-E6V72TM2.mjs → acorn-SHZZDBSI.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-EIOVKQ2C.mjs → chunk-2LDG7OD4.mjs} +5 -5
  28. package/dist-lib/esm-chunks/{chunk-ISH6XB23.mjs → chunk-3XZGWT62.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-Q7KCK4YO.mjs → chunk-6PZI7TYE.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-RLWITQ5C.mjs → chunk-7Z7YJ4FU.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-4GNQG2GT.mjs → chunk-A4R4YGFJ.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-GP3KL2GC.mjs → chunk-A66VNSO6.mjs} +565 -290
  33. package/dist-lib/esm-chunks/{chunk-XOAOND7F.mjs → chunk-DVMKYLDN.mjs} +9 -8
  34. package/dist-lib/esm-chunks/{chunk-IGB7TRLS.mjs → chunk-F4YHL4UM.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-4BJIJ3GP.mjs → chunk-JRU2VXUU.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-EI7CZDMR.mjs → chunk-JVEJLPJC.mjs} +2 -2
  37. package/dist-lib/esm-chunks/{chunk-UCW7ITXE.mjs → chunk-KA4AQDVF.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-RLWTJ6II.mjs → chunk-LJYNZ5HM.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-RBXTTEI6.mjs → chunk-M2FEKSK3.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-KPG4FUTY.mjs → chunk-OCCZJOSA.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-CXNXKUNJ.mjs → chunk-P542MMIN.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-NOM66H2G.mjs → chunk-Q5NI4L3Z.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-V2CHR3OI.mjs → chunk-R4FFTWPL.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-W3X7RP3H.mjs → chunk-RJWEWNAJ.mjs} +3 -3
  45. package/dist-lib/esm-chunks/{chunk-B5OQSD4B.mjs → chunk-RXXCTHJG.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-B4APPUTT.mjs → chunk-SRIRVPNX.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-6MNE57DC.mjs → chunk-ULHG6CND.mjs} +22 -13
  48. package/dist-lib/esm-chunks/{chunk-PAEJF2JP.mjs → chunk-W4HQINQ6.mjs} +4 -4
  49. package/dist-lib/esm-chunks/{chunk-RVM3WWST.mjs → chunk-XQBHCWS4.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-Q4ZATFEN.mjs → chunk-Z6AH6AQC.mjs} +1 -1
  51. package/dist-lib/esm-chunks/{metro-layout-parser-OHVROLNJ.mjs → metro-layout-parser-GJHR7FCR.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-DRAUK6KR.mjs → swift-package-prebuilt-UVRGKTD4.mjs} +12 -12
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-U2M7CMKA.mjs → swift-sdk-app-module-U3MUJ7QD.mjs} +107 -20
  54. package/dist-lib/esm-chunks/{swift-sdk-image-ZHWSHCNI.mjs → swift-sdk-image-U4W7QMAT.mjs} +16 -18
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-EOJUCK7N.mjs → swift-sdk-image-producer-TFFZDNRK.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +918 -516
  57. package/dist-lib/expo-swift-metadata.cjs +1 -1
  58. package/dist-lib/expo-swift-metadata.mjs +7 -7
  59. package/dist-lib/home-paths.cjs +1 -1
  60. package/dist-lib/host/bridge-host.cjs +1025 -623
  61. package/dist-lib/host/fetch-proxy-handler.cjs +10 -9
  62. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  63. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  64. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  65. package/dist-lib/host/websocket-proxy.cjs +1 -1
  66. package/dist-lib/index.cjs +1 -1
  67. package/dist-lib/kotlin-host.cjs +1 -1
  68. package/dist-lib/menu.cjs +1 -1
  69. package/dist-lib/menu.mjs +3 -3
  70. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  71. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  72. package/dist-lib/metro-production-bundle.cjs +1 -1
  73. package/dist-lib/metro-production-bundle.mjs +4 -4
  74. package/dist-lib/native-app-identity-project.cjs +33 -17
  75. package/dist-lib/native-app-identity-project.mjs +44 -29
  76. package/dist-lib/native-app-identity.cjs +1 -1
  77. package/dist-lib/native-app-identity.mjs +6 -6
  78. package/dist-lib/native-firebase-metadata.cjs +1 -1
  79. package/dist-lib/native-firebase-metadata.mjs +3 -3
  80. package/dist-lib/pdfium-raster.cjs +1 -1
  81. package/dist-lib/pdfium-raster.mjs +2 -2
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +3 -3
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +87 -86
  87. package/dist-lib/public-origins-lib.json +69 -64
  88. package/dist-lib/react-native-host-modules.cjs +1 -1
  89. package/dist-lib/react-native-host-modules.mjs +2 -2
  90. package/dist-lib/reap-browser.cjs +1 -1
  91. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  92. package/dist-lib/sdk.cjs +1 -1
  93. package/dist-lib/sdk.mjs +8 -8
  94. package/dist-lib/skills.cjs +1062 -660
  95. package/dist-lib/swift-compile.cjs +708 -336
  96. package/dist-lib/swift-compile.mjs +12 -12
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +3 -3
  99. package/dist-lib/swift-submit.cjs +1 -1
  100. package/dist-lib/swift-submit.mjs +6 -6
  101. package/dist-lib/swift-svg-raster.cjs +1 -1
  102. package/dist-lib/swift-svg-raster.mjs +2 -2
  103. package/dist-lib/swift-toolchain.cjs +1 -1
  104. package/dist-lib/swift.cjs +1 -1
  105. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/magic-string.cjs +1 -1
  110. package/dist-lib/vendor/stream-json.cjs +1 -1
  111. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase.cjs +1 -1
  116. package/dist-lib/vendor/terser.cjs +1 -1
  117. package/dist-lib/vendor/valibot.cjs +1 -1
  118. package/dist-lib/vendor/ws.cjs +1 -1
  119. package/dist-lib/vendor/zod.cjs +1 -1
  120. package/dist-lib/worklet-executable.cjs +1 -1
  121. package/dist-lib/worklet-executable.mjs +3 -3
  122. package/package.json +1 -1
  123. package/src/bazel-project.ts +34 -18
  124. package/src/binaryen.lock.json +3 -3
  125. package/src/swift-compile.ts +8 -0
  126. package/src/swift-distribution-contract.ts +6 -1
  127. package/src/swift-distribution.lock.json +4 -2
  128. package/src/swift-guest-compile.ts +170 -160
  129. package/src/swift-guest-dyld-table.ts +22 -9
  130. package/src/swift-guest-link.ts +116 -42
  131. package/src/swift-guest-linked-spans.ts +63 -14
  132. package/src/swift-guest-projection-storage.ts +7 -6
  133. package/src/swift-guest-source-inputs.ts +35 -21
  134. package/src/swift-objc-compile.ts +1 -0
  135. package/src/swift-sdk-app-module.ts +118 -15
  136. package/src/swift-sdk-image-recipe.ts +20 -0
  137. package/src/swift-sdk-image-wasm.ts +119 -17
  138. package/src/swift-sdk-image.ts +6 -5
  139. package/src/swift-wasm-prune.ts +71 -41
  140. package/src/wasm-narrow-boundary.ts +31 -6
@@ -1,7 +1,7 @@
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 { execFile, execFileSync } from 'node:child_process'
4
+ import { execFile, execFileSync, spawn } from 'node:child_process'
5
5
  import fs from 'node:fs'
6
6
  import path from 'node:path'
7
7
  import { promisify } from 'node:util'
@@ -93,6 +93,8 @@ export interface GuestLinkOptions {
93
93
  readonly hasContainingObject: (identity: string) => boolean
94
94
  }
95
95
  readonly onSplitInputs?: (inputs: GuestSplitInputs) => void
96
+ /** Overlap sharedSdk app-module linking with the final whole-program link. */
97
+ readonly onFinalLink?: (done: Promise<void>) => void
96
98
  /** the whole image's dlsym rows: aliases it exports for lazy rows, placed after lowering, and each row's name and image in linked value order. */
97
99
  readonly onDyldRows?: (
98
100
  rows: Pick<GuestImageLedger, 'lazyFunctions' | 'dyldSymbols'>,
@@ -428,6 +430,7 @@ function withOutput(
428
430
  discovery: boolean,
429
431
  ): string[] {
430
432
  const result: string[] = []
433
+ let stripsDebug = false
431
434
  for (let i = 0; i < args.length; i++) {
432
435
  const arg = args[i]!
433
436
  if (arg === '-o' || arg === '--output') {
@@ -437,10 +440,14 @@ function withOutput(
437
440
  if (arg.startsWith('--output=')) continue
438
441
  if (discovery && (arg.startsWith('--why-extract=') || arg.startsWith('--Map=')))
439
442
  continue
443
+ if (arg === '--strip-debug' || arg === '-S' || arg === '--strip-all' || arg === '-s')
444
+ stripsDebug = true
440
445
  result.push(arg)
441
446
  }
442
447
  // scratch links use flat names. the final link checks the image-qualified names.
443
448
  if (discovery) result.push('--allow-multiple-definition')
449
+ // lowering always runs strip-dwarf; drop DWARF at link time while preserving the name section.
450
+ if (!stripsDebug) result.push('--strip-debug')
444
451
  result.push('-o', output)
445
452
  return result
446
453
  }
@@ -474,6 +481,37 @@ export async function linkGuestImages(
474
481
  }
475
482
  return fs.readFileSync(trace, 'utf8')
476
483
  }
484
+ const runLinkAsync = async (name: string, arguments_: readonly string[]) => {
485
+ const response = path.join(directory, `${name}.rsp`)
486
+ const trace = path.join(directory, `${name}-inputs.txt`)
487
+ fs.writeFileSync(
488
+ response,
489
+ [...arguments_, '--trace'].map((argument) => JSON.stringify(argument)).join(' '),
490
+ )
491
+ const output = fs.openSync(trace, 'w')
492
+ try {
493
+ await new Promise<void>((resolve, reject) => {
494
+ const child = spawn(wasmLd, [`@${response}`], {
495
+ stdio: ['ignore', output, 'pipe'],
496
+ })
497
+ const stderr: Buffer[] = []
498
+ child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk))
499
+ child.once('error', reject)
500
+ child.once('close', (code, signal) => {
501
+ if (code === 0) resolve()
502
+ else
503
+ reject(
504
+ new Error(
505
+ `wasm-ld (${name}) failed (${signal ?? code}): ${Buffer.concat(stderr).toString('utf8')}`,
506
+ ),
507
+ )
508
+ })
509
+ })
510
+ } finally {
511
+ fs.closeSync(output)
512
+ }
513
+ return fs.readFileSync(trace, 'utf8')
514
+ }
477
515
  const preselection =
478
516
  options.projection && options.preselectionDiscovery
479
517
  ? options.preselectionDiscovery
@@ -731,6 +769,7 @@ export async function linkGuestImages(
731
769
  options.onSplitInputs && ledger.appLLVMIR
732
770
  ? compileLedgerAsync('app-ledger', ledger.appLLVMIR)
733
771
  : undefined
772
+ let deferredFinalLink: Promise<void> | undefined
734
773
  try {
735
774
  const replacements = new Map<string, string>()
736
775
  const linkedOwners = new Map<string, number>()
@@ -851,19 +890,50 @@ export async function linkGuestImages(
851
890
  })
852
891
  const finalOutput = path.join(directory, 'final.wasm')
853
892
  const finalWhy = path.join(directory, 'final-why-extract.txt')
893
+ const finalLinkArgs = (projectionObject?: string, layoutMap?: string) => [
894
+ ...withOutput(finalArgs, finalOutput, false),
895
+ ledgerObject,
896
+ `@${lazyExports}`,
897
+ ...(projectionObject ? [projectionObject] : []),
898
+ ...(provider ? [`--undefined=${providerSymbol}`] : []),
899
+ ...(layoutMap ? [`--Map=${layoutMap}`] : []),
900
+ `--why-extract=${finalWhy}`,
901
+ ]
854
902
  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
- ])
903
+ runLink('final', finalLinkArgs(projectionObject, layoutMap))
904
+ const finalizeFinalLink = (trace: string) => {
905
+ // the ledger and rewritten references can change archive extraction. every
906
+ // selected member must have participated in ledger construction, so do not
907
+ // publish a link whose final inputs differ from the discovery link.
908
+ const finalSelection = selectedGuestLinkInputs(
909
+ remapGuestLinkPlan(plan, replacements),
910
+ finalArgs,
911
+ fs.readFileSync(finalWhy, 'utf8'),
912
+ trace,
913
+ finalArchives,
914
+ )
915
+ const original = new Map(
916
+ [...replacements].map(([before, after]) => [after, before]),
917
+ )
918
+ const key = (item: GuestLinkSelection) =>
919
+ JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member])
920
+ const before = new Set(selected.map(key))
921
+ const after = new Set(finalSelection.map(key))
922
+ const changed = [...before].filter((item) => !after.has(item))
923
+ changed.push(...[...after].filter((item) => !before.has(item)))
924
+ if (changed.length)
925
+ throw new Error(
926
+ `guest link selected different inputs after rewriting:\n${changed.join('\n')}`,
927
+ )
928
+ fs.renameSync(finalOutput, outputPath(args))
929
+ if (KEEP_WASM_NAMES)
930
+ fs.writeFileSync(
931
+ outputPath(args),
932
+ nameGuestImageAliases(fs.readFileSync(outputPath(args)), plan.symbols),
933
+ )
934
+ }
864
935
  let projectionObject: string | undefined
865
936
  let projectionStorage: ReservedGuestProjectionStorage | undefined
866
- let finalTrace: string
867
937
  if (options.projection) {
868
938
  const projection = options.projection
869
939
  if (!plan.images.some((image) => image.id === projection.image))
@@ -928,10 +998,25 @@ export async function linkGuestImages(
928
998
  [...projection.clangOptions, '-c', projectionSource, '-o', projectionObject],
929
999
  { stdio: 'pipe' },
930
1000
  )
931
- finalTrace = linkFinal(projectionObject, callerMap ? undefined : layoutMap)
932
1001
  // sharedSdk builds never finalize final.wasm; app-module reserves and validates
933
1002
  // the combined app + SDK projection storage against app.wasm instead.
934
- if (sharedSdk) break
1003
+ if (
1004
+ sharedSdk &&
1005
+ options.onFinalLink &&
1006
+ options.onSplitInputs &&
1007
+ appLedgerObjectPromise
1008
+ ) {
1009
+ deferredFinalLink = runLinkAsync(
1010
+ 'final',
1011
+ finalLinkArgs(projectionObject, callerMap ? undefined : layoutMap),
1012
+ ).then((trace) => finalizeFinalLink(trace))
1013
+ break
1014
+ }
1015
+ const finalTrace = linkFinal(projectionObject, callerMap ? undefined : layoutMap)
1016
+ if (sharedSdk) {
1017
+ finalizeFinalLink(finalTrace)
1018
+ break
1019
+ }
935
1020
  const wasm = fs.readFileSync(finalOutput)
936
1021
  const actual = guestProjectionRegionCounts(
937
1022
  images.length,
@@ -943,41 +1028,17 @@ export async function linkGuestImages(
943
1028
  sectionOwners,
944
1029
  ),
945
1030
  )
946
- if (actual.every((count, index) => count <= capacities[index]!.regions)) break
1031
+ if (actual.every((count, index) => count <= capacities[index]!.regions)) {
1032
+ finalizeFinalLink(finalTrace)
1033
+ break
1034
+ }
947
1035
  capacities = capacities.map((capacity, index) => ({
948
1036
  ...capacity,
949
1037
  regions: Math.max(actual[index]!, capacity.regions),
950
1038
  }))
951
1039
  }
952
1040
  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,
963
- )
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
- )
1041
+ } else finalizeFinalLink(linkFinal())
981
1042
  if (projectionStorage && projectionObject)
982
1043
  options.projection!.onReserved(projectionStorage, projectionObject)
983
1044
  options.onLinkedOwners?.(linkedOwners)
@@ -1013,11 +1074,13 @@ export async function linkGuestImages(
1013
1074
  appDefinedSymbols,
1014
1075
  })
1015
1076
  }
1077
+ if (deferredFinalLink) options.onFinalLink?.(deferredFinalLink)
1016
1078
  return selected
1017
1079
  } catch (error) {
1018
1080
  await Promise.allSettled([
1019
1081
  ledgerObjectPromise,
1020
1082
  ...(appLedgerObjectPromise ? [appLedgerObjectPromise] : []),
1083
+ ...(deferredFinalLink ? [deferredFinalLink] : []),
1021
1084
  ])
1022
1085
  throw error
1023
1086
  }
@@ -1787,6 +1850,7 @@ export interface PrunedGuestLinkOptions {
1787
1850
  readonly resolvePlan?: GuestLinkOptions['resolvePlan']
1788
1851
  readonly sharedSdk?: GuestLinkOptions['sharedSdk']
1789
1852
  readonly onSplitInputs?: GuestLinkOptions['onSplitInputs']
1853
+ readonly deferFinalLink?: boolean
1790
1854
  readonly onDyldRows?: GuestLinkOptions['onDyldRows']
1791
1855
  /** Return original input paths; the prune step supplies the exact rewrites. */
1792
1856
  readonly plan: (
@@ -1803,6 +1867,8 @@ export interface PrunedGuestLinkResult {
1803
1867
  readonly generatedSectionOwners: ReadonlyMap<string, number>
1804
1868
  readonly sdk: SwiftPrunedSdkInputs
1805
1869
  readonly mapPath: string
1870
+ // cross-request-promise: host-only build link promise scoped to one compileGuestLink call.
1871
+ readonly finalLinkDone?: Promise<void>
1806
1872
  }
1807
1873
 
1808
1874
  /** Run the normal pruner and use its selected, owned inputs for the guest link. */
@@ -1930,6 +1996,8 @@ export async function linkPrunedGuestImages(
1930
1996
  identities: aliasGuestLinkIdentities(identities, prepared.archives),
1931
1997
  }
1932
1998
  }
1999
+ // cross-request-promise: host-only build link promise scoped to one compileGuestLink call.
2000
+ let finalLinkDone: Promise<void> | undefined
1933
2001
  const selected = await linkCompleteGuestImages({
1934
2002
  plan,
1935
2003
  args: [...linkedArgs, `--Map=${options.mapPath}`],
@@ -1943,6 +2011,11 @@ export async function linkPrunedGuestImages(
1943
2011
  resolvePlan: options.resolvePlan,
1944
2012
  sharedSdk: options.sharedSdk,
1945
2013
  onSplitInputs: options.onSplitInputs,
2014
+ onFinalLink: options.deferFinalLink
2015
+ ? (done) => {
2016
+ finalLinkDone = done
2017
+ }
2018
+ : undefined,
1946
2019
  onDyldRows: options.onDyldRows,
1947
2020
  onLinkedOwners: (value) => {
1948
2021
  owners = value
@@ -1957,5 +2030,6 @@ export async function linkPrunedGuestImages(
1957
2030
  generatedSectionOwners,
1958
2031
  sdk,
1959
2032
  mapPath: options.mapPath,
2033
+ finalLinkDone,
1960
2034
  }
1961
2035
  }
@@ -440,6 +440,12 @@ export interface GuestLinkedSpansExtra {
440
440
  readonly trackedObject?: string
441
441
  readonly trackedObjectOwner?: number
442
442
  readonly trackedLinearSpans?: GuestLinkedSpan[]
443
+ /** Also record data segments parsed from `after`, avoiding a second layout scan. */
444
+ readonly optimizedDataSegments?: {
445
+ readonly address: number
446
+ readonly offset: number
447
+ readonly length: number
448
+ }[]
443
449
  }
444
450
 
445
451
  /**
@@ -464,6 +470,15 @@ export function guestLinkedSpans(
464
470
  const unchanged = before === after
465
471
  const original = layout(before, !unchanged, !importsLayout)
466
472
  const optimized = unchanged ? original : layout(after, true, !importsLayout)
473
+ if (extra?.optimizedDataSegments) {
474
+ for (const segment of optimized.data) {
475
+ extra.optimizedDataSegments.push({
476
+ address: segment.address,
477
+ offset: segment.bytes.byteOffset - after.byteOffset,
478
+ length: segment.bytes.length,
479
+ })
480
+ }
481
+ }
467
482
  const collectSymbols = extra?.collectSymbols
468
483
  const trackedObject = extra?.trackedObject
469
484
  const trackedObjectOwner = extra?.trackedObjectOwner
@@ -660,18 +675,46 @@ export function guestLinkedSpans(
660
675
  }
661
676
  return result
662
677
  }
678
+ const singleSegmentSlice = (
679
+ module: WasmLayout,
680
+ start: number,
681
+ length: number,
682
+ ): Uint8Array | undefined => {
683
+ const segs = module.dataByAddress
684
+ let low = 0
685
+ let high = segs.length
686
+ while (low < high) {
687
+ const middle = (low + high) >> 1
688
+ if (segs[middle]!.maximumEnd <= start) low = middle + 1
689
+ else high = middle
690
+ }
691
+ let found: (typeof segs)[number] | undefined
692
+ const end = start + length
693
+ for (let index = low; index < segs.length; index++) {
694
+ const segment = segs[index]!
695
+ if (segment.address >= end) break
696
+ if (segment.address + segment.bytes.length > start) {
697
+ if (found) return undefined
698
+ found = segment
699
+ }
700
+ }
701
+ if (!found || found.address > start || found.address + found.bytes.length < end)
702
+ return undefined
703
+ return found.bytes.subarray(start - found.address, end - found.address)
704
+ }
705
+ const sameDataAt = (start: number, length: number): boolean => {
706
+ const origSlice = singleSegmentSlice(original, start, length)
707
+ const optSlice = origSlice ? singleSegmentSlice(optimized, start, length) : undefined
708
+ if (origSlice && optSlice) return Buffer.compare(origSlice, optSlice) === 0
709
+ return dataAt(original, start, length).equals(dataAt(optimized, start, length))
710
+ }
663
711
  for (const span of spans) {
664
712
  if (
665
713
  span.address + span.length > original.memoryBytes ||
666
714
  span.address + span.length > optimized.memoryBytes
667
715
  )
668
716
  throw new Error(`linked data lies outside guest memory at ${span.address}`)
669
- if (
670
- !unchanged &&
671
- !dataAt(original, span.address, span.length).equals(
672
- dataAt(optimized, span.address, span.length),
673
- )
674
- )
717
+ if (!unchanged && !sameDataAt(span.address, span.length))
675
718
  throw new Error(`optimization changed linked data at ${span.address}`)
676
719
  }
677
720
  let previous: GuestLinkedSpan | undefined
@@ -821,7 +864,7 @@ export function takeGuestStartupData(
821
864
  const bytes = new Uint8Array(length)
822
865
  const emptied = new Set<number>()
823
866
  let covered = 0
824
- const result = Buffer.from(wasm)
867
+ const patchedBody = Buffer.from(wasm.subarray(body[0], body[1]))
825
868
  for (const initializer of startupDataInitializers(wasm.subarray(...body))) {
826
869
  const end = initializer.address + initializer.length
827
870
  if (end <= address || initializer.address >= address + length || !initializer.length)
@@ -843,19 +886,18 @@ export function takeGuestStartupData(
843
886
  emptied.add(initializer.segment)
844
887
  // a zero padded to the immediate's width keeps every code offset.
845
888
  const [at, immediateEnd] = initializer.lengthImmediate
846
- result.fill(0x80, body[0] + at, body[0] + immediateEnd - 1)
847
- result[body[0] + immediateEnd - 1] = 0
889
+ patchedBody.fill(0x80, at, immediateEnd - 1)
890
+ patchedBody[immediateEnd - 1] = 0
848
891
  }
849
892
  if (covered !== length)
850
893
  throw new Error('guest startup data does not initialize the whole range')
851
- const parts: Uint8Array[] = [result.subarray(0, data[0])]
852
- const payload: Uint8Array[] = [result.subarray(data[1], segments[0]!.header)]
894
+ const payload: Uint8Array[] = [wasm.subarray(data[1], segments[0]!.header)]
853
895
  for (const [index, segment] of segments.entries()) {
854
896
  if (!emptied.has(index)) {
855
- payload.push(result.subarray(segment.header, segment.payload + segment.length))
897
+ payload.push(wasm.subarray(segment.header, segment.payload + segment.length))
856
898
  continue
857
899
  }
858
- payload.push(result.subarray(segment.header, segment.sizeAt), Uint8Array.of(0))
900
+ payload.push(wasm.subarray(segment.header, segment.sizeAt), Uint8Array.of(0))
859
901
  }
860
902
  const section = Buffer.concat(payload)
861
903
  const size: number[] = []
@@ -866,6 +908,13 @@ export function takeGuestStartupData(
866
908
  }
867
909
  size.push((rest % 128) | 128)
868
910
  }
869
- parts.push(Uint8Array.of(11, ...size), section, result.subarray(data[2]))
911
+ const parts: Uint8Array[] = [
912
+ wasm.subarray(0, body[0]),
913
+ patchedBody,
914
+ wasm.subarray(body[1], data[0]),
915
+ Uint8Array.of(11, ...size),
916
+ section,
917
+ wasm.subarray(data[2]),
918
+ ]
870
919
  return { wasm: Buffer.concat(parts), bytes }
871
920
  }
@@ -1,8 +1,4 @@
1
- import {
2
- guestLinkedSpans,
3
- guestWasmDataSegments,
4
- type GuestLinkedSpan,
5
- } from './swift-guest-linked-spans'
1
+ import { guestLinkedSpans, type GuestLinkedSpan } from './swift-guest-linked-spans'
6
2
  import {
7
3
  GUEST_PROJECTION_RANGE_LIMIT,
8
4
  reserveGuestImageProjection,
@@ -283,6 +279,11 @@ export function finalizeGuestProjectionStorage(options: {
283
279
  const owner = options.owners.get(options.projectionObject)
284
280
  if (owner === undefined) throw new Error('guest projection object has no image owner')
285
281
  const ranges: GuestLinkedSpan[] = []
282
+ const data: {
283
+ readonly address: number
284
+ readonly offset: number
285
+ readonly length: number
286
+ }[] = []
286
287
  const spans = guestLinkedSpans(
287
288
  options.map,
288
289
  options.linked,
@@ -294,6 +295,7 @@ export function finalizeGuestProjectionStorage(options: {
294
295
  trackedObject: options.projectionObject,
295
296
  trackedObjectOwner: owner,
296
297
  trackedLinearSpans: ranges,
298
+ optimizedDataSegments: data,
297
299
  },
298
300
  )
299
301
  const images = planGuestProjectionRegions(
@@ -302,7 +304,6 @@ export function finalizeGuestProjectionStorage(options: {
302
304
  options.sdkSpans ? [...spans, ...options.sdkSpans] : spans,
303
305
  )
304
306
  const result = Buffer.from(options.optimized)
305
- const data = guestWasmDataSegments(options.optimized, options.sdkSpans === undefined)
306
307
  const locations = new Map<number, number>()
307
308
  const counts = new Map<number, number>()
308
309
  const uuids = new Map<number, number>()
@@ -115,8 +115,14 @@ function clangBinaryStamp(file: string): string {
115
115
  return [file, stat.size, stat.mtimeNs].join(':')
116
116
  }
117
117
 
118
+ function sha256Hex(bytes: Buffer | string): string {
119
+ if (typeof Bun !== 'undefined')
120
+ return new Bun.CryptoHasher('sha256').update(bytes).digest('hex')
121
+ return createHash('sha256').update(bytes).digest('hex')
122
+ }
123
+
118
124
  function clangWrapperStamp(file: string): string {
119
- return createHash('sha256').update(readFileSync(file)).digest('hex')
125
+ return sha256Hex(readFileSync(file))
120
126
  }
121
127
 
122
128
  function clangArgsNeedCwd(args: readonly string[]): boolean {
@@ -296,7 +302,18 @@ export function sourceGuestClangLinkOptions(options: {
296
302
  cacheFile: string
297
303
  key: string
298
304
  }[] = []
305
+ const realPathCache = new Map<string, string>()
306
+ const cachedRealpath = (file: string) => {
307
+ let resolved = realPathCache.get(file)
308
+ if (resolved === undefined) {
309
+ resolved = realpathSync(file)
310
+ realPathCache.set(file, resolved)
311
+ }
312
+ return resolved
313
+ }
314
+ const resolvedSwiftCompiler = cachedRealpath(options.swiftCompiler)
299
315
  let clang: string | undefined
316
+ let clangWrapper: string | undefined
300
317
  let clangStamp: string | undefined
301
318
  let wrapperStamp: string | undefined
302
319
  for (const file of wanted) {
@@ -305,39 +322,36 @@ export function sourceGuestClangLinkOptions(options: {
305
322
  if (command.tool === 'shell') {
306
323
  if (
307
324
  !command.args.length ||
308
- realpathSync(command.args[0]!) !== realpathSync(options.swiftCompiler)
325
+ cachedRealpath(command.args[0]!) !== resolvedSwiftCompiler
309
326
  )
310
327
  throw new Error(`unsupported source object producer ${file}`)
311
328
  continue
312
329
  }
313
- const compiler = command.args[0] ? realpathSync(command.args[0]) : ''
314
- clang ??= realpathSync(path.join(options.toolchainBin, 'clang'))
330
+ const compiler = command.args[0] ? cachedRealpath(command.args[0]) : ''
331
+ clang ??= cachedRealpath(path.join(options.toolchainBin, 'clang'))
315
332
  if (
316
333
  command.tool !== 'clang' ||
317
334
  (compiler !== clang &&
318
335
  compiler !==
319
- realpathSync(path.join(options.buildDirectory, CLANG_TARGET_MODULE_WRAPPER)))
336
+ (clangWrapper ??= cachedRealpath(
337
+ path.join(options.buildDirectory, CLANG_TARGET_MODULE_WRAPPER),
338
+ )))
320
339
  )
321
340
  throw new Error(`unsupported source object producer ${file}`)
322
341
  // the object can stay byte-identical when only a linker pragma changes.
323
342
  // swiftpm's object incarnation also changes in that case.
324
- const key = createHash('sha256')
325
- .update(
326
- JSON.stringify([
327
- 'clang-link-options/v2',
328
- clangArgsNeedCwd(command.args) ? process.cwd() : null,
329
- driverEnvironment,
330
- command.args,
331
- (clangStamp ??= clangBinaryStamp(clang)),
332
- compiler === clang ? null : (wrapperStamp ??= clangWrapperStamp(compiler)),
333
- clangProducerStamp(file),
334
- ]),
335
- )
336
- .digest('hex')
337
- const cacheFile = path.join(
338
- cacheDirectory,
339
- createHash('sha256').update(file).digest('hex') + '.json',
343
+ const key = sha256Hex(
344
+ JSON.stringify([
345
+ 'clang-link-options/v2',
346
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
347
+ driverEnvironment,
348
+ command.args,
349
+ (clangStamp ??= clangBinaryStamp(clang)),
350
+ compiler === clang ? null : (wrapperStamp ??= clangWrapperStamp(compiler)),
351
+ clangProducerStamp(file),
352
+ ]),
340
353
  )
354
+ const cacheFile = path.join(cacheDirectory, sha256Hex(file) + '.json')
341
355
  const cached = readClangLinkOptions(cacheFile, key)
342
356
  if (cached) {
343
357
  validateClangLinkOptions(cached)
@@ -1811,6 +1811,7 @@ async function prepareXcodeNativeInputs(
1811
1811
  ...flags,
1812
1812
  ...(target.prefix ? ['-include', staged(target.prefix)] : []),
1813
1813
  '-Os',
1814
+ ...(purpose === 'objects' ? ['-g0'] : []),
1814
1815
  '-c',
1815
1816
  staged(file),
1816
1817
  '-o',