peachsim 0.1.2774 → 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 (141) 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 +196 -181
  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-WYOHSUVU.mjs → acorn-CTIC3GCU.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-ETJLJYIY.mjs → chunk-2YTHEKWJ.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-CRXKBBYS.mjs → chunk-3WU4YTJR.mjs} +173 -157
  29. package/dist-lib/esm-chunks/{chunk-TRALQNBC.mjs → chunk-4B46TF64.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-TJMPCXFB.mjs → chunk-C5EU2DRL.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-KGVTCLU7.mjs → chunk-CFNSLWMQ.mjs} +4 -4
  32. package/dist-lib/esm-chunks/{chunk-RC56H3GQ.mjs → chunk-E6ULRDAP.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-K7A5D6XB.mjs → chunk-ESP2U4IX.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-M45GB4YE.mjs → chunk-ESWEEZZP.mjs} +2 -2
  35. package/dist-lib/esm-chunks/{chunk-3SQGKA6Z.mjs → chunk-FBN2C43P.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-F3K2ACFM.mjs → chunk-FVUN2533.mjs} +3 -3
  37. package/dist-lib/esm-chunks/{chunk-62NI6YCH.mjs → chunk-GKKZLYBA.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-ONTQLRM4.mjs → chunk-H5TBKFDB.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-RGFBDGCR.mjs → chunk-ITTQHQD5.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-W2YKROSW.mjs → chunk-JERE5CAK.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-VR25GACU.mjs → chunk-MJSKVK7E.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-R7HK74K2.mjs → chunk-NV5NLKKN.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-MZX6AAGH.mjs → chunk-RGOPQX37.mjs} +6 -6
  44. package/dist-lib/esm-chunks/{chunk-CDZ6YIIB.mjs → chunk-S47B7YHJ.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-2JGH43VT.mjs → chunk-SK4FQLNJ.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-AEE6PLCM.mjs → chunk-TE3WHBF3.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-P5VUFHVB.mjs → chunk-W42DUKWD.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-B3GMGDAC.mjs → chunk-WB5OWF4G.mjs} +5 -5
  49. package/dist-lib/esm-chunks/{chunk-4K3ZR6YW.mjs → chunk-XMBGLLON.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-IKCQ5XQP.mjs → chunk-YRKGWASL.mjs} +6 -6
  51. package/dist-lib/esm-chunks/{metro-layout-parser-QG6UBS3S.mjs → metro-layout-parser-2RQ3WC37.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-KQJ2G4YJ.mjs → swift-package-prebuilt-L5SWVH6U.mjs} +12 -12
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-RL3LZGNU.mjs → swift-sdk-app-module-5SWDBTBY.mjs} +16 -16
  54. package/dist-lib/esm-chunks/{swift-sdk-image-L7SO7UED.mjs → swift-sdk-image-OOSMI47A.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-QYH6Z7VW.mjs → swift-sdk-image-producer-DL4VEBXN.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +196 -181
  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 +4205 -4191
  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 +2790 -2776
  95. package/dist-lib/swift-compile.cjs +192 -177
  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/react-native/AppState.d.ts +0 -1
  123. package/dist-types/packages/peach-engine/src/react-native/Keyboard.d.ts +0 -1
  124. package/dist-types/packages/peach-kit/src/ring-mode-state.d.ts +0 -1
  125. package/dist-types/packages/peach-kit/src/transitions/screen-transition-math.d.ts +0 -31
  126. package/package.json +1 -1
  127. package/src/assetCatalogContract.ts +0 -6
  128. package/src/expo-pod-prebuilt.ts +0 -63
  129. package/src/native-package-slice.ts +0 -2
  130. package/src/podfile-cocoapods.ts +0 -5
  131. package/src/runtime-assets.ts +0 -9
  132. package/src/swift-compile.ts +9 -6
  133. package/src/swift-distribution-mirror.ts +16 -5
  134. package/src/swift-guest-link.ts +0 -9
  135. package/src/swift-guest-projection.ts +1 -46
  136. package/src/swift-guest-runtime-plan.ts +4 -80
  137. package/src/swift-header-compiler.ts +24 -9
  138. package/src/swift-wasm-prune.ts +0 -5
  139. package/src/swiftRuntimeProductContract.ts +1 -0
  140. package/src/wasm-narrow-boundary.ts +0 -13
  141. package/src/wasm-lazy-split-tool.ts +0 -210
@@ -256,15 +256,6 @@ export function guestLinkInputFiles(args: readonly string[]): string[] {
256
256
  return guestLinkInputFilesWithKind(args).map((item) => item.path)
257
257
  }
258
258
 
259
- /** Actual object and archive inputs that have not been assigned to an image. */
260
- export function unownedGuestLinkInputs(
261
- plan: GuestLinkPlan,
262
- args: readonly string[],
263
- ): string[] {
264
- const owned = new Set(plan.artifacts.map((artifact) => path.resolve(artifact.path)))
265
- return guestLinkInputFiles(args).filter((file) => !owned.has(file))
266
- }
267
-
268
259
  function occurrences(plan: GuestLinkPlan, args: readonly string[]): InputOccurrence[] {
269
260
  const dirs: string[] = []
270
261
  for (let i = 0; i < args.length; i++) {
@@ -1,8 +1,4 @@
1
- import {
2
- guestLinkedSpans,
3
- guestWasmDataSegments,
4
- type GuestLinkedSpan,
5
- } from './swift-guest-linked-spans'
1
+ import { guestWasmDataSegments } from './swift-guest-linked-spans'
6
2
  import {
7
3
  isSwiftGuestImageManifest,
8
4
  type SwiftGuestImageManifest,
@@ -169,47 +165,6 @@ export function finalizeGuestImageProjection(
169
165
  return result
170
166
  }
171
167
 
172
- /** Bind manifests to the final map and optimized module, then fill their ranges. */
173
- export function finalizeLinkedGuestImages(options: {
174
- readonly map: string
175
- readonly linked: Uint8Array
176
- readonly optimized: Uint8Array
177
- readonly owners: ReadonlyMap<string, number>
178
- readonly sectionOwners: ReadonlyMap<string, number>
179
- readonly projectionObject: string
180
- readonly reserved: ReservedGuestImageProjection
181
- readonly manifests: (
182
- spans: readonly GuestLinkedSpan[],
183
- ) => readonly SwiftGuestImageManifest[]
184
- }): { readonly wasm: Uint8Array; readonly images: readonly SwiftGuestImageManifest[] } {
185
- const image = options.owners.get(options.projectionObject)
186
- if (image === undefined) throw new Error('guest projection object has no image owner')
187
- const projectionData: GuestLinkedSpan[] = []
188
- const spans = guestLinkedSpans(
189
- options.map,
190
- options.linked,
191
- options.optimized,
192
- options.owners,
193
- options.sectionOwners,
194
- false,
195
- {
196
- trackedObject: options.projectionObject,
197
- trackedObjectOwner: image,
198
- trackedLinearSpans: projectionData,
199
- },
200
- )
201
- const images = options.manifests(spans)
202
- return {
203
- images,
204
- wasm: finalizeGuestImageProjection(
205
- options.optimized,
206
- options.reserved,
207
- images,
208
- projectionData,
209
- ),
210
- }
211
- }
212
-
213
168
  // emit exact utf8 bytes; octal escapes have fixed width even before a digit.
214
169
  function cString(value: string): string {
215
170
  return `"${[...Buffer.from(value, 'utf8')]
@@ -15,6 +15,7 @@ import {
15
15
  } from './swift-wasm-prune'
16
16
  import {
17
17
  SWIFT_FRAMEWORK_PRODUCT_FILE,
18
+ SWIFT_SDK_PRODUCT_DIRECTORY,
18
19
  SWIFT_SDK_PRODUCT_FILE,
19
20
  swiftFrameworkProductSchema,
20
21
  swiftSdkProductsSchema,
@@ -28,7 +29,6 @@ import type {
28
29
  GuestLinkSelection,
29
30
  } from './swift-guest-link-plan'
30
31
 
31
- const SDK_CATALOG_DIRECTORY = 'swift.xctoolchain/usr/lib/swift_static/wasi'
32
32
  export const SDK_CONTAINING_IMAGE = 'wasi/containing-image'
33
33
 
34
34
  function canonicalArchivePath(file: string): string {
@@ -44,10 +44,10 @@ function sdkArtifactBytes(root: string, artifact: SwiftSdkProduct['artifacts'][n
44
44
  if (hash(linked) === artifact.sha256) return { source: linked, linked }
45
45
  if (
46
46
  artifact.kind !== 'archive' ||
47
- artifact.path !== `${SDK_CATALOG_DIRECTORY}/libFoundation.a`
47
+ artifact.path !== `${SWIFT_SDK_PRODUCT_DIRECTORY}/libFoundation.a`
48
48
  )
49
49
  throw new Error(`SDK product artifact changed ${file}`)
50
- const catalog = path.join(root, SDK_CATALOG_DIRECTORY, SWIFT_SDK_PRODUCT_FILE)
50
+ const catalog = path.join(root, SWIFT_SDK_PRODUCT_DIRECTORY, SWIFT_SDK_PRODUCT_FILE)
51
51
  const sourceDirectory = path.dirname(realpathSync(catalog))
52
52
  const source = readFileSync(path.join(sourceDirectory, 'libFoundation.a'))
53
53
  if (hash(source) !== artifact.sha256)
@@ -108,13 +108,7 @@ export function readGuestRuntimeCatalogs(
108
108
  )
109
109
  const sdk = v.parse(
110
110
  swiftSdkProductsSchema,
111
- read(
112
- path.join(
113
- sdkRoot,
114
- 'swift.xctoolchain/usr/lib/swift_static/wasi',
115
- SWIFT_SDK_PRODUCT_FILE,
116
- ),
117
- ),
111
+ read(path.join(sdkRoot, SWIFT_SDK_PRODUCT_DIRECTORY, SWIFT_SDK_PRODUCT_FILE)),
118
112
  )
119
113
  const distribution = v.parse(
120
114
  swiftSdkProductsSchema,
@@ -798,73 +792,3 @@ export function guestCxxMemberOwners(
798
792
  return { origin: match.original, image: owner.image, sha256: match.sha256 }
799
793
  })
800
794
  }
801
-
802
- /** Own runtime archives and unpacked SDK members actually supplied to the link. */
803
- export function guestCxxLinkArtifacts(
804
- sdk: SwiftPrunedSdkInputs,
805
- linkedArchives: readonly string[],
806
- products: GuestCxxProducts,
807
- ): GuestLinkArtifact[] {
808
- const runtimeArchives = new Set(
809
- [products.libcxx, products.libcxxabi, products.unwind].map((product) =>
810
- path.resolve(product.archive),
811
- ),
812
- )
813
- const objects = [...sdk.objectOrigins.values()].filter((origin) =>
814
- runtimeArchives.has(path.resolve(origin.archive)),
815
- )
816
- const archives = linkedArchives.filter((archive) =>
817
- runtimeArchives.has(path.resolve(archive)),
818
- )
819
- const origins: SwiftSdkObjectOrigin[] = [...objects]
820
- for (const archive of archives) {
821
- const members = readArMembers(readFileSync(archive))
822
- const names = new Set<string>()
823
- for (const member of members) {
824
- if (names.has(member.name)) throw new Error(`ambiguous runtime archive ${archive}`)
825
- names.add(member.name)
826
- origins.push({ archive, member: member.name, ordinal: 1 })
827
- }
828
- }
829
- const owners = guestCxxMemberOwners(origins, products)
830
- const byOrigin = new Map(
831
- owners.map(({ origin, image }) => [
832
- JSON.stringify([path.resolve(origin.archive), origin.member, origin.ordinal]),
833
- image,
834
- ]),
835
- )
836
- const imageOf = (origin: SwiftSdkObjectOrigin) => {
837
- const image = byOrigin.get(
838
- JSON.stringify([path.resolve(origin.archive), origin.member, origin.ordinal]),
839
- )
840
- if (image === undefined) throw new Error(`unowned runtime object ${origin.member}`)
841
- return image
842
- }
843
- return [
844
- ...objects.map(
845
- (origin) =>
846
- ({
847
- path: origin.original,
848
- kind: 'object',
849
- image: imageOf(origin),
850
- instrumentDynamicLookups: false,
851
- }) satisfies GuestLinkArtifact,
852
- ),
853
- ...archives.map(
854
- (archive) =>
855
- ({
856
- path: archive,
857
- kind: 'archive',
858
- image: null,
859
- memberImages: new Map(
860
- owners
861
- .filter(
862
- ({ origin }) => path.resolve(origin.archive) === path.resolve(archive),
863
- )
864
- .map(({ origin, image }) => [origin.member, image]),
865
- ),
866
- instrumentDynamicLookups: false,
867
- }) satisfies GuestLinkArtifact,
868
- ),
869
- ]
870
- }
@@ -64,19 +64,34 @@ function compilerCheckpoint(
64
64
  }
65
65
  const outputMap = value('-output-file-map')
66
66
  const module = value('-emit-module-path')
67
- if (!outputMap || !module || !args.includes('-whole-module-optimization')) return
67
+ const wholeModule =
68
+ args.lastIndexOf('-whole-module-optimization') >
69
+ args.lastIndexOf('-no-whole-module-optimization')
70
+ const batch = args.includes('-enable-batch-mode') && !args.includes('-incremental')
71
+ if (!outputMap || !module || (!wholeModule && !batch)) return
68
72
  const mapText = readFileSync(outputMap, 'utf8')
69
73
  const map: unknown = JSON.parse(mapText)
70
- if (!isRecord(map) || !isRecord(map['']) || typeof map[''].dependencies !== 'string')
71
- return
72
- const objects: string[] = []
73
- for (const [source, outputs] of Object.entries(map)) {
74
+ if (!isRecord(map)) return
75
+ const outputs = [module, header]
76
+ if (wholeModule) {
77
+ if (!isRecord(map['']) || typeof map[''].dependencies !== 'string') return
78
+ outputs.push(map[''].dependencies)
79
+ }
80
+ let objects = 0
81
+ for (const [source, fileOutputs] of Object.entries(map)) {
74
82
  if (!source) continue
75
- if (!isRecord(outputs) || typeof outputs.object !== 'string') return
76
- objects.push(outputs.object)
83
+ if (!isRecord(fileOutputs) || typeof fileOutputs.object !== 'string') return
84
+ objects++
85
+ const object = fileOutputs.object
86
+ outputs.push(object)
87
+ if (!wholeModule) {
88
+ const dependencies = fileOutputs.dependencies
89
+ if (typeof dependencies === 'string') outputs.push(dependencies)
90
+ else if (object.endsWith('.o')) outputs.push(`${object.slice(0, -2)}.d`)
91
+ else return
92
+ }
77
93
  }
78
- if (!objects.length) return
79
- const outputs = [module, header, map[''].dependencies, ...objects]
94
+ if (objects === 0) return
80
95
  const digest = createHash('sha256')
81
96
  .update(recipe)
82
97
  .update(JSON.stringify(args))
@@ -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(
@@ -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
- }