peachsim 0.1.2773 → 0.1.2775

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 (148) 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 +318 -199
  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-3SGU25AX.mjs → acorn-CTIC3GCU.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-KMMFDGYA.mjs → chunk-2YTHEKWJ.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-2HWUPAOD.mjs → chunk-3WU4YTJR.mjs} +205 -166
  29. package/dist-lib/esm-chunks/{chunk-ORGP6SSO.mjs → chunk-4B46TF64.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-QMI7ECNF.mjs → chunk-C5EU2DRL.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-DFVWY2BW.mjs → chunk-CFNSLWMQ.mjs} +4 -4
  32. package/dist-lib/esm-chunks/{chunk-HN7CHPZK.mjs → chunk-E6ULRDAP.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-IQF674WE.mjs → chunk-ESP2U4IX.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-5DQRSOJ5.mjs → chunk-ESWEEZZP.mjs} +2 -2
  35. package/dist-lib/esm-chunks/{chunk-4FVDW5QX.mjs → chunk-FBN2C43P.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-NH3CEIBN.mjs → chunk-FVUN2533.mjs} +3 -3
  37. package/dist-lib/esm-chunks/{chunk-IM2IAOAZ.mjs → chunk-GKKZLYBA.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-SZ7TVJHH.mjs → chunk-H5TBKFDB.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-GSZLZNZM.mjs → chunk-ITTQHQD5.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-XXLSXSUK.mjs → chunk-JERE5CAK.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-WBPJJXMA.mjs → chunk-MJSKVK7E.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-Q2EEH42W.mjs → chunk-NV5NLKKN.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-G5TS3L6A.mjs → chunk-RGOPQX37.mjs} +6 -6
  44. package/dist-lib/esm-chunks/{chunk-KEVJJ3QT.mjs → chunk-S47B7YHJ.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-FRPS6V6P.mjs → chunk-SK4FQLNJ.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-YZRKIUVZ.mjs → chunk-TE3WHBF3.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-ANTOZ3UC.mjs → chunk-W42DUKWD.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-DYKZYFHH.mjs → chunk-WB5OWF4G.mjs} +5 -5
  49. package/dist-lib/esm-chunks/{chunk-KZ2NH7C4.mjs → chunk-XMBGLLON.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-MRQ72NMR.mjs → chunk-YRKGWASL.mjs} +6 -6
  51. package/dist-lib/esm-chunks/{metro-layout-parser-5MEY33AK.mjs → metro-layout-parser-2RQ3WC37.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-3FLCNBQT.mjs → swift-package-prebuilt-L5SWVH6U.mjs} +12 -12
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-PPJ4LUOW.mjs → swift-sdk-app-module-5SWDBTBY.mjs} +107 -25
  54. package/dist-lib/esm-chunks/{swift-sdk-image-L5MERITP.mjs → swift-sdk-image-OOSMI47A.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-IILRYXVN.mjs → swift-sdk-image-producer-DL4VEBXN.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +318 -199
  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 +4327 -4209
  61. package/dist-lib/host/fetch-proxy-handler.cjs +343 -340
  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 +1 -1
  75. package/dist-lib/native-app-identity-project.mjs +15 -15
  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 +86 -86
  87. package/dist-lib/public-origins-lib.json +96 -96
  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 +2912 -2794
  95. package/dist-lib/swift-compile.cjs +314 -195
  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/dist-types/packages/peach-engine/src/ios/duo-vertical-bar-geometry.d.ts +0 -15
  123. package/dist-types/packages/peach-engine/src/ios/flex-interaction.d.ts +0 -1
  124. package/dist-types/packages/peach-engine/src/react-native/AppState.d.ts +0 -1
  125. package/dist-types/packages/peach-engine/src/react-native/Keyboard.d.ts +0 -1
  126. package/dist-types/packages/peach-kit/src/ring-mode-state.d.ts +0 -1
  127. package/dist-types/packages/peach-kit/src/transitions/screen-transition-math.d.ts +0 -31
  128. package/package.json +1 -1
  129. package/src/assetCatalogContract.ts +0 -6
  130. package/src/expo-pod-prebuilt.ts +0 -63
  131. package/src/native-package-slice.ts +0 -2
  132. package/src/podfile-cocoapods.ts +0 -5
  133. package/src/runtime-assets.ts +0 -9
  134. package/src/sfSymbolMetricsContract.ts +51 -23
  135. package/src/swift-compile.ts +9 -6
  136. package/src/swift-distribution-mirror.ts +16 -5
  137. package/src/swift-guest-compile.ts +18 -7
  138. package/src/swift-guest-link.ts +0 -9
  139. package/src/swift-guest-projection-storage.ts +15 -2
  140. package/src/swift-guest-projection.ts +1 -46
  141. package/src/swift-guest-runtime-plan.ts +4 -80
  142. package/src/swift-header-compiler.ts +24 -9
  143. package/src/swift-sdk-app-module.ts +113 -10
  144. package/src/swift-wasm-prune.ts +0 -5
  145. package/src/swiftRuntimeProductContract.ts +1 -0
  146. package/src/swiftSdkLinkContract.ts +10 -0
  147. package/src/wasm-narrow-boundary.ts +0 -13
  148. package/src/wasm-lazy-split-tool.ts +0 -210
@@ -34,6 +34,7 @@ import {
34
34
  import { SWIFT_DISTRIBUTION_MIRROR, SWIFT_SDK_MIRROR } from './swift-distribution-mirror'
35
35
  import { guestLazyExports, placeGuestLazyFunctions } from './swift-guest-dyld-functions'
36
36
  import { guestWasmDataSegments, type GuestLinkedSpan } from './swift-guest-linked-spans'
37
+ import { planGuestProjectionRegions } from './swift-guest-projection-storage'
37
38
  import { projectOutputFile, type SwiftProjectUser } from './swift-project-user'
38
39
  import {
39
40
  readSwiftSdkManifest,
@@ -522,7 +523,7 @@ export async function linkSwiftAppModule(options: {
522
523
  { maxBuffer: 64 << 20, ...options.project },
523
524
  )
524
525
  const module = path.join(work, 'app.module.wasm')
525
- const { bytes, linkage } = resolveSdkReferences(
526
+ const { bytes, linkage, staticEnd, globalValues } = resolveSdkReferences(
526
527
  readFileSync(
527
528
  options.project ? projectOutputFile(work, linked, options.project) : linked,
528
529
  ),
@@ -565,6 +566,8 @@ export async function linkSwiftAppModule(options: {
565
566
  .digest('hex'))
566
567
  return {
567
568
  linkage,
569
+ staticEnd,
570
+ globalValues,
568
571
  async lower() {
569
572
  const receipt = loweringCache && `${loweringCache.file}.key`
570
573
  if (
@@ -782,7 +785,7 @@ function resolveSdkReferences(
782
785
  source: Buffer,
783
786
  sdk: SwiftSdkImage,
784
787
  forwarders: ReadonlySet<string>,
785
- ): { bytes: Buffer; linkage: SwiftSdkAppLinkage } {
788
+ ) {
786
789
  const bytes = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)
787
790
  const { data: sdkData, signatures } = sdk.sdkInterface
788
791
  const sections = wasmSections(bytes)
@@ -1146,6 +1149,7 @@ function resolveSdkReferences(
1146
1149
  const er = wasmReader(bytes, exportSection.start)
1147
1150
  const exportCount = er.u()
1148
1151
  const originalExportsStart = er.at
1152
+ let staticEnd = 0
1149
1153
  for (let i = 0; i < exportCount; i++) {
1150
1154
  const name = er.name()
1151
1155
  const kind = er.byte()
@@ -1158,8 +1162,10 @@ function resolveSdkReferences(
1158
1162
  const op = raw.byte()
1159
1163
  const value = op === 0x23 ? BigInt(raw.u()) : raw.s()
1160
1164
  raw.skip(1)
1161
- if (j === index && value > BigInt(SWIFT_SDK_MEMORY_BASE))
1165
+ if (j !== index) continue
1166
+ if (value <= 0n || value > BigInt(SWIFT_SDK_MEMORY_BASE))
1162
1167
  throw new Error('Swift app exceeds its reserved static memory range')
1168
+ staticEnd = Number(value)
1163
1169
  }
1164
1170
  }
1165
1171
  const exportParts: Uint8Array[] = [
@@ -1203,7 +1209,12 @@ function resolveSdkReferences(
1203
1209
  parts.push(bytes.subarray(s.offset, s.end))
1204
1210
  }
1205
1211
  }
1206
- return { bytes: Buffer.concat(parts), linkage }
1212
+ return {
1213
+ bytes: Buffer.concat(parts),
1214
+ linkage,
1215
+ staticEnd,
1216
+ globalValues: [...new Set(got.values())],
1217
+ }
1207
1218
  }
1208
1219
 
1209
1220
  function expandSdkRelocations(
@@ -1259,27 +1270,117 @@ export function bindSwiftAppModule(
1259
1270
  throw new Error(`SDK image has no compatible function ${name}`)
1260
1271
  return slot
1261
1272
  })
1262
- const values = BigInt64Array.from(linkage.values, ({ kind, name, addend }) => {
1273
+ const projection =
1274
+ linkage.replayProjection?.sdk === sdk.key ? undefined : linkage.replayProjection
1275
+ const optional = projection && new Set(projection.lookupValues)
1276
+ const values = linkage.values.map(({ kind, name, addend }, index) => {
1263
1277
  const value =
1264
1278
  kind === 'function' ? functions[name] : kind === 'address' ? data[name] : tls[name]
1279
+ if (value === undefined && optional?.has(index)) return 0n
1265
1280
  if (value === undefined || (kind === 'tls' && tls.errno === undefined))
1266
1281
  throw new Error(`SDK image has no ${kind} symbol ${name}`)
1267
1282
  return BigInt(value + addend - (kind === 'tls' ? tls.errno! : 0))
1268
1283
  })
1284
+ const fixups = projection
1285
+ ? appendReplayProjectionFixups(linkage.data, values, projection, sdk)
1286
+ : linkage.data
1269
1287
  const words = Uint32Array.from([
1270
1288
  values.length,
1271
1289
  slots.length,
1272
- linkage.data.length,
1290
+ fixups.length,
1273
1291
  linkage.tls.length,
1274
1292
  ])
1275
1293
  return Buffer.concat([
1276
- ...[words, values, slots, Uint32Array.from(linkage.tls)].map(
1294
+ ...[words, BigInt64Array.from(values), slots, Uint32Array.from(linkage.tls)].map(
1277
1295
  (part) => new Uint8Array(part.buffer),
1278
1296
  ),
1279
- encodeNativeSdkFixups(linkage.data),
1297
+ encodeNativeSdkFixups(fixups),
1280
1298
  ])
1281
1299
  }
1282
1300
 
1301
+ function appendReplayProjectionFixups(
1302
+ data: readonly number[],
1303
+ values: bigint[],
1304
+ projection: NonNullable<SwiftSdkAppLinkage['replayProjection']>,
1305
+ sdk: SwiftSdkImage,
1306
+ ): number[] {
1307
+ const { countAddresses, images, staticEnd } = projection
1308
+ if (
1309
+ !Number.isSafeInteger(staticEnd) ||
1310
+ staticEnd < SWIFT_SDK_APP_MEMORY_BASE ||
1311
+ staticEnd >= SWIFT_SDK_MEMORY_BASE ||
1312
+ countAddresses.length !== images.length ||
1313
+ new Set(countAddresses).size !== images.length
1314
+ )
1315
+ throw new Error('invalid retained app projection storage')
1316
+ const objects = new Map(projection.objects)
1317
+ const products = new Map(projection.products)
1318
+ const sdkSpans = swiftSdkProjectionSpans(
1319
+ sdk,
1320
+ (object, product) => objects.get(object) ?? products.get(product),
1321
+ )
1322
+ const regions = planGuestProjectionRegions(
1323
+ images,
1324
+ images.map(() => ({
1325
+ regions: Number.MAX_SAFE_INTEGER,
1326
+ memoryProtection: { initial: 3, maximum: 3 },
1327
+ tableProtection: { initial: 5, maximum: 5 },
1328
+ })),
1329
+ [
1330
+ ...images.flatMap(({ regions }, image) =>
1331
+ regions.map(({ space, address, length }) => ({ image, space, address, length })),
1332
+ ),
1333
+ ...sdkSpans,
1334
+ ],
1335
+ )
1336
+ const fixups = [...data]
1337
+ const literals = new Map<bigint, number>()
1338
+ const add = (address: number, width: 4 | 8, value: bigint) => {
1339
+ let index = literals.get(value)
1340
+ if (index === undefined) {
1341
+ index = values.length
1342
+ literals.set(value, index)
1343
+ values.push(value)
1344
+ }
1345
+ fixups.push(address, width, index)
1346
+ }
1347
+ // the app's static data ends before the SDK's reserved base. the SDK owns the heap.
1348
+ const name = Math.ceil(staticEnd / 8) * 8
1349
+ let next = name + 8
1350
+ if (next > SWIFT_SDK_MEMORY_BASE)
1351
+ throw new Error('rebound SDK projection exceeds the app static memory reservation')
1352
+ add(name, 8, Buffer.from('__WASM\0\0').readBigInt64LE())
1353
+ for (const [image, { regions: ranges }] of regions.entries()) {
1354
+ const count = countAddresses[image]!
1355
+ if (
1356
+ !Number.isSafeInteger(count) ||
1357
+ count < SWIFT_SDK_APP_MEMORY_BASE ||
1358
+ count + 16 > staticEnd ||
1359
+ count % 8 !== 0
1360
+ )
1361
+ throw new Error('retained app projection record is out of range')
1362
+ add(count, 4, BigInt(ranges.length))
1363
+ add(count + 8, 8, BigInt(next))
1364
+ for (const range of ranges) {
1365
+ if (next + 40 > SWIFT_SDK_MEMORY_BASE)
1366
+ throw new Error(
1367
+ 'rebound SDK projection exceeds the app static memory reservation',
1368
+ )
1369
+ add(next, 8, BigInt(name))
1370
+ add(
1371
+ next + 8,
1372
+ 8,
1373
+ (BigInt(range.address) << 32n) | BigInt(range.space === 'function-table'),
1374
+ )
1375
+ add(next + 16, 8, (BigInt(range.initialProtection) << 32n) | BigInt(range.length))
1376
+ add(next + 24, 8, BigInt(range.maximumProtection))
1377
+ add(next + 32, 8, 0n)
1378
+ next += 40
1379
+ }
1380
+ }
1381
+ return fixups
1382
+ }
1383
+
1283
1384
  interface Piece {
1284
1385
  address: number
1285
1386
  size: number
@@ -1663,8 +1764,10 @@ function selectSwiftSdkData(
1663
1764
  const { functions, data } = sdk.sdkInterface
1664
1765
  for (const { name } of linkage.functions) boundSlots.add(functions[name]!)
1665
1766
  for (const { kind, name } of linkage.values) {
1666
- if (kind === 'function') boundSlots.add(functions[name]!)
1667
- else if (kind === 'address') visit(data[name]!)
1767
+ const address = kind === 'function' ? functions[name] : data[name]
1768
+ if (address === undefined) continue
1769
+ if (kind === 'function') boundSlots.add(address)
1770
+ else if (kind === 'address') visit(address)
1668
1771
  }
1669
1772
  }
1670
1773
  const slots = block('functionSlots')
@@ -1118,11 +1118,6 @@ function parseWasmObjectCached(
1118
1118
  return parsed
1119
1119
  }
1120
1120
 
1121
- /** Original undefined symbols from a selected Wasm object. */
1122
- export function guestWasmUndefinedSymbols(bytes: Uint8Array): string[] {
1123
- return guestWasmSymbols(bytes).undefined
1124
- }
1125
-
1126
1121
  /** Original undefined and externally visible symbols from a selected object. */
1127
1122
  export function guestWasmSymbols(bytes: Uint8Array): {
1128
1123
  importsDlsym: boolean
@@ -41,6 +41,7 @@ export const swiftFrameworkProductSchema = v.object({
41
41
  export type SwiftFrameworkProduct = v.InferOutput<typeof swiftFrameworkProductSchema>
42
42
 
43
43
  export const SWIFT_SDK_PRODUCT_FILE = 'runtime-products.json'
44
+ export const SWIFT_SDK_PRODUCT_DIRECTORY = 'swift.xctoolchain/usr/lib/swift_static/wasi'
44
45
 
45
46
  /** producer facts; the consuming compiler resolves guest image scopes and build versions. */
46
47
  export const swiftSdkProductSchema = v.pipe(
@@ -1,4 +1,5 @@
1
1
  import type { WasmMapChunkIdentity } from './swift-sdk-image-map'
2
+ import type { SwiftGuestImageManifest } from './swiftGuestImageContract'
2
3
 
3
4
  export const SWIFT_SDK_FUNCTION_ADDRESS_PREFIX = '__peach_sdk_function_address.'
4
5
  export const SWIFT_SDK_APP_TABLE_BASE = 524288
@@ -17,6 +18,15 @@ export interface SwiftSdkAppLinkage {
17
18
  readonly values: SwiftSdkSymbolValue[]
18
19
  readonly data: number[]
19
20
  readonly tls: number[]
21
+ readonly replayProjection?: {
22
+ readonly sdk: string
23
+ readonly staticEnd: number
24
+ readonly countAddresses: readonly number[]
25
+ readonly images: readonly SwiftGuestImageManifest[]
26
+ readonly objects: readonly (readonly [string, number])[]
27
+ readonly products: readonly (readonly [string, number])[]
28
+ readonly lookupValues: readonly number[]
29
+ }
20
30
  }
21
31
 
22
32
  export interface SwiftSdkUsage {
@@ -323,19 +323,6 @@ export function compactSparseWasmTable(bytes: Buffer<ArrayBuffer>): Buffer<Array
323
323
  ])
324
324
  }
325
325
 
326
- export function hasWasmExport(bytes: Uint8Array, name: string): boolean {
327
- const section = sections(bytes).find((value) => value.id === 7)
328
- if (!section) return false
329
- const input = reader(bytes, section.start, section.end)
330
- for (let count = input.number(); count > 0; count--) {
331
- const found = input.name()
332
- input.byte()
333
- input.number()
334
- if (found === name) return true
335
- }
336
- return false
337
- }
338
-
339
326
  // replaces whole sections and keeps every other byte.
340
327
  function withSections(
341
328
  bytes: Uint8Array,
@@ -1,210 +0,0 @@
1
- import { execFile } from 'node:child_process'
2
- import { createHash } from 'node:crypto'
3
- import {
4
- existsSync,
5
- mkdirSync,
6
- readFileSync,
7
- renameSync,
8
- rmSync,
9
- writeFileSync,
10
- } from 'node:fs'
11
- import { dirname, join } from 'node:path'
12
- import { promisify } from 'node:util'
13
-
14
- const source = String.raw`
15
- #include <binaryen-c.h>
16
- #include <fstream>
17
- #include <iostream>
18
- #include <iterator>
19
- #include <map>
20
- #include <set>
21
- #include <stdexcept>
22
- #include <string>
23
- #include <vector>
24
-
25
- BinaryenModuleRef read(const char* path) {
26
- std::ifstream file(path, std::ios::binary);
27
- if (!file) throw std::runtime_error("lazy split input is missing");
28
- std::vector<char> bytes{std::istreambuf_iterator<char>(file), {}};
29
- auto module = BinaryenModuleRead(bytes.data(), bytes.size());
30
- if (!module) throw std::runtime_error("lazy split input is invalid");
31
- return module;
32
- }
33
- void write(BinaryenModuleRef module, const char* path) {
34
- if (!BinaryenModuleValidate(module)) throw std::runtime_error("lazy split output is invalid");
35
- BinaryenSetDebugInfo(true);
36
- auto bytes = BinaryenModuleAllocateAndWrite(module, nullptr);
37
- std::ofstream file(path, std::ios::binary);
38
- file.write(static_cast<char*>(bytes.binary), bytes.binaryBytes);
39
- free(bytes.binary);
40
- free(bytes.sourceMap);
41
- if (!file) throw std::runtime_error("lazy split output cannot be written");
42
- }
43
- int main(int argc, char** argv) {
44
- try {
45
- if (argc != 4) throw std::runtime_error("lazy split needs primary, side and module id");
46
- if (std::string(argv[1]) == "--check") {
47
- auto input = read(argv[2]);
48
- std::ifstream selection(argv[3]);
49
- if (!selection) throw std::runtime_error("lazy split selection is missing");
50
- std::set<std::string> selected;
51
- for (std::string name; std::getline(selection, name);) {
52
- auto function = BinaryenGetFunction(input, name.c_str());
53
- if (!function || !BinaryenFunctionGetBody(function) || !selected.insert(name).second)
54
- throw std::runtime_error("lazy split selection lacks a unique defined function: " + name);
55
- }
56
- if (selected.empty()) throw std::runtime_error("lazy split selection is empty");
57
- BinaryenModuleDispose(input);
58
- return 0;
59
- }
60
- auto primary = read(argv[1]);
61
- auto side = read(argv[2]);
62
- auto id = std::stoul(argv[3]);
63
- if (id > 0x7fffffff) throw std::runtime_error("lazy module id is out of range");
64
- if (BinaryenGetStart(side) || BinaryenGetNumDataSegments(side))
65
- throw std::runtime_error("lazy code image cannot initialize data or have a start function");
66
- if (BinaryenGetStart(primary))
67
- throw std::runtime_error("lazy code images require explicit post-instantiation startup");
68
- if (BinaryenGetNumTables(primary) != 1)
69
- throw std::runtime_error("lazy code split needs one lowered function table");
70
- const std::string table = BinaryenTableGetName(BinaryenGetTableByIndex(primary, 0));
71
- if (BinaryenTableHasMax(BinaryenGetTableByIndex(primary, 0)))
72
- throw std::runtime_error("lazy code images require a growable process function table");
73
- if (!BinaryenGetExport(side, "__indirect_function_table"))
74
- BinaryenAddTableExport(side, BinaryenTableGetName(BinaryenGetTableByIndex(side, 0)), "__indirect_function_table");
75
- std::map<uint32_t, std::string> functions;
76
- while (BinaryenGetNumElementSegments(side)) {
77
- auto segment = BinaryenGetElementSegmentByIndex(side, 0);
78
- auto offset = BinaryenElementSegmentGetOffset(segment);
79
- if (BinaryenElementSegmentIsPassive(segment) || !offset || BinaryenExpressionGetId(offset) != BinaryenConstId())
80
- throw std::runtime_error("lazy side has an unsupported element initializer");
81
- auto first = uint32_t(BinaryenConstGetValueI32(offset));
82
- for (BinaryenIndex i = 0; i < BinaryenElementSegmentGetLength(segment); ++i) {
83
- auto name = BinaryenElementSegmentGetData(segment, i);
84
- if (!name || !functions.emplace(first + i, name).second)
85
- throw std::runtime_error("lazy side has overlapping or null elements");
86
- }
87
- BinaryenRemoveElementSegment(side, BinaryenElementSegmentGetName(segment));
88
- }
89
- if (functions.empty()) throw std::runtime_error("lazy side contains no callable functions");
90
- const std::string base = "peach.lazy.base." + std::to_string(id);
91
- const std::string load = "peach.lazy.load";
92
- if (BinaryenGetGlobal(primary, base.c_str())) throw std::runtime_error("lazy split global already exists");
93
- BinaryenAddGlobal(primary, base.c_str(), BinaryenTypeInt32(), true, BinaryenConst(primary, BinaryenLiteralInt32(-1)));
94
- if (!BinaryenGetFunction(primary, load.c_str()))
95
- BinaryenAddFunctionImport(primary, load.c_str(), "peach_lazy", "load", BinaryenTypeInt32(), BinaryenTypeInt32());
96
- std::map<uint32_t, std::string> placeholders;
97
- for (BinaryenIndex i = 0; i < BinaryenGetNumFunctions(primary); ++i) {
98
- auto function = BinaryenGetFunctionByIndex(primary, i);
99
- if (BinaryenFunctionGetBody(function)) continue;
100
- auto space = BinaryenFunctionImportGetModule(function);
101
- if (space && std::string(space) == "placeholder.deferred")
102
- placeholders.emplace(std::stoul(BinaryenFunctionImportGetBase(function)), BinaryenFunctionGetName(function));
103
- }
104
- if (placeholders.size() != functions.size()) throw std::runtime_error("lazy placeholder set differs from side elements");
105
- uint32_t ordinal = 0;
106
- for (const auto& [slot, name] : functions) {
107
- auto found = placeholders.find(slot);
108
- if (found == placeholders.end()) throw std::runtime_error("lazy side element has no primary placeholder");
109
- auto function = BinaryenGetFunction(primary, found->second.c_str());
110
- auto params = BinaryenFunctionGetParams(function);
111
- auto results = BinaryenFunctionGetResults(function);
112
- auto heapType = BinaryenFunctionGetType(function);
113
- std::vector<BinaryenType> types(BinaryenTypeArity(params));
114
- BinaryenTypeExpand(params, types.data());
115
- std::vector<BinaryenExpressionRef> args;
116
- for (uint32_t i = 0; i < types.size(); ++i) args.push_back(BinaryenLocalGet(primary, i, types[i]));
117
- auto getBase = [&]() { return BinaryenGlobalGet(primary, base.c_str(), BinaryenTypeInt32()); };
118
- auto equalMissing = [&]() { return BinaryenBinary(primary, BinaryenEqInt32(), getBase(), BinaryenConst(primary, BinaryenLiteralInt32(-1))); };
119
- BinaryenExpressionRef moduleId[] = {BinaryenConst(primary, BinaryenLiteralInt32(id))};
120
- BinaryenExpressionRef body[] = {
121
- BinaryenIf(primary, equalMissing(), BinaryenGlobalSet(primary, base.c_str(), BinaryenCall(primary, load.c_str(), moduleId, 1, BinaryenTypeInt32())), nullptr),
122
- BinaryenIf(primary, equalMissing(), BinaryenUnreachable(primary), nullptr),
123
- BinaryenCallIndirect(primary, table.c_str(), BinaryenBinary(primary, BinaryenAddInt32(), getBase(), BinaryenConst(primary, BinaryenLiteralInt32(ordinal))), args.data(), args.size(), params, results)
124
- };
125
- const std::string thunk = found->second;
126
- BinaryenRemoveFunction(primary, thunk.c_str());
127
- BinaryenAddFunctionWithHeapType(primary, thunk.c_str(), heapType, nullptr, 0, BinaryenBlock(primary, nullptr, body, 3, results));
128
- const std::string exported = "peach_lazy_" + std::to_string(ordinal++);
129
- BinaryenAddFunctionExport(side, name.c_str(), exported.c_str());
130
- }
131
- struct Element { std::string name, table; BinaryenExpressionRef offset; std::vector<std::string> names; };
132
- std::vector<Element> elements;
133
- for (BinaryenIndex i = 0; i < BinaryenGetNumElementSegments(primary); ++i) {
134
- auto segment = BinaryenGetElementSegmentByIndex(primary, i);
135
- Element element{BinaryenElementSegmentGetName(segment), BinaryenElementSegmentGetTable(segment), BinaryenElementSegmentGetOffset(segment), {}};
136
- for (BinaryenIndex j = 0; j < BinaryenElementSegmentGetLength(segment); ++j) {
137
- auto name = BinaryenElementSegmentGetData(segment, j);
138
- if (!name) throw std::runtime_error("lazy primary has an unsupported null element");
139
- element.names.emplace_back(name);
140
- }
141
- elements.push_back(std::move(element));
142
- }
143
- for (const auto& element : elements) BinaryenRemoveElementSegment(primary, element.name.c_str());
144
- for (const auto& element : elements) {
145
- std::vector<const char*> names;
146
- for (const auto& name : element.names) names.push_back(name.c_str());
147
- if (element.offset) BinaryenAddActiveElementSegment(primary, element.table.c_str(), element.name.c_str(), names.data(), names.size(), element.offset);
148
- else BinaryenAddPassiveElementSegment(primary, element.name.c_str(), names.data(), names.size());
149
- }
150
- write(primary, argv[1]);
151
- write(side, argv[2]);
152
- std::cout << ordinal << '\n';
153
- BinaryenModuleDispose(primary);
154
- BinaryenModuleDispose(side);
155
- return 0;
156
- } catch (const std::exception& error) {
157
- std::cerr << error.what() << '\n';
158
- return 1;
159
- }
160
- }
161
- `
162
-
163
- const installed = new Map<string, Promise<string>>()
164
-
165
- export function lazySplitTool(binaryen: string): Promise<string> {
166
- let tool = installed.get(binaryen)
167
- if (!tool) {
168
- tool = install(binaryen)
169
- installed.set(binaryen, tool)
170
- }
171
- return tool
172
- }
173
-
174
- async function install(binaryen: string): Promise<string> {
175
- const root = dirname(dirname(binaryen))
176
- const library = join(
177
- root,
178
- 'lib',
179
- process.platform === 'darwin' ? 'libbinaryen.dylib' : 'libbinaryen.a',
180
- )
181
- const identity = createHash('sha256')
182
- .update(source)
183
- .update(readFileSync(library))
184
- .digest('hex')
185
- const directory = join(root, 'lazy-split', identity)
186
- const tool = join(directory, 'split')
187
- if (existsSync(tool)) return tool
188
- mkdirSync(directory, { recursive: true })
189
- const temporary = join(directory, `${process.pid}-${Date.now()}`)
190
- writeFileSync(`${temporary}.cpp`, source)
191
- try {
192
- await promisify(execFile)(process.env.CXX ?? 'c++', [
193
- '-std=c++17',
194
- '-O2',
195
- '-pthread',
196
- `${temporary}.cpp`,
197
- '-I',
198
- join(root, 'include'),
199
- library,
200
- `-Wl,-rpath,${join(root, 'lib')}`,
201
- '-o',
202
- temporary,
203
- ])
204
- renameSync(temporary, tool)
205
- return tool
206
- } finally {
207
- rmSync(`${temporary}.cpp`, { force: true })
208
- rmSync(temporary, { force: true })
209
- }
210
- }