peachsim 0.1.2589 → 0.1.2590

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 (137) 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 +1172 -446
  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-65FNEARV.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-EAIFG4MQ.mjs → chunk-2GUB5OLB.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-FQQ2DMXS.mjs → chunk-462CWTWI.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-L3OSVIGA.mjs → chunk-4VCRUQ36.mjs} +1178 -452
  30. package/dist-lib/esm-chunks/{chunk-5QWQDXXD.mjs → chunk-5GNGHM5B.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-JLOJZF2Y.mjs → chunk-ADKUIQXX.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-M4KUWGU3.mjs → chunk-BZS5SIYK.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-47K4QPVA.mjs → chunk-EFKDUMB5.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-I22LAVD5.mjs → chunk-GBD26EBV.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-CRIYVOMB.mjs → chunk-HZTK7TP5.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-5EFD2VBY.mjs → chunk-JG4AANWA.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-FMWEI6OI.mjs → chunk-N2II5SRJ.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-33SCXU3Y.mjs → chunk-NZY4GOG5.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-KFHCRS5K.mjs → chunk-OZJ66CXY.mjs} +2 -2
  40. package/dist-lib/esm-chunks/{chunk-464CBA5U.mjs → chunk-RGC2JNCL.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-57FFWABF.mjs → chunk-SLPXTLBK.mjs} +5 -5
  42. package/dist-lib/esm-chunks/{chunk-Y4PV4HZB.mjs → chunk-SRFKOU76.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-3VNUC4DT.mjs → chunk-V5TTEXYO.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-MKSOJCRT.mjs → chunk-WPDY5IAD.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-WQ73RKJY.mjs → chunk-WYDRQRJL.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-BSAAJR25.mjs → chunk-X2EKFONU.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-PUBH3EXI.mjs → chunk-XE3VHAU2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-XTKKROVU.mjs → chunk-YPPH6F77.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-T5QIJTEV.mjs → metro-layout-parser-CRI3GMCM.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-AWTZHPDM.mjs → swift-package-prebuilt-5XDZ2HZZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-MGTJTVKU.mjs → swift-sdk-app-module-6H3G6AXD.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-JABGF3ZR.mjs → swift-sdk-image-WAC7GG2R.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-RJRJ3EFU.mjs → swift-sdk-image-producer-B3L27QTG.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1171 -445
  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 +1200 -469
  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 +1202 -471
  93. package/dist-lib/swift-compile.cjs +1168 -442
  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 +2 -2
  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 +255 -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-sdk-image-map.ts +137 -35
  136. package/src/swift-wasm-prune.ts +263 -85
  137. package/src/swiftGuestImageContract.ts +1 -1
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2589 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2590 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  let __sootsim_import_meta_url = '', __sootsim_import_meta_dirname = '', __sootsim_import_meta_filename = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; __sootsim_import_meta_dirname = __dirname; __sootsim_import_meta_filename = __filename; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
@@ -6192,24 +6192,56 @@ function layout(bytes, readData = true, requireExports = true) {
6192
6192
  const code = sections.get(10);
6193
6193
  if (code) {
6194
6194
  let pos = code[0];
6195
- let count;
6196
- [count, pos] = number(bytes, pos);
6195
+ const codeStart = code[0];
6196
+ const codeEnd = code[1];
6197
+ let count = 0;
6198
+ {
6199
+ let shift = 0;
6200
+ for (; ; ) {
6201
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
6202
+ const byte = bytes[pos++];
6203
+ count += (byte & 127) * 2 ** shift;
6204
+ if (!(byte & 128)) break;
6205
+ shift += 7;
6206
+ }
6207
+ }
6197
6208
  for (let i = 0; i < count; i++) {
6198
6209
  const prefix = pos;
6199
- let size;
6200
- [size, pos] = number(bytes, pos);
6201
- functionsByCodeOffset.set(prefix - code[0], imports + i);
6210
+ let size = 0;
6211
+ const b0 = bytes[pos++];
6212
+ if (b0 < 128) {
6213
+ size = b0;
6214
+ } else {
6215
+ size = b0 & 127;
6216
+ let shift = 7;
6217
+ for (; ; ) {
6218
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
6219
+ const byte = bytes[pos++];
6220
+ size += (byte & 127) * 2 ** shift;
6221
+ if (!(byte & 128)) break;
6222
+ shift += 7;
6223
+ }
6224
+ }
6225
+ functionsByCodeOffset.set(prefix - codeStart, imports + i);
6202
6226
  if (imports + i === startFunction) startup = bytes.subarray(pos, pos + size);
6203
6227
  pos += size;
6204
- if (pos > code[1]) throw new Error("invalid wasm code");
6228
+ if (pos > codeEnd) throw new Error("invalid wasm code");
6205
6229
  }
6206
- if (pos !== code[1]) throw new Error("invalid wasm code section");
6230
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
6207
6231
  }
6208
6232
  const functionsByTableSlot = /* @__PURE__ */ new Map();
6209
6233
  const elements = sections.get(9);
6210
6234
  if (elements) {
6211
6235
  let pos = elements[0];
6236
+ const elemEnd = elements[1];
6212
6237
  const read = () => {
6238
+ if (pos < elemEnd) {
6239
+ const b0 = bytes[pos];
6240
+ if (b0 < 128) {
6241
+ pos++;
6242
+ return b0;
6243
+ }
6244
+ }
6213
6245
  const [value, next] = number(bytes, pos);
6214
6246
  pos = next;
6215
6247
  return value;
@@ -6239,7 +6271,7 @@ function layout(bytes, readData = true, requireExports = true) {
6239
6271
  functionsByTableSlot.set(slot, read());
6240
6272
  }
6241
6273
  }
6242
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
6274
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
6243
6275
  }
6244
6276
  const data = [];
6245
6277
  const passive = /* @__PURE__ */ new Map();
@@ -6304,36 +6336,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
6304
6336
  length: segment.bytes.length
6305
6337
  }));
6306
6338
  }
6307
- function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
6339
+ function isMapSpace(code) {
6340
+ return code === 32 || code >= 9 && code <= 13;
6341
+ }
6342
+ function isMapHex(code) {
6343
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
6344
+ }
6345
+ function mapHexDigit(code) {
6346
+ return code <= 57 ? code - 48 : code - 87;
6347
+ }
6348
+ function* stringLines(text2) {
6349
+ let start = 0;
6350
+ for (let end = text2.indexOf("\n"); end !== -1; end = text2.indexOf("\n", start)) {
6351
+ yield text2.slice(start, end);
6352
+ start = end + 1;
6353
+ }
6354
+ yield text2.slice(start);
6355
+ }
6356
+ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
6308
6357
  const unchanged = before === after;
6309
6358
  const original = layout(before, !unchanged, !importsLayout);
6310
6359
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
6360
+ const collectSymbols = extra?.collectSymbols;
6361
+ const trackedObject = extra?.trackedObject;
6362
+ const trackedObjectOwner = extra?.trackedObjectOwner;
6363
+ const trackedLinearSpans = extra?.trackedLinearSpans;
6364
+ const hasSectionOwners = sectionOwners.size > 0;
6311
6365
  let codeOffset;
6312
6366
  let outputSection = "";
6313
6367
  const codeOwners = /* @__PURE__ */ new Map();
6314
6368
  const pieces = [];
6315
- for (const line of typeof map === "string" ? map.split("\n") : map) {
6316
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
6317
- if (!match) continue;
6318
- const [, address, offset, size, indent, source] = match;
6319
- if (address === "-" && indent === " ") {
6320
- outputSection = source;
6321
- if (source === "CODE") codeOffset = parseInt(offset, 16);
6369
+ const lines = typeof map === "string" ? stringLines(map) : map;
6370
+ for (const line of lines) {
6371
+ const lineLen = line.length;
6372
+ let pos = 0;
6373
+ let onlySpaces = true;
6374
+ while (pos < lineLen) {
6375
+ const ch = line.charCodeAt(pos);
6376
+ if (!isMapSpace(ch)) break;
6377
+ if (ch !== 32) onlySpaces = false;
6378
+ pos++;
6379
+ }
6380
+ const leadingSpaces = pos;
6381
+ if (pos >= lineLen) continue;
6382
+ const addrStart = pos;
6383
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
6384
+ const addrEnd = pos;
6385
+ if (pos >= lineLen) continue;
6386
+ const s1 = pos;
6387
+ while (pos < lineLen) {
6388
+ const ch = line.charCodeAt(pos);
6389
+ if (!isMapSpace(ch)) break;
6390
+ if (ch !== 32) onlySpaces = false;
6391
+ pos++;
6392
+ }
6393
+ if (pos === s1 || pos >= lineLen) continue;
6394
+ const offStart = pos;
6395
+ let offsetVal = 0;
6396
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
6397
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
6398
+ }
6399
+ if (pos === offStart || pos >= lineLen) continue;
6400
+ const s2 = pos;
6401
+ while (pos < lineLen) {
6402
+ const ch = line.charCodeAt(pos);
6403
+ if (!isMapSpace(ch)) break;
6404
+ if (ch !== 32) onlySpaces = false;
6405
+ pos++;
6406
+ }
6407
+ if (pos === s2 || pos >= lineLen) continue;
6408
+ const sizeStart = pos;
6409
+ let sizeVal = 0;
6410
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
6411
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
6412
+ }
6413
+ if (pos === sizeStart || pos >= lineLen) continue;
6414
+ const indentStart = pos;
6415
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
6416
+ const indentLen = pos - indentStart;
6417
+ if (indentLen === 0 || pos >= lineLen) continue;
6418
+ const firstCh = line.charCodeAt(pos);
6419
+ if (isMapSpace(firstCh)) continue;
6420
+ const sourceStart = pos;
6421
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
6422
+ let symEnd = sourceStart + 1;
6423
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
6424
+ collectSymbols.add(line.slice(sourceStart, symEnd));
6425
+ }
6426
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
6427
+ if (isDash && indentLen === 1) {
6428
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
6429
+ outputSection = line.slice(sourceStart);
6430
+ if (outputSection === "CODE") codeOffset = offsetVal;
6322
6431
  continue;
6323
6432
  }
6324
- const separator = source.indexOf(":(");
6433
+ if (sizeVal === 0) continue;
6434
+ const separator = line.indexOf(":(", sourceStart);
6325
6435
  if (separator < 0) continue;
6326
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
6327
- const length = parseInt(size, 16);
6328
- if (!length) continue;
6329
- if (address !== "-") {
6330
- if (outputSection === "DATA")
6331
- pieces.push({ image, address: parseInt(address, 16), length });
6436
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
6437
+ let hasLineSep = false;
6438
+ for (let i = sourceStart; i < lineLen; i++) {
6439
+ const ch = line.charCodeAt(i);
6440
+ if (ch === 8232 || ch === 8233) {
6441
+ hasLineSep = true;
6442
+ break;
6443
+ }
6444
+ }
6445
+ if (hasLineSep) continue;
6446
+ const objectPath = line.slice(sourceStart, separator);
6447
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
6448
+ if (image === void 0) image = owners.get(objectPath);
6449
+ if (!isDash) {
6450
+ if (outputSection === "DATA") {
6451
+ let addressVal = 0;
6452
+ let allHex = true;
6453
+ for (let i = addrStart; i < addrEnd; i++) {
6454
+ const ch = line.charCodeAt(i);
6455
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
6456
+ else {
6457
+ allHex = false;
6458
+ break;
6459
+ }
6460
+ }
6461
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
6462
+ pieces.push({
6463
+ image,
6464
+ address: addressVal,
6465
+ length: sizeVal,
6466
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
6467
+ });
6468
+ }
6332
6469
  continue;
6333
6470
  }
6334
6471
  if (image === void 0 || outputSection !== "CODE") continue;
6335
6472
  if (codeOffset === void 0) throw new Error("link map has no code section");
6336
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
6473
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
6337
6474
  if (index === void 0) throw new Error("link map function has no wasm body");
6338
6475
  const existing = codeOwners.get(index);
6339
6476
  if (existing !== void 0 && existing !== image)
@@ -6342,12 +6479,23 @@ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE
6342
6479
  }
6343
6480
  pieces.sort((a, b) => a.address - b.address);
6344
6481
  const spans = [];
6345
- for (const [index, { image, address, length }] of pieces.entries()) {
6346
- if (image === void 0) continue;
6482
+ for (let index = 0; index < pieces.length; index++) {
6483
+ const piece = pieces[index];
6484
+ const { image, address, length, tracked } = piece;
6485
+ if (image === void 0 && !tracked) continue;
6347
6486
  let next = index + 1;
6348
6487
  while (next < pieces.length && pieces[next].address < address + length) next++;
6349
6488
  const end = pieces[next]?.address ?? address + length;
6350
- spans.push({ image, space: "linear-memory", address, length: end - address });
6489
+ const spanLength = end - address;
6490
+ if (image !== void 0)
6491
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
6492
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
6493
+ trackedLinearSpans.push({
6494
+ image: trackedObjectOwner,
6495
+ space: "linear-memory",
6496
+ address,
6497
+ length: spanLength
6498
+ });
6351
6499
  }
6352
6500
  const optimizedOwners = /* @__PURE__ */ new Map();
6353
6501
  const dataAt = (module2, start, length) => {
@@ -6386,7 +6534,7 @@ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE
6386
6534
  throw new Error(`optimization changed linked data at ${span.address}`);
6387
6535
  }
6388
6536
  let previous;
6389
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
6537
+ for (const span of spans) {
6390
6538
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
6391
6539
  throw new Error("linked data belongs to multiple images");
6392
6540
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -6568,6 +6716,20 @@ var init_swift_guest_linked_spans = __esm({
6568
6716
  });
6569
6717
 
6570
6718
  // src/swift-sdk-image-map.ts
6719
+ function isHexChar(code) {
6720
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
6721
+ }
6722
+ function hexDigit(code) {
6723
+ return code <= 57 ? code - 48 : code - 87;
6724
+ }
6725
+ function hasLineBreak(line, from) {
6726
+ if (line.indexOf("\r", from) >= 0) return true;
6727
+ for (let i = from; i < line.length; i++) {
6728
+ const ch = line.charCodeAt(i);
6729
+ if (ch === 8232 || ch === 8233) return true;
6730
+ }
6731
+ return false;
6732
+ }
6571
6733
  function readWasmLinkMap(file, partition) {
6572
6734
  const segments = /* @__PURE__ */ new Map();
6573
6735
  const data = [];
@@ -6575,48 +6737,117 @@ function readWasmLinkMap(file, partition) {
6575
6737
  let kind = "";
6576
6738
  let segment = "";
6577
6739
  let previous;
6578
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
6579
6740
  for (const line of guestLinkLines(file)) {
6580
- const symbol = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
6581
- if (symbol) {
6582
- previous?.symbols.push({
6583
- name: symbol[3],
6584
- address: hex(symbol[1]),
6585
- size: parseInt(symbol[2], 16)
6586
- });
6741
+ const length = line.length;
6742
+ let pos = 0;
6743
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6744
+ if (pos >= length) continue;
6745
+ const leadingSpaces = pos;
6746
+ let address = -1;
6747
+ if (line.charCodeAt(pos) === 45) {
6748
+ pos++;
6749
+ } else {
6750
+ const start = pos;
6751
+ let value = 0;
6752
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
6753
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
6754
+ }
6755
+ if (pos === start) continue;
6756
+ address = value;
6757
+ }
6758
+ const s1 = pos;
6759
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6760
+ if (pos === s1 || pos >= length) continue;
6761
+ const offStart = pos;
6762
+ let offset = 0;
6763
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
6764
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
6765
+ }
6766
+ if (pos === offStart) continue;
6767
+ const s2 = pos;
6768
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6769
+ if (pos === s2 || pos >= length) continue;
6770
+ const sizeStart = pos;
6771
+ let size = 0;
6772
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
6773
+ size = size * 16 + hexDigit(line.charCodeAt(pos++));
6774
+ }
6775
+ if (pos === sizeStart || pos >= length) continue;
6776
+ const indentStart = pos;
6777
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6778
+ const indent = pos - indentStart;
6779
+ if (indent === 0 || pos >= length) continue;
6780
+ if (indent === 17) {
6781
+ if (previous) {
6782
+ const first = line.charCodeAt(pos);
6783
+ if (first > 32 && !hasLineBreak(line, pos)) {
6784
+ previous.symbols.push({
6785
+ name: line.slice(pos),
6786
+ address,
6787
+ size
6788
+ });
6789
+ }
6790
+ }
6587
6791
  continue;
6588
6792
  }
6589
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
6590
- if (output) {
6591
- kind = output[1];
6793
+ if (indent === 1) {
6794
+ let hasWhitespace = false;
6795
+ for (let i = pos; i < length; i++) {
6796
+ const ch = line.charCodeAt(i);
6797
+ if (ch <= 32) {
6798
+ hasWhitespace = true;
6799
+ break;
6800
+ }
6801
+ }
6802
+ if (hasWhitespace) continue;
6803
+ if (address < 0 && leadingSpaces > 0) {
6804
+ kind = line.slice(pos);
6805
+ } else if (kind === "DATA" && address >= 0) {
6806
+ segment = line.slice(pos);
6807
+ segments.set(segment, { address, size });
6808
+ }
6592
6809
  continue;
6593
6810
  }
6594
- if (kind === "DATA") {
6595
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
6596
- if (top) {
6597
- segment = top[3];
6598
- segments.set(segment, { address: hex(top[1]), size: parseInt(top[2], 16) });
6599
- continue;
6811
+ if (indent === 9 && (kind === "DATA" || kind === "CODE")) {
6812
+ const first = line.charCodeAt(pos);
6813
+ if (first !== 47 && first !== 60) continue;
6814
+ if (hasLineBreak(line, pos)) continue;
6815
+ const name3 = line.slice(pos);
6816
+ let filePath = name3;
6817
+ let section2 = "";
6818
+ if (name3.charCodeAt(name3.length - 1) === 41) {
6819
+ const splitAt = name3.indexOf(":(");
6820
+ if (splitAt >= 0) {
6821
+ filePath = name3.slice(0, splitAt);
6822
+ section2 = name3.slice(splitAt + 2, -1);
6823
+ }
6600
6824
  }
6825
+ let objectName;
6826
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
6827
+ const open = filePath.lastIndexOf("(");
6828
+ if (open >= 0 && open + 1 < filePath.length - 1) {
6829
+ const close = filePath.indexOf(")", open + 1);
6830
+ if (close === filePath.length - 1) {
6831
+ objectName = filePath.slice(open + 1, -1);
6832
+ }
6833
+ }
6834
+ }
6835
+ if (objectName === void 0) objectName = (0, import_node_path16.basename)(filePath);
6836
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
6837
+ objectName = objectName.replace(/^lib\w*?__/, "");
6838
+ }
6839
+ previous = {
6840
+ inputFile: filePath,
6841
+ segment,
6842
+ address,
6843
+ offset,
6844
+ size,
6845
+ object: objectName,
6846
+ section: section2,
6847
+ symbols: []
6848
+ };
6849
+ (kind === "DATA" ? data : code).push(previous);
6601
6850
  }
6602
- if (kind !== "DATA" && kind !== "CODE") continue;
6603
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
6604
- if (!input) continue;
6605
- const name3 = input[4];
6606
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
6607
- const path42 = split ? split[1] : name3;
6608
- const member = /\(([^()]+)\)$/.exec(path42);
6609
- previous = {
6610
- inputFile: path42,
6611
- segment,
6612
- address: hex(input[1]),
6613
- offset: parseInt(input[2], 16),
6614
- size: parseInt(input[3], 16),
6615
- object: (member ? member[1] : (0, import_node_path16.basename)(path42)).replace(/^lib\w*?__/, ""),
6616
- section: split ? split[2] : "",
6617
- symbols: []
6618
- };
6619
- (kind === "DATA" ? data : code).push(previous);
6620
6851
  }
6621
6852
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
6622
6853
  }
@@ -7762,6 +7993,7 @@ function patchSwiftrtObject(src) {
7762
7993
  return buf;
7763
7994
  }
7764
7995
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7996
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
7765
7997
  let pos = 8;
7766
7998
  let numImportFuncs = 0;
7767
7999
  let importsDlsym = false;
@@ -7797,10 +8029,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7797
8029
  let [cnt, cp] = readULEB2(buf, p);
7798
8030
  for (let i = 0; i < cnt; i++) {
7799
8031
  const [mLen, m2] = readULEB2(buf, cp);
7800
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
8032
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
7801
8033
  cp = m2 + mLen;
7802
8034
  const [fLen, f2] = readULEB2(buf, cp);
7803
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
8035
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
7804
8036
  cp = f2 + fLen;
7805
8037
  const kind = buf[cp++];
7806
8038
  if (kind === 0) {
@@ -7880,7 +8112,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7880
8112
  }
7881
8113
  } else if (id === 0) {
7882
8114
  const [nLen, np] = readULEB2(buf, p);
7883
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
8115
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
7884
8116
  const cp = np + nLen;
7885
8117
  if (name3 === "linking") {
7886
8118
  let [, lp] = readULEB2(buf, cp);
@@ -7893,7 +8125,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7893
8125
  let cur = p2;
7894
8126
  for (let i = 0; i < cnt; i++) {
7895
8127
  const [sLen, s2] = readULEB2(buf, cur);
7896
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
8128
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
7897
8129
  cur = s2 + sLen;
7898
8130
  const [, s3] = readULEB2(buf, cur);
7899
8131
  const [fl, s4] = readULEB2(buf, s3);
@@ -7933,7 +8165,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7933
8165
  let sName = "";
7934
8166
  if (!isUndef || isExplicitName) {
7935
8167
  const [sLen, c4] = readULEB2(buf, cur);
7936
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
8168
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
7937
8169
  cur = c4 + sLen;
7938
8170
  } else if (kind === 0) {
7939
8171
  sName = importFuncNames[el] ?? "";
@@ -7949,7 +8181,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7949
8181
  symNames.push(sName);
7950
8182
  } else if (kind === 1) {
7951
8183
  const [sLen, c3] = readULEB2(buf, cur);
7952
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
8184
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
7953
8185
  cur = c3 + sLen;
7954
8186
  if (!isUndef) {
7955
8187
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -8064,9 +8296,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
8064
8296
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
8065
8297
  let ownerSymIdx = -1;
8066
8298
  const topList = segTopSyms.get(lo);
8067
- if (topList) {
8068
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
8069
- if (owner) ownerSymIdx = owner.symIdx;
8299
+ if (topList && topList.length > 0) {
8300
+ let tLo = 0;
8301
+ let tHi = topList.length - 1;
8302
+ while (tLo <= tHi) {
8303
+ const tMid = tLo + tHi >> 1;
8304
+ const top = topList[tMid];
8305
+ if (offInSeg < top.off) {
8306
+ tHi = tMid - 1;
8307
+ } else if (offInSeg >= top.end) {
8308
+ tLo = tMid + 1;
8309
+ } else {
8310
+ ownerSymIdx = top.symIdx;
8311
+ break;
8312
+ }
8313
+ }
8070
8314
  }
8071
8315
  if (ownerSymIdx !== -1) {
8072
8316
  let list = symDataRelocs.get(ownerSymIdx);
@@ -8304,54 +8548,151 @@ function parseWasmObjectCached(file, isDist, entries2) {
8304
8548
  return parsed;
8305
8549
  }
8306
8550
  function guestWasmSymbols(bytes) {
8307
- const object3 = parseWasmObjectBytes("", bytes, false);
8551
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
8552
+ let cur = 8;
8553
+ const readU = () => {
8554
+ const b0 = bytes[cur++];
8555
+ if (b0 < 128) return b0;
8556
+ let res = b0 & 127;
8557
+ let shift = 7;
8558
+ while (true) {
8559
+ const byte = bytes[cur++];
8560
+ res |= (byte & 127) << shift;
8561
+ if ((byte & 128) === 0) return res;
8562
+ shift += 7;
8563
+ }
8564
+ };
8565
+ let importsDlsym = false;
8566
+ const importFuncNames = [];
8567
+ const importFuncModules = [];
8568
+ const importGlobalNames = [];
8569
+ const importTableNames = [];
8570
+ const importEventNames = [];
8571
+ const undefinedSyms = /* @__PURE__ */ new Set();
8572
+ const tags = /* @__PURE__ */ new Set();
8573
+ const globals = /* @__PURE__ */ new Set();
8574
+ const hostImports = /* @__PURE__ */ new Set();
8575
+ const weakUndefined = /* @__PURE__ */ new Set();
8576
+ const defined = /* @__PURE__ */ new Set();
8577
+ const weakDefined = /* @__PURE__ */ new Set();
8578
+ while (cur < bytes.length) {
8579
+ const id = bytes[cur++];
8580
+ const sz = readU();
8581
+ const end = cur + sz;
8582
+ if (id === 2) {
8583
+ const cnt = readU();
8584
+ for (let i = 0; i < cnt; i++) {
8585
+ const mLen = readU();
8586
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
8587
+ cur += mLen;
8588
+ const fLen = readU();
8589
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
8590
+ cur += fLen;
8591
+ const kind = bytes[cur++];
8592
+ if (kind === 0) {
8593
+ readU();
8594
+ importFuncNames.push(fName);
8595
+ importFuncModules.push(mName);
8596
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
8597
+ } else if (kind === 1) {
8598
+ cur++;
8599
+ const fl = readU();
8600
+ readU();
8601
+ if (fl & 1) readU();
8602
+ importTableNames.push(fName);
8603
+ } else if (kind === 2) {
8604
+ const fl = readU();
8605
+ readU();
8606
+ if (fl & 1) readU();
8607
+ } else if (kind === 3) {
8608
+ cur += 2;
8609
+ importGlobalNames.push(fName);
8610
+ } else if (kind === 4) {
8611
+ cur++;
8612
+ readU();
8613
+ importEventNames.push(fName);
8614
+ }
8615
+ }
8616
+ } else if (id === 0) {
8617
+ const nLen = readU();
8618
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
8619
+ cur += nLen;
8620
+ readU();
8621
+ while (cur < end) {
8622
+ const subId = bytes[cur++];
8623
+ const subLen = readU();
8624
+ const subEnd = cur + subLen;
8625
+ if (subId === 8) {
8626
+ const cnt = readU();
8627
+ for (let i = 0; i < cnt; i++) {
8628
+ const kind = bytes[cur++];
8629
+ const fl = readU();
8630
+ const isUndef = (fl & 16) !== 0;
8631
+ const isExplicitName = (fl & 64) !== 0;
8632
+ let sName = "";
8633
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
8634
+ const el = readU();
8635
+ if (!isUndef || isExplicitName) {
8636
+ const sLen = readU();
8637
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
8638
+ cur += sLen;
8639
+ } else if (kind === 0) {
8640
+ sName = importFuncNames[el] ?? "";
8641
+ } else if (kind === 2) {
8642
+ sName = importGlobalNames[el] ?? "";
8643
+ } else if (kind === 4) {
8644
+ sName = importEventNames[el] ?? "";
8645
+ } else if (kind === 5) {
8646
+ sName = importTableNames[el] ?? "";
8647
+ }
8648
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
8649
+ hostImports.add(sName);
8650
+ } else if (kind === 1) {
8651
+ const sLen = readU();
8652
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
8653
+ cur += sLen;
8654
+ if (!isUndef) {
8655
+ readU();
8656
+ readU();
8657
+ readU();
8658
+ }
8659
+ } else if (kind === 3) {
8660
+ readU();
8661
+ }
8662
+ if (sName) {
8663
+ if (isUndef) {
8664
+ undefinedSyms.add(sName);
8665
+ if ((fl & 19) === 17) weakUndefined.add(sName);
8666
+ } else if ((fl & 3) !== 2) {
8667
+ defined.add(sName);
8668
+ if ((fl & 19) === 1) weakDefined.add(sName);
8669
+ }
8670
+ if (kind === 4) tags.add(sName);
8671
+ else if (kind === 2 || kind === 5) globals.add(sName);
8672
+ }
8673
+ }
8674
+ break;
8675
+ }
8676
+ cur = subEnd;
8677
+ }
8678
+ break;
8679
+ }
8680
+ }
8681
+ cur = end;
8682
+ }
8308
8683
  return {
8309
- importsDlsym: object3.importsDlsym,
8310
- undefined: [
8311
- ...new Set(
8312
- object3.symNames.filter(
8313
- (name3, index) => name3 && (object3.symFlags[index] & 16) !== 0
8314
- )
8315
- )
8316
- ],
8684
+ importsDlsym,
8685
+ undefined: [...undefinedSyms],
8317
8686
  // a wasm tag is one module entity unified by name across the link, as the
8318
8687
  // main module owns it for dynamic images, so no image scope applies.
8319
- tags: [
8320
- ...new Set(
8321
- object3.symNames.filter((name3, index) => name3 && object3.symKind[index] === 4)
8322
- )
8323
- ],
8324
- globals: [
8325
- ...new Set(
8326
- object3.symNames.filter(
8327
- (name3, index) => name3 && (object3.symKind[index] === 2 || object3.symKind[index] === 5)
8328
- )
8329
- )
8330
- ],
8688
+ tags: [...tags],
8689
+ globals: [...globals],
8331
8690
  // an undefined function imported from a module other than env is supplied
8332
8691
  // by the host, whatever linker symbol names it.
8333
- hostImports: [...object3.hostImportNames],
8334
- weakUndefined: [
8335
- ...new Set(
8336
- object3.symNames.filter(
8337
- (name3, index) => name3 && (object3.symFlags[index] & 19) === 17
8338
- )
8339
- )
8340
- ],
8341
- defined: [
8342
- ...new Set(
8343
- object3.symNames.filter(
8344
- (name3, index) => name3 && (object3.symFlags[index] & 16) === 0 && (object3.symFlags[index] & 3) !== 2
8345
- )
8346
- )
8347
- ],
8348
- weakDefined: [
8349
- ...new Set(
8350
- object3.symNames.filter(
8351
- (name3, index) => name3 && (object3.symFlags[index] & 19) === 1
8352
- )
8353
- )
8354
- ]
8692
+ hostImports: [...hostImports],
8693
+ weakUndefined: [...weakUndefined],
8694
+ defined: [...defined],
8695
+ weakDefined: [...weakDefined]
8355
8696
  };
8356
8697
  }
8357
8698
  function sdkObjectName(archive, member, ordinal) {
@@ -8868,9 +9209,12 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8868
9209
  for (const entry of waiting) tryActivateConformance(entry);
8869
9210
  }
8870
9211
  };
9212
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
8871
9213
  const checkProtocolTrigger = (rawSymName) => {
8872
9214
  if (!rawSymName) return;
8873
9215
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
9216
+ if (checkedProtocolTriggers.has(sName)) return;
9217
+ checkedProtocolTriggers.add(sName);
8874
9218
  if (knownProtocols.has(sName)) {
8875
9219
  markProtocolLive(sName);
8876
9220
  return;
@@ -8903,6 +9247,43 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8903
9247
  }
8904
9248
  }
8905
9249
  };
9250
+ const typeIndexes = /* @__PURE__ */ new Map();
9251
+ const getTypeIndex = (obj) => {
9252
+ let idx = typeIndexes.get(obj);
9253
+ if (idx) return idx;
9254
+ const mnByPrefix = /* @__PURE__ */ new Map();
9255
+ for (let i = 0; i < obj.symNames.length; i++) {
9256
+ const name3 = obj.symNames[i];
9257
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
9258
+ const pref = name3.slice(0, -2);
9259
+ let list = mnByPrefix.get(pref);
9260
+ if (!list) mnByPrefix.set(pref, list = []);
9261
+ list.push(i);
9262
+ }
9263
+ }
9264
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
9265
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
9266
+ let list = objcRegByPrefix.get(p);
9267
+ if (!list) objcRegByPrefix.set(p, list = []);
9268
+ list.push(lf);
9269
+ }
9270
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
9271
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
9272
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
9273
+ let list = objcClassByPrefix.get(p);
9274
+ if (!list) objcClassByPrefix.set(p, list = []);
9275
+ list.push(classSym.slice("._OBJC_CLASS_".length));
9276
+ }
9277
+ let minPrefLen = Infinity;
9278
+ let maxPrefLen = 0;
9279
+ for (const p of obj.typePrefixesInObj) {
9280
+ if (p.length < minPrefLen) minPrefLen = p.length;
9281
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
9282
+ }
9283
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
9284
+ typeIndexes.set(obj, idx);
9285
+ return idx;
9286
+ };
8906
9287
  const markTypeLive = (obj, pref) => {
8907
9288
  const set = liveTypes.get(obj);
8908
9289
  if (set.has(pref)) return;
@@ -8916,22 +9297,10 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8916
9297
  const outer = pref.slice(0, n);
8917
9298
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
8918
9299
  }
8919
- const mnName = `${pref}Mn`;
8920
- for (let i = 0; i < obj.symNames.length; i++) {
8921
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
8922
- activateSymbolInObj(obj, i);
8923
- }
8924
- }
8925
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
8926
- if (p === pref) {
8927
- markFuncLive(obj, lf);
8928
- }
8929
- }
8930
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
8931
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
8932
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
8933
- }
8934
- }
9300
+ const idx = getTypeIndex(obj);
9301
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
9302
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
9303
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
8935
9304
  };
8936
9305
  const checkTypeTrigger = (obj, rawSymName) => {
8937
9306
  if (!rawSymName) return;
@@ -8956,11 +9325,12 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8956
9325
  }
8957
9326
  }
8958
9327
  }
8959
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
8960
- for (const pref of obj.typePrefixesInObj) {
8961
- if (sName.startsWith(pref)) {
8962
- markTypeLive(obj, pref);
8963
- }
9328
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
9329
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
9330
+ const hi = Math.min(sName.length, maxPrefLen);
9331
+ for (let n = minPrefLen; n <= hi; n++) {
9332
+ const cand = sName.slice(0, n);
9333
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
8964
9334
  }
8965
9335
  }
8966
9336
  };
@@ -9053,7 +9423,8 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
9053
9423
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
9054
9424
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
9055
9425
  for (const name3 of obj.symNames) {
9056
- const loaded = name3?.match(/^_c_(\w+)__load$/)?.[1];
9426
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
9427
+ const loaded = name3.match(/^_c_(\w+)__load$/)?.[1];
9057
9428
  if (!loaded) continue;
9058
9429
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded}`);
9059
9430
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -9201,14 +9572,30 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
9201
9572
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
9202
9573
  const range = obj.segPayloadRanges[segIdx];
9203
9574
  if (!range) return;
9575
+ const [rangeStart, rangeEnd] = range;
9576
+ if (rangeEnd - rangeStart < 4) return;
9204
9577
  let bytes = objectBytes.get(obj);
9205
9578
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs16.default.readFileSync(obj.file));
9206
- const text2 = bytes.toString("latin1", range[0], range[1]);
9207
- for (const match of text2.matchAll(/So(\d+)/g)) {
9208
- const start = match.index + 2 + match[1].length;
9209
- const length = Number(match[1]);
9210
- if (text2[start + length] !== "C") continue;
9211
- const symbol = `._OBJC_CLASS_${text2.slice(start, start + length)}`;
9579
+ let pos = rangeStart;
9580
+ while (pos < rangeEnd - 3) {
9581
+ const at = bytes.indexOf("So", pos);
9582
+ if (at < 0 || at >= rangeEnd - 2) break;
9583
+ let digitEnd = at + 2;
9584
+ let length = 0;
9585
+ while (digitEnd < rangeEnd) {
9586
+ const ch = bytes[digitEnd];
9587
+ if (ch < 48 || ch > 57) break;
9588
+ length = length * 10 + (ch - 48);
9589
+ digitEnd++;
9590
+ }
9591
+ if (digitEnd === at + 2) {
9592
+ pos = at + 2;
9593
+ continue;
9594
+ }
9595
+ pos = digitEnd;
9596
+ const nameEnd = digitEnd + length;
9597
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
9598
+ const symbol = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
9212
9599
  for (const provider of lazyProviders.get(symbol) ?? []) {
9213
9600
  eagerDynamicObjects.add(provider);
9214
9601
  extractObject(provider);
@@ -10145,6 +10532,10 @@ var init_nativeDyldTableContract = __esm({
10145
10532
 
10146
10533
  // src/swift-guest-image-ledger.ts
10147
10534
  function readNumber(bytes, position) {
10535
+ if (position < bytes.length) {
10536
+ const first = bytes[position];
10537
+ if (first < 128) return [first, position + 1];
10538
+ }
10148
10539
  let value = 0;
10149
10540
  let shift = 0;
10150
10541
  for (; ; ) {
@@ -10156,6 +10547,7 @@ function readNumber(bytes, position) {
10156
10547
  }
10157
10548
  }
10158
10549
  function encodeNumber(value) {
10550
+ if (value < 128) return Buffer.from([value]);
10159
10551
  const bytes = [];
10160
10552
  do {
10161
10553
  let byte = value % 128;
@@ -10177,6 +10569,9 @@ function encodedString(value) {
10177
10569
  const bytes = Buffer.from(value);
10178
10570
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
10179
10571
  }
10572
+ function isWasmMagic(bytes) {
10573
+ return bytes.length >= 8 && bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115 && bytes[3] === 109 && bytes[4] === 1 && bytes[5] === 0 && bytes[6] === 0 && bytes[7] === 0;
10574
+ }
10180
10575
  function llvmType(value) {
10181
10576
  switch (value) {
10182
10577
  case 127:
@@ -10192,11 +10587,12 @@ function llvmType(value) {
10192
10587
  }
10193
10588
  }
10194
10589
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options = {}) {
10195
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
10196
- throw new Error("expected wasm object");
10590
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
10591
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
10197
10592
  const { sdkLookupOnly, sdkProduct } = options;
10198
10593
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
10199
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
10594
+ const rewrite = binding !== void 0;
10595
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
10200
10596
  const types = [];
10201
10597
  const functionTypes = [];
10202
10598
  const definitions = [];
@@ -10210,45 +10606,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10210
10606
  const usedSymbols = /* @__PURE__ */ new Set();
10211
10607
  let position = 8;
10212
10608
  while (position < bytes.length) {
10609
+ const headerStart = position;
10213
10610
  const id = bytes[position++];
10214
- const [size, start] = readNumber(bytes, position);
10611
+ let size = 0;
10612
+ if (position < bytes.length && bytes[position] < 128) {
10613
+ size = bytes[position++];
10614
+ } else {
10615
+ const [val, next] = readNumber(bytes, position);
10616
+ size = val;
10617
+ position = next;
10618
+ }
10619
+ const start = position;
10215
10620
  const end = start + size;
10216
10621
  if (end > bytes.length) throw new Error("invalid wasm section");
10217
10622
  position = end;
10218
- if (!sections && id > 3) continue;
10219
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size);
10220
- let offset = 0;
10623
+ if (id > 3) {
10624
+ if (sections) sections.push(bytes.subarray(headerStart, end));
10625
+ continue;
10626
+ }
10627
+ let offset = start;
10221
10628
  const number3 = () => {
10222
- const [value, next] = readNumber(section2, offset);
10223
- offset = next;
10224
- return value;
10629
+ if (offset < end) {
10630
+ const first = bytes[offset];
10631
+ if (first < 128) {
10632
+ offset++;
10633
+ return first;
10634
+ }
10635
+ }
10636
+ let value = 0;
10637
+ let shift = 0;
10638
+ for (; ; ) {
10639
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
10640
+ const byte = bytes[offset++];
10641
+ value += (byte & 127) * 2 ** shift;
10642
+ if (!(byte & 128)) return value;
10643
+ shift += 7;
10644
+ }
10225
10645
  };
10226
10646
  const string4 = () => {
10227
- const [value, next] = readString(section2, offset);
10228
- offset = next;
10647
+ const length = number3();
10648
+ const strEnd = offset + length;
10649
+ if (strEnd > end) throw new Error("invalid wasm string");
10650
+ const value = rawBuf.toString("utf8", offset, strEnd);
10651
+ offset = strEnd;
10229
10652
  return value;
10230
10653
  };
10654
+ let rewrittenSection;
10231
10655
  if (id === 1) {
10232
10656
  const count = number3();
10233
10657
  for (let i = 0; i < count; i++) {
10234
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
10658
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
10235
10659
  const parameterCount = number3();
10236
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
10237
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
10238
- offset += parameterCount;
10660
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
10661
+ const parameters = new Array(parameterCount);
10662
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
10239
10663
  const resultCount = number3();
10240
- const results = [...section2.subarray(offset, offset + resultCount)];
10241
- if (results.length !== resultCount) throw new Error("invalid wasm type");
10242
- offset += resultCount;
10664
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
10665
+ const results = new Array(resultCount);
10666
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
10243
10667
  types.push({ parameters, results });
10244
10668
  }
10245
10669
  } else if (id === 2) {
10246
10670
  const count = number3();
10247
- const imports = sections ? [encodeNumber(count)] : void 0;
10671
+ const importWriter = rewrite ? new ByteWriter(size + 64) : void 0;
10672
+ importWriter?.uleb(count);
10248
10673
  for (let i = 0; i < count; i++) {
10249
10674
  const module2 = string4();
10250
10675
  const name3 = string4();
10251
- const kind = section2[offset++];
10676
+ const kind = bytes[offset++];
10252
10677
  const typeStart = offset;
10253
10678
  let functionType = -1;
10254
10679
  if (kind === 0) {
@@ -10256,7 +10681,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10256
10681
  functionTypes.push(functionType);
10257
10682
  functionImportNames.push(name3);
10258
10683
  } else if (kind === 1) {
10259
- const referenceType = section2[offset++];
10684
+ const referenceType = bytes[offset++];
10260
10685
  if (referenceType !== 112 && referenceType !== 111)
10261
10686
  throw new Error("unsupported table type");
10262
10687
  const flags = number3();
@@ -10275,11 +10700,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10275
10700
  } else throw new Error("unsupported wasm import");
10276
10701
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
10277
10702
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
10278
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
10279
- if (module2 === "env" && kind === 0 && names.has(name3)) {
10280
- const type = types[functionType];
10281
- if (!type) throw new Error(`missing import type for ${name3}`);
10282
- functionImports.set(name3, type);
10703
+ if (!rewrite) {
10704
+ if (module2 === "env" && names.has(name3)) {
10705
+ usedSymbols.add(name3);
10706
+ if (kind === 0) {
10707
+ const type = types[functionType];
10708
+ if (!type) throw new Error(`missing import type for ${name3}`);
10709
+ functionImports.set(name3, type);
10710
+ }
10711
+ }
10283
10712
  }
10284
10713
  if (isDlsym || isDlerror) {
10285
10714
  const type = types[functionType];
@@ -10289,17 +10718,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10289
10718
  }
10290
10719
  if (isDlsym) usesDlsym = true;
10291
10720
  if (isDlerror) usesDlerror = true;
10292
- imports?.push(
10293
- encodedString(module2),
10294
- encodedString(
10295
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
10296
- ),
10297
- Buffer.from([kind]),
10298
- section2.subarray(typeStart, offset)
10299
- );
10721
+ if (importWriter && binding) {
10722
+ importWriter.string(module2);
10723
+ importWriter.string(
10724
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
10725
+ );
10726
+ importWriter.byte(kind);
10727
+ importWriter.bytes(bytes, typeStart, offset);
10728
+ }
10300
10729
  }
10301
- if (offset !== section2.length) throw new Error("invalid wasm import section");
10302
- if (imports) section2 = Buffer.concat(imports);
10730
+ if (offset !== end) throw new Error("invalid wasm import section");
10731
+ if (importWriter) rewrittenSection = importWriter.finish();
10303
10732
  } else if (id === 3) {
10304
10733
  const count = number3();
10305
10734
  for (let i = 0; i < count; i++) functionTypes.push(number3());
@@ -10308,43 +10737,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10308
10737
  if (sectionName === "linking") {
10309
10738
  const version2 = number3();
10310
10739
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
10311
- const subsections = [];
10740
+ const subsections = rewrite ? [] : void 0;
10312
10741
  let objcLoader;
10313
- while (offset < section2.length) {
10314
- const kind = section2[offset++];
10742
+ while (offset < end) {
10743
+ const kind = bytes[offset++];
10315
10744
  const length = number3();
10316
10745
  const stop = offset + length;
10317
- if (stop > section2.length) throw new Error("invalid linking subsection");
10318
- let content = section2.subarray(offset, stop);
10319
- if (kind === 7 && !sdkLookupOnly) {
10320
- const groups = [];
10746
+ if (stop > end) throw new Error("invalid linking subsection");
10747
+ const contentStart = offset;
10748
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
10749
+ const comdatWriter = new ByteWriter(length + 64);
10321
10750
  const count = number3();
10322
- groups.push(encodeNumber(count));
10751
+ comdatWriter.uleb(count);
10323
10752
  for (let i = 0; i < count; i++) {
10324
10753
  const group = string4();
10325
10754
  const begin = offset;
10326
10755
  number3();
10327
10756
  const members = number3();
10328
10757
  for (let member = 0; member < members * 2; member++) number3();
10329
- groups.push(
10330
- encodedString(
10331
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
10332
- ),
10333
- section2.subarray(begin, offset)
10758
+ comdatWriter.string(
10759
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
10334
10760
  );
10761
+ comdatWriter.bytes(bytes, begin, offset);
10335
10762
  }
10336
10763
  if (offset !== stop) throw new Error("invalid comdat subsection");
10337
- content = Buffer.concat(groups);
10338
- }
10339
- if (kind === 8) {
10340
- const entries2 = [];
10341
- const extraEntries = [];
10764
+ const buf = comdatWriter.finish();
10765
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
10766
+ } else if (kind === 8) {
10767
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
10768
+ let extraWriter;
10342
10769
  const count = number3();
10343
- entries2.push(encodeNumber(count));
10344
10770
  let added = 0;
10345
10771
  for (let i = 0; i < count; i++) {
10346
10772
  const begin = offset;
10347
- const symbolKind = section2[offset++];
10773
+ const symbolKind = bytes[offset++];
10348
10774
  const flags = number3();
10349
10775
  const flagsEnd = offset;
10350
10776
  let index = -1;
@@ -10372,25 +10798,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10372
10798
  }
10373
10799
  } else if (symbolKind === 3) number3();
10374
10800
  else throw new Error("unsupported wasm symbol kind");
10375
- if (symbolKind === 0)
10801
+ if (!rewrite && symbolKind === 0)
10376
10802
  functionSymbols[i] = name3 || functionImportNames[index];
10377
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
10803
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
10378
10804
  objcLoader = i;
10379
10805
  }
10380
10806
  const alias = names.get(name3);
10381
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
10382
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
10383
- entries2.push(
10384
- section2.subarray(begin, nameStart),
10385
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
10386
- section2.subarray(nameEnd, offset)
10387
- );
10388
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
10389
- entries2.push(
10390
- section2.subarray(begin, nameStart),
10391
- encodedString(binding(name3)),
10392
- section2.subarray(nameEnd, offset)
10393
- );
10807
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
10808
+ usedSymbols.add(name3);
10809
+ if (entryWriter && binding) {
10810
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
10811
+ entryWriter.bytes(bytes, begin, nameStart);
10812
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
10813
+ entryWriter.bytes(bytes, nameEnd, offset);
10814
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
10815
+ entryWriter.bytes(bytes, begin, nameStart);
10816
+ entryWriter.string(binding(name3));
10817
+ entryWriter.bytes(bytes, nameEnd, offset);
10818
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
10819
+ if (symbolKind !== 0 && symbolKind !== 1)
10820
+ throw new Error(`unsupported symbol ${name3}`);
10821
+ if (preserveCanonical.has(name3)) {
10822
+ entryWriter.bytes(bytes, begin, offset);
10823
+ extraWriter ??= new ByteWriter(256);
10824
+ extraWriter.byte(bytes[begin]);
10825
+ extraWriter.uleb(flags & ~32);
10826
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
10827
+ extraWriter.string(alias);
10828
+ extraWriter.bytes(bytes, nameEnd, offset);
10829
+ added++;
10830
+ } else {
10831
+ entryWriter.bytes(bytes, begin, nameStart);
10832
+ entryWriter.string(alias);
10833
+ entryWriter.bytes(bytes, nameEnd, offset);
10834
+ }
10835
+ } else {
10836
+ entryWriter.bytes(bytes, begin, offset);
10837
+ }
10394
10838
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
10395
10839
  if (symbolKind !== 0 && symbolKind !== 1)
10396
10840
  throw new Error(`unsupported symbol ${name3}`);
@@ -10404,63 +10848,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10404
10848
  hidden: (flags & 4) !== 0,
10405
10849
  type
10406
10850
  });
10407
- if (preserveCanonical.has(name3)) {
10408
- entries2.push(section2.subarray(begin, offset));
10409
- extraEntries.push(
10410
- section2.subarray(begin, begin + 1),
10411
- encodeNumber(flags & ~32),
10412
- section2.subarray(flagsEnd, nameStart),
10413
- encodedString(alias),
10414
- section2.subarray(nameEnd, offset)
10415
- );
10416
- added++;
10417
- } else {
10418
- entries2.push(
10419
- section2.subarray(begin, nameStart),
10420
- encodedString(alias),
10421
- section2.subarray(nameEnd, offset)
10422
- );
10423
- }
10424
- } else entries2.push(section2.subarray(begin, offset));
10851
+ }
10425
10852
  }
10426
10853
  if (offset !== stop) throw new Error("invalid symbol subsection");
10427
- entries2[0] = encodeNumber(count + added);
10428
- content = Buffer.concat([...entries2, ...extraEntries]);
10854
+ if (entryWriter) {
10855
+ const countBytes = encodeNumber(count + added);
10856
+ const entryBuf = entryWriter.finish();
10857
+ if (extraWriter) {
10858
+ const extraBuf = extraWriter.finish();
10859
+ subsections.push({
10860
+ kind,
10861
+ parts: [countBytes, entryBuf, extraBuf],
10862
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
10863
+ });
10864
+ } else {
10865
+ subsections.push({
10866
+ kind,
10867
+ parts: [countBytes, entryBuf],
10868
+ byteLength: countBytes.length + entryBuf.length
10869
+ });
10870
+ }
10871
+ }
10872
+ } else if (subsections) {
10873
+ subsections.push({
10874
+ kind,
10875
+ parts: [bytes.subarray(contentStart, stop)],
10876
+ byteLength: length
10877
+ });
10429
10878
  }
10430
10879
  offset = stop;
10431
- subsections.push({ kind, content });
10432
10880
  }
10433
- const parts = [encodedString(sectionName), encodeNumber(version2)];
10434
- for (const subsection of subsections) {
10435
- let content = subsection.content;
10436
- if (subsection.kind === 6 && objcLoader !== void 0) {
10437
- const [count, entriesStart] = readNumber(content, 0);
10438
- const entries2 = [content.subarray(0, entriesStart)];
10439
- let entryStart = entriesStart;
10440
- for (let i = 0; i < count; i++) {
10441
- const [, symbolStart] = readNumber(content, entryStart);
10442
- const [symbol, entryEnd] = readNumber(content, symbolStart);
10443
- if (symbol === objcLoader) entries2.push(encodeNumber(1));
10444
- entries2.push(
10445
- content.subarray(
10446
- symbol === objcLoader ? symbolStart : entryStart,
10447
- entryEnd
10448
- )
10449
- );
10450
- entryStart = entryEnd;
10881
+ if (subsections) {
10882
+ const linkingWriter = new ByteWriter(size + 128);
10883
+ linkingWriter.string(sectionName);
10884
+ linkingWriter.uleb(version2);
10885
+ for (const subsection of subsections) {
10886
+ if (subsection.kind === 6 && objcLoader !== void 0) {
10887
+ const content = subsection.parts[0];
10888
+ const [count, entriesStart] = readNumber(content, 0);
10889
+ const initWriter = new ByteWriter(content.length + 16);
10890
+ initWriter.bytes(content, 0, entriesStart);
10891
+ let entryStart = entriesStart;
10892
+ for (let i = 0; i < count; i++) {
10893
+ const [, symbolStart] = readNumber(content, entryStart);
10894
+ const [symbol, entryEnd] = readNumber(content, symbolStart);
10895
+ if (symbol === objcLoader) {
10896
+ initWriter.uleb(1);
10897
+ initWriter.bytes(content, symbolStart, entryEnd);
10898
+ } else {
10899
+ initWriter.bytes(content, entryStart, entryEnd);
10900
+ }
10901
+ entryStart = entryEnd;
10902
+ }
10903
+ if (entryStart !== content.length)
10904
+ throw new Error("invalid init functions subsection");
10905
+ const initBuf = initWriter.finish();
10906
+ linkingWriter.byte(subsection.kind);
10907
+ linkingWriter.uleb(initBuf.length);
10908
+ linkingWriter.bytes(initBuf);
10909
+ } else {
10910
+ linkingWriter.byte(subsection.kind);
10911
+ linkingWriter.uleb(subsection.byteLength);
10912
+ for (const part of subsection.parts) linkingWriter.bytes(part);
10451
10913
  }
10452
- if (entryStart !== content.length)
10453
- throw new Error("invalid init functions subsection");
10454
- content = Buffer.concat(entries2);
10455
10914
  }
10456
- parts.push(
10457
- Buffer.from([subsection.kind]),
10458
- encodeNumber(content.length),
10459
- content
10460
- );
10915
+ rewrittenSection = linkingWriter.finish();
10461
10916
  }
10462
- section2 = Buffer.concat(parts);
10463
- } else if (!sections && sectionName.startsWith("reloc.")) {
10917
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
10464
10918
  number3();
10465
10919
  for (let count = number3(); count > 0; count--) {
10466
10920
  const type = number3();
@@ -10470,18 +10924,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10470
10924
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
10471
10925
  addressTaken.add(name3);
10472
10926
  }
10473
- if (offset !== section2.length)
10474
- throw new Error(`invalid relocation section ${sectionName}`);
10927
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
10928
+ }
10929
+ }
10930
+ if (sections) {
10931
+ if (rewrittenSection) {
10932
+ sections.push(
10933
+ Buffer.from([id]),
10934
+ encodeNumber(rewrittenSection.length),
10935
+ rewrittenSection
10936
+ );
10937
+ } else {
10938
+ sections.push(bytes.subarray(headerStart, end));
10475
10939
  }
10476
10940
  }
10477
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
10478
10941
  }
10479
10942
  return {
10480
10943
  bytes: sections ? Buffer.concat(sections) : bytes,
10481
10944
  definitions,
10482
10945
  functionImports,
10483
10946
  usesDlsym,
10484
- usedSymbols: [...usedSymbols],
10947
+ usedSymbols,
10485
10948
  addressTaken: [...addressTaken]
10486
10949
  };
10487
10950
  }
@@ -10570,36 +11033,51 @@ function createGuestImageLedger(input) {
10570
11033
  }
10571
11034
  }
10572
11035
  }
10573
- const nameBytes = /* @__PURE__ */ new Map();
10574
- for (const definition of definitions)
10575
- if (!nameBytes.has(definition.name))
10576
- nameBytes.set(definition.name, Buffer.from(definition.name));
10577
- definitions.sort(
10578
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
10579
- );
11036
+ let hasNonAscii = false;
11037
+ for (const definition of definitions) {
11038
+ const s = definition.name;
11039
+ for (let i = 0; i < s.length; i++) {
11040
+ if (s.charCodeAt(i) > 127) {
11041
+ hasNonAscii = true;
11042
+ break;
11043
+ }
11044
+ }
11045
+ if (hasNonAscii) break;
11046
+ }
11047
+ if (hasNonAscii) {
11048
+ const nameBytes = /* @__PURE__ */ new Map();
11049
+ for (const definition of definitions)
11050
+ if (!nameBytes.has(definition.name))
11051
+ nameBytes.set(definition.name, Buffer.from(definition.name));
11052
+ definitions.sort(
11053
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
11054
+ );
11055
+ } else {
11056
+ definitions.sort(
11057
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
11058
+ );
11059
+ }
10580
11060
  const preserveCanonical = /* @__PURE__ */ new Set();
10581
11061
  const definitionsByName = Map.groupBy(definitions, (definition) => definition.name);
10582
- for (const name3 of input.symbols) {
11062
+ if (symbolIndices.has("__cxa_throw")) {
11063
+ const name3 = "__cxa_throw";
10583
11064
  const matching = definitionsByName.get(name3) ?? [];
10584
- if (new Set(matching.map((definition) => definition.image)).size < 2 || !matching.some((definition) => definition.weak))
10585
- continue;
10586
- const weak = matching.filter((definition) => definition.weak);
10587
- const strong = matching.filter((definition) => !definition.weak);
10588
- if (name3 !== "__cxa_throw") continue;
10589
- if (weak.length !== 1 || strong.length !== 1)
10590
- throw new Error(`unsupported weak interposition for ${name3}`);
10591
- const [local] = weak;
10592
- const [runtime] = strong;
10593
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
10594
- throw new Error(`incompatible weak interposition for ${name3}`);
10595
- for (const caller of input.callers) {
10596
- const uses = caller.image === local.image || units.some(
10597
- (unit) => unit.image === caller.image && unit.usedSymbols.includes(name3)
10598
- );
10599
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
10600
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
11065
+ if (new Set(matching.map((definition) => definition.image)).size >= 2 && matching.some((definition) => definition.weak)) {
11066
+ const weak = matching.filter((definition) => definition.weak);
11067
+ const strong = matching.filter((definition) => !definition.weak);
11068
+ if (weak.length !== 1 || strong.length !== 1)
11069
+ throw new Error(`unsupported weak interposition for ${name3}`);
11070
+ const [local] = weak;
11071
+ const [runtime] = strong;
11072
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
11073
+ throw new Error(`incompatible weak interposition for ${name3}`);
11074
+ for (const caller of input.callers) {
11075
+ const uses = caller.image === local.image || units.some((unit) => unit.image === caller.image && unit.usedSymbols.has(name3));
11076
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
11077
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
11078
+ }
11079
+ preserveCanonical.add(name3);
10601
11080
  }
10602
- preserveCanonical.add(name3);
10603
11081
  }
10604
11082
  for (const name3 of [
10605
11083
  "dlsym",
@@ -10611,40 +11089,76 @@ function createGuestImageLedger(input) {
10611
11089
  ])
10612
11090
  preserveCanonical.add(name3);
10613
11091
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
10614
- const bindingsByImage = /* @__PURE__ */ new Map();
10615
- const definitionsByImage = Map.groupBy(definitions, (definition) => definition.image);
11092
+ const imageAliases = /* @__PURE__ */ new Map();
11093
+ const imageWeakNames = /* @__PURE__ */ new Map();
11094
+ const singleOwnerByName = /* @__PURE__ */ new Map();
11095
+ for (const definition of definitions) {
11096
+ let aliases = imageAliases.get(definition.image);
11097
+ if (!aliases) imageAliases.set(definition.image, aliases = /* @__PURE__ */ new Map());
11098
+ const existing = aliases.get(definition.name);
11099
+ if (existing === void 0) {
11100
+ aliases.set(definition.name, definition.alias);
11101
+ if (definition.weak) {
11102
+ let weak = imageWeakNames.get(definition.image);
11103
+ if (!weak) imageWeakNames.set(definition.image, weak = /* @__PURE__ */ new Set());
11104
+ weak.add(definition.name);
11105
+ }
11106
+ const owner = singleOwnerByName.get(definition.name);
11107
+ if (owner === void 0)
11108
+ singleOwnerByName.set(definition.name, {
11109
+ image: definition.image,
11110
+ alias: definition.alias
11111
+ });
11112
+ else if (owner !== null && owner.image !== definition.image)
11113
+ singleOwnerByName.set(definition.name, null);
11114
+ } else if (!definition.weak && imageWeakNames.get(definition.image)?.has(definition.name)) {
11115
+ aliases.set(definition.name, definition.alias);
11116
+ imageWeakNames.get(definition.image).delete(definition.name);
11117
+ const owner = singleOwnerByName.get(definition.name);
11118
+ if (owner && owner.image === definition.image) owner.alias = definition.alias;
11119
+ }
11120
+ }
11121
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
10616
11122
  for (const caller of input.callers) {
10617
- const bindings = /* @__PURE__ */ new Map();
10618
- const seen = /* @__PURE__ */ new Map();
10619
11123
  const scope = [caller.image, ...caller.next];
10620
11124
  if (input.systemImage !== void 0 && !scope.includes(input.systemImage))
10621
11125
  scope.push(input.systemImage);
10622
- for (const image of scope)
10623
- for (const definition of definitionsByImage.get(image) ?? []) {
10624
- const previous = seen.get(definition.name);
10625
- if (previous?.image === definition.image) {
10626
- if (previous.weak && !definition.weak) {
10627
- seen.set(definition.name, definition);
10628
- if (!preserveCanonical.has(definition.name))
10629
- bindings.set(definition.name, definition.alias);
10630
- }
10631
- continue;
10632
- }
10633
- if (!previous) {
10634
- seen.set(definition.name, definition);
10635
- if (!preserveCanonical.has(definition.name))
10636
- bindings.set(definition.name, definition.alias);
11126
+ const scopeSet = new Set(scope);
11127
+ const scopeMaps = [];
11128
+ const seenImages = /* @__PURE__ */ new Set();
11129
+ for (const image of scope) {
11130
+ if (seenImages.has(image)) continue;
11131
+ seenImages.add(image);
11132
+ const aliases = imageAliases.get(image);
11133
+ if (aliases) scopeMaps.push(aliases);
11134
+ }
11135
+ const cache = /* @__PURE__ */ new Map();
11136
+ sharedLookupByImage.set(caller.image, (name3) => {
11137
+ if (preserveCanonical.has(name3)) return void 0;
11138
+ const single = singleOwnerByName.get(name3);
11139
+ if (single === void 0) return void 0;
11140
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
11141
+ const hit = cache.get(name3);
11142
+ if (hit !== void 0) return hit ?? void 0;
11143
+ for (const aliases of scopeMaps) {
11144
+ const alias = aliases.get(name3);
11145
+ if (alias !== void 0) {
11146
+ cache.set(name3, alias);
11147
+ return alias;
10637
11148
  }
10638
11149
  }
10639
- bindingsByImage.set(caller.image, bindings);
11150
+ cache.set(name3, null);
11151
+ return void 0;
11152
+ });
10640
11153
  }
10641
11154
  const startup = /* @__PURE__ */ new Map();
11155
+ const unitsByPath = new Map(units.map((unit) => [unit.object.path, unit]));
10642
11156
  for (const binding of input.directBindings ?? []) {
10643
- const unit = units.find(({ object: object3 }) => object3.path === binding.object);
11157
+ const unit = unitsByPath.get(binding.object);
10644
11158
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
10645
11159
  (definition) => definition.object === binding.providerObject && definition.image === binding.providerImage
10646
11160
  );
10647
- if (!unit || !unit.usedSymbols.includes(binding.symbol) || matches.length !== 1)
11161
+ if (!unit || !unit.usedSymbols.has(binding.symbol) || matches.length !== 1)
10648
11162
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
10649
11163
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
10650
11164
  if (bindings.has(binding.symbol))
@@ -10685,11 +11199,11 @@ function createGuestImageLedger(input) {
10685
11199
  }
10686
11200
  }
10687
11201
  const objects = units.map(({ image, object: object3, aliases, functionImports }) => {
10688
- const shared = bindingsByImage.get(image);
11202
+ const shared = sharedLookupByImage.get(image);
10689
11203
  const own = startup.get(object3.path);
10690
11204
  const bindings = new Map(own);
10691
11205
  const weak = input.sdkWeakReferences?.get(object3.path);
10692
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
11206
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
10693
11207
  for (const [name3, type] of functionImports) {
10694
11208
  const alias = binding(name3);
10695
11209
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -10954,7 +11468,7 @@ function nameGuestImageAliases(wasm, symbols) {
10954
11468
  }
10955
11469
  return Buffer.concat(parts);
10956
11470
  }
10957
- var import_node_crypto10, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
11471
+ var import_node_crypto10, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
10958
11472
  var init_swift_guest_image_ledger = __esm({
10959
11473
  "src/swift-guest-image-ledger.ts"() {
10960
11474
  "use strict";
@@ -10962,6 +11476,57 @@ var init_swift_guest_image_ledger = __esm({
10962
11476
  init_nativeWasmContract();
10963
11477
  init_swift_sdk_image_wasm();
10964
11478
  init_swiftSdkLinkContract();
11479
+ ByteWriter = class {
11480
+ buf;
11481
+ pos = 0;
11482
+ constructor(initialCapacity = 256) {
11483
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
11484
+ }
11485
+ ensure(extra) {
11486
+ const needed = this.pos + extra;
11487
+ if (needed <= this.buf.length) return;
11488
+ let next = this.buf.length * 2;
11489
+ while (next < needed) next *= 2;
11490
+ const grown = Buffer.allocUnsafe(next);
11491
+ this.buf.copy(grown, 0, 0, this.pos);
11492
+ this.buf = grown;
11493
+ }
11494
+ byte(value) {
11495
+ this.ensure(1);
11496
+ this.buf[this.pos++] = value;
11497
+ }
11498
+ uleb(value) {
11499
+ this.ensure(10);
11500
+ let pos = this.pos;
11501
+ const buf = this.buf;
11502
+ do {
11503
+ let byte = value % 128;
11504
+ value = Math.floor(value / 128);
11505
+ if (value) byte |= 128;
11506
+ buf[pos++] = byte;
11507
+ } while (value);
11508
+ this.pos = pos;
11509
+ }
11510
+ bytes(source, start = 0, end = source.length) {
11511
+ const len = end - start;
11512
+ if (len <= 0) return;
11513
+ this.ensure(len);
11514
+ this.buf.set(source.subarray(start, end), this.pos);
11515
+ this.pos += len;
11516
+ }
11517
+ string(value) {
11518
+ const len = Buffer.byteLength(value, "utf8");
11519
+ this.uleb(len);
11520
+ if (len > 0) {
11521
+ this.ensure(len);
11522
+ this.buf.write(value, this.pos, len, "utf8");
11523
+ this.pos += len;
11524
+ }
11525
+ }
11526
+ finish() {
11527
+ return this.buf.subarray(0, this.pos);
11528
+ }
11529
+ };
10965
11530
  OBJC_INIT_RECORD = ".objc_init";
10966
11531
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
10967
11532
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -11405,8 +11970,11 @@ function moveGuestDyldTable(map, wasm, symbols, bindingValues = /* @__PURE__ */
11405
11970
  function guestDyldValueRange(map) {
11406
11971
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
11407
11972
  let found;
11408
- for (const line of map.split("\n")) {
11409
- if (!line.endsWith(suffix)) continue;
11973
+ for (let at = map.indexOf(suffix); at !== -1; at = map.indexOf(suffix, at + suffix.length)) {
11974
+ const lineEnd = at + suffix.length;
11975
+ if (lineEnd < map.length && map.charCodeAt(lineEnd) !== 10) continue;
11976
+ const lineStart = map.lastIndexOf("\n", at) + 1;
11977
+ const line = map.slice(lineStart, lineEnd);
11410
11978
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
11411
11979
  if (!match) throw new Error("unreadable dyld values map line");
11412
11980
  if (found) throw new Error("link map has several dyld value sections");
@@ -11444,7 +12012,7 @@ var init_swift_guest_link_plan = __esm({
11444
12012
  });
11445
12013
 
11446
12014
  // src/swift-guest-manifest.ts
11447
- function selectedGuestManifestInputs(plan, selection, identities) {
12015
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
11448
12016
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
11449
12017
  const archives = /* @__PURE__ */ new Map();
11450
12018
  const images = /* @__PURE__ */ new Map();
@@ -11455,19 +12023,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
11455
12023
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
11456
12024
  let bytes;
11457
12025
  let memberIdentity = null;
11458
- if (item.member === null) bytes = (0, import_node_fs18.readFileSync)(item.artifact);
11459
- else {
11460
- let members = archives.get(item.artifact);
11461
- if (!members) {
11462
- members = readArMembers((0, import_node_fs18.readFileSync)(item.artifact));
11463
- archives.set(item.artifact, members);
12026
+ if (item.member === null) {
12027
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs18.readFileSync)(item.artifact);
12028
+ } else {
12029
+ if (readSelected) {
12030
+ bytes = readSelected(item);
12031
+ } else {
12032
+ let members = archives.get(item.artifact);
12033
+ if (!members) {
12034
+ members = /* @__PURE__ */ new Map();
12035
+ for (const member of readArMembers((0, import_node_fs18.readFileSync)(item.artifact))) {
12036
+ let list = members.get(member.name);
12037
+ if (!list) members.set(member.name, list = []);
12038
+ list.push(member.bytes);
12039
+ }
12040
+ archives.set(item.artifact, members);
12041
+ }
12042
+ const matching = members.get(item.member);
12043
+ if (!matching || matching.length !== 1)
12044
+ throw new Error(
12045
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
12046
+ );
12047
+ bytes = matching[0];
11464
12048
  }
11465
- const matching = members.filter((member) => member.name === item.member);
11466
- if (matching.length !== 1)
11467
- throw new Error(
11468
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
11469
- );
11470
- bytes = matching[0].bytes;
11471
12049
  const origin = artifact.memberOrigins?.get(item.member);
11472
12050
  if (artifact.memberOrigins && !origin)
11473
12051
  throw new Error(
@@ -11559,7 +12137,7 @@ var init_swift_guest_manifest = __esm({
11559
12137
  function isSwiftGuestImageManifest(value) {
11560
12138
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
11561
12139
  const text2 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
11562
- const name3 = (value2) => text2(value2) && new TextEncoder().encode(value2).length <= 16;
12140
+ const name3 = (value2) => text2(value2) && Buffer.byteLength(value2, "utf8") <= 16;
11563
12141
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
11564
12142
  if (!isRecord(value) || value.version !== 1 || !text2(value.id) || !text2(value.installName) || value.resourceBundlePath !== void 0 && !isSwiftBundlePath(value.resourceBundlePath) || value.fileType !== "executable" && value.fileType !== "dylib" || !isRecord(value.target) || value.target.triple !== SWIFT_WASM_TRIPLE || value.target.pointerWidth !== 64 || value.target.byteOrder !== "little" || value.target.cpuType !== -1 || value.target.cpuSubtype !== 0 || typeof value.inputsSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.inputsSha256) || value.uuid !== value.inputsSha256.slice(0, 32) || !isRecord(value.buildVersion) || !uint(value.buildVersion.platform, 4294967295) || !version2(value.buildVersion.minimum) || !version2(value.buildVersion.sdk) || !Array.isArray(value.regions))
11565
12143
  return false;
@@ -11873,27 +12451,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
11873
12451
  function finalizeGuestProjectionStorage(options) {
11874
12452
  const owner = options.owners.get(options.projectionObject);
11875
12453
  if (owner === void 0) throw new Error("guest projection object has no image owner");
12454
+ const ranges = [];
11876
12455
  const spans = guestLinkedSpans(
11877
12456
  options.map,
11878
12457
  options.linked,
11879
12458
  options.optimized,
11880
12459
  options.owners,
11881
12460
  options.sectionOwners,
11882
- options.sdkSpans !== void 0
12461
+ options.sdkSpans !== void 0,
12462
+ {
12463
+ trackedObject: options.projectionObject,
12464
+ trackedObjectOwner: owner,
12465
+ trackedLinearSpans: ranges
12466
+ }
11883
12467
  );
11884
12468
  const images = planGuestProjectionRegions(
11885
12469
  options.reserved.images,
11886
12470
  options.reserved.capacities,
11887
12471
  options.sdkSpans ? [...spans, ...options.sdkSpans] : spans
11888
12472
  );
11889
- const ranges = guestLinkedSpans(
11890
- options.map,
11891
- options.linked,
11892
- options.optimized,
11893
- /* @__PURE__ */ new Map([[options.projectionObject, owner]]),
11894
- void 0,
11895
- options.sdkSpans !== void 0
11896
- ).filter((span) => span.space === "linear-memory");
11897
12473
  const result = Buffer.from(options.optimized);
11898
12474
  const data = guestWasmDataSegments(options.optimized, options.sdkSpans === void 0);
11899
12475
  const locations = /* @__PURE__ */ new Map();
@@ -13294,7 +13870,7 @@ function occurrences(plan, args) {
13294
13870
  throw new Error("guest plan does not match linker inputs");
13295
13871
  return found;
13296
13872
  }
13297
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13873
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
13298
13874
  const rows = whyExtract.trimEnd().split("\n");
13299
13875
  if (rows.shift() !== "reference extracted symbol")
13300
13876
  throw new Error("invalid wasm-ld extraction report");
@@ -13309,8 +13885,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13309
13885
  for (const file of extracted)
13310
13886
  if (!traced.has(file))
13311
13887
  throw new Error(`extracted guest input is absent from link trace ${file}`);
13888
+ const foundOccurrences = occurrences(plan, args);
13889
+ const archivePaths = /* @__PURE__ */ new Set();
13890
+ for (const { artifact } of foundOccurrences)
13891
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
13892
+ const tracedMembers = /* @__PURE__ */ new Map();
13893
+ if (archivePaths.size > 0) {
13894
+ const archivePrefixes = [...archivePaths].map(
13895
+ (archivePath) => [archivePath, `${archivePath}(`]
13896
+ );
13897
+ for (const item of traced) {
13898
+ if (!item.endsWith(")")) continue;
13899
+ const open = item.lastIndexOf("(");
13900
+ if (open > 0) {
13901
+ const archivePath = item.slice(0, open);
13902
+ if (archivePaths.has(archivePath)) {
13903
+ let list = tracedMembers.get(archivePath);
13904
+ if (!list) tracedMembers.set(archivePath, list = []);
13905
+ list.push(item.slice(open + 1, -1));
13906
+ continue;
13907
+ }
13908
+ }
13909
+ for (const [archivePath, prefix] of archivePrefixes) {
13910
+ if (item.startsWith(prefix)) {
13911
+ let list = tracedMembers.get(archivePath);
13912
+ if (!list) tracedMembers.set(archivePath, list = []);
13913
+ list.push(item.slice(prefix.length, -1));
13914
+ }
13915
+ }
13916
+ }
13917
+ }
13312
13918
  const result = [];
13313
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
13919
+ for (const { artifact, lazy, whole } of foundOccurrences) {
13314
13920
  if (artifact.kind === "object") {
13315
13921
  if (!lazy && !traced.has(artifact.path))
13316
13922
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -13318,15 +13924,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13318
13924
  result.push({ artifact: artifact.path, member: null });
13319
13925
  continue;
13320
13926
  }
13321
- const prefix = `${artifact.path}(`;
13322
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
13323
- const members = readArMembers(import_node_fs24.default.readFileSync(artifact.path));
13927
+ const names = tracedMembers.get(artifact.path) ?? [];
13928
+ const nameSet = new Set(names);
13929
+ let members = archiveCache?.get(artifact.path);
13930
+ if (!members) {
13931
+ members = readArMembers(import_node_fs24.default.readFileSync(artifact.path));
13932
+ archiveCache?.set(artifact.path, members);
13933
+ }
13934
+ const memberCounts = /* @__PURE__ */ new Map();
13324
13935
  for (const member of members) {
13325
- if (whole || names.includes(member.name))
13936
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
13937
+ if (whole || nameSet.has(member.name))
13326
13938
  result.push({ artifact: artifact.path, member: member.name });
13327
13939
  }
13328
13940
  for (const name3 of names)
13329
- if (members.filter((member) => member.name === name3).length !== 1)
13941
+ if (memberCounts.get(name3) !== 1)
13330
13942
  throw new Error(
13331
13943
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
13332
13944
  );
@@ -13403,14 +14015,25 @@ function linkGuestImages(options) {
13403
14015
  }
13404
14016
  const archives = /* @__PURE__ */ new Map();
13405
14017
  const memberBytes = /* @__PURE__ */ new Map();
14018
+ const objectBytes = /* @__PURE__ */ new Map();
13406
14019
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
13407
14020
  const providerSymbol = "__peach_dlsym_from_image";
13408
14021
  const readSelected = (item) => {
13409
- if (item.member === null) return import_node_fs24.default.readFileSync(item.artifact);
14022
+ if (item.member === null) {
14023
+ let bytes = objectBytes.get(item.artifact);
14024
+ if (!bytes) {
14025
+ bytes = import_node_fs24.default.readFileSync(item.artifact);
14026
+ objectBytes.set(item.artifact, bytes);
14027
+ }
14028
+ return bytes;
14029
+ }
13410
14030
  let byName = memberBytes.get(item.artifact);
13411
14031
  if (!byName) {
13412
- const members = readArMembers(import_node_fs24.default.readFileSync(item.artifact));
13413
- archives.set(item.artifact, members);
14032
+ let members = archives.get(item.artifact);
14033
+ if (!members) {
14034
+ members = readArMembers(import_node_fs24.default.readFileSync(item.artifact));
14035
+ archives.set(item.artifact, members);
14036
+ }
13414
14037
  byName = /* @__PURE__ */ new Map();
13415
14038
  for (const member of members)
13416
14039
  if (!byName.has(member.name))
@@ -13434,7 +14057,13 @@ function linkGuestImages(options) {
13434
14057
  `--why-extract=${whyPath}`,
13435
14058
  `--Map=${mapPath}`
13436
14059
  ]);
13437
- return selectedGuestLinkInputs(plan, args, import_node_fs24.default.readFileSync(whyPath, "utf8"), trace);
14060
+ return selectedGuestLinkInputs(
14061
+ plan,
14062
+ args,
14063
+ import_node_fs24.default.readFileSync(whyPath, "utf8"),
14064
+ trace,
14065
+ archives
14066
+ );
13438
14067
  };
13439
14068
  const needsProvider = (item) => {
13440
14069
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -13474,7 +14103,7 @@ function linkGuestImages(options) {
13474
14103
  )
13475
14104
  ]);
13476
14105
  const originalOwnership = identity(plan);
13477
- const resolved = options.resolvePlan(selected, plan);
14106
+ const resolved = options.resolvePlan(selected, plan, readSelected);
13478
14107
  if (identity(resolved) !== originalOwnership)
13479
14108
  throw new Error("resolved guest scopes changed input ownership");
13480
14109
  plan = resolved;
@@ -13528,6 +14157,7 @@ function linkGuestImages(options) {
13528
14157
  }
13529
14158
  }
13530
14159
  let discoveryRegions;
14160
+ let liveSymbols;
13531
14161
  if (discoveryProjection && options.projection) {
13532
14162
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options.projection.image]]);
13533
14163
  for (const item of selected)
@@ -13536,10 +14166,15 @@ function linkGuestImages(options) {
13536
14166
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
13537
14167
  );
13538
14168
  const wasm = import_node_fs24.default.readFileSync(discovery);
14169
+ liveSymbols = /* @__PURE__ */ new Set();
13539
14170
  discoveryRegions = guestProjectionRegionCounts(
13540
14171
  plan.images.length,
13541
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
14172
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
14173
+ collectSymbols: liveSymbols
14174
+ })
13542
14175
  );
14176
+ } else {
14177
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
13543
14178
  }
13544
14179
  const ledger = createGuestImageLedger({
13545
14180
  images: plan.images.map((image) => ({
@@ -13548,7 +14183,7 @@ function linkGuestImages(options) {
13548
14183
  })),
13549
14184
  callers: plan.callers,
13550
14185
  symbols: plan.symbols,
13551
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
14186
+ liveSymbols,
13552
14187
  commandLineSymbols: commandLineSymbols(args),
13553
14188
  directBindings: plan.directBindings,
13554
14189
  registerAppTables: sdkCallers !== void 0,
@@ -13680,7 +14315,8 @@ function linkGuestImages(options) {
13680
14315
  const selectedInputs = selectedGuestManifestInputs(
13681
14316
  plan,
13682
14317
  selected,
13683
- projection.identities
14318
+ projection.identities,
14319
+ readSelected
13684
14320
  );
13685
14321
  const images = projection.images.map(
13686
14322
  (image) => createGuestImageManifest({
@@ -13690,6 +14326,9 @@ function linkGuestImages(options) {
13690
14326
  regions: []
13691
14327
  })
13692
14328
  );
14329
+ objectBytes.clear();
14330
+ memberBytes.clear();
14331
+ archives.clear();
13693
14332
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
13694
14333
  const regionsBefore = discoveryRegions;
13695
14334
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs24.default.readFileSync(ledgerObject)], 0);
@@ -13783,10 +14422,47 @@ ${changed.join("\n")}`
13783
14422
  }
13784
14423
  function linkedMapSymbols(lines) {
13785
14424
  const names = /* @__PURE__ */ new Set();
13786
- const symbol = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
13787
14425
  for (const line of lines) {
13788
- const match = symbol.exec(line);
13789
- if (match) names.add(match[1]);
14426
+ const length = line.length;
14427
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
14428
+ let pos = 1;
14429
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14430
+ const c1 = pos;
14431
+ while (pos < length) {
14432
+ const ch = line.charCodeAt(pos);
14433
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
14434
+ pos++;
14435
+ }
14436
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
14437
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14438
+ const c2 = pos;
14439
+ while (pos < length) {
14440
+ const ch = line.charCodeAt(pos);
14441
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
14442
+ pos++;
14443
+ }
14444
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
14445
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14446
+ const c3 = pos;
14447
+ while (pos < length) {
14448
+ const ch = line.charCodeAt(pos);
14449
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
14450
+ pos++;
14451
+ }
14452
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
14453
+ const sStart = pos;
14454
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14455
+ if (pos - sStart < 9 || pos >= length) continue;
14456
+ const first = line.charCodeAt(pos);
14457
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
14458
+ continue;
14459
+ let end = pos + 1;
14460
+ while (end < length) {
14461
+ const ch = line.charCodeAt(end);
14462
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
14463
+ end++;
14464
+ }
14465
+ names.add(line.slice(pos, end));
13790
14466
  }
13791
14467
  return names;
13792
14468
  }
@@ -13885,7 +14561,7 @@ function discoverGuestLinkInputs(options) {
13885
14561
  import_node_fs24.default.mkdirSync(options.directory, { recursive: true });
13886
14562
  const why = import_node_path24.default.join(options.directory, "preselection-why.txt");
13887
14563
  const response = import_node_path24.default.join(options.directory, "preselection.rsp");
13888
- const output = import_node_path24.default.join(options.directory, "preselection.wasm");
14564
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path24.default.join(options.directory, "preselection.wasm");
13889
14565
  const flags = [
13890
14566
  ...withOutput(args, output, true),
13891
14567
  ...options.objects,
@@ -13983,7 +14659,7 @@ function prepareGuestRuntimeInputs(options) {
13983
14659
  });
13984
14660
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
13985
14661
  }
13986
- function selectedGuestSymbolInputs(plan, selected) {
14662
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
13987
14663
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
13988
14664
  const archives = /* @__PURE__ */ new Map();
13989
14665
  const symbols = /* @__PURE__ */ new Set();
@@ -13999,22 +14675,27 @@ function selectedGuestSymbolInputs(plan, selected) {
13999
14675
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
14000
14676
  let bytes;
14001
14677
  let name3 = item.artifact;
14002
- if (item.member === null) bytes = import_node_fs24.default.readFileSync(item.artifact);
14003
- else {
14004
- let members = archives.get(item.artifact);
14005
- if (!members) {
14006
- members = Map.groupBy(
14007
- readArMembers(import_node_fs24.default.readFileSync(item.artifact)),
14008
- (member) => member.name
14009
- );
14010
- archives.set(item.artifact, members);
14678
+ if (item.member === null) {
14679
+ bytes = readSelected ? readSelected(item) : import_node_fs24.default.readFileSync(item.artifact);
14680
+ } else {
14681
+ if (readSelected) {
14682
+ bytes = readSelected(item);
14683
+ } else {
14684
+ let members = archives.get(item.artifact);
14685
+ if (!members) {
14686
+ members = Map.groupBy(
14687
+ readArMembers(import_node_fs24.default.readFileSync(item.artifact)),
14688
+ (member) => member.name
14689
+ );
14690
+ archives.set(item.artifact, members);
14691
+ }
14692
+ const matching = members.get(item.member) ?? [];
14693
+ if (matching.length !== 1)
14694
+ throw new Error(
14695
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
14696
+ );
14697
+ bytes = matching[0].bytes;
14011
14698
  }
14012
- const matching = members.get(item.member) ?? [];
14013
- if (matching.length !== 1)
14014
- throw new Error(
14015
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
14016
- );
14017
- bytes = matching[0].bytes;
14018
14699
  name3 += `(${item.member})`;
14019
14700
  }
14020
14701
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -14027,9 +14708,9 @@ function selectedGuestSymbolInputs(plan, selected) {
14027
14708
  for (const symbol of names.tags) tags.add(symbol);
14028
14709
  for (const symbol of names.defined) {
14029
14710
  definitions.add(symbol);
14030
- const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14711
+ let objects = definitionObjects.get(symbol);
14712
+ if (!objects) definitionObjects.set(symbol, objects = /* @__PURE__ */ new Set());
14031
14713
  objects.add(name3);
14032
- definitionObjects.set(symbol, objects);
14033
14714
  }
14034
14715
  }
14035
14716
  return {
@@ -14050,7 +14731,7 @@ function verifyGuestSymbolScopes(options) {
14050
14731
  if (!symbols.length) return { bindings: [], directBindings: [] };
14051
14732
  import_node_fs24.default.mkdirSync(options.directory, { recursive: true });
14052
14733
  const response = import_node_path24.default.join(options.directory, "scope-trace.rsp");
14053
- const output = import_node_path24.default.join(options.directory, "scope-trace.wasm");
14734
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path24.default.join(options.directory, "scope-trace.wasm");
14054
14735
  const args = [
14055
14736
  ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
14056
14737
  ...options.objects,
@@ -14068,55 +14749,76 @@ function verifyGuestSymbolScopes(options) {
14068
14749
  import_node_fs24.default.closeSync(traceOutput);
14069
14750
  }
14070
14751
  const records = /* @__PURE__ */ new Map();
14071
- const consume = (line) => {
14072
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
14073
- if (!match) return;
14074
- const [, object3, kind, symbol] = match;
14075
- if (!requested.has(symbol)) return;
14076
- if (options.hostImports.has(symbol)) return;
14077
- const record = records.get(symbol) ?? {
14078
- references: /* @__PURE__ */ new Map(),
14079
- providers: /* @__PURE__ */ new Map(),
14080
- physicalModule: false
14081
- };
14752
+ for (const line of guestLinkLines(tracePath)) {
14753
+ const refSep = line.lastIndexOf(": reference to ");
14754
+ const defSep = line.lastIndexOf(": definition of ");
14755
+ if (refSep < 0 && defSep < 0) continue;
14756
+ const isRef = refSep > defSep;
14757
+ const sep = isRef ? refSep : defSep;
14758
+ const symbol = line.slice(sep + (isRef ? 15 : 16));
14759
+ if (!requested.has(symbol) || options.hostImports.has(symbol)) continue;
14760
+ let record = records.get(symbol);
14761
+ if (!record) {
14762
+ record = {
14763
+ references: /* @__PURE__ */ new Map(),
14764
+ providers: /* @__PURE__ */ new Map(),
14765
+ physicalModule: false
14766
+ };
14767
+ records.set(symbol, record);
14768
+ }
14769
+ const object3 = line.slice(0, sep);
14082
14770
  if (object3 === "<internal>") {
14083
- if (kind === "definition of") record.physicalModule = true;
14771
+ if (!isRef) record.physicalModule = true;
14084
14772
  } else {
14085
14773
  const image = options.owners.get(object3);
14086
14774
  if (image === void 0)
14087
14775
  throw new Error(`traced guest object has no owner ${object3}`);
14088
- (kind === "reference to" ? record.references : record.providers).set(
14089
- object3,
14090
- image
14091
- );
14776
+ (isRef ? record.references : record.providers).set(object3, image);
14092
14777
  }
14093
- records.set(symbol, record);
14094
- };
14095
- for (const line of guestLinkLines(tracePath)) consume(line);
14778
+ }
14096
14779
  const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]));
14780
+ const callerSets = new Map(
14781
+ options.callers.map((caller) => [caller.image, new Set(caller.next)])
14782
+ );
14783
+ const rootScope = callerSets.get(0);
14097
14784
  const result = [];
14098
14785
  const directBindings = [];
14099
14786
  for (const symbol of symbols) {
14100
14787
  const record = records.get(symbol);
14101
14788
  if (!record || !record.references.size) continue;
14102
14789
  if (!record.providers.size && options.hostImports.has(symbol)) continue;
14103
- const startupReferences = [...record.references].filter(
14104
- ([object3]) => options.startupObjects.has(object3) && options.weakReferences.get(object3)?.has(symbol)
14105
- );
14106
- const otherReferences = [...record.references].filter(
14107
- ([object3]) => !startupReferences.some(([startup]) => startup === object3)
14108
- );
14790
+ const startupReferences = [];
14791
+ const otherReferences = [];
14792
+ let allWeakRefs = true;
14793
+ for (const [object3, caller] of record.references) {
14794
+ const isWeakRef = options.weakReferences.get(object3)?.has(symbol) === true;
14795
+ if (!isWeakRef) allWeakRefs = false;
14796
+ if (isWeakRef && options.startupObjects.has(object3)) {
14797
+ startupReferences.push([object3, caller]);
14798
+ } else {
14799
+ otherReferences.push([object3, caller]);
14800
+ }
14801
+ }
14109
14802
  for (const [, caller] of startupReferences)
14110
14803
  if (!callers.has(caller))
14111
14804
  throw new Error(`guest image has no caller scope ${caller}`);
14112
14805
  if (startupReferences.length && !record.physicalModule) {
14113
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14114
- if (candidates.size > 1 || record.providers.size > 1)
14806
+ const candidates2 = options.definitionObjects.get(symbol);
14807
+ const candidateSize = candidates2?.size ?? 0;
14808
+ if (candidateSize > 1 || record.providers.size > 1)
14115
14809
  throw new Error(`ambiguous startup provider ${symbol}`);
14116
- if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object3) => !candidates.has(object3)))
14117
- throw new Error(`unproven startup provider ${symbol}`);
14810
+ let unproven = candidateSize !== record.providers.size;
14811
+ if (!unproven && candidates2) {
14812
+ for (const object3 of record.providers.keys()) {
14813
+ if (!candidates2.has(object3)) {
14814
+ unproven = true;
14815
+ break;
14816
+ }
14817
+ }
14818
+ }
14819
+ if (unproven) throw new Error(`unproven startup provider ${symbol}`);
14118
14820
  if (record.providers.size === 1) {
14119
- const [providerObject, providerImage] = [...record.providers][0];
14821
+ const [providerObject, providerImage] = record.providers.entries().next().value;
14120
14822
  if (options.weakDefinitions.get(providerObject)?.has(symbol))
14121
14823
  throw new Error(`weak startup provider ${symbol}`);
14122
14824
  for (const [object3] of startupReferences)
@@ -14124,28 +14826,34 @@ function verifyGuestSymbolScopes(options) {
14124
14826
  }
14125
14827
  if (!otherReferences.length) continue;
14126
14828
  }
14127
- if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
14128
- (object3) => options.weakReferences.get(object3)?.has(symbol)
14129
- ))
14130
- continue;
14829
+ if (!record.providers.size && !record.physicalModule && allWeakRefs) continue;
14131
14830
  const providerImages = new Set(record.providers.values());
14132
- const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
14133
- (object3) => {
14831
+ const candidates = options.definitionObjects.get(symbol);
14832
+ const copyImages = /* @__PURE__ */ new Set();
14833
+ const strongImages = /* @__PURE__ */ new Set();
14834
+ let weakDefinerImages;
14835
+ if (candidates) {
14836
+ for (const object3 of candidates) {
14134
14837
  const image = options.owners.get(object3);
14135
- return image === void 0 ? [] : [{ image, weak: !!options.weakDefinitions.get(object3)?.has(symbol) }];
14838
+ if (image === void 0) continue;
14839
+ copyImages.add(image);
14840
+ if (options.weakDefinitions.get(object3)?.has(symbol)) {
14841
+ ;
14842
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
14843
+ } else {
14844
+ strongImages.add(image);
14845
+ }
14136
14846
  }
14137
- );
14138
- const copyImages = new Set(copies.map((copy) => copy.image));
14139
- const strongImages = new Set(
14140
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
14141
- );
14847
+ }
14142
14848
  const interposed = !record.physicalModule && copyImages.size > 1;
14143
14849
  const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
14144
14850
  if (!providerCount) continue;
14145
14851
  if (providerCount !== 1)
14146
14852
  throw new Error(`guest symbol has ambiguous provider ${symbol}`);
14147
- const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
14148
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
14853
+ const scopedReferences = record.physicalModule ? record.references : otherReferences;
14854
+ const firstProviderImage = providerImages.values().next().value;
14855
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
14856
+ let interposedByCaller;
14149
14857
  for (const [object3, caller] of scopedReferences) {
14150
14858
  const scope = callers.get(caller);
14151
14859
  if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
@@ -14153,18 +14861,35 @@ function verifyGuestSymbolScopes(options) {
14153
14861
  result.push({ symbol, caller, provider: { kind: "physical-module" } });
14154
14862
  continue;
14155
14863
  }
14156
- const provider = interposed ? [caller, ...scope].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
14864
+ let provider;
14865
+ if (interposed) {
14866
+ if (interposedByCaller?.has(caller)) {
14867
+ provider = interposedByCaller.get(caller);
14868
+ } else {
14869
+ if (copyImages.has(caller)) {
14870
+ provider = caller;
14871
+ } else {
14872
+ for (const image of scope) {
14873
+ if (copyImages.has(image)) {
14874
+ provider = image;
14875
+ break;
14876
+ }
14877
+ }
14878
+ if (provider === void 0) provider = uniqueProvider;
14879
+ }
14880
+ ;
14881
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
14882
+ }
14883
+ } else {
14884
+ provider = firstProviderImage;
14885
+ }
14157
14886
  if (provider === void 0) {
14158
14887
  if (options.weakReferences.get(object3)?.has(symbol)) continue;
14159
14888
  throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
14160
14889
  }
14161
14890
  if (caller === provider) continue;
14162
- if ([...options.definitionObjects.get(symbol) ?? []].some(
14163
- (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
14164
- ))
14165
- continue;
14166
- if (!scope.includes(provider)) {
14167
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14891
+ if (weakDefinerImages?.has(caller)) continue;
14892
+ if (!callerSets.get(caller).has(provider)) {
14168
14893
  const traced = [...record.providers.keys()];
14169
14894
  const strongTraced = traced.filter(
14170
14895
  (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
@@ -14172,16 +14897,17 @@ function verifyGuestSymbolScopes(options) {
14172
14897
  const providers = strongTraced.length === 1 ? strongTraced : traced;
14173
14898
  if (options.weakReferences.get(object3)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
14174
14899
  continue;
14175
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
14900
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
14901
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
14176
14902
  (definer) => options.weakDefinitions.get(definer)?.has(symbol)
14177
14903
  );
14178
- const strongCandidates = [...candidates].filter(
14904
+ const strongCandidates = [...candidateSet].filter(
14179
14905
  (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
14180
14906
  );
14181
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
14182
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
14907
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
14908
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
14183
14909
  // scope, the root image and its dependency closure, as in elf.
14184
- provider === 0 || callers.get(0)?.includes(provider) || !options.weakReferences.get(object3)?.has(symbol) && options.frameworkProviders.get(object3)?.has(providers[0]))))
14910
+ provider === 0 || rootScope?.has(provider) || !options.weakReferences.get(object3)?.has(symbol) && options.frameworkProviders.get(object3)?.has(providers[0]))))
14185
14911
  throw new Error(
14186
14912
  `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
14187
14913
  );
@@ -18292,9 +19018,9 @@ async function compileGuestLink(options) {
18292
19018
  }
18293
19019
  };
18294
19020
  },
18295
- resolvePlan: (selected, plan) => {
19021
+ resolvePlan: (selected, plan, readSelected) => {
18296
19022
  if (!prepared) throw new Error("guest runtime selection is unavailable");
18297
- const scope = selectedGuestSymbolInputs(plan, selected);
19023
+ const scope = selectedGuestSymbolInputs(plan, selected, readSelected);
18298
19024
  const owners = new Map(scope.owners);
18299
19025
  owners.set(import_node_path37.default.join(directory, "projection-discovery.o"), 0);
18300
19026
  const providersByImage = Map.groupBy(scope.owners, ([, image]) => image);
@@ -26170,7 +26896,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
26170
26896
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
26171
26897
  MULTI_MANIFEST_VERSION = 76;
26172
26898
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
26173
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
26899
+ compilerSourceDigest = true ? "7b91fa4405159335b5484c82700e001e4c27abf15621b724ea8af4edea693f66" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
26174
26900
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
26175
26901
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
26176
26902
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));