peachsim 0.1.2589 → 0.1.2591

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 (139) 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 +1490 -534
  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-6FUOY6FX.mjs → acorn-EMX4WZ72.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-33SCXU3Y.mjs → chunk-4QHHRGO4.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-Y4PV4HZB.mjs → chunk-7627LKJK.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-M4KUWGU3.mjs → chunk-AKKHSVJ4.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-MKSOJCRT.mjs → chunk-EGKH2L6J.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-5EFD2VBY.mjs → chunk-ILWFGZWW.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-57FFWABF.mjs → chunk-J676B57D.mjs} +5 -5
  33. package/dist-lib/esm-chunks/{chunk-JLOJZF2Y.mjs → chunk-JHXDM3YU.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-464CBA5U.mjs → chunk-MC6NMYWY.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-CRIYVOMB.mjs → chunk-NX23AMX4.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-EAIFG4MQ.mjs → chunk-Q4NA6PUR.mjs} +3 -3
  37. package/dist-lib/esm-chunks/{chunk-47K4QPVA.mjs → chunk-QBMFX3J2.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-FQQ2DMXS.mjs → chunk-RKQZGWX2.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-5QWQDXXD.mjs → chunk-SOAYP72T.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-XTKKROVU.mjs → chunk-TFG4LZ5T.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-KFHCRS5K.mjs → chunk-UIVXVMS5.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-BSAAJR25.mjs → chunk-UYJXLDCG.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-FMWEI6OI.mjs → chunk-VD27WNCT.mjs} +4 -4
  44. package/dist-lib/esm-chunks/{chunk-3VNUC4DT.mjs → chunk-VF5WVB3D.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-WQ73RKJY.mjs → chunk-VRVXRZI4.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-L3OSVIGA.mjs → chunk-VYZ5DC3M.mjs} +1359 -487
  47. package/dist-lib/esm-chunks/{chunk-I22LAVD5.mjs → chunk-YR6DNV76.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-PUBH3EXI.mjs → chunk-ZL5N6ENT.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-T5QIJTEV.mjs → metro-layout-parser-ANKZARNW.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-AWTZHPDM.mjs → swift-package-prebuilt-4N5CXBOZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-MGTJTVKU.mjs → swift-sdk-app-module-5IUSRXYA.mjs} +151 -67
  52. package/dist-lib/esm-chunks/{swift-sdk-image-JABGF3ZR.mjs → swift-sdk-image-7T2LMQS5.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-RJRJ3EFU.mjs → swift-sdk-image-producer-7QJ3BF6E.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1489 -533
  55. package/dist-lib/expo-swift-metadata.cjs +1 -1
  56. package/dist-lib/expo-swift-metadata.mjs +7 -7
  57. package/dist-lib/home-paths.cjs +1 -1
  58. package/dist-lib/host/bridge-host.cjs +1518 -557
  59. package/dist-lib/host/fetch-proxy-handler.cjs +4 -4
  60. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  61. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  62. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  63. package/dist-lib/host/websocket-proxy.cjs +1 -1
  64. package/dist-lib/index.cjs +1 -1
  65. package/dist-lib/kotlin-host.cjs +1 -1
  66. package/dist-lib/menu.cjs +1 -1
  67. package/dist-lib/menu.mjs +3 -3
  68. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  69. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  70. package/dist-lib/metro-production-bundle.cjs +1 -1
  71. package/dist-lib/metro-production-bundle.mjs +4 -4
  72. package/dist-lib/native-app-identity-project.cjs +2 -2
  73. package/dist-lib/native-app-identity-project.mjs +16 -16
  74. package/dist-lib/native-app-identity.cjs +1 -1
  75. package/dist-lib/native-app-identity.mjs +6 -6
  76. package/dist-lib/native-firebase-metadata.cjs +1 -1
  77. package/dist-lib/native-firebase-metadata.mjs +3 -3
  78. package/dist-lib/pdfium-raster.cjs +1 -1
  79. package/dist-lib/pdfium-raster.mjs +2 -2
  80. package/dist-lib/plist.cjs +1 -1
  81. package/dist-lib/plist.mjs +3 -3
  82. package/dist-lib/profiles.cjs +1 -1
  83. package/dist-lib/public-brand.cjs +1 -1
  84. package/dist-lib/public-origins-lib-esm.json +81 -81
  85. package/dist-lib/public-origins-lib.json +69 -69
  86. package/dist-lib/react-native-host-modules.cjs +1 -1
  87. package/dist-lib/react-native-host-modules.mjs +2 -2
  88. package/dist-lib/reap-browser.cjs +1 -1
  89. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  90. package/dist-lib/sdk.cjs +1 -1
  91. package/dist-lib/sdk.mjs +8 -8
  92. package/dist-lib/skills.cjs +1520 -559
  93. package/dist-lib/swift-compile.cjs +1486 -530
  94. package/dist-lib/swift-compile.mjs +10 -10
  95. package/dist-lib/swift-package.cjs +1 -1
  96. package/dist-lib/swift-package.mjs +3 -3
  97. package/dist-lib/swift-submit.cjs +1 -1
  98. package/dist-lib/swift-submit.mjs +6 -6
  99. package/dist-lib/swift-svg-raster.cjs +1 -1
  100. package/dist-lib/swift-svg-raster.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +1 -1
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/kotlin/sdk.tar.gz +0 -0
  126. package/package.json +1 -1
  127. package/src/swift-guest-compile.ts +43 -10
  128. package/src/swift-guest-dyld-table.ts +9 -2
  129. package/src/swift-guest-image-ledger.ts +403 -208
  130. package/src/swift-guest-link.ts +258 -113
  131. package/src/swift-guest-linked-spans.ts +217 -28
  132. package/src/swift-guest-manifest.ts +24 -13
  133. package/src/swift-guest-projection-storage.ts +6 -8
  134. package/src/swift-guest-projection.ts +7 -6
  135. package/src/swift-guest-source-inputs.ts +158 -30
  136. package/src/swift-sdk-app-module.ts +146 -59
  137. package/src/swift-sdk-image-map.ts +137 -35
  138. package/src/swift-wasm-prune.ts +263 -85
  139. package/src/swiftGuestImageContract.ts +1 -1
@@ -80,7 +80,63 @@ export interface GuestImageLedger {
80
80
  readonly appLazyFunctions?: readonly string[]
81
81
  }
82
82
 
83
+ class ByteWriter {
84
+ private buf: Buffer
85
+ private pos = 0
86
+ constructor(initialCapacity = 256) {
87
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity))
88
+ }
89
+ private ensure(extra: number) {
90
+ const needed = this.pos + extra
91
+ if (needed <= this.buf.length) return
92
+ let next = this.buf.length * 2
93
+ while (next < needed) next *= 2
94
+ const grown = Buffer.allocUnsafe(next)
95
+ this.buf.copy(grown, 0, 0, this.pos)
96
+ this.buf = grown
97
+ }
98
+ byte(value: number) {
99
+ this.ensure(1)
100
+ this.buf[this.pos++] = value
101
+ }
102
+ uleb(value: number) {
103
+ this.ensure(10)
104
+ let pos = this.pos
105
+ const buf = this.buf
106
+ do {
107
+ let byte = value % 128
108
+ value = Math.floor(value / 128)
109
+ if (value) byte |= 128
110
+ buf[pos++] = byte
111
+ } while (value)
112
+ this.pos = pos
113
+ }
114
+ bytes(source: Uint8Array, start = 0, end = source.length) {
115
+ const len = end - start
116
+ if (len <= 0) return
117
+ this.ensure(len)
118
+ this.buf.set(source.subarray(start, end), this.pos)
119
+ this.pos += len
120
+ }
121
+ string(value: string) {
122
+ const len = Buffer.byteLength(value, 'utf8')
123
+ this.uleb(len)
124
+ if (len > 0) {
125
+ this.ensure(len)
126
+ this.buf.write(value, this.pos, len, 'utf8')
127
+ this.pos += len
128
+ }
129
+ }
130
+ finish(): Buffer {
131
+ return this.buf.subarray(0, this.pos)
132
+ }
133
+ }
134
+
83
135
  function readNumber(bytes: Uint8Array, position: number): [number, number] {
136
+ if (position < bytes.length) {
137
+ const first = bytes[position]!
138
+ if (first < 128) return [first, position + 1]
139
+ }
84
140
  let value = 0
85
141
  let shift = 0
86
142
  for (;;) {
@@ -93,6 +149,7 @@ function readNumber(bytes: Uint8Array, position: number): [number, number] {
93
149
  }
94
150
 
95
151
  function encodeNumber(value: number): Buffer {
152
+ if (value < 128) return Buffer.from([value])
96
153
  const bytes: number[] = []
97
154
  do {
98
155
  let byte = value % 128
@@ -117,6 +174,20 @@ function encodedString(value: string): Buffer {
117
174
  return Buffer.concat([encodeNumber(bytes.length), bytes])
118
175
  }
119
176
 
177
+ function isWasmMagic(bytes: Uint8Array): boolean {
178
+ return (
179
+ bytes.length >= 8 &&
180
+ bytes[0] === 0x00 &&
181
+ bytes[1] === 0x61 &&
182
+ bytes[2] === 0x73 &&
183
+ bytes[3] === 0x6d &&
184
+ bytes[4] === 0x01 &&
185
+ bytes[5] === 0x00 &&
186
+ bytes[6] === 0x00 &&
187
+ bytes[7] === 0x00
188
+ )
189
+ }
190
+
120
191
  interface FunctionType {
121
192
  readonly parameters: readonly number[]
122
193
  readonly results: readonly number[]
@@ -164,17 +235,18 @@ function rewriteObject(
164
235
  readonly definitions: readonly ObjectDefinition[]
165
236
  readonly functionImports: ReadonlyMap<string, FunctionType>
166
237
  readonly usesDlsym: boolean
167
- readonly usedSymbols: readonly string[]
238
+ readonly usedSymbols: ReadonlySet<string>
168
239
  readonly addressTaken: readonly string[]
169
240
  } {
170
- if (Buffer.from(bytes.subarray(0, 8)).toString('hex') !== '0061736d01000000')
171
- throw new Error('expected wasm object')
241
+ if (!isWasmMagic(bytes)) throw new Error('expected wasm object')
242
+ const rawBuf = Buffer.isBuffer(bytes)
243
+ ? bytes
244
+ : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
172
245
  const { sdkLookupOnly, sdkProduct } = options
173
246
  const comdatScope =
174
247
  sdkProduct === undefined ? callerAlias : `${callerAlias}:${sdkProduct}`
175
- const sections: Buffer[] | undefined = binding
176
- ? [Buffer.from(bytes.subarray(0, 8))]
177
- : undefined
248
+ const rewrite = binding !== undefined
249
+ const sections: Uint8Array[] | undefined = rewrite ? [bytes.subarray(0, 8)] : undefined
178
250
  const types: FunctionType[] = []
179
251
  const functionTypes: number[] = []
180
252
  const definitions: ObjectDefinition[] = []
@@ -188,45 +260,74 @@ function rewriteObject(
188
260
  const usedSymbols = new Set<string>()
189
261
  let position = 8
190
262
  while (position < bytes.length) {
263
+ const headerStart = position
191
264
  const id = bytes[position++]!
192
- const [size, start] = readNumber(bytes, position)
265
+ let size = 0
266
+ if (position < bytes.length && bytes[position]! < 128) {
267
+ size = bytes[position++]!
268
+ } else {
269
+ const [val, next] = readNumber(bytes, position)
270
+ size = val
271
+ position = next
272
+ }
273
+ const start = position
193
274
  const end = start + size
194
275
  if (end > bytes.length) throw new Error('invalid wasm section')
195
276
  position = end
196
- if (!sections && id > 3) continue
197
- let section = Buffer.from(bytes.buffer, bytes.byteOffset + start, size)
198
- let offset = 0
277
+ if (id > 3) {
278
+ if (sections) sections.push(bytes.subarray(headerStart, end))
279
+ continue
280
+ }
281
+ let offset = start
199
282
  const number = (): number => {
200
- const [value, next] = readNumber(section, offset)
201
- offset = next
202
- return value
283
+ if (offset < end) {
284
+ const first = bytes[offset]!
285
+ if (first < 128) {
286
+ offset++
287
+ return first
288
+ }
289
+ }
290
+ let value = 0
291
+ let shift = 0
292
+ for (;;) {
293
+ if (offset >= end || shift > 63) throw new Error('invalid wasm integer')
294
+ const byte = bytes[offset++]!
295
+ value += (byte & 127) * 2 ** shift
296
+ if (!(byte & 128)) return value
297
+ shift += 7
298
+ }
203
299
  }
204
300
  const string = (): string => {
205
- const [value, next] = readString(section, offset)
206
- offset = next
301
+ const length = number()
302
+ const strEnd = offset + length
303
+ if (strEnd > end) throw new Error('invalid wasm string')
304
+ const value = rawBuf.toString('utf8', offset, strEnd)
305
+ offset = strEnd
207
306
  return value
208
307
  }
308
+ let rewrittenSection: Uint8Array | undefined
209
309
  if (id === 1) {
210
310
  const count = number()
211
311
  for (let i = 0; i < count; i++) {
212
- if (section[offset++] !== 0x60) throw new Error('unsupported wasm type')
312
+ if (bytes[offset++] !== 0x60) throw new Error('unsupported wasm type')
213
313
  const parameterCount = number()
214
- const parameters = [...section.subarray(offset, offset + parameterCount)]
215
- if (parameterCount !== parameters.length) throw new Error('invalid wasm type')
216
- offset += parameterCount
314
+ if (offset + parameterCount > end) throw new Error('invalid wasm type')
315
+ const parameters: number[] = new Array(parameterCount)
316
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++]!
217
317
  const resultCount = number()
218
- const results = [...section.subarray(offset, offset + resultCount)]
219
- if (results.length !== resultCount) throw new Error('invalid wasm type')
220
- offset += resultCount
318
+ if (offset + resultCount > end) throw new Error('invalid wasm type')
319
+ const results: number[] = new Array(resultCount)
320
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++]!
221
321
  types.push({ parameters, results })
222
322
  }
223
323
  } else if (id === 2) {
224
324
  const count = number()
225
- const imports: Buffer[] | undefined = sections ? [encodeNumber(count)] : undefined
325
+ const importWriter = rewrite ? new ByteWriter(size + 64) : undefined
326
+ importWriter?.uleb(count)
226
327
  for (let i = 0; i < count; i++) {
227
328
  const module = string()
228
329
  const name = string()
229
- const kind = section[offset++]!
330
+ const kind = bytes[offset++]!
230
331
  const typeStart = offset
231
332
  let functionType = -1
232
333
  if (kind === 0) {
@@ -234,7 +335,7 @@ function rewriteObject(
234
335
  functionTypes.push(functionType)
235
336
  functionImportNames.push(name)
236
337
  } else if (kind === 1) {
237
- const referenceType = section[offset++]
338
+ const referenceType = bytes[offset++]
238
339
  if (referenceType !== 0x70 && referenceType !== 0x6f)
239
340
  throw new Error('unsupported table type')
240
341
  const flags = number()
@@ -255,11 +356,15 @@ function rewriteObject(
255
356
  instrumentDynamicLookups && module === 'env' && name === 'dlsym' && kind === 0
256
357
  const isDlerror =
257
358
  instrumentDynamicLookups && module === 'env' && name === 'dlerror' && kind === 0
258
- if (module === 'env' && names.has(name)) usedSymbols.add(name)
259
- if (module === 'env' && kind === 0 && names.has(name)) {
260
- const type = types[functionType]
261
- if (!type) throw new Error(`missing import type for ${name}`)
262
- functionImports.set(name, type)
359
+ if (!rewrite) {
360
+ if (module === 'env' && names.has(name)) {
361
+ usedSymbols.add(name)
362
+ if (kind === 0) {
363
+ const type = types[functionType]
364
+ if (!type) throw new Error(`missing import type for ${name}`)
365
+ functionImports.set(name, type)
366
+ }
367
+ }
263
368
  }
264
369
  if (isDlsym || isDlerror) {
265
370
  const type = types[functionType]
@@ -272,23 +377,23 @@ function rewriteObject(
272
377
  }
273
378
  if (isDlsym) usesDlsym = true
274
379
  if (isDlerror) usesDlerror = true
275
- imports?.push(
276
- encodedString(module),
277
- encodedString(
380
+ if (importWriter && binding) {
381
+ importWriter.string(module)
382
+ importWriter.string(
278
383
  isDlsym
279
384
  ? callerAlias
280
385
  : isDlerror
281
386
  ? dlerrorAlias
282
387
  : module === 'env' && name !== 'dlsym' && name !== 'dlerror'
283
- ? (binding?.(name) ?? name)
388
+ ? (binding(name) ?? name)
284
389
  : name,
285
- ),
286
- Buffer.from([kind]),
287
- section.subarray(typeStart, offset),
288
- )
390
+ )
391
+ importWriter.byte(kind)
392
+ importWriter.bytes(bytes, typeStart, offset)
393
+ }
289
394
  }
290
- if (offset !== section.length) throw new Error('invalid wasm import section')
291
- if (imports) section = Buffer.concat(imports)
395
+ if (offset !== end) throw new Error('invalid wasm import section')
396
+ if (importWriter) rewrittenSection = importWriter.finish()
292
397
  } else if (id === 3) {
293
398
  const count = number()
294
399
  for (let i = 0; i < count; i++) functionTypes.push(number())
@@ -297,49 +402,48 @@ function rewriteObject(
297
402
  if (sectionName === 'linking') {
298
403
  const version = number()
299
404
  if (version !== 2) throw new Error('unsupported wasm linking version')
300
- const subsections: { kind: number; content: Buffer }[] = []
405
+ const subsections:
406
+ | { kind: number; parts: Uint8Array[]; byteLength: number }[]
407
+ | undefined = rewrite ? [] : undefined
301
408
  let objcLoader: number | undefined
302
- while (offset < section.length) {
303
- const kind = section[offset++]!
409
+ while (offset < end) {
410
+ const kind = bytes[offset++]!
304
411
  const length = number()
305
412
  const stop = offset + length
306
- if (stop > section.length) throw new Error('invalid linking subsection')
307
- let content = section.subarray(offset, stop)
308
- if (kind === 7 && !sdkLookupOnly) {
413
+ if (stop > end) throw new Error('invalid linking subsection')
414
+ const contentStart = offset
415
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
309
416
  // comdat ownership follows symbol aliases, including sdk products
310
417
  // that share an image with app objects.
311
418
  // the Objective-C init record is the exception: the module has one
312
419
  // runtime and its record spans every image's class section, so a record
313
420
  // per image would register each class once per image, where one shared
314
421
  // record makes every constructor after the first return early.
315
- const groups: Buffer[] = []
422
+ const comdatWriter = new ByteWriter(length + 64)
316
423
  const count = number()
317
- groups.push(encodeNumber(count))
424
+ comdatWriter.uleb(count)
318
425
  for (let i = 0; i < count; i++) {
319
426
  const group = string()
320
427
  const begin = offset
321
428
  number()
322
429
  const members = number()
323
430
  for (let member = 0; member < members * 2; member++) number()
324
- groups.push(
325
- encodedString(
326
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`,
327
- ),
328
- section.subarray(begin, offset),
431
+ comdatWriter.string(
432
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`,
329
433
  )
434
+ comdatWriter.bytes(bytes, begin, offset)
330
435
  }
331
436
  if (offset !== stop) throw new Error('invalid comdat subsection')
332
- content = Buffer.concat(groups)
333
- }
334
- if (kind === 8) {
335
- const entries: Buffer[] = []
336
- const extraEntries: Buffer[] = []
437
+ const buf = comdatWriter.finish()
438
+ subsections!.push({ kind, parts: [buf], byteLength: buf.length })
439
+ } else if (kind === 8) {
440
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : undefined
441
+ let extraWriter: ByteWriter | undefined
337
442
  const count = number()
338
- entries.push(encodeNumber(count))
339
443
  let added = 0
340
444
  for (let i = 0; i < count; i++) {
341
445
  const begin = offset
342
- const symbolKind = section[offset++]!
446
+ const symbolKind = bytes[offset++]!
343
447
  const flags = number()
344
448
  const flagsEnd = offset
345
449
  let index = -1
@@ -372,9 +476,10 @@ function rewriteObject(
372
476
  }
373
477
  } else if (symbolKind === 3) number()
374
478
  else throw new Error('unsupported wasm symbol kind')
375
- if (symbolKind === 0)
479
+ if (!rewrite && symbolKind === 0)
376
480
  functionSymbols[i] = name || functionImportNames[index]
377
481
  if (
482
+ rewrite &&
378
483
  !sdkLookupOnly &&
379
484
  name === OBJC_LOAD_FUNCTION &&
380
485
  symbolKind === 0 &&
@@ -384,30 +489,49 @@ function rewriteObject(
384
489
  }
385
490
  const alias = names.get(name)
386
491
  // an undefined data symbol has no wasm import, only this linking entry.
387
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name)
388
- if (
389
- ((name === 'dlsym' && usesDlsym) ||
390
- (name === 'dlerror' && usesDlerror)) &&
391
- flags & 16 &&
392
- flags & 64 &&
393
- symbolKind === 0
394
- ) {
395
- entries.push(
396
- section.subarray(begin, nameStart),
397
- encodedString(name === 'dlsym' ? callerAlias : dlerrorAlias),
398
- section.subarray(nameEnd, offset),
399
- )
400
- } else if (
401
- flags & 16 &&
402
- name !== 'dlsym' &&
403
- name !== 'dlerror' &&
404
- binding?.(name) !== undefined
405
- ) {
406
- entries.push(
407
- section.subarray(begin, nameStart),
408
- encodedString(binding(name)!),
409
- section.subarray(nameEnd, offset),
410
- )
492
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
493
+ usedSymbols.add(name)
494
+ if (entryWriter && binding) {
495
+ if (
496
+ ((name === 'dlsym' && usesDlsym) ||
497
+ (name === 'dlerror' && usesDlerror)) &&
498
+ flags & 16 &&
499
+ flags & 64 &&
500
+ symbolKind === 0
501
+ ) {
502
+ entryWriter.bytes(bytes, begin, nameStart)
503
+ entryWriter.string(name === 'dlsym' ? callerAlias : dlerrorAlias)
504
+ entryWriter.bytes(bytes, nameEnd, offset)
505
+ } else if (
506
+ flags & 16 &&
507
+ name !== 'dlsym' &&
508
+ name !== 'dlerror' &&
509
+ binding(name) !== undefined
510
+ ) {
511
+ entryWriter.bytes(bytes, begin, nameStart)
512
+ entryWriter.string(binding(name)!)
513
+ entryWriter.bytes(bytes, nameEnd, offset)
514
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
515
+ if (symbolKind !== 0 && symbolKind !== 1)
516
+ throw new Error(`unsupported symbol ${name}`)
517
+ if (preserveCanonical.has(name)) {
518
+ entryWriter.bytes(bytes, begin, offset)
519
+ // the canonical symbol keeps the export; its alias only names the table slot.
520
+ extraWriter ??= new ByteWriter(256)
521
+ extraWriter.byte(bytes[begin]!)
522
+ extraWriter.uleb(flags & ~0x20)
523
+ extraWriter.bytes(bytes, flagsEnd, nameStart)
524
+ extraWriter.string(alias)
525
+ extraWriter.bytes(bytes, nameEnd, offset)
526
+ added++
527
+ } else {
528
+ entryWriter.bytes(bytes, begin, nameStart)
529
+ entryWriter.string(alias)
530
+ entryWriter.bytes(bytes, nameEnd, offset)
531
+ }
532
+ } else {
533
+ entryWriter.bytes(bytes, begin, offset)
534
+ }
411
535
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
412
536
  if (symbolKind !== 0 && symbolKind !== 1)
413
537
  throw new Error(`unsupported symbol ${name}`)
@@ -421,65 +545,74 @@ function rewriteObject(
421
545
  hidden: (flags & 4) !== 0,
422
546
  type,
423
547
  })
424
- if (preserveCanonical.has(name)) {
425
- entries.push(section.subarray(begin, offset))
426
- // the canonical symbol keeps the export; its alias only names the table slot.
427
- extraEntries.push(
428
- section.subarray(begin, begin + 1),
429
- encodeNumber(flags & ~0x20),
430
- section.subarray(flagsEnd, nameStart),
431
- encodedString(alias),
432
- section.subarray(nameEnd, offset),
433
- )
434
- added++
435
- } else {
436
- entries.push(
437
- section.subarray(begin, nameStart),
438
- encodedString(alias),
439
- section.subarray(nameEnd, offset),
440
- )
441
- }
442
- } else entries.push(section.subarray(begin, offset))
548
+ }
443
549
  }
444
550
  if (offset !== stop) throw new Error('invalid symbol subsection')
445
- entries[0] = encodeNumber(count + added)
446
- content = Buffer.concat([...entries, ...extraEntries])
551
+ if (entryWriter) {
552
+ const countBytes = encodeNumber(count + added)
553
+ const entryBuf = entryWriter.finish()
554
+ if (extraWriter) {
555
+ const extraBuf = extraWriter.finish()
556
+ subsections!.push({
557
+ kind,
558
+ parts: [countBytes, entryBuf, extraBuf],
559
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length,
560
+ })
561
+ } else {
562
+ subsections!.push({
563
+ kind,
564
+ parts: [countBytes, entryBuf],
565
+ byteLength: countBytes.length + entryBuf.length,
566
+ })
567
+ }
568
+ }
569
+ } else if (subsections) {
570
+ subsections.push({
571
+ kind,
572
+ parts: [bytes.subarray(contentStart, stop)],
573
+ byteLength: length,
574
+ })
447
575
  }
448
576
  offset = stop
449
- subsections.push({ kind, content })
450
577
  }
451
- const parts = [encodedString(sectionName), encodeNumber(version)]
452
- for (const subsection of subsections) {
453
- let content = subsection.content
454
- if (subsection.kind === 6 && objcLoader !== undefined) {
455
- const [count, entriesStart] = readNumber(content, 0)
456
- const entries = [content.subarray(0, entriesStart)]
457
- let entryStart = entriesStart
458
- for (let i = 0; i < count; i++) {
459
- const [, symbolStart] = readNumber(content, entryStart)
460
- const [symbol, entryEnd] = readNumber(content, symbolStart)
461
- // load the merged objc metadata after Swift registration (0) and before user constructors (101+).
462
- if (symbol === objcLoader) entries.push(encodeNumber(1))
463
- entries.push(
464
- content.subarray(
465
- symbol === objcLoader ? symbolStart : entryStart,
466
- entryEnd,
467
- ),
468
- )
469
- entryStart = entryEnd
578
+ if (subsections) {
579
+ const linkingWriter = new ByteWriter(size + 128)
580
+ linkingWriter.string(sectionName)
581
+ linkingWriter.uleb(version)
582
+ for (const subsection of subsections) {
583
+ if (subsection.kind === 6 && objcLoader !== undefined) {
584
+ const content = subsection.parts[0]!
585
+ const [count, entriesStart] = readNumber(content, 0)
586
+ const initWriter = new ByteWriter(content.length + 16)
587
+ initWriter.bytes(content, 0, entriesStart)
588
+ let entryStart = entriesStart
589
+ for (let i = 0; i < count; i++) {
590
+ const [, symbolStart] = readNumber(content, entryStart)
591
+ const [symbol, entryEnd] = readNumber(content, symbolStart)
592
+ // load the merged objc metadata after Swift registration (0) and before user constructors (101+).
593
+ if (symbol === objcLoader) {
594
+ initWriter.uleb(1)
595
+ initWriter.bytes(content, symbolStart, entryEnd)
596
+ } else {
597
+ initWriter.bytes(content, entryStart, entryEnd)
598
+ }
599
+ entryStart = entryEnd
600
+ }
601
+ if (entryStart !== content.length)
602
+ throw new Error('invalid init functions subsection')
603
+ const initBuf = initWriter.finish()
604
+ linkingWriter.byte(subsection.kind)
605
+ linkingWriter.uleb(initBuf.length)
606
+ linkingWriter.bytes(initBuf)
607
+ } else {
608
+ linkingWriter.byte(subsection.kind)
609
+ linkingWriter.uleb(subsection.byteLength)
610
+ for (const part of subsection.parts) linkingWriter.bytes(part)
470
611
  }
471
- if (entryStart !== content.length)
472
- throw new Error('invalid init functions subsection')
473
- content = Buffer.concat(entries)
474
612
  }
475
- parts.push(
476
- Buffer.from([subsection.kind]),
477
- encodeNumber(content.length),
478
- content,
479
- )
613
+ rewrittenSection = linkingWriter.finish()
480
614
  }
481
- section = Buffer.concat(parts)
482
- } else if (!sections && sectionName.startsWith('reloc.')) {
615
+ } else if (!rewrite && sectionName.startsWith('reloc.')) {
483
616
  // the analysis pass records which functions any object takes the address of.
484
617
  number()
485
618
  for (let count = number(); count > 0; count--) {
@@ -490,18 +623,27 @@ function rewriteObject(
490
623
  if (name !== undefined && TABLE_INDEX_RELOCATIONS.has(type))
491
624
  addressTaken.add(name)
492
625
  }
493
- if (offset !== section.length)
494
- throw new Error(`invalid relocation section ${sectionName}`)
626
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`)
627
+ }
628
+ }
629
+ if (sections) {
630
+ if (rewrittenSection) {
631
+ sections.push(
632
+ Buffer.from([id]),
633
+ encodeNumber(rewrittenSection.length),
634
+ rewrittenSection,
635
+ )
636
+ } else {
637
+ sections.push(bytes.subarray(headerStart, end))
495
638
  }
496
639
  }
497
- sections?.push(Buffer.from([id]), encodeNumber(section.length), section)
498
640
  }
499
641
  return {
500
642
  bytes: sections ? Buffer.concat(sections) : bytes,
501
643
  definitions,
502
644
  functionImports,
503
645
  usesDlsym,
504
- usedSymbols: [...usedSymbols],
646
+ usedSymbols,
505
647
  addressTaken: [...addressTaken],
506
648
  }
507
649
  }
@@ -534,7 +676,7 @@ export function createGuestImageLedger(input: GuestImageLedgerInput): GuestImage
534
676
  image: number
535
677
  object: GuestImageObject
536
678
  aliases: Pick<ReadonlyMap<string, string>, 'get' | 'has'>
537
- usedSymbols: readonly string[]
679
+ usedSymbols: ReadonlySet<string>
538
680
  functionImports: ReadonlyMap<string, FunctionType>
539
681
  }[] = []
540
682
  const callersUsingDlsym = new Set<number>()
@@ -604,54 +746,69 @@ export function createGuestImageLedger(input: GuestImageLedgerInput): GuestImage
604
746
  }
605
747
  }
606
748
  }
607
- const nameBytes = new Map<string, Buffer>()
608
- for (const definition of definitions)
609
- if (!nameBytes.has(definition.name))
610
- nameBytes.set(definition.name, Buffer.from(definition.name))
611
- definitions.sort(
612
- (a, b) =>
613
- Buffer.compare(nameBytes.get(a.name)!, nameBytes.get(b.name)!) || a.image - b.image,
614
- )
749
+ let hasNonAscii = false
750
+ for (const definition of definitions) {
751
+ const s = definition.name
752
+ for (let i = 0; i < s.length; i++) {
753
+ if (s.charCodeAt(i) > 0x7f) {
754
+ hasNonAscii = true
755
+ break
756
+ }
757
+ }
758
+ if (hasNonAscii) break
759
+ }
760
+ if (hasNonAscii) {
761
+ const nameBytes = new Map<string, Buffer>()
762
+ for (const definition of definitions)
763
+ if (!nameBytes.has(definition.name))
764
+ nameBytes.set(definition.name, Buffer.from(definition.name))
765
+ definitions.sort(
766
+ (a, b) =>
767
+ Buffer.compare(nameBytes.get(a.name)!, nameBytes.get(b.name)!) ||
768
+ a.image - b.image,
769
+ )
770
+ } else {
771
+ definitions.sort((a, b) =>
772
+ a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image,
773
+ )
774
+ }
615
775
  const preserveCanonical = new Set<string>()
616
776
  const definitionsByName = Map.groupBy(definitions, (definition) => definition.name)
617
- for (const name of input.symbols) {
777
+ if (symbolIndices.has('__cxa_throw')) {
778
+ const name = '__cxa_throw'
618
779
  const matching = definitionsByName.get(name) ?? []
619
780
  if (
620
- new Set(matching.map((definition) => definition.image)).size < 2 ||
621
- !matching.some((definition) => definition.weak)
622
- )
623
- continue
624
- const weak = matching.filter((definition) => definition.weak)
625
- const strong = matching.filter((definition) => !definition.weak)
626
- // every other name is odr-equivalent across images, so the first definition in the caller's lookup order binds.
627
- if (name !== '__cxa_throw') continue
628
- // the measured iOS throw path lets the runtime's strong definition win;
629
- // aliases keep both implementations addressable for scoped lookup.
630
- if (weak.length !== 1 || strong.length !== 1)
631
- throw new Error(`unsupported weak interposition for ${name}`)
632
- const [local] = weak
633
- const [runtime] = strong
634
- if (
635
- local!.kind !== 'function' ||
636
- runtime!.kind !== 'function' ||
637
- local!.result !== runtime!.result ||
638
- local!.parameters.join(',') !== runtime!.parameters.join(',')
639
- )
640
- throw new Error(`incompatible weak interposition for ${name}`)
641
- for (const caller of input.callers) {
642
- const uses =
643
- caller.image === local!.image ||
644
- units.some(
645
- (unit) => unit.image === caller.image && unit.usedSymbols.includes(name),
646
- )
781
+ new Set(matching.map((definition) => definition.image)).size >= 2 &&
782
+ matching.some((definition) => definition.weak)
783
+ ) {
784
+ const weak = matching.filter((definition) => definition.weak)
785
+ const strong = matching.filter((definition) => !definition.weak)
786
+ // the measured iOS throw path lets the runtime's strong definition win;
787
+ // aliases keep both implementations addressable for scoped lookup.
788
+ if (weak.length !== 1 || strong.length !== 1)
789
+ throw new Error(`unsupported weak interposition for ${name}`)
790
+ const [local] = weak
791
+ const [runtime] = strong
647
792
  if (
648
- uses &&
649
- caller.image !== runtime!.image &&
650
- !caller.next.includes(runtime!.image)
793
+ local!.kind !== 'function' ||
794
+ runtime!.kind !== 'function' ||
795
+ local!.result !== runtime!.result ||
796
+ local!.parameters.join(',') !== runtime!.parameters.join(',')
651
797
  )
652
- throw new Error(`weak interposition scope excludes runtime for ${name}`)
798
+ throw new Error(`incompatible weak interposition for ${name}`)
799
+ for (const caller of input.callers) {
800
+ const uses =
801
+ caller.image === local!.image ||
802
+ units.some((unit) => unit.image === caller.image && unit.usedSymbols.has(name))
803
+ if (
804
+ uses &&
805
+ caller.image !== runtime!.image &&
806
+ !caller.next.includes(runtime!.image)
807
+ )
808
+ throw new Error(`weak interposition scope excludes runtime for ${name}`)
809
+ }
810
+ preserveCanonical.add(name)
653
811
  }
654
- preserveCanonical.add(name)
655
812
  }
656
813
  // the loader runtime calls the platform lookup entry points it implements
657
814
  // under their own names, so they bind no image alias.
@@ -665,44 +822,82 @@ export function createGuestImageLedger(input: GuestImageLedgerInput): GuestImage
665
822
  ])
666
823
  preserveCanonical.add(name)
667
824
  for (const name of input.commandLineSymbols ?? []) preserveCanonical.add(name)
668
- const bindingsByImage = new Map<number, Map<string, string>>()
669
- const definitionsByImage = Map.groupBy(definitions, (definition) => definition.image)
825
+ // per-image winner: the first definition binds and a strong one beats a weak one.
826
+ const imageAliases = new Map<number, Map<string, string>>()
827
+ const imageWeakNames = new Map<number, Set<string>>()
828
+ const singleOwnerByName = new Map<string, { image: number; alias: string } | null>()
829
+ for (const definition of definitions) {
830
+ let aliases = imageAliases.get(definition.image)
831
+ if (!aliases) imageAliases.set(definition.image, (aliases = new Map()))
832
+ const existing = aliases.get(definition.name)
833
+ if (existing === undefined) {
834
+ aliases.set(definition.name, definition.alias)
835
+ if (definition.weak) {
836
+ let weak = imageWeakNames.get(definition.image)
837
+ if (!weak) imageWeakNames.set(definition.image, (weak = new Set()))
838
+ weak.add(definition.name)
839
+ }
840
+ const owner = singleOwnerByName.get(definition.name)
841
+ if (owner === undefined)
842
+ singleOwnerByName.set(definition.name, {
843
+ image: definition.image,
844
+ alias: definition.alias,
845
+ })
846
+ else if (owner !== null && owner.image !== definition.image)
847
+ singleOwnerByName.set(definition.name, null)
848
+ } else if (
849
+ !definition.weak &&
850
+ imageWeakNames.get(definition.image)?.has(definition.name)
851
+ ) {
852
+ aliases.set(definition.name, definition.alias)
853
+ imageWeakNames.get(definition.image)!.delete(definition.name)
854
+ const owner = singleOwnerByName.get(definition.name)
855
+ if (owner && owner.image === definition.image) owner.alias = definition.alias
856
+ }
857
+ }
858
+ const sharedLookupByImage = new Map<number, (name: string) => string | undefined>()
670
859
  for (const caller of input.callers) {
671
- const bindings = new Map<string, string>()
672
- const seen = new Map<string, GuestImageDefinition>()
673
860
  const scope = [caller.image, ...caller.next]
674
861
  if (input.systemImage !== undefined && !scope.includes(input.systemImage))
675
862
  scope.push(input.systemImage)
676
- for (const image of scope)
677
- for (const definition of definitionsByImage.get(image) ?? []) {
678
- const previous = seen.get(definition.name)
679
- // the linker already accepted the image, so duplicate definitions inside
680
- // it resolve as in a static link: the first binds and a strong one beats a weak one.
681
- if (previous?.image === definition.image) {
682
- if (previous.weak && !definition.weak) {
683
- seen.set(definition.name, definition)
684
- if (!preserveCanonical.has(definition.name))
685
- bindings.set(definition.name, definition.alias)
686
- }
687
- continue
688
- }
689
- if (!previous) {
690
- seen.set(definition.name, definition)
691
- if (!preserveCanonical.has(definition.name))
692
- bindings.set(definition.name, definition.alias)
863
+ const scopeSet = new Set(scope)
864
+ const scopeMaps: Map<string, string>[] = []
865
+ const seenImages = new Set<number>()
866
+ for (const image of scope) {
867
+ if (seenImages.has(image)) continue
868
+ seenImages.add(image)
869
+ const aliases = imageAliases.get(image)
870
+ if (aliases) scopeMaps.push(aliases)
871
+ }
872
+ const cache = new Map<string, string | null>()
873
+ sharedLookupByImage.set(caller.image, (name: string): string | undefined => {
874
+ if (preserveCanonical.has(name)) return undefined
875
+ const single = singleOwnerByName.get(name)
876
+ if (single === undefined) return undefined
877
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : undefined
878
+ const hit = cache.get(name)
879
+ if (hit !== undefined) return hit ?? undefined
880
+ for (const aliases of scopeMaps) {
881
+ const alias = aliases.get(name)
882
+ if (alias !== undefined) {
883
+ cache.set(name, alias)
884
+ return alias
693
885
  }
694
886
  }
695
- bindingsByImage.set(caller.image, bindings)
887
+ cache.set(name, null)
888
+ return undefined
889
+ })
696
890
  }
697
891
  const startup = new Map<string, Map<string, string>>()
892
+ const unitsByPath = new Map(units.map((unit) => [unit.object.path, unit]))
698
893
  for (const binding of input.directBindings ?? []) {
699
- const unit = units.find(({ object }) => object.path === binding.object)
894
+ const unit = unitsByPath.get(binding.object)
700
895
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
701
896
  (definition) =>
702
897
  definition.object === binding.providerObject &&
703
898
  definition.image === binding.providerImage,
704
899
  )
705
- if (!unit || !unit.usedSymbols.includes(binding.symbol) || matches.length !== 1)
900
+ if (!unit || !unit.usedSymbols.has(binding.symbol) || matches.length !== 1)
706
901
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`)
707
902
  const bindings = startup.get(binding.object) ?? new Map<string, string>()
708
903
  if (bindings.has(binding.symbol))
@@ -753,14 +948,14 @@ export function createGuestImageLedger(input: GuestImageLedgerInput): GuestImage
753
948
  }
754
949
  }
755
950
  const objects = units.map(({ image, object, aliases, functionImports }) => {
756
- const shared = bindingsByImage.get(image)!
951
+ const shared = sharedLookupByImage.get(image)!
757
952
  const own = startup.get(object.path)
758
953
  const bindings = new Map(own)
759
954
  const weak = input.sdkWeakReferences?.get(object.path)
760
955
  // a strong static reference can bind a unique process definition outside the dyld scope.
761
956
  const binding = (name: string) =>
762
957
  bindings.get(name) ??
763
- shared.get(name) ??
958
+ shared(name) ??
764
959
  (weak?.has(name) ? undefined : sdkGlobalBindings.get(name))
765
960
  for (const [name, type] of functionImports) {
766
961
  const alias = binding(name)