peachsim 0.1.1880 → 0.1.1886

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/cli/commands/control.ts +11 -10
  2. package/cli/commands/reset.ts +1 -1
  3. package/cli/outbound-endpoints.ts +1 -1
  4. package/detox/index.ts +62 -1
  5. package/dist-lib/agent-daemon-client.cjs +1 -1
  6. package/dist-lib/agent-events.cjs +1 -1
  7. package/dist-lib/attached-projects.cjs +1 -1
  8. package/dist-lib/auth/shared-session.cjs +1 -1
  9. package/dist-lib/backend-origin.cjs +1 -1
  10. package/dist-lib/beta.cjs +1 -1
  11. package/dist-lib/beta.mjs +1 -1
  12. package/dist-lib/bridge-constants.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.mjs +1 -1
  15. package/dist-lib/bridge-contract.cjs +1 -1
  16. package/dist-lib/bridge-contract.mjs +1 -1
  17. package/dist-lib/bundle-channel.cjs +8980 -4279
  18. package/dist-lib/capture-contract.cjs +1 -1
  19. package/dist-lib/capture-contract.mjs +1 -1
  20. package/dist-lib/cloud-contract.cjs +1 -1
  21. package/dist-lib/cloud-contract.mjs +1 -1
  22. package/dist-lib/cloud-test-args.cjs +1 -1
  23. package/dist-lib/cloud-test-args.mjs +1 -1
  24. package/dist-lib/cloud.cjs +1 -1
  25. package/dist-lib/cloud.mjs +1 -1
  26. package/dist-lib/config.cjs +1 -1
  27. package/dist-lib/config.mjs +1 -1
  28. package/dist-lib/detox/index.cjs +35 -2
  29. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  30. package/dist-lib/expo-swift-bundle.cjs +8500 -3912
  31. package/dist-lib/expo-swift-metadata.cjs +5 -1
  32. package/dist-lib/expo-swift-metadata.mjs +5 -1
  33. package/dist-lib/home-paths.cjs +1 -1
  34. package/dist-lib/host/bridge-host.cjs +9744 -5071
  35. package/dist-lib/host/fetch-proxy-handler.cjs +93 -13
  36. package/dist-lib/host/fetch-proxy-overrides.cjs +10 -2
  37. package/dist-lib/host/fetch-proxy-overrides.mjs +8 -2
  38. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  39. package/dist-lib/host/websocket-proxy.cjs +1 -1
  40. package/dist-lib/index.cjs +525 -120
  41. package/dist-lib/jump-to-source-babel.cjs +1 -1
  42. package/dist-lib/jump-to-source-native.cjs +1 -1
  43. package/dist-lib/kotlin-host.cjs +1 -1
  44. package/dist-lib/menu.cjs +1 -1
  45. package/dist-lib/menu.mjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  48. package/dist-lib/metro-production-bundle.cjs +1 -1
  49. package/dist-lib/metro-production-bundle.mjs +1 -1
  50. package/dist-lib/metro.cjs +523 -118
  51. package/dist-lib/native-app-identity-project.cjs +395 -72
  52. package/dist-lib/native-app-identity-project.mjs +723 -375
  53. package/dist-lib/native-app-identity.cjs +37 -1
  54. package/dist-lib/native-app-identity.mjs +36 -1
  55. package/dist-lib/native-firebase-metadata.cjs +1 -1
  56. package/dist-lib/native-firebase-metadata.mjs +1 -1
  57. package/dist-lib/pdfium-raster.cjs +1 -1
  58. package/dist-lib/pdfium-raster.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +1 -1
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/public-origins-lib-esm.json +58 -28
  64. package/dist-lib/public-origins-lib.json +233 -92
  65. package/dist-lib/react-native-host-modules.cjs +1 -1
  66. package/dist-lib/react-native-host-modules.mjs +1 -1
  67. package/dist-lib/reap-browser.cjs +1 -1
  68. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  69. package/dist-lib/sdk.cjs +1 -1
  70. package/dist-lib/sdk.mjs +1 -1
  71. package/dist-lib/skills.cjs +30639 -25833
  72. package/dist-lib/swift-compile.cjs +6823 -2525
  73. package/dist-lib/swift-compile.mjs +6809 -2509
  74. package/dist-lib/swift-package.cjs +20 -3
  75. package/dist-lib/swift-package.mjs +20 -3
  76. package/dist-lib/swift-submit.cjs +2 -2
  77. package/dist-lib/swift-submit.mjs +2 -2
  78. package/dist-lib/swift-toolchain.cjs +19 -1
  79. package/dist-lib/swift.cjs +1 -1
  80. package/dist-lib/vite-swift.cjs +8704 -4124
  81. package/dist-lib/vite.cjs +93 -13
  82. package/dist-lib/worklet-executable.cjs +1 -1
  83. package/dist-lib/worklet-executable.mjs +1 -1
  84. package/dist-types/packages/peach-engine/src/engine/canvaskit-api.d.ts +1 -1
  85. package/dist-types/packages/peach-engine/src/engine/fontDataContract.d.ts +2 -0
  86. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  87. package/dist-types/packages/peach-engine/src/render-worker/native-ui-protocol.d.ts +1 -0
  88. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +11 -1
  89. package/dist-types/packages/peach-engine/src/render-worker/shell-tree-wire.d.ts +2 -1
  90. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  91. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +10 -1
  92. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  93. package/dist-types/packages/peach-kit/src/ui/popover-placement.d.ts +1 -1
  94. package/dist-types/packages/sootsim-swift/src/securityHostContract.d.ts +10 -0
  95. package/package.json +1 -1
  96. package/runtime-companion.json +1 -1
  97. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHost.h +555 -0
  98. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +1 -0
  99. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes +6 -0
  100. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSURLProtocol.h +0 -1
  101. package/sdk/ios/System/Library/Frameworks/QuartzCore.framework/Modules/module.modulemap +6 -0
  102. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarButtonItemBadge.h +1 -1
  103. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarMinimization.h +1 -1
  104. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIScrollView.h +1 -1
  105. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UISearchTab.h +1 -1
  106. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITab.h +1 -1
  107. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITabAccessory.h +2 -2
  108. package/sdk/ios/usr/include/os/activity.h +534 -0
  109. package/sdk/ios/usr/include/os.modulemap +15 -0
  110. package/sdk/ios/wasm/include/fcntl.h +16 -0
  111. package/sdk/ios/wasm/include/string.h +5 -0
  112. package/sdk/native-hashes.json +1 -1
  113. package/src/dns-over-https.ts +61 -9
  114. package/src/expo-swift-host.ts +11 -3
  115. package/src/host/fetch-proxy-handler.ts +51 -2
  116. package/src/host/fetch-proxy-overrides.ts +4 -0
  117. package/src/host/hostname-resolver.ts +9 -5
  118. package/src/native-app-identity-project.ts +13 -2
  119. package/src/native-app-identity.ts +47 -0
  120. package/src/nitro-adapter.lock.json +260 -260
  121. package/src/nitro-superset.lock.json +4 -4
  122. package/src/storageSnapshotContract.ts +20 -1
  123. package/src/swift-compile.ts +534 -136
  124. package/src/swift-compiler-digest.ts +15 -0
  125. package/src/swift-coverage/xcode-packages.ts +3 -2
  126. package/src/swift-distribution.lock.json +12 -12
  127. package/src/swift-guest-archive.ts +153 -0
  128. package/src/swift-guest-compile.ts +449 -0
  129. package/src/swift-guest-image-ledger.ts +656 -0
  130. package/src/swift-guest-link-plan.ts +52 -0
  131. package/src/swift-guest-link.ts +1414 -0
  132. package/src/swift-guest-linked-spans.ts +338 -0
  133. package/src/swift-guest-manifest.ts +141 -0
  134. package/src/swift-guest-projection-storage.ts +310 -0
  135. package/src/swift-guest-projection.ts +252 -0
  136. package/src/swift-guest-runtime-plan.ts +834 -0
  137. package/src/swift-guest-source-inputs.ts +427 -0
  138. package/src/swift-guest-source-plan.ts +279 -0
  139. package/src/swift-host.ts +125 -17
  140. package/src/swift-link-roots.ts +27 -50
  141. package/src/swift-package-manifest.ts +34 -18
  142. package/src/swift-package.ts +32 -2
  143. package/src/swift-packages.ts +138 -17
  144. package/src/swift-runtime-products.ts +73 -0
  145. package/src/swift-shared-sdk.ts +1 -1
  146. package/src/swift-submit.ts +13 -3
  147. package/src/swift-toolchain.ts +18 -0
  148. package/src/swift-wasm-prune.ts +313 -14
  149. package/src/swiftContract.ts +83 -0
  150. package/src/swiftRuntimeProductContract.ts +85 -45
  151. package/src/turbo-runtime.lock.json +23 -23
  152. package/src/turbo-source.ts +4 -1
  153. package/src/wasm-optimize.ts +16 -4
  154. package/src/xcode-project.ts +142 -14
@@ -0,0 +1,656 @@
1
+ // link-time guest image identity for source-built applications. the caller
2
+ // supplies graph-derived scopes; global image order is not an RTLD_NEXT scope.
3
+
4
+ export interface GuestImageObject {
5
+ readonly path: string
6
+ readonly bytes: Uint8Array
7
+ readonly instrumentDynamicLookups: boolean
8
+ }
9
+
10
+ export interface GuestImage {
11
+ readonly id: number
12
+ readonly name: string
13
+ readonly dependencies: readonly number[]
14
+ readonly objects: readonly GuestImageObject[]
15
+ }
16
+
17
+ export interface GuestCallerScope {
18
+ readonly image: number
19
+ readonly next: readonly number[]
20
+ }
21
+
22
+ export interface GuestImageLedgerInput {
23
+ readonly images: readonly GuestImage[]
24
+ readonly callers: readonly GuestCallerScope[]
25
+ readonly symbols: readonly string[]
26
+ /** Definitions the discovery link kept. The dyld symbol table lists only these, so it never keeps a definition alive. */
27
+ readonly liveSymbols: ReadonlySet<string>
28
+ /** Symbols the linker command line names, which must stay defined under their own name. */
29
+ readonly commandLineSymbols?: readonly string[]
30
+ readonly directBindings?: readonly {
31
+ object: string
32
+ symbol: string
33
+ providerObject: string
34
+ providerImage: number
35
+ }[]
36
+ }
37
+
38
+ export interface GuestImageDefinition {
39
+ readonly name: string
40
+ readonly image: number
41
+ readonly object: string
42
+ readonly alias: string
43
+ readonly kind: 'function' | 'data'
44
+ readonly weak: boolean
45
+ readonly parameters: readonly string[]
46
+ readonly result: string
47
+ }
48
+
49
+ export interface GuestImageLedger {
50
+ readonly images: readonly GuestImage[]
51
+ readonly callers: readonly GuestCallerScope[]
52
+ readonly definitions: readonly GuestImageDefinition[]
53
+ readonly objects: readonly GuestImageObject[]
54
+ readonly callerWrappers: readonly { symbol: string; image: number }[]
55
+ readonly llvmIR: string
56
+ }
57
+
58
+ function readNumber(bytes: Uint8Array, position: number): [number, number] {
59
+ let value = 0
60
+ let shift = 0
61
+ for (;;) {
62
+ if (position >= bytes.length || shift > 28) throw new Error('invalid wasm integer')
63
+ const byte = bytes[position++]!
64
+ value += (byte & 127) * 2 ** shift
65
+ if (!(byte & 128)) return [value, position]
66
+ shift += 7
67
+ }
68
+ }
69
+
70
+ function encodeNumber(value: number): Buffer {
71
+ const bytes: number[] = []
72
+ do {
73
+ let byte = value % 128
74
+ value = Math.floor(value / 128)
75
+ if (value) byte |= 128
76
+ bytes.push(byte)
77
+ } while (value)
78
+ return Buffer.from(bytes)
79
+ }
80
+
81
+ function readString(bytes: Uint8Array, position: number): [string, number] {
82
+ const [length, start] = readNumber(bytes, position)
83
+ if (start + length > bytes.length) throw new Error('invalid wasm string')
84
+ return [
85
+ Buffer.from(bytes.subarray(start, start + length)).toString('utf8'),
86
+ start + length,
87
+ ]
88
+ }
89
+
90
+ function encodedString(value: string): Buffer {
91
+ const bytes = Buffer.from(value)
92
+ return Buffer.concat([encodeNumber(bytes.length), bytes])
93
+ }
94
+
95
+ interface FunctionType {
96
+ readonly parameters: readonly number[]
97
+ readonly results: readonly number[]
98
+ }
99
+
100
+ interface ObjectDefinition {
101
+ readonly name: string
102
+ readonly kind: 'function' | 'data'
103
+ readonly weak: boolean
104
+ readonly type?: FunctionType
105
+ }
106
+
107
+ function llvmType(value: number): string {
108
+ switch (value) {
109
+ case 0x7f:
110
+ return 'i32'
111
+ case 0x7e:
112
+ return 'i64'
113
+ case 0x7d:
114
+ return 'float'
115
+ case 0x7c:
116
+ return 'double'
117
+ default:
118
+ throw new Error(`unsupported wasm function value type ${value}`)
119
+ }
120
+ }
121
+
122
+ const OBJC_INIT_RECORD = '.objc_init'
123
+
124
+ // change definition names in the linking symbol table, preserving symbol
125
+ // indices and relocations. no app or dependency source bodies are changed.
126
+ function rewriteObject(
127
+ bytes: Uint8Array,
128
+ names: ReadonlyMap<string, string>,
129
+ callerAlias: string,
130
+ bindings: ReadonlyMap<string, string>,
131
+ instrumentDynamicLookups: boolean,
132
+ preserveCanonical: ReadonlySet<string>,
133
+ ): {
134
+ readonly bytes: Uint8Array
135
+ readonly definitions: readonly ObjectDefinition[]
136
+ readonly usesDlsym: boolean
137
+ readonly usedSymbols: readonly string[]
138
+ } {
139
+ if (Buffer.from(bytes.subarray(0, 8)).toString('hex') !== '0061736d01000000')
140
+ throw new Error('expected wasm object')
141
+ const sections: Buffer[] = [Buffer.from(bytes.subarray(0, 8))]
142
+ const types: FunctionType[] = []
143
+ const functionTypes: number[] = []
144
+ const definitions: ObjectDefinition[] = []
145
+ let usesDlsym = false
146
+ let usesDlerror = false
147
+ const usedSymbols = new Set<string>()
148
+ let position = 8
149
+ while (position < bytes.length) {
150
+ const id = bytes[position++]!
151
+ const [size, start] = readNumber(bytes, position)
152
+ const end = start + size
153
+ if (end > bytes.length) throw new Error('invalid wasm section')
154
+ let section = Buffer.from(bytes.subarray(start, end))
155
+ position = end
156
+ let offset = 0
157
+ const number = (): number => {
158
+ const [value, next] = readNumber(section, offset)
159
+ offset = next
160
+ return value
161
+ }
162
+ const string = (): string => {
163
+ const [value, next] = readString(section, offset)
164
+ offset = next
165
+ return value
166
+ }
167
+ if (id === 1) {
168
+ const count = number()
169
+ for (let i = 0; i < count; i++) {
170
+ if (section[offset++] !== 0x60) throw new Error('unsupported wasm type')
171
+ const parameterCount = number()
172
+ const parameters = [...section.subarray(offset, offset + parameterCount)]
173
+ if (parameterCount !== parameters.length) throw new Error('invalid wasm type')
174
+ offset += parameterCount
175
+ const resultCount = number()
176
+ const results = [...section.subarray(offset, offset + resultCount)]
177
+ if (results.length !== resultCount) throw new Error('invalid wasm type')
178
+ offset += resultCount
179
+ types.push({ parameters, results })
180
+ }
181
+ } else if (id === 2) {
182
+ const count = number()
183
+ const imports: Buffer[] = [encodeNumber(count)]
184
+ for (let i = 0; i < count; i++) {
185
+ const module = string()
186
+ const name = string()
187
+ const kind = section[offset++]!
188
+ const typeStart = offset
189
+ let functionType = -1
190
+ if (kind === 0) {
191
+ functionType = number()
192
+ functionTypes.push(functionType)
193
+ } else if (kind === 1) {
194
+ const referenceType = section[offset++]
195
+ if (referenceType !== 0x70 && referenceType !== 0x6f)
196
+ throw new Error('unsupported table type')
197
+ const flags = number()
198
+ if (flags & ~3) throw new Error('unsupported table limits')
199
+ number()
200
+ if (flags & 1) number()
201
+ } else if (kind === 2) {
202
+ const flags = number()
203
+ if (flags & ~3) throw new Error('unsupported memory limits')
204
+ number()
205
+ if (flags & 1) number()
206
+ } else if (kind === 3) offset += 2
207
+ else if (kind === 4) {
208
+ number()
209
+ number()
210
+ } else throw new Error('unsupported wasm import')
211
+ const isDlsym =
212
+ instrumentDynamicLookups && module === 'env' && name === 'dlsym' && kind === 0
213
+ const isDlerror =
214
+ instrumentDynamicLookups && module === 'env' && name === 'dlerror' && kind === 0
215
+ if (module === 'env' && names.has(name)) usedSymbols.add(name)
216
+ if (isDlsym || isDlerror) {
217
+ const type = types[functionType]
218
+ const expected = isDlsym ? '127,127:127' : ':127'
219
+ if (
220
+ !type ||
221
+ `${type.parameters.join(',')}:${type.results.join(',')}` !== expected
222
+ )
223
+ throw new Error(`unexpected ${name} import type`)
224
+ }
225
+ if (isDlsym) usesDlsym = true
226
+ if (isDlerror) usesDlerror = true
227
+ imports.push(
228
+ encodedString(module),
229
+ encodedString(
230
+ isDlsym
231
+ ? callerAlias
232
+ : isDlerror
233
+ ? '__peach_dlerror'
234
+ : module === 'env' && name !== 'dlsym' && name !== 'dlerror'
235
+ ? (bindings.get(name) ?? name)
236
+ : name,
237
+ ),
238
+ Buffer.from([kind]),
239
+ section.subarray(typeStart, offset),
240
+ )
241
+ }
242
+ if (offset !== section.length) throw new Error('invalid wasm import section')
243
+ section = Buffer.concat(imports)
244
+ } else if (id === 3) {
245
+ const count = number()
246
+ for (let i = 0; i < count; i++) functionTypes.push(number())
247
+ } else if (id === 0) {
248
+ const sectionName = string()
249
+ if (sectionName === 'linking') {
250
+ const version = number()
251
+ if (version !== 2) throw new Error('unsupported wasm linking version')
252
+ const parts: Buffer[] = [encodedString(sectionName), encodeNumber(version)]
253
+ while (offset < section.length) {
254
+ const kind = section[offset++]!
255
+ const length = number()
256
+ const stop = offset + length
257
+ if (stop > section.length) throw new Error('invalid linking subsection')
258
+ let content = section.subarray(offset, stop)
259
+ if (kind === 7) {
260
+ // a comdat group dedupes within an image as in a static link and
261
+ // never across images, whose copies bind through separate aliases.
262
+ // the Objective-C init record is the exception: the module has one
263
+ // runtime and its record spans every image's class section, so a record
264
+ // per image would register each class once per image, where one shared
265
+ // record makes every constructor after the first return early.
266
+ const groups: Buffer[] = []
267
+ const count = number()
268
+ groups.push(encodeNumber(count))
269
+ for (let i = 0; i < count; i++) {
270
+ const group = string()
271
+ const begin = offset
272
+ number()
273
+ const members = number()
274
+ for (let member = 0; member < members * 2; member++) number()
275
+ groups.push(
276
+ encodedString(
277
+ group === OBJC_INIT_RECORD ? group : `${callerAlias}:${group}`,
278
+ ),
279
+ section.subarray(begin, offset),
280
+ )
281
+ }
282
+ if (offset !== stop) throw new Error('invalid comdat subsection')
283
+ content = Buffer.concat(groups)
284
+ }
285
+ if (kind === 8) {
286
+ const entries: Buffer[] = []
287
+ const extraEntries: Buffer[] = []
288
+ const count = number()
289
+ entries.push(encodeNumber(count))
290
+ let added = 0
291
+ for (let i = 0; i < count; i++) {
292
+ const begin = offset
293
+ const symbolKind = section[offset++]!
294
+ const flags = number()
295
+ const flagsEnd = offset
296
+ let index = -1
297
+ let name = ''
298
+ let nameStart = -1
299
+ let nameEnd = -1
300
+ if (
301
+ symbolKind === 0 ||
302
+ symbolKind === 2 ||
303
+ symbolKind === 4 ||
304
+ symbolKind === 5
305
+ ) {
306
+ index = number()
307
+ if (!(flags & 16) || flags & 64) {
308
+ nameStart = offset
309
+ name = string()
310
+ nameEnd = offset
311
+ }
312
+ } else if (symbolKind === 1) {
313
+ nameStart = offset
314
+ name = string()
315
+ nameEnd = offset
316
+ if (!(flags & 16)) {
317
+ if ((flags & 3) !== 3) {
318
+ number()
319
+ number()
320
+ }
321
+ number()
322
+ if ((flags & 3) === 3) offset++
323
+ }
324
+ } else if (symbolKind === 3) number()
325
+ else throw new Error('unsupported wasm symbol kind')
326
+ const alias = names.get(name)
327
+ // an undefined data symbol has no wasm import, only this linking entry.
328
+ if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name)
329
+ if (
330
+ ((name === 'dlsym' && usesDlsym) ||
331
+ (name === 'dlerror' && usesDlerror)) &&
332
+ flags & 16 &&
333
+ flags & 64 &&
334
+ symbolKind === 0
335
+ ) {
336
+ entries.push(
337
+ section.subarray(begin, nameStart),
338
+ encodedString(name === 'dlsym' ? callerAlias : '__peach_dlerror'),
339
+ section.subarray(nameEnd, offset),
340
+ )
341
+ } else if (
342
+ flags & 16 &&
343
+ name !== 'dlsym' &&
344
+ name !== 'dlerror' &&
345
+ bindings.has(name)
346
+ ) {
347
+ entries.push(
348
+ section.subarray(begin, nameStart),
349
+ encodedString(bindings.get(name)!),
350
+ section.subarray(nameEnd, offset),
351
+ )
352
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
353
+ if (symbolKind !== 0 && symbolKind !== 1)
354
+ throw new Error(`unsupported symbol ${name}`)
355
+ const type = symbolKind === 0 ? types[functionTypes[index]!] : undefined
356
+ if (symbolKind === 0 && !type) throw new Error(`missing type for ${name}`)
357
+ definitions.push({
358
+ name,
359
+ kind: symbolKind === 0 ? 'function' : 'data',
360
+ weak: (flags & 3) === 1,
361
+ type,
362
+ })
363
+ if (preserveCanonical.has(name)) {
364
+ entries.push(section.subarray(begin, offset))
365
+ // the canonical symbol keeps the export; its alias only names the table slot.
366
+ extraEntries.push(
367
+ section.subarray(begin, begin + 1),
368
+ encodeNumber(flags & ~0x20),
369
+ section.subarray(flagsEnd, nameStart),
370
+ encodedString(alias),
371
+ section.subarray(nameEnd, offset),
372
+ )
373
+ added++
374
+ } else {
375
+ entries.push(
376
+ section.subarray(begin, nameStart),
377
+ encodedString(alias),
378
+ section.subarray(nameEnd, offset),
379
+ )
380
+ }
381
+ } else entries.push(section.subarray(begin, offset))
382
+ }
383
+ if (offset !== stop) throw new Error('invalid symbol subsection')
384
+ entries[0] = encodeNumber(count + added)
385
+ content = Buffer.concat([...entries, ...extraEntries])
386
+ }
387
+ offset = stop
388
+ parts.push(Buffer.from([kind]), encodeNumber(content.length), content)
389
+ }
390
+ section = Buffer.concat(parts)
391
+ }
392
+ }
393
+ sections.push(Buffer.from([id]), encodeNumber(section.length), section)
394
+ }
395
+ return {
396
+ bytes: Buffer.concat(sections),
397
+ definitions,
398
+ usesDlsym,
399
+ usedSymbols: [...usedSymbols],
400
+ }
401
+ }
402
+
403
+ export function createGuestImageLedger(input: GuestImageLedgerInput): GuestImageLedger {
404
+ const imageIds = new Set(input.images.map((image) => image.id))
405
+ if (imageIds.size !== input.images.length) throw new Error('duplicate guest image id')
406
+ for (const id of imageIds)
407
+ if (!Number.isInteger(id) || id < 0 || id > 0xffffffff)
408
+ throw new Error(`invalid guest image id ${id}`)
409
+ if (new Set(input.symbols).size !== input.symbols.length)
410
+ throw new Error('duplicate requested symbol')
411
+ if (input.symbols.some((name) => !name || name.includes('\0')))
412
+ throw new Error('invalid symbol name')
413
+ if (new Set(input.callers.map((caller) => caller.image)).size !== input.callers.length)
414
+ throw new Error('duplicate caller scope')
415
+ for (const image of input.images)
416
+ for (const dependency of image.dependencies)
417
+ if (!imageIds.has(dependency)) throw new Error(`unknown dependency ${dependency}`)
418
+ for (const caller of input.callers) {
419
+ if (!imageIds.has(caller.image)) throw new Error(`unknown caller ${caller.image}`)
420
+ for (const image of caller.next)
421
+ if (!imageIds.has(image)) throw new Error(`unknown scope image ${image}`)
422
+ }
423
+ for (const image of input.images)
424
+ if (!input.callers.some((caller) => caller.image === image.id))
425
+ throw new Error(`missing scope for image ${image.id}`)
426
+ const definitions: GuestImageDefinition[] = []
427
+ const units: {
428
+ image: number
429
+ object: GuestImageObject
430
+ aliases: Map<string, string>
431
+ usedSymbols: readonly string[]
432
+ }[] = []
433
+ const callersUsingDlsym = new Set<number>()
434
+ for (const image of input.images) {
435
+ // one alias per image and name: weak or comdat copies in sibling objects
436
+ // of an image dedupe in the linker exactly as in a static link.
437
+ const aliases = new Map(
438
+ input.symbols
439
+ .map((name, index): [string, string] => [
440
+ name,
441
+ `__peach_image_${image.id}_symbol_${index}`,
442
+ ])
443
+ .filter(([name]) => name !== OBJC_INIT_RECORD),
444
+ )
445
+ for (const object of image.objects) {
446
+ const rewritten = rewriteObject(
447
+ object.bytes,
448
+ aliases,
449
+ `__peach_dlsym_caller_${image.id}`,
450
+ new Map(),
451
+ object.instrumentDynamicLookups,
452
+ new Set(),
453
+ )
454
+ if (rewritten.usesDlsym) callersUsingDlsym.add(image.id)
455
+ units.push({ image: image.id, object, aliases, usedSymbols: rewritten.usedSymbols })
456
+ for (const symbol of rewritten.definitions) {
457
+ if (symbol.type && symbol.type.results.length > 1)
458
+ throw new Error(`multiple results for ${symbol.name}`)
459
+ definitions.push({
460
+ name: symbol.name,
461
+ image: image.id,
462
+ object: object.path,
463
+ alias: aliases.get(symbol.name)!,
464
+ kind: symbol.kind,
465
+ weak: symbol.weak,
466
+ parameters: symbol.type?.parameters.map(llvmType) ?? [],
467
+ result: symbol.type?.results.length
468
+ ? llvmType(symbol.type.results[0]!)
469
+ : 'void',
470
+ })
471
+ }
472
+ }
473
+ }
474
+ definitions.sort(
475
+ (a, b) =>
476
+ Buffer.compare(Buffer.from(a.name), Buffer.from(b.name)) || a.image - b.image,
477
+ )
478
+ const preserveCanonical = new Set<string>()
479
+ const definitionsByName = Map.groupBy(definitions, (definition) => definition.name)
480
+ for (const name of input.symbols) {
481
+ const matching = definitionsByName.get(name) ?? []
482
+ if (
483
+ new Set(matching.map((definition) => definition.image)).size < 2 ||
484
+ !matching.some((definition) => definition.weak)
485
+ )
486
+ continue
487
+ const weak = matching.filter((definition) => definition.weak)
488
+ const strong = matching.filter((definition) => !definition.weak)
489
+ // every other name is odr-equivalent across images, so the first definition in the caller's lookup order binds.
490
+ if (name !== '__cxa_throw') continue
491
+ // the measured iOS throw path lets the runtime's strong definition win;
492
+ // aliases keep both implementations addressable for scoped lookup.
493
+ if (weak.length !== 1 || strong.length !== 1)
494
+ throw new Error(`unsupported weak interposition for ${name}`)
495
+ const [local] = weak
496
+ const [runtime] = strong
497
+ if (
498
+ local!.kind !== 'function' ||
499
+ runtime!.kind !== 'function' ||
500
+ local!.result !== runtime!.result ||
501
+ local!.parameters.join(',') !== runtime!.parameters.join(',')
502
+ )
503
+ throw new Error(`incompatible weak interposition for ${name}`)
504
+ for (const caller of input.callers) {
505
+ const uses =
506
+ caller.image === local!.image ||
507
+ units.some(
508
+ (unit) => unit.image === caller.image && unit.usedSymbols.includes(name),
509
+ )
510
+ if (
511
+ uses &&
512
+ caller.image !== runtime!.image &&
513
+ !caller.next.includes(runtime!.image)
514
+ )
515
+ throw new Error(`weak interposition scope excludes runtime for ${name}`)
516
+ }
517
+ preserveCanonical.add(name)
518
+ }
519
+ // the loader runtime calls the platform lookup entry points it implements
520
+ // under their own names, so they bind no image alias.
521
+ for (const name of ['dlsym', 'dlerror', '__peach_dlsym_from_image'])
522
+ preserveCanonical.add(name)
523
+ for (const name of input.commandLineSymbols ?? []) preserveCanonical.add(name)
524
+ const bindingsByImage = new Map<number, Map<string, string>>()
525
+ for (const caller of input.callers) {
526
+ const bindings = new Map<string, string>()
527
+ const seen = new Map<string, GuestImageDefinition>()
528
+ for (const image of [caller.image, ...caller.next])
529
+ for (const definition of definitions) {
530
+ if (definition.image !== image) continue
531
+ const previous = seen.get(definition.name)
532
+ // the linker already accepted the image, so duplicate definitions inside
533
+ // it resolve as in a static link: the first binds and a strong one beats a weak one.
534
+ if (previous?.image === definition.image) {
535
+ if (previous.weak && !definition.weak) {
536
+ seen.set(definition.name, definition)
537
+ if (!preserveCanonical.has(definition.name))
538
+ bindings.set(definition.name, definition.alias)
539
+ }
540
+ continue
541
+ }
542
+ if (!previous) {
543
+ seen.set(definition.name, definition)
544
+ if (!preserveCanonical.has(definition.name))
545
+ bindings.set(definition.name, definition.alias)
546
+ }
547
+ }
548
+ bindingsByImage.set(caller.image, bindings)
549
+ }
550
+ const startup = new Map<string, Map<string, string>>()
551
+ for (const binding of input.directBindings ?? []) {
552
+ const unit = units.find(({ object }) => object.path === binding.object)
553
+ const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
554
+ (definition) =>
555
+ definition.object === binding.providerObject &&
556
+ definition.image === binding.providerImage,
557
+ )
558
+ if (!unit || !unit.usedSymbols.includes(binding.symbol) || matches.length !== 1)
559
+ throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`)
560
+ const bindings = startup.get(binding.object) ?? new Map<string, string>()
561
+ if (bindings.has(binding.symbol))
562
+ throw new Error(`duplicate startup binding ${binding.symbol}`)
563
+ bindings.set(binding.symbol, matches[0]!.alias)
564
+ startup.set(binding.object, bindings)
565
+ }
566
+ const objects = units.map(({ image, object, aliases }) => {
567
+ const bindings = new Map(bindingsByImage.get(image)!)
568
+ for (const [name, alias] of startup.get(object.path) ?? []) bindings.set(name, alias)
569
+ return {
570
+ path: object.path,
571
+ instrumentDynamicLookups: object.instrumentDynamicLookups,
572
+ bytes: rewriteObject(
573
+ object.bytes,
574
+ aliases,
575
+ `__peach_dlsym_caller_${image}`,
576
+ bindings,
577
+ object.instrumentDynamicLookups,
578
+ preserveCanonical,
579
+ ).bytes,
580
+ }
581
+ })
582
+ const exported = new Map<string, GuestImageDefinition>()
583
+ for (const definition of definitions) {
584
+ if (!input.liveSymbols.has(definition.name)) continue
585
+ const previous = exported.get(definition.alias)
586
+ if (!previous || (previous.weak && !definition.weak))
587
+ exported.set(definition.alias, definition)
588
+ }
589
+ const names = [...new Set([...exported.values()].map((definition) => definition.name))]
590
+ const nameIndex = new Map(names.map((name, index) => [name, index]))
591
+ const ir = ['target triple = "wasm32-unknown-wasip1"']
592
+ names.forEach((name, index) => {
593
+ const bytes = Buffer.concat([Buffer.from(name), Buffer.from([0])])
594
+ const contents = [...bytes]
595
+ .map((byte) => `\\${byte.toString(16).padStart(2, '0')}`)
596
+ .join('')
597
+ ir.push(`@.name${index} = private constant [${bytes.length} x i8] c"${contents}"`)
598
+ })
599
+ for (const definition of exported.values()) {
600
+ if (definition.kind === 'function')
601
+ ir.push(
602
+ `declare ${definition.result} @${definition.alias}(${definition.parameters.join(', ')})`,
603
+ )
604
+ else ir.push(`@${definition.alias} = external global i8`)
605
+ }
606
+ ir.push(`@__peach_dyld_symbols = constant [${exported.size} x { ptr, i32, ptr }] [`)
607
+ ir.push(
608
+ [...exported.values()]
609
+ .map(
610
+ (definition) =>
611
+ ` { ptr, i32, ptr } { ptr @.name${nameIndex.get(definition.name)}, i32 ${definition.image}, ptr @${definition.alias} }`,
612
+ )
613
+ .join(',\n'),
614
+ )
615
+ ir.push(']', `@__peach_dyld_symbol_count = constant i32 ${exported.size}`)
616
+ input.callers.forEach((caller, index) => {
617
+ const items = caller.next.map((image) => `i32 ${image}`).join(', ')
618
+ ir.push(`@.scope${index} = private constant [${caller.next.length} x i32] [${items}]`)
619
+ })
620
+ ir.push(
621
+ `@__peach_dyld_callers = constant [${input.callers.length} x { i32, ptr, i32 }] [`,
622
+ )
623
+ ir.push(
624
+ input.callers
625
+ .map(
626
+ (caller, index) =>
627
+ ` { i32, ptr, i32 } { i32 ${caller.image}, ptr @.scope${index}, i32 ${caller.next.length} }`,
628
+ )
629
+ .join(',\n'),
630
+ )
631
+ ir.push(']', `@__peach_dyld_caller_count = constant i32 ${input.callers.length}`)
632
+ if (callersUsingDlsym.size) {
633
+ ir.push('declare ptr @__peach_dlsym_from_image(i32, ptr, ptr)')
634
+ for (const image of callersUsingDlsym) {
635
+ if (!input.callers.some((caller) => caller.image === image))
636
+ throw new Error(`missing scope for caller ${image}`)
637
+ ir.push(
638
+ `define ptr @__peach_dlsym_caller_${image}(ptr %handle, ptr %name) {`,
639
+ ` %result = call ptr @__peach_dlsym_from_image(i32 ${image}, ptr %handle, ptr %name)`,
640
+ ' ret ptr %result',
641
+ '}',
642
+ )
643
+ }
644
+ }
645
+ return {
646
+ images: input.images,
647
+ callers: input.callers,
648
+ definitions,
649
+ objects,
650
+ callerWrappers: [...callersUsingDlsym].map((image) => ({
651
+ symbol: `__peach_dlsym_caller_${image}`,
652
+ image,
653
+ })),
654
+ llvmIR: ir.join('\n') + '\n',
655
+ }
656
+ }