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
@@ -61,22 +61,47 @@ export const CLANG_TARGET_MODULE_WRAPPER = '.peach-clang'
61
61
 
62
62
  const PARALLEL_REPLAY = `
63
63
  const { spawn } = require('node:child_process')
64
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
64
+ const fs = require('node:fs')
65
+ const commands = JSON.parse(fs.readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
66
+ const results = new Array(commands.length)
65
67
  let next = 0
66
68
  const run = () => {
67
69
  if (next >= commands.length) return Promise.resolve()
68
- const [file, ...args] = commands[next++]
70
+ const index = next++
71
+ const [file, ...args] = commands[index]
69
72
  return new Promise((resolve, reject) => {
70
- const child = spawn(file, args, { stdio: 'inherit' })
73
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'inherit'] })
74
+ const metadata = []
75
+ let pending = ''
76
+ child.stdout.setEncoding('utf8')
77
+ child.stdout.on('data', (chunk) => {
78
+ const text = pending + chunk
79
+ let start = 0
80
+ for (let nl = text.indexOf('\\n'); nl !== -1; nl = text.indexOf('\\n', start)) {
81
+ if (text.charCodeAt(start) === 33) metadata.push(text.slice(start, nl))
82
+ start = nl + 1
83
+ }
84
+ pending = text.slice(start)
85
+ })
71
86
  child.on('error', reject)
72
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
87
+ child.on('close', (code) => {
88
+ if (pending.charCodeAt(0) === 33) metadata.push(pending)
89
+ if (code === 0) {
90
+ results[index] = metadata.join('\\n')
91
+ resolve()
92
+ } else reject(new Error('clang link replay failed: ' + file))
93
+ })
73
94
  }).then(run)
74
95
  }
75
96
  const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
76
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
77
- console.error(error.message)
78
- process.exit(1)
79
- })
97
+ Promise.all(Array.from({ length: jobs }, run))
98
+ .then(() => {
99
+ fs.writeFileSync(process.env.PEACH_CLANG_RESULTS, JSON.stringify(results))
100
+ })
101
+ .catch((error) => {
102
+ console.error(error.message)
103
+ process.exit(1)
104
+ })
80
105
  `
81
106
 
82
107
  function clangProducerStamp(file: string): string {
@@ -84,6 +109,89 @@ function clangProducerStamp(file: string): string {
84
109
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(':')
85
110
  }
86
111
 
112
+ function clangBinaryStamp(file: string): string {
113
+ const stat = statSync(file, { bigint: true })
114
+ return [file, stat.size, stat.mtimeNs].join(':')
115
+ }
116
+
117
+ function clangWrapperStamp(file: string): string {
118
+ return createHash('sha256').update(readFileSync(file)).digest('hex')
119
+ }
120
+
121
+ function clangArgsNeedCwd(args: readonly string[]): boolean {
122
+ const pathFlags = new Set([
123
+ '-I',
124
+ '-isystem',
125
+ '-iquote',
126
+ '-F',
127
+ '-iframework',
128
+ '-isysroot',
129
+ '-o',
130
+ '-MF',
131
+ ])
132
+ const includeFlags = new Set(['-include', '-imacros'])
133
+ const valueFlags = new Set([
134
+ '-x',
135
+ '-target',
136
+ '-MT',
137
+ '-MQ',
138
+ '-D',
139
+ '-U',
140
+ '-mllvm',
141
+ '-Xclang',
142
+ '-arch',
143
+ '-std',
144
+ ])
145
+ const prefixFlags = [
146
+ '-I',
147
+ '-F',
148
+ '-isystem',
149
+ '-iquote',
150
+ '--sysroot=',
151
+ '-fmodule-map-file=',
152
+ '-fmodules-cache-path=',
153
+ ]
154
+ const isRelativePath = (value: string) =>
155
+ value.length > 0 && !value.startsWith('/') && !value.startsWith('=/') && value !== '-'
156
+ for (let i = 1; i < args.length; i++) {
157
+ const arg = args[i]!
158
+ if (pathFlags.has(arg)) {
159
+ if (isRelativePath(args[++i] ?? '')) return true
160
+ continue
161
+ }
162
+ if (includeFlags.has(arg)) {
163
+ const value = args[++i] ?? ''
164
+ if (isRelativePath(value) && (value.includes('/') || existsSync(value))) return true
165
+ continue
166
+ }
167
+ if (valueFlags.has(arg)) {
168
+ i++
169
+ continue
170
+ }
171
+ if (arg.startsWith('@')) {
172
+ if (isRelativePath(arg.slice(1))) return true
173
+ continue
174
+ }
175
+ if (arg.startsWith('-')) {
176
+ if (arg.startsWith('-include') && arg.length > 8) {
177
+ const value = arg.slice(8)
178
+ if (isRelativePath(value) && (value.includes('/') || existsSync(value)))
179
+ return true
180
+ continue
181
+ }
182
+ for (const prefix of prefixFlags) {
183
+ if (arg.startsWith(prefix) && arg.length > prefix.length) {
184
+ if (isRelativePath(arg.slice(prefix.length))) return true
185
+ break
186
+ }
187
+ }
188
+ continue
189
+ }
190
+ if (isRelativePath(arg)) return true
191
+ }
192
+ return false
193
+ }
194
+
87
195
  function validateClangLinkOptions(flags: readonly string[]): void {
88
196
  for (let index = 0; index < flags.length; index++) {
89
197
  const flag = flags[index]!
@@ -184,14 +292,13 @@ export function sourceGuestClangLinkOptions(options: {
184
292
  file: string
185
293
  compiler: string
186
294
  args: string[]
187
- output: string
188
295
  cacheFile: string
189
296
  key: string
190
297
  }[] = []
191
298
  let clang: string | undefined
192
299
  let clangStamp: string | undefined
193
300
  let wrapperStamp: string | undefined
194
- for (const [index, file] of [...wanted].entries()) {
301
+ for (const file of wanted) {
195
302
  const command = commands.get(file)
196
303
  if (!command) throw new Error(`missing source object producer ${file}`)
197
304
  if (command.tool === 'shell') {
@@ -216,12 +323,12 @@ export function sourceGuestClangLinkOptions(options: {
216
323
  const key = createHash('sha256')
217
324
  .update(
218
325
  JSON.stringify([
219
- 'clang-link-options/v1',
220
- process.cwd(),
326
+ 'clang-link-options/v2',
327
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
221
328
  driverEnvironment,
222
329
  command.args,
223
- (clangStamp ??= clangProducerStamp(clang)),
224
- compiler === clang ? null : (wrapperStamp ??= clangProducerStamp(compiler)),
330
+ (clangStamp ??= clangBinaryStamp(clang)),
331
+ compiler === clang ? null : (wrapperStamp ??= clangWrapperStamp(compiler)),
225
332
  clangProducerStamp(file),
226
333
  ]),
227
334
  )
@@ -237,29 +344,41 @@ export function sourceGuestClangLinkOptions(options: {
237
344
  continue
238
345
  }
239
346
  result.set(file, [])
240
- const args = command.args.slice(1).filter((arg) => arg !== '-c')
241
- // the replay keeps the object's <target>.build directory name
347
+ // pipe IR to stdout without writing .ll or .d files; preserve .peach-clang's module name.
242
348
  const targetBuild = path
243
349
  .relative(options.buildDirectory, file)
244
350
  .split(path.sep)
245
351
  .findLast((part) => part !== '.build' && part.endsWith('.build'))
246
- const outputDirectory = path.join(
247
- options.directory,
248
- targetBuild ?? path.basename(path.dirname(file)),
249
- )
250
- mkdirSync(outputDirectory, { recursive: true })
251
- const output = path.join(outputDirectory, `clang-link-${index}.ll`)
252
- for (const flag of ['-o', '-MF']) {
253
- const index = args.lastIndexOf(flag)
254
- if (index < 0 || index + 1 >= args.length)
255
- throw new Error(`missing clang ${flag} for ${file}`)
256
- args[index + 1] = flag === '-o' ? output : `${output}.d`
352
+ const args: string[] = []
353
+ let sawOutput = false
354
+ let explicitModuleName = false
355
+ for (let i = 1; i < command.args.length; i++) {
356
+ const arg = command.args[i]!
357
+ if (arg === '-c' || arg === '-MD' || arg === '-MMD' || arg === '-MP') continue
358
+ if (arg === '-MF' || arg === '-MT' || arg === '-MQ') {
359
+ if (i + 1 >= command.args.length)
360
+ throw new Error(`missing clang ${arg} for ${file}`)
361
+ i++
362
+ continue
363
+ }
364
+ if (arg === '-o') {
365
+ if (i + 1 >= command.args.length) throw new Error(`missing clang -o for ${file}`)
366
+ i++
367
+ args.push('-o', '-')
368
+ sawOutput = true
369
+ continue
370
+ }
371
+ if (arg.startsWith('-fmodule-name=')) explicitModuleName = true
372
+ args.push(arg)
373
+ }
374
+ if (!sawOutput) throw new Error(`missing clang -o for ${file}`)
375
+ if (compiler !== clang && targetBuild && !explicitModuleName) {
376
+ args.unshift(`-fmodule-name=${targetBuild.slice(0, -'.build'.length)}`)
257
377
  }
258
378
  replays.push({
259
379
  file,
260
380
  compiler: command.args[0]!,
261
381
  args: [...args, '-S', '-emit-llvm', '-Xclang', '-disable-llvm-passes'],
262
- output,
263
382
  cacheFile,
264
383
  key,
265
384
  })
@@ -267,6 +386,7 @@ export function sourceGuestClangLinkOptions(options: {
267
386
  if (replays.length === 0) return result
268
387
  // the pruner's plan callback is synchronous, so one child runs the replays concurrently
269
388
  const plan = path.join(options.directory, 'clang-link-replays.json')
389
+ const resultsPath = path.join(options.directory, 'clang-link-results.json')
270
390
  writeFileSync(
271
391
  plan,
272
392
  JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args])),
@@ -279,12 +399,20 @@ export function sourceGuestClangLinkOptions(options: {
279
399
  ...process.env,
280
400
  [PEACH_FORKED_SCRIPT_ENV]: '1',
281
401
  PEACH_CLANG_REPLAYS: plan,
402
+ PEACH_CLANG_RESULTS: resultsPath,
282
403
  PEACH_CLANG_JOBS: String(options.jobs),
283
404
  },
284
405
  })
406
+ const replayMetadata: unknown = JSON.parse(readFileSync(resultsPath, 'utf8'))
407
+ if (
408
+ !Array.isArray(replayMetadata) ||
409
+ replayMetadata.length !== replays.length ||
410
+ !replayMetadata.every((item) => typeof item === 'string')
411
+ )
412
+ throw new Error('invalid clang link replay results')
285
413
  mkdirSync(cacheDirectory, { recursive: true })
286
- for (const { file, output, cacheFile, key } of replays) {
287
- const flags = clangIrLinkOptions(readFileSync(output, 'utf8'))
414
+ for (const [index, { file, cacheFile, key }] of replays.entries()) {
415
+ const flags = clangIrLinkOptions(replayMetadata[index]!)
288
416
  validateClangLinkOptions(flags)
289
417
  const temporary = `${cacheFile}.${process.pid}`
290
418
  writeFileSync(temporary, JSON.stringify({ key, flags }))
@@ -242,15 +242,18 @@ async function compileSdkForwarders(
242
242
  index++
243
243
  }
244
244
  const errno = tls.errno
245
+ let declaredErrno = false
245
246
  for (const name of referenced) {
246
247
  const offset = tls[name]
247
248
  if (offset === undefined || defined.has(name)) continue
248
249
  if (errno === undefined || signatures.__errno_location !== ':j')
249
250
  throw new Error('the sdk image has no errno to find its thread block by')
250
- if (!lines.some((line) => line.startsWith('char *__peach_errno(')))
251
+ if (!declaredErrno) {
252
+ declaredErrno = true
251
253
  lines.push(
252
254
  `__attribute__((import_module("env"), import_name("__errno_location"))) char *__peach_errno(void);`,
253
255
  )
256
+ }
254
257
  // the sdk's thread block starts errno's offset below errno
255
258
  lines.push(
256
259
  `__attribute__((weak)) _Thread_local char t${index} __asm__(${literal(name)});`,
@@ -717,6 +720,20 @@ function resolveSdkReferences(
717
720
  .map((symbol) => [symbol.name.slice(SDK_TLS_HELPER.length), symbol.index]),
718
721
  )
719
722
  const segments = guestWasmDataSegments(bytes, false)
723
+ const segmentsByOffset = [...segments].sort((a, b) => a.offset - b.offset)
724
+ const segmentNameSet = new Set(segmentNames)
725
+ const findSegmentByOffset = (at: number, size: number) => {
726
+ let lo = 0
727
+ let hi = segmentsByOffset.length - 1
728
+ while (lo <= hi) {
729
+ const mid = (lo + hi) >> 1
730
+ const entry = segmentsByOffset[mid]!
731
+ if (at < entry.offset) hi = mid - 1
732
+ else if (at >= entry.offset + entry.length) lo = mid + 1
733
+ else return at + size <= entry.offset + entry.length ? entry : undefined
734
+ }
735
+ return undefined
736
+ }
720
737
  const tdata = segmentNames.indexOf('.tdata')
721
738
  const tlsTemplate = tdata < 0 ? undefined : passiveSegments(bytes)[tdata]
722
739
  const tlsStart = tlsTemplate && tlsTemplate.byteOffset - bytes.byteOffset
@@ -789,7 +806,7 @@ function resolveSdkReferences(
789
806
  const encoding = width.width
790
807
  if (kind === 'address' && target.id === 11 && encoding === 'u64' && addend === 0n) {
791
808
  const section = OBJC_SECTION_BOUNDARY.exec(name)?.[1]
792
- if (section && !segmentNames.includes(section)) {
809
+ if (section && !segmentNameSet.has(section)) {
793
810
  // objc's app initializer uses a null range for an absent app section.
794
811
  bytes.fill(0, at, at + 8)
795
812
  continue
@@ -806,9 +823,7 @@ function resolveSdkReferences(
806
823
  )
807
824
  linkage.tls.push(at - tlsStart, size, value)
808
825
  else {
809
- const segment = segments.find(
810
- (entry) => at >= entry.offset && at + size <= entry.offset + entry.length,
811
- )
826
+ const segment = findSegmentByOffset(at, size)
812
827
  if (!segment)
813
828
  throw new Error(`Swift SDK relocation has no load address for ${name}`)
814
829
  linkage.data.push(segment.address + at - segment.offset, size, value)
@@ -855,18 +870,32 @@ function resolveSdkReferences(
855
870
  }
856
871
  }
857
872
  }
858
- const entries = imports.map((entry) => {
873
+ const encodedNameBuf = (name: string): Buffer => {
874
+ const raw = Buffer.from(name, 'utf8')
875
+ const len = uleb(raw.length)
876
+ const out = Buffer.allocUnsafe(len.length + raw.length)
877
+ for (let i = 0; i < len.length; i++) out[i] = len[i]!
878
+ raw.copy(out, len.length)
879
+ return out
880
+ }
881
+ const importParts: Uint8Array[] = []
882
+ let importEntryCount = imports.length + 1
883
+ for (const entry of imports) {
859
884
  const slot =
860
885
  entry.kind === 0 && entry.module === 'env'
861
886
  ? functionSlots.get(entry.name)
862
887
  : undefined
863
- return [
864
- ...encodedName(slot === undefined ? entry.module : NATIVE_SDK_IMPORT_MODULE),
865
- ...encodedName(slot === undefined ? entry.name : String(slot)),
866
- ...bytes.subarray(entry.start, entry.end),
867
- ]
868
- })
869
- entries.push([...encodedName('env'), ...encodedName('__stack_pointer'), 3, 0x7e, 1])
888
+ importParts.push(
889
+ encodedNameBuf(slot === undefined ? entry.module : NATIVE_SDK_IMPORT_MODULE),
890
+ encodedNameBuf(slot === undefined ? entry.name : String(slot)),
891
+ bytes.subarray(entry.start, entry.end),
892
+ )
893
+ }
894
+ importParts.push(
895
+ encodedNameBuf('env'),
896
+ encodedNameBuf('__stack_pointer'),
897
+ Buffer.from([3, 0x7e, 1]),
898
+ )
870
899
  const tags = sections.find((section) => section.id === 13)
871
900
  if (tags) {
872
901
  const r = wasmReader(bytes, tags.start)
@@ -886,15 +915,18 @@ function resolveSdkReferences(
886
915
  throw new Error(
887
916
  `Swift app defines an exception tag the sdk does not own: ${name}`,
888
917
  )
889
- entries.push([
890
- ...encodedName('env'),
891
- ...encodedName(name),
892
- 4,
893
- ...bytes.subarray(start, r.at),
894
- ])
918
+ importParts.push(
919
+ encodedNameBuf('env'),
920
+ encodedNameBuf(name),
921
+ Buffer.from([4]),
922
+ bytes.subarray(start, r.at),
923
+ )
924
+ importEntryCount++
895
925
  }
896
926
  }
897
- const globals: number[] = []
927
+ const globalParts: Uint8Array[] = [
928
+ Buffer.from(uleb(globalCount - 1 + syntheticGlobals.length)),
929
+ ]
898
930
  for (let index = 0; index < globalCount; index++) {
899
931
  const start = gr.at
900
932
  const type = gr.byte()
@@ -907,8 +939,8 @@ function resolveSdkReferences(
907
939
  // the first global is __stack_pointer, which becomes the sdk's import
908
940
  if (index === 0) continue
909
941
  const value = got.get(index)
910
- if (value === undefined) globals.push(...bytes.subarray(start, gr.at))
911
- else globals.push(type, 1, type === 0x7e ? 0x42 : 0x41, 0, 0x0b)
942
+ if (value === undefined) globalParts.push(bytes.subarray(start, gr.at))
943
+ else globalParts.push(Buffer.from([type, 1, type === 0x7e ? 0x42 : 0x41, 0, 0x0b]))
912
944
  }
913
945
  for (const type of syntheticGlobals) {
914
946
  const zero =
@@ -917,7 +949,7 @@ function resolveSdkReferences(
917
949
  : type === 0x7c
918
950
  ? [0x44, 0, 0, 0, 0, 0, 0, 0, 0]
919
951
  : [type === 0x7e ? 0x42 : 0x41, 0]
920
- globals.push(type, 1, ...zero, 0x0b)
952
+ globalParts.push(Buffer.from([type, 1, ...zero, 0x0b]))
921
953
  }
922
954
  const exportSection = sections.find((s) => s.id === 7)
923
955
  if (!exportSection) throw new Error('app link has no exports')
@@ -940,24 +972,21 @@ function resolveSdkReferences(
940
972
  throw new Error('Swift app exceeds its reserved static memory range')
941
973
  }
942
974
  }
943
- const replaced = new Map<number, number[]>([
944
- [2, [...uleb(entries.length), ...entries.flat()]],
945
- [6, [...uleb(globalCount - 1 + syntheticGlobals.length), ...globals]],
946
- [
947
- 7,
948
- [
949
- ...uleb(exportCount + 1 + got.size),
950
- ...bytes.subarray(originalExportsStart, exportSection.end),
951
- ...[...got].flatMap(([index, value]) => [
952
- ...encodedName(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
953
- 3,
954
- ...uleb(index),
955
- ]),
956
- ...encodedName('__indirect_function_table'),
957
- 1,
958
- 0,
959
- ],
960
- ],
975
+ const exportParts: Uint8Array[] = [
976
+ Buffer.from(uleb(exportCount + 1 + got.size)),
977
+ bytes.subarray(originalExportsStart, exportSection.end),
978
+ ]
979
+ for (const [index, value] of got) {
980
+ exportParts.push(
981
+ encodedNameBuf(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
982
+ Buffer.from([3, ...uleb(index)]),
983
+ )
984
+ }
985
+ exportParts.push(encodedNameBuf('__indirect_function_table'), Buffer.from([1, 0]))
986
+ const replaced = new Map<number, Buffer>([
987
+ [2, Buffer.concat([Buffer.from(uleb(importEntryCount)), ...importParts])],
988
+ [6, Buffer.concat(globalParts)],
989
+ [7, Buffer.concat(exportParts)],
961
990
  ])
962
991
  const rebuiltCode = expanded.length
963
992
  ? expandSdkRelocations(
@@ -976,13 +1005,13 @@ function resolveSdkReferences(
976
1005
  )
977
1006
  continue
978
1007
  const payload = replaced.get(s.id)
979
- parts.push(
980
- s.id === 10 && rebuiltCode
981
- ? rebuiltCode
982
- : payload
983
- ? Uint8Array.from([s.id, ...uleb(payload.length), ...payload])
984
- : bytes.subarray(s.offset, s.end),
985
- )
1008
+ if (s.id === 10 && rebuiltCode) {
1009
+ parts.push(rebuiltCode)
1010
+ } else if (payload) {
1011
+ parts.push(Buffer.from([s.id, ...uleb(payload.length)]), payload)
1012
+ } else {
1013
+ parts.push(bytes.subarray(s.offset, s.end))
1014
+ }
986
1015
  }
987
1016
  return { bytes: Buffer.concat(parts), linkage }
988
1017
  }
@@ -1134,6 +1163,54 @@ export function readSwiftSdkUsage(
1134
1163
  }
1135
1164
  }
1136
1165
 
1166
+ /** SDK address and table spans owned by guest images, independent of app module layout. */
1167
+ export function swiftSdkProjectionSpans(
1168
+ sdk: SwiftSdkImage,
1169
+ imageFor: (object: string, product: string) => number | undefined,
1170
+ ): GuestLinkedSpan[] {
1171
+ const { manifest, block } = readSwiftSdkManifest(sdk)
1172
+ const guestObjects = manifest.guestObjects
1173
+ if (!guestObjects) return []
1174
+ const { strings } = manifest
1175
+ const fields = block('pieces')
1176
+ const ordered: { object: string; address: number; size: number }[] = []
1177
+ for (let i = 0; i < fields.length; i += SWIFT_SDK_PIECE_FIELDS) {
1178
+ const size = fields[i + 1]!
1179
+ if (!size) continue
1180
+ ordered.push({
1181
+ address: fields[i]!,
1182
+ size,
1183
+ object: strings[fields[i + 3]!]!,
1184
+ })
1185
+ }
1186
+ ordered.sort((a, b) => a.address - b.address)
1187
+ const imageOf = (object: string) => {
1188
+ const product = guestObjects[object]?.product
1189
+ return product === undefined ? undefined : imageFor(object, product)
1190
+ }
1191
+ const spans: GuestLinkedSpan[] = []
1192
+ for (let index = 0; index < ordered.length; index++) {
1193
+ const { object, address, size } = ordered[index]!
1194
+ const image = imageOf(object)
1195
+ if (image === undefined) continue
1196
+ let next = index + 1
1197
+ while (next < ordered.length && ordered[next]!.address < address + size) next++
1198
+ const end = ordered[next]?.address ?? address + size
1199
+ spans.push({ image, space: 'linear-memory', address, length: end - address })
1200
+ }
1201
+ const functionKeys = block('functions')
1202
+ const slots = block('functionSlots')
1203
+ for (let index = 0; index < functionKeys.length; index++) {
1204
+ const slot = slots[index]!
1205
+ if (!slot) continue
1206
+ const key = strings[functionKeys[index]!]!
1207
+ const image = imageOf(key.slice(0, key.indexOf(':')))
1208
+ if (image !== undefined)
1209
+ spans.push({ image, space: 'function-table', address: slot, length: 1 })
1210
+ }
1211
+ return spans
1212
+ }
1213
+
1137
1214
  /**
1138
1215
  * the sdk data an app uses, as runs the loader writes before the sdk instantiates: the data
1139
1216
  * pieces its pruned link keeps, their transitive dependencies, the live swift record table and
@@ -1167,18 +1244,31 @@ export function selectSwiftSdkData(
1167
1244
  })
1168
1245
  }
1169
1246
  const memory = new Map(segments.map((segment) => [segment.name, segment]))
1170
- const read = (address: number, size: number) => {
1247
+ let lastSegment = segments[0]
1248
+ const segmentAt = (address: number, size: number) => {
1249
+ if (
1250
+ lastSegment &&
1251
+ address >= lastSegment.address &&
1252
+ address + size <= lastSegment.address + lastSegment.data.length
1253
+ )
1254
+ return lastSegment
1171
1255
  for (const segment of segments)
1172
1256
  if (
1173
1257
  address >= segment.address &&
1174
1258
  address + size <= segment.address + segment.data.length
1175
- )
1176
- return segment.data.subarray(
1177
- address - segment.address,
1178
- address - segment.address + size,
1179
- )
1259
+ ) {
1260
+ lastSegment = segment
1261
+ return segment
1262
+ }
1180
1263
  return undefined
1181
1264
  }
1265
+ const read = (address: number, size: number) => {
1266
+ const segment = segmentAt(address, size)
1267
+ return segment?.data.subarray(
1268
+ address - segment.address,
1269
+ address - segment.address + size,
1270
+ )
1271
+ }
1182
1272
  const appSectionsByObject = new Map<string, Set<string>>()
1183
1273
  const appSections = new Set<string>()
1184
1274
  const appSymbols = new Set<string>()
@@ -1295,10 +1385,7 @@ export function selectSwiftSdkData(
1295
1385
  const classAddress = Number(
1296
1386
  new DataView(field.buffer, field.byteOffset, 8).getBigUint64(0, true),
1297
1387
  )
1298
- const segment = segments.find(
1299
- ({ address, data }) =>
1300
- classAddress >= address && classAddress < address + data.length,
1301
- )
1388
+ const segment = segmentAt(classAddress, 1)
1302
1389
  if (!segment) continue
1303
1390
  const start = classAddress - segment.address
1304
1391
  const end = segment.data.indexOf(0, start)
@@ -1546,7 +1633,7 @@ export function selectSwiftSdkData(
1546
1633
  if (current)
1547
1634
  runs.push({
1548
1635
  address: current.address,
1549
- bytes: Uint8Array.from(Buffer.concat(current.parts)),
1636
+ bytes: Buffer.concat(current.parts),
1550
1637
  })
1551
1638
  }
1552
1639
  for (const piece of loaded) {