peachsim 0.1.2588 → 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 (140) 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 +1174 -447
  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-DG2TVZRD.mjs → acorn-65FNEARV.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-LW5F24Y7.mjs → chunk-2GUB5OLB.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-4PNMHEJB.mjs → chunk-462CWTWI.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-ASL4MACC.mjs → chunk-4VCRUQ36.mjs} +1180 -453
  30. package/dist-lib/esm-chunks/{chunk-UFXK4UQL.mjs → chunk-5GNGHM5B.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-BAU3IFLL.mjs → chunk-ADKUIQXX.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-4GOTTBDL.mjs → chunk-BZS5SIYK.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-JE7EWYAV.mjs → chunk-EFKDUMB5.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-WZHOX3BM.mjs → chunk-GBD26EBV.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-QRKZ3NSY.mjs → chunk-HZTK7TP5.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-ELSAXANF.mjs → chunk-JG4AANWA.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-V2PI4V6K.mjs → chunk-N2II5SRJ.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-C7MHFZIA.mjs → chunk-NZY4GOG5.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-AGQHPM6E.mjs → chunk-OZJ66CXY.mjs} +2 -2
  40. package/dist-lib/esm-chunks/{chunk-PL3OUSN3.mjs → chunk-RGC2JNCL.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-GIS6FXRN.mjs → chunk-SLPXTLBK.mjs} +5 -5
  42. package/dist-lib/esm-chunks/{chunk-BSPFA6V2.mjs → chunk-SRFKOU76.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-BGCADZA2.mjs → chunk-V5TTEXYO.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-NSNT4FFS.mjs → chunk-WPDY5IAD.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-YHJXN2S6.mjs → chunk-WYDRQRJL.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-CJ6UJWGD.mjs → chunk-X2EKFONU.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-OLEYCMVV.mjs → chunk-XE3VHAU2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-SDGYG4FM.mjs → chunk-YPPH6F77.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-VWCTMFOO.mjs → metro-layout-parser-CRI3GMCM.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-W7FEW6PS.mjs → swift-package-prebuilt-5XDZ2HZZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-J4KH7G35.mjs → swift-sdk-app-module-6H3G6AXD.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-MUWMBAKB.mjs → swift-sdk-image-WAC7GG2R.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-BLO2DZ2C.mjs → swift-sdk-image-producer-B3L27QTG.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1173 -446
  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 +1215 -480
  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 +1225 -484
  93. package/dist-lib/swift-compile.cjs +1170 -443
  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/dist-types/packages/peach-engine/src/ios/apps/canvas-map-data.d.ts +1 -1
  126. package/kotlin/sdk.tar.gz +0 -0
  127. package/package.json +1 -1
  128. package/src/one-native-controls-package.ts +8 -7
  129. package/src/swift-guest-compile.ts +2 -2
  130. package/src/swift-guest-dyld-table.ts +9 -2
  131. package/src/swift-guest-image-ledger.ts +403 -208
  132. package/src/swift-guest-link.ts +255 -113
  133. package/src/swift-guest-linked-spans.ts +217 -28
  134. package/src/swift-guest-manifest.ts +24 -13
  135. package/src/swift-guest-projection-storage.ts +6 -8
  136. package/src/swift-guest-projection.ts +7 -6
  137. package/src/swift-sdk-image-map.ts +137 -35
  138. package/src/swift-shared-sdk.ts +8 -4
  139. package/src/swift-wasm-prune.ts +263 -85
  140. package/src/swiftGuestImageContract.ts +1 -1
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2588 | (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;
@@ -4437,6 +4437,7 @@ function stageOverlaySlot(realRoot, stagingRoot, relPath) {
4437
4437
  const segment = segments[i];
4438
4438
  for (const entry of (0, import_node_fs11.readdirSync)(real)) {
4439
4439
  if (entry === segment || i === 0 && entry === SWIFT_CACHE_HOLD_MARKER) continue;
4440
+ if (mirror === stagingRoot && entry === "configuration") continue;
4440
4441
  const dest = import_node_path11.default.join(mirror, entry);
4441
4442
  if (!import_node_fs11.default.lstatSync(dest, { throwIfNoEntry: false })) {
4442
4443
  import_node_fs11.default.symlinkSync(import_node_path11.default.join(real, entry), dest);
@@ -4471,7 +4472,7 @@ function swiftSharedSdkViewOptions(moduleRoot, distribution, toolchainBin, sdk)
4471
4472
  const stdint = import_node_path11.default.join(overlay, "include/stdint.h");
4472
4473
  const key = JSON.stringify([
4473
4474
  // bump the recipe when the transformation changes; bundling changes function text.
4474
- "v38",
4475
+ "v39",
4475
4476
  [...WEAKEN_FOUNDATION_SYMS],
4476
4477
  toolchainBin,
4477
4478
  sdk,
@@ -6191,24 +6192,56 @@ function layout(bytes, readData = true, requireExports = true) {
6191
6192
  const code = sections.get(10);
6192
6193
  if (code) {
6193
6194
  let pos = code[0];
6194
- let count;
6195
- [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
+ }
6196
6208
  for (let i = 0; i < count; i++) {
6197
6209
  const prefix = pos;
6198
- let size;
6199
- [size, pos] = number(bytes, pos);
6200
- 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);
6201
6226
  if (imports + i === startFunction) startup = bytes.subarray(pos, pos + size);
6202
6227
  pos += size;
6203
- if (pos > code[1]) throw new Error("invalid wasm code");
6228
+ if (pos > codeEnd) throw new Error("invalid wasm code");
6204
6229
  }
6205
- if (pos !== code[1]) throw new Error("invalid wasm code section");
6230
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
6206
6231
  }
6207
6232
  const functionsByTableSlot = /* @__PURE__ */ new Map();
6208
6233
  const elements = sections.get(9);
6209
6234
  if (elements) {
6210
6235
  let pos = elements[0];
6236
+ const elemEnd = elements[1];
6211
6237
  const read = () => {
6238
+ if (pos < elemEnd) {
6239
+ const b0 = bytes[pos];
6240
+ if (b0 < 128) {
6241
+ pos++;
6242
+ return b0;
6243
+ }
6244
+ }
6212
6245
  const [value, next] = number(bytes, pos);
6213
6246
  pos = next;
6214
6247
  return value;
@@ -6238,7 +6271,7 @@ function layout(bytes, readData = true, requireExports = true) {
6238
6271
  functionsByTableSlot.set(slot, read());
6239
6272
  }
6240
6273
  }
6241
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
6274
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
6242
6275
  }
6243
6276
  const data = [];
6244
6277
  const passive = /* @__PURE__ */ new Map();
@@ -6303,36 +6336,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
6303
6336
  length: segment.bytes.length
6304
6337
  }));
6305
6338
  }
6306
- 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) {
6307
6357
  const unchanged = before === after;
6308
6358
  const original = layout(before, !unchanged, !importsLayout);
6309
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;
6310
6365
  let codeOffset;
6311
6366
  let outputSection = "";
6312
6367
  const codeOwners = /* @__PURE__ */ new Map();
6313
6368
  const pieces = [];
6314
- for (const line of typeof map === "string" ? map.split("\n") : map) {
6315
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
6316
- if (!match) continue;
6317
- const [, address, offset, size, indent, source] = match;
6318
- if (address === "-" && indent === " ") {
6319
- outputSection = source;
6320
- 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;
6321
6431
  continue;
6322
6432
  }
6323
- const separator = source.indexOf(":(");
6433
+ if (sizeVal === 0) continue;
6434
+ const separator = line.indexOf(":(", sourceStart);
6324
6435
  if (separator < 0) continue;
6325
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
6326
- const length = parseInt(size, 16);
6327
- if (!length) continue;
6328
- if (address !== "-") {
6329
- if (outputSection === "DATA")
6330
- 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
+ }
6331
6469
  continue;
6332
6470
  }
6333
6471
  if (image === void 0 || outputSection !== "CODE") continue;
6334
6472
  if (codeOffset === void 0) throw new Error("link map has no code section");
6335
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
6473
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
6336
6474
  if (index === void 0) throw new Error("link map function has no wasm body");
6337
6475
  const existing = codeOwners.get(index);
6338
6476
  if (existing !== void 0 && existing !== image)
@@ -6341,12 +6479,23 @@ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE
6341
6479
  }
6342
6480
  pieces.sort((a, b) => a.address - b.address);
6343
6481
  const spans = [];
6344
- for (const [index, { image, address, length }] of pieces.entries()) {
6345
- 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;
6346
6486
  let next = index + 1;
6347
6487
  while (next < pieces.length && pieces[next].address < address + length) next++;
6348
6488
  const end = pieces[next]?.address ?? address + length;
6349
- 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
+ });
6350
6499
  }
6351
6500
  const optimizedOwners = /* @__PURE__ */ new Map();
6352
6501
  const dataAt = (module2, start, length) => {
@@ -6385,7 +6534,7 @@ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE
6385
6534
  throw new Error(`optimization changed linked data at ${span.address}`);
6386
6535
  }
6387
6536
  let previous;
6388
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
6537
+ for (const span of spans) {
6389
6538
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
6390
6539
  throw new Error("linked data belongs to multiple images");
6391
6540
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -6567,6 +6716,20 @@ var init_swift_guest_linked_spans = __esm({
6567
6716
  });
6568
6717
 
6569
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
+ }
6570
6733
  function readWasmLinkMap(file, partition) {
6571
6734
  const segments = /* @__PURE__ */ new Map();
6572
6735
  const data = [];
@@ -6574,48 +6737,117 @@ function readWasmLinkMap(file, partition) {
6574
6737
  let kind = "";
6575
6738
  let segment = "";
6576
6739
  let previous;
6577
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
6578
6740
  for (const line of guestLinkLines(file)) {
6579
- const symbol = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
6580
- if (symbol) {
6581
- previous?.symbols.push({
6582
- name: symbol[3],
6583
- address: hex(symbol[1]),
6584
- size: parseInt(symbol[2], 16)
6585
- });
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
+ }
6586
6791
  continue;
6587
6792
  }
6588
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
6589
- if (output) {
6590
- 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
+ }
6591
6809
  continue;
6592
6810
  }
6593
- if (kind === "DATA") {
6594
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
6595
- if (top) {
6596
- segment = top[3];
6597
- segments.set(segment, { address: hex(top[1]), size: parseInt(top[2], 16) });
6598
- 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
+ }
6599
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);
6600
6850
  }
6601
- if (kind !== "DATA" && kind !== "CODE") continue;
6602
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
6603
- if (!input) continue;
6604
- const name3 = input[4];
6605
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
6606
- const path42 = split ? split[1] : name3;
6607
- const member = /\(([^()]+)\)$/.exec(path42);
6608
- previous = {
6609
- inputFile: path42,
6610
- segment,
6611
- address: hex(input[1]),
6612
- offset: parseInt(input[2], 16),
6613
- size: parseInt(input[3], 16),
6614
- object: (member ? member[1] : (0, import_node_path16.basename)(path42)).replace(/^lib\w*?__/, ""),
6615
- section: split ? split[2] : "",
6616
- symbols: []
6617
- };
6618
- (kind === "DATA" ? data : code).push(previous);
6619
6851
  }
6620
6852
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
6621
6853
  }
@@ -7761,6 +7993,7 @@ function patchSwiftrtObject(src) {
7761
7993
  return buf;
7762
7994
  }
7763
7995
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7996
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
7764
7997
  let pos = 8;
7765
7998
  let numImportFuncs = 0;
7766
7999
  let importsDlsym = false;
@@ -7796,10 +8029,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7796
8029
  let [cnt, cp] = readULEB2(buf, p);
7797
8030
  for (let i = 0; i < cnt; i++) {
7798
8031
  const [mLen, m2] = readULEB2(buf, cp);
7799
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
8032
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
7800
8033
  cp = m2 + mLen;
7801
8034
  const [fLen, f2] = readULEB2(buf, cp);
7802
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
8035
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
7803
8036
  cp = f2 + fLen;
7804
8037
  const kind = buf[cp++];
7805
8038
  if (kind === 0) {
@@ -7879,7 +8112,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7879
8112
  }
7880
8113
  } else if (id === 0) {
7881
8114
  const [nLen, np] = readULEB2(buf, p);
7882
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
8115
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
7883
8116
  const cp = np + nLen;
7884
8117
  if (name3 === "linking") {
7885
8118
  let [, lp] = readULEB2(buf, cp);
@@ -7892,7 +8125,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7892
8125
  let cur = p2;
7893
8126
  for (let i = 0; i < cnt; i++) {
7894
8127
  const [sLen, s2] = readULEB2(buf, cur);
7895
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
8128
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
7896
8129
  cur = s2 + sLen;
7897
8130
  const [, s3] = readULEB2(buf, cur);
7898
8131
  const [fl, s4] = readULEB2(buf, s3);
@@ -7932,7 +8165,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7932
8165
  let sName = "";
7933
8166
  if (!isUndef || isExplicitName) {
7934
8167
  const [sLen, c4] = readULEB2(buf, cur);
7935
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
8168
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
7936
8169
  cur = c4 + sLen;
7937
8170
  } else if (kind === 0) {
7938
8171
  sName = importFuncNames[el] ?? "";
@@ -7948,7 +8181,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7948
8181
  symNames.push(sName);
7949
8182
  } else if (kind === 1) {
7950
8183
  const [sLen, c3] = readULEB2(buf, cur);
7951
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
8184
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
7952
8185
  cur = c3 + sLen;
7953
8186
  if (!isUndef) {
7954
8187
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -8063,9 +8296,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
8063
8296
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
8064
8297
  let ownerSymIdx = -1;
8065
8298
  const topList = segTopSyms.get(lo);
8066
- if (topList) {
8067
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
8068
- 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
+ }
8069
8314
  }
8070
8315
  if (ownerSymIdx !== -1) {
8071
8316
  let list = symDataRelocs.get(ownerSymIdx);
@@ -8303,54 +8548,151 @@ function parseWasmObjectCached(file, isDist, entries2) {
8303
8548
  return parsed;
8304
8549
  }
8305
8550
  function guestWasmSymbols(bytes) {
8306
- 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
+ }
8307
8683
  return {
8308
- importsDlsym: object3.importsDlsym,
8309
- undefined: [
8310
- ...new Set(
8311
- object3.symNames.filter(
8312
- (name3, index) => name3 && (object3.symFlags[index] & 16) !== 0
8313
- )
8314
- )
8315
- ],
8684
+ importsDlsym,
8685
+ undefined: [...undefinedSyms],
8316
8686
  // a wasm tag is one module entity unified by name across the link, as the
8317
8687
  // main module owns it for dynamic images, so no image scope applies.
8318
- tags: [
8319
- ...new Set(
8320
- object3.symNames.filter((name3, index) => name3 && object3.symKind[index] === 4)
8321
- )
8322
- ],
8323
- globals: [
8324
- ...new Set(
8325
- object3.symNames.filter(
8326
- (name3, index) => name3 && (object3.symKind[index] === 2 || object3.symKind[index] === 5)
8327
- )
8328
- )
8329
- ],
8688
+ tags: [...tags],
8689
+ globals: [...globals],
8330
8690
  // an undefined function imported from a module other than env is supplied
8331
8691
  // by the host, whatever linker symbol names it.
8332
- hostImports: [...object3.hostImportNames],
8333
- weakUndefined: [
8334
- ...new Set(
8335
- object3.symNames.filter(
8336
- (name3, index) => name3 && (object3.symFlags[index] & 19) === 17
8337
- )
8338
- )
8339
- ],
8340
- defined: [
8341
- ...new Set(
8342
- object3.symNames.filter(
8343
- (name3, index) => name3 && (object3.symFlags[index] & 16) === 0 && (object3.symFlags[index] & 3) !== 2
8344
- )
8345
- )
8346
- ],
8347
- weakDefined: [
8348
- ...new Set(
8349
- object3.symNames.filter(
8350
- (name3, index) => name3 && (object3.symFlags[index] & 19) === 1
8351
- )
8352
- )
8353
- ]
8692
+ hostImports: [...hostImports],
8693
+ weakUndefined: [...weakUndefined],
8694
+ defined: [...defined],
8695
+ weakDefined: [...weakDefined]
8354
8696
  };
8355
8697
  }
8356
8698
  function sdkObjectName(archive, member, ordinal) {
@@ -8867,9 +9209,12 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8867
9209
  for (const entry of waiting) tryActivateConformance(entry);
8868
9210
  }
8869
9211
  };
9212
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
8870
9213
  const checkProtocolTrigger = (rawSymName) => {
8871
9214
  if (!rawSymName) return;
8872
9215
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
9216
+ if (checkedProtocolTriggers.has(sName)) return;
9217
+ checkedProtocolTriggers.add(sName);
8873
9218
  if (knownProtocols.has(sName)) {
8874
9219
  markProtocolLive(sName);
8875
9220
  return;
@@ -8902,6 +9247,43 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8902
9247
  }
8903
9248
  }
8904
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
+ };
8905
9287
  const markTypeLive = (obj, pref) => {
8906
9288
  const set = liveTypes.get(obj);
8907
9289
  if (set.has(pref)) return;
@@ -8915,22 +9297,10 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8915
9297
  const outer = pref.slice(0, n);
8916
9298
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
8917
9299
  }
8918
- const mnName = `${pref}Mn`;
8919
- for (let i = 0; i < obj.symNames.length; i++) {
8920
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
8921
- activateSymbolInObj(obj, i);
8922
- }
8923
- }
8924
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
8925
- if (p === pref) {
8926
- markFuncLive(obj, lf);
8927
- }
8928
- }
8929
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
8930
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
8931
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
8932
- }
8933
- }
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);
8934
9304
  };
8935
9305
  const checkTypeTrigger = (obj, rawSymName) => {
8936
9306
  if (!rawSymName) return;
@@ -8955,11 +9325,12 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8955
9325
  }
8956
9326
  }
8957
9327
  }
8958
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
8959
- for (const pref of obj.typePrefixesInObj) {
8960
- if (sName.startsWith(pref)) {
8961
- markTypeLive(obj, pref);
8962
- }
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);
8963
9334
  }
8964
9335
  }
8965
9336
  };
@@ -9052,7 +9423,8 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
9052
9423
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
9053
9424
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
9054
9425
  for (const name3 of obj.symNames) {
9055
- 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];
9056
9428
  if (!loaded) continue;
9057
9429
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded}`);
9058
9430
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -9200,14 +9572,30 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
9200
9572
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
9201
9573
  const range = obj.segPayloadRanges[segIdx];
9202
9574
  if (!range) return;
9575
+ const [rangeStart, rangeEnd] = range;
9576
+ if (rangeEnd - rangeStart < 4) return;
9203
9577
  let bytes = objectBytes.get(obj);
9204
9578
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs16.default.readFileSync(obj.file));
9205
- const text2 = bytes.toString("latin1", range[0], range[1]);
9206
- for (const match of text2.matchAll(/So(\d+)/g)) {
9207
- const start = match.index + 2 + match[1].length;
9208
- const length = Number(match[1]);
9209
- if (text2[start + length] !== "C") continue;
9210
- 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)}`;
9211
9599
  for (const provider of lazyProviders.get(symbol) ?? []) {
9212
9600
  eagerDynamicObjects.add(provider);
9213
9601
  extractObject(provider);
@@ -10144,6 +10532,10 @@ var init_nativeDyldTableContract = __esm({
10144
10532
 
10145
10533
  // src/swift-guest-image-ledger.ts
10146
10534
  function readNumber(bytes, position) {
10535
+ if (position < bytes.length) {
10536
+ const first = bytes[position];
10537
+ if (first < 128) return [first, position + 1];
10538
+ }
10147
10539
  let value = 0;
10148
10540
  let shift = 0;
10149
10541
  for (; ; ) {
@@ -10155,6 +10547,7 @@ function readNumber(bytes, position) {
10155
10547
  }
10156
10548
  }
10157
10549
  function encodeNumber(value) {
10550
+ if (value < 128) return Buffer.from([value]);
10158
10551
  const bytes = [];
10159
10552
  do {
10160
10553
  let byte = value % 128;
@@ -10176,6 +10569,9 @@ function encodedString(value) {
10176
10569
  const bytes = Buffer.from(value);
10177
10570
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
10178
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
+ }
10179
10575
  function llvmType(value) {
10180
10576
  switch (value) {
10181
10577
  case 127:
@@ -10191,11 +10587,12 @@ function llvmType(value) {
10191
10587
  }
10192
10588
  }
10193
10589
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options = {}) {
10194
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
10195
- 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);
10196
10592
  const { sdkLookupOnly, sdkProduct } = options;
10197
10593
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
10198
- 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;
10199
10596
  const types = [];
10200
10597
  const functionTypes = [];
10201
10598
  const definitions = [];
@@ -10209,45 +10606,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10209
10606
  const usedSymbols = /* @__PURE__ */ new Set();
10210
10607
  let position = 8;
10211
10608
  while (position < bytes.length) {
10609
+ const headerStart = position;
10212
10610
  const id = bytes[position++];
10213
- 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;
10214
10620
  const end = start + size;
10215
10621
  if (end > bytes.length) throw new Error("invalid wasm section");
10216
10622
  position = end;
10217
- if (!sections && id > 3) continue;
10218
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size);
10219
- let offset = 0;
10623
+ if (id > 3) {
10624
+ if (sections) sections.push(bytes.subarray(headerStart, end));
10625
+ continue;
10626
+ }
10627
+ let offset = start;
10220
10628
  const number3 = () => {
10221
- const [value, next] = readNumber(section2, offset);
10222
- offset = next;
10223
- 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
+ }
10224
10645
  };
10225
10646
  const string4 = () => {
10226
- const [value, next] = readString(section2, offset);
10227
- 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;
10228
10652
  return value;
10229
10653
  };
10654
+ let rewrittenSection;
10230
10655
  if (id === 1) {
10231
10656
  const count = number3();
10232
10657
  for (let i = 0; i < count; i++) {
10233
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
10658
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
10234
10659
  const parameterCount = number3();
10235
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
10236
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
10237
- 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++];
10238
10663
  const resultCount = number3();
10239
- const results = [...section2.subarray(offset, offset + resultCount)];
10240
- if (results.length !== resultCount) throw new Error("invalid wasm type");
10241
- 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++];
10242
10667
  types.push({ parameters, results });
10243
10668
  }
10244
10669
  } else if (id === 2) {
10245
10670
  const count = number3();
10246
- const imports = sections ? [encodeNumber(count)] : void 0;
10671
+ const importWriter = rewrite ? new ByteWriter(size + 64) : void 0;
10672
+ importWriter?.uleb(count);
10247
10673
  for (let i = 0; i < count; i++) {
10248
10674
  const module2 = string4();
10249
10675
  const name3 = string4();
10250
- const kind = section2[offset++];
10676
+ const kind = bytes[offset++];
10251
10677
  const typeStart = offset;
10252
10678
  let functionType = -1;
10253
10679
  if (kind === 0) {
@@ -10255,7 +10681,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10255
10681
  functionTypes.push(functionType);
10256
10682
  functionImportNames.push(name3);
10257
10683
  } else if (kind === 1) {
10258
- const referenceType = section2[offset++];
10684
+ const referenceType = bytes[offset++];
10259
10685
  if (referenceType !== 112 && referenceType !== 111)
10260
10686
  throw new Error("unsupported table type");
10261
10687
  const flags = number3();
@@ -10274,11 +10700,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10274
10700
  } else throw new Error("unsupported wasm import");
10275
10701
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
10276
10702
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
10277
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
10278
- if (module2 === "env" && kind === 0 && names.has(name3)) {
10279
- const type = types[functionType];
10280
- if (!type) throw new Error(`missing import type for ${name3}`);
10281
- 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
+ }
10282
10712
  }
10283
10713
  if (isDlsym || isDlerror) {
10284
10714
  const type = types[functionType];
@@ -10288,17 +10718,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10288
10718
  }
10289
10719
  if (isDlsym) usesDlsym = true;
10290
10720
  if (isDlerror) usesDlerror = true;
10291
- imports?.push(
10292
- encodedString(module2),
10293
- encodedString(
10294
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
10295
- ),
10296
- Buffer.from([kind]),
10297
- section2.subarray(typeStart, offset)
10298
- );
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
+ }
10299
10729
  }
10300
- if (offset !== section2.length) throw new Error("invalid wasm import section");
10301
- if (imports) section2 = Buffer.concat(imports);
10730
+ if (offset !== end) throw new Error("invalid wasm import section");
10731
+ if (importWriter) rewrittenSection = importWriter.finish();
10302
10732
  } else if (id === 3) {
10303
10733
  const count = number3();
10304
10734
  for (let i = 0; i < count; i++) functionTypes.push(number3());
@@ -10307,43 +10737,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10307
10737
  if (sectionName === "linking") {
10308
10738
  const version2 = number3();
10309
10739
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
10310
- const subsections = [];
10740
+ const subsections = rewrite ? [] : void 0;
10311
10741
  let objcLoader;
10312
- while (offset < section2.length) {
10313
- const kind = section2[offset++];
10742
+ while (offset < end) {
10743
+ const kind = bytes[offset++];
10314
10744
  const length = number3();
10315
10745
  const stop = offset + length;
10316
- if (stop > section2.length) throw new Error("invalid linking subsection");
10317
- let content = section2.subarray(offset, stop);
10318
- if (kind === 7 && !sdkLookupOnly) {
10319
- 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);
10320
10750
  const count = number3();
10321
- groups.push(encodeNumber(count));
10751
+ comdatWriter.uleb(count);
10322
10752
  for (let i = 0; i < count; i++) {
10323
10753
  const group = string4();
10324
10754
  const begin = offset;
10325
10755
  number3();
10326
10756
  const members = number3();
10327
10757
  for (let member = 0; member < members * 2; member++) number3();
10328
- groups.push(
10329
- encodedString(
10330
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
10331
- ),
10332
- section2.subarray(begin, offset)
10758
+ comdatWriter.string(
10759
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
10333
10760
  );
10761
+ comdatWriter.bytes(bytes, begin, offset);
10334
10762
  }
10335
10763
  if (offset !== stop) throw new Error("invalid comdat subsection");
10336
- content = Buffer.concat(groups);
10337
- }
10338
- if (kind === 8) {
10339
- const entries2 = [];
10340
- 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;
10341
10769
  const count = number3();
10342
- entries2.push(encodeNumber(count));
10343
10770
  let added = 0;
10344
10771
  for (let i = 0; i < count; i++) {
10345
10772
  const begin = offset;
10346
- const symbolKind = section2[offset++];
10773
+ const symbolKind = bytes[offset++];
10347
10774
  const flags = number3();
10348
10775
  const flagsEnd = offset;
10349
10776
  let index = -1;
@@ -10371,25 +10798,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10371
10798
  }
10372
10799
  } else if (symbolKind === 3) number3();
10373
10800
  else throw new Error("unsupported wasm symbol kind");
10374
- if (symbolKind === 0)
10801
+ if (!rewrite && symbolKind === 0)
10375
10802
  functionSymbols[i] = name3 || functionImportNames[index];
10376
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
10803
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
10377
10804
  objcLoader = i;
10378
10805
  }
10379
10806
  const alias = names.get(name3);
10380
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
10381
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
10382
- entries2.push(
10383
- section2.subarray(begin, nameStart),
10384
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
10385
- section2.subarray(nameEnd, offset)
10386
- );
10387
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
10388
- entries2.push(
10389
- section2.subarray(begin, nameStart),
10390
- encodedString(binding(name3)),
10391
- section2.subarray(nameEnd, offset)
10392
- );
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
+ }
10393
10838
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
10394
10839
  if (symbolKind !== 0 && symbolKind !== 1)
10395
10840
  throw new Error(`unsupported symbol ${name3}`);
@@ -10403,63 +10848,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10403
10848
  hidden: (flags & 4) !== 0,
10404
10849
  type
10405
10850
  });
10406
- if (preserveCanonical.has(name3)) {
10407
- entries2.push(section2.subarray(begin, offset));
10408
- extraEntries.push(
10409
- section2.subarray(begin, begin + 1),
10410
- encodeNumber(flags & ~32),
10411
- section2.subarray(flagsEnd, nameStart),
10412
- encodedString(alias),
10413
- section2.subarray(nameEnd, offset)
10414
- );
10415
- added++;
10416
- } else {
10417
- entries2.push(
10418
- section2.subarray(begin, nameStart),
10419
- encodedString(alias),
10420
- section2.subarray(nameEnd, offset)
10421
- );
10422
- }
10423
- } else entries2.push(section2.subarray(begin, offset));
10851
+ }
10424
10852
  }
10425
10853
  if (offset !== stop) throw new Error("invalid symbol subsection");
10426
- entries2[0] = encodeNumber(count + added);
10427
- 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
+ });
10428
10878
  }
10429
10879
  offset = stop;
10430
- subsections.push({ kind, content });
10431
10880
  }
10432
- const parts = [encodedString(sectionName), encodeNumber(version2)];
10433
- for (const subsection of subsections) {
10434
- let content = subsection.content;
10435
- if (subsection.kind === 6 && objcLoader !== void 0) {
10436
- const [count, entriesStart] = readNumber(content, 0);
10437
- const entries2 = [content.subarray(0, entriesStart)];
10438
- let entryStart = entriesStart;
10439
- for (let i = 0; i < count; i++) {
10440
- const [, symbolStart] = readNumber(content, entryStart);
10441
- const [symbol, entryEnd] = readNumber(content, symbolStart);
10442
- if (symbol === objcLoader) entries2.push(encodeNumber(1));
10443
- entries2.push(
10444
- content.subarray(
10445
- symbol === objcLoader ? symbolStart : entryStart,
10446
- entryEnd
10447
- )
10448
- );
10449
- 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);
10450
10913
  }
10451
- if (entryStart !== content.length)
10452
- throw new Error("invalid init functions subsection");
10453
- content = Buffer.concat(entries2);
10454
10914
  }
10455
- parts.push(
10456
- Buffer.from([subsection.kind]),
10457
- encodeNumber(content.length),
10458
- content
10459
- );
10915
+ rewrittenSection = linkingWriter.finish();
10460
10916
  }
10461
- section2 = Buffer.concat(parts);
10462
- } else if (!sections && sectionName.startsWith("reloc.")) {
10917
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
10463
10918
  number3();
10464
10919
  for (let count = number3(); count > 0; count--) {
10465
10920
  const type = number3();
@@ -10469,18 +10924,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10469
10924
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
10470
10925
  addressTaken.add(name3);
10471
10926
  }
10472
- if (offset !== section2.length)
10473
- 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));
10474
10939
  }
10475
10940
  }
10476
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
10477
10941
  }
10478
10942
  return {
10479
10943
  bytes: sections ? Buffer.concat(sections) : bytes,
10480
10944
  definitions,
10481
10945
  functionImports,
10482
10946
  usesDlsym,
10483
- usedSymbols: [...usedSymbols],
10947
+ usedSymbols,
10484
10948
  addressTaken: [...addressTaken]
10485
10949
  };
10486
10950
  }
@@ -10569,36 +11033,51 @@ function createGuestImageLedger(input) {
10569
11033
  }
10570
11034
  }
10571
11035
  }
10572
- const nameBytes = /* @__PURE__ */ new Map();
10573
- for (const definition of definitions)
10574
- if (!nameBytes.has(definition.name))
10575
- nameBytes.set(definition.name, Buffer.from(definition.name));
10576
- definitions.sort(
10577
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
10578
- );
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
+ }
10579
11060
  const preserveCanonical = /* @__PURE__ */ new Set();
10580
11061
  const definitionsByName = Map.groupBy(definitions, (definition) => definition.name);
10581
- for (const name3 of input.symbols) {
11062
+ if (symbolIndices.has("__cxa_throw")) {
11063
+ const name3 = "__cxa_throw";
10582
11064
  const matching = definitionsByName.get(name3) ?? [];
10583
- if (new Set(matching.map((definition) => definition.image)).size < 2 || !matching.some((definition) => definition.weak))
10584
- continue;
10585
- const weak = matching.filter((definition) => definition.weak);
10586
- const strong = matching.filter((definition) => !definition.weak);
10587
- if (name3 !== "__cxa_throw") continue;
10588
- if (weak.length !== 1 || strong.length !== 1)
10589
- throw new Error(`unsupported weak interposition for ${name3}`);
10590
- const [local] = weak;
10591
- const [runtime] = strong;
10592
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
10593
- throw new Error(`incompatible weak interposition for ${name3}`);
10594
- for (const caller of input.callers) {
10595
- const uses = caller.image === local.image || units.some(
10596
- (unit) => unit.image === caller.image && unit.usedSymbols.includes(name3)
10597
- );
10598
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
10599
- 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);
10600
11080
  }
10601
- preserveCanonical.add(name3);
10602
11081
  }
10603
11082
  for (const name3 of [
10604
11083
  "dlsym",
@@ -10610,40 +11089,76 @@ function createGuestImageLedger(input) {
10610
11089
  ])
10611
11090
  preserveCanonical.add(name3);
10612
11091
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
10613
- const bindingsByImage = /* @__PURE__ */ new Map();
10614
- 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();
10615
11122
  for (const caller of input.callers) {
10616
- const bindings = /* @__PURE__ */ new Map();
10617
- const seen = /* @__PURE__ */ new Map();
10618
11123
  const scope = [caller.image, ...caller.next];
10619
11124
  if (input.systemImage !== void 0 && !scope.includes(input.systemImage))
10620
11125
  scope.push(input.systemImage);
10621
- for (const image of scope)
10622
- for (const definition of definitionsByImage.get(image) ?? []) {
10623
- const previous = seen.get(definition.name);
10624
- if (previous?.image === definition.image) {
10625
- if (previous.weak && !definition.weak) {
10626
- seen.set(definition.name, definition);
10627
- if (!preserveCanonical.has(definition.name))
10628
- bindings.set(definition.name, definition.alias);
10629
- }
10630
- continue;
10631
- }
10632
- if (!previous) {
10633
- seen.set(definition.name, definition);
10634
- if (!preserveCanonical.has(definition.name))
10635
- 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;
10636
11148
  }
10637
11149
  }
10638
- bindingsByImage.set(caller.image, bindings);
11150
+ cache.set(name3, null);
11151
+ return void 0;
11152
+ });
10639
11153
  }
10640
11154
  const startup = /* @__PURE__ */ new Map();
11155
+ const unitsByPath = new Map(units.map((unit) => [unit.object.path, unit]));
10641
11156
  for (const binding of input.directBindings ?? []) {
10642
- const unit = units.find(({ object: object3 }) => object3.path === binding.object);
11157
+ const unit = unitsByPath.get(binding.object);
10643
11158
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
10644
11159
  (definition) => definition.object === binding.providerObject && definition.image === binding.providerImage
10645
11160
  );
10646
- if (!unit || !unit.usedSymbols.includes(binding.symbol) || matches.length !== 1)
11161
+ if (!unit || !unit.usedSymbols.has(binding.symbol) || matches.length !== 1)
10647
11162
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
10648
11163
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
10649
11164
  if (bindings.has(binding.symbol))
@@ -10684,11 +11199,11 @@ function createGuestImageLedger(input) {
10684
11199
  }
10685
11200
  }
10686
11201
  const objects = units.map(({ image, object: object3, aliases, functionImports }) => {
10687
- const shared = bindingsByImage.get(image);
11202
+ const shared = sharedLookupByImage.get(image);
10688
11203
  const own = startup.get(object3.path);
10689
11204
  const bindings = new Map(own);
10690
11205
  const weak = input.sdkWeakReferences?.get(object3.path);
10691
- 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));
10692
11207
  for (const [name3, type] of functionImports) {
10693
11208
  const alias = binding(name3);
10694
11209
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -10953,7 +11468,7 @@ function nameGuestImageAliases(wasm, symbols) {
10953
11468
  }
10954
11469
  return Buffer.concat(parts);
10955
11470
  }
10956
- 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;
10957
11472
  var init_swift_guest_image_ledger = __esm({
10958
11473
  "src/swift-guest-image-ledger.ts"() {
10959
11474
  "use strict";
@@ -10961,6 +11476,57 @@ var init_swift_guest_image_ledger = __esm({
10961
11476
  init_nativeWasmContract();
10962
11477
  init_swift_sdk_image_wasm();
10963
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
+ };
10964
11530
  OBJC_INIT_RECORD = ".objc_init";
10965
11531
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
10966
11532
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -11404,8 +11970,11 @@ function moveGuestDyldTable(map, wasm, symbols, bindingValues = /* @__PURE__ */
11404
11970
  function guestDyldValueRange(map) {
11405
11971
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
11406
11972
  let found;
11407
- for (const line of map.split("\n")) {
11408
- 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);
11409
11978
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
11410
11979
  if (!match) throw new Error("unreadable dyld values map line");
11411
11980
  if (found) throw new Error("link map has several dyld value sections");
@@ -11443,7 +12012,7 @@ var init_swift_guest_link_plan = __esm({
11443
12012
  });
11444
12013
 
11445
12014
  // src/swift-guest-manifest.ts
11446
- function selectedGuestManifestInputs(plan, selection, identities) {
12015
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
11447
12016
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
11448
12017
  const archives = /* @__PURE__ */ new Map();
11449
12018
  const images = /* @__PURE__ */ new Map();
@@ -11454,19 +12023,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
11454
12023
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
11455
12024
  let bytes;
11456
12025
  let memberIdentity = null;
11457
- if (item.member === null) bytes = (0, import_node_fs18.readFileSync)(item.artifact);
11458
- else {
11459
- let members = archives.get(item.artifact);
11460
- if (!members) {
11461
- members = readArMembers((0, import_node_fs18.readFileSync)(item.artifact));
11462
- 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];
11463
12048
  }
11464
- const matching = members.filter((member) => member.name === item.member);
11465
- if (matching.length !== 1)
11466
- throw new Error(
11467
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
11468
- );
11469
- bytes = matching[0].bytes;
11470
12049
  const origin = artifact.memberOrigins?.get(item.member);
11471
12050
  if (artifact.memberOrigins && !origin)
11472
12051
  throw new Error(
@@ -11558,7 +12137,7 @@ var init_swift_guest_manifest = __esm({
11558
12137
  function isSwiftGuestImageManifest(value) {
11559
12138
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
11560
12139
  const text2 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
11561
- const name3 = (value2) => text2(value2) && new TextEncoder().encode(value2).length <= 16;
12140
+ const name3 = (value2) => text2(value2) && Buffer.byteLength(value2, "utf8") <= 16;
11562
12141
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
11563
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))
11564
12143
  return false;
@@ -11872,27 +12451,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
11872
12451
  function finalizeGuestProjectionStorage(options) {
11873
12452
  const owner = options.owners.get(options.projectionObject);
11874
12453
  if (owner === void 0) throw new Error("guest projection object has no image owner");
12454
+ const ranges = [];
11875
12455
  const spans = guestLinkedSpans(
11876
12456
  options.map,
11877
12457
  options.linked,
11878
12458
  options.optimized,
11879
12459
  options.owners,
11880
12460
  options.sectionOwners,
11881
- options.sdkSpans !== void 0
12461
+ options.sdkSpans !== void 0,
12462
+ {
12463
+ trackedObject: options.projectionObject,
12464
+ trackedObjectOwner: owner,
12465
+ trackedLinearSpans: ranges
12466
+ }
11882
12467
  );
11883
12468
  const images = planGuestProjectionRegions(
11884
12469
  options.reserved.images,
11885
12470
  options.reserved.capacities,
11886
12471
  options.sdkSpans ? [...spans, ...options.sdkSpans] : spans
11887
12472
  );
11888
- const ranges = guestLinkedSpans(
11889
- options.map,
11890
- options.linked,
11891
- options.optimized,
11892
- /* @__PURE__ */ new Map([[options.projectionObject, owner]]),
11893
- void 0,
11894
- options.sdkSpans !== void 0
11895
- ).filter((span) => span.space === "linear-memory");
11896
12473
  const result = Buffer.from(options.optimized);
11897
12474
  const data = guestWasmDataSegments(options.optimized, options.sdkSpans === void 0);
11898
12475
  const locations = /* @__PURE__ */ new Map();
@@ -13293,7 +13870,7 @@ function occurrences(plan, args) {
13293
13870
  throw new Error("guest plan does not match linker inputs");
13294
13871
  return found;
13295
13872
  }
13296
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13873
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
13297
13874
  const rows = whyExtract.trimEnd().split("\n");
13298
13875
  if (rows.shift() !== "reference extracted symbol")
13299
13876
  throw new Error("invalid wasm-ld extraction report");
@@ -13308,8 +13885,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13308
13885
  for (const file of extracted)
13309
13886
  if (!traced.has(file))
13310
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
+ }
13311
13918
  const result = [];
13312
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
13919
+ for (const { artifact, lazy, whole } of foundOccurrences) {
13313
13920
  if (artifact.kind === "object") {
13314
13921
  if (!lazy && !traced.has(artifact.path))
13315
13922
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -13317,15 +13924,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13317
13924
  result.push({ artifact: artifact.path, member: null });
13318
13925
  continue;
13319
13926
  }
13320
- const prefix = `${artifact.path}(`;
13321
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
13322
- 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();
13323
13935
  for (const member of members) {
13324
- if (whole || names.includes(member.name))
13936
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
13937
+ if (whole || nameSet.has(member.name))
13325
13938
  result.push({ artifact: artifact.path, member: member.name });
13326
13939
  }
13327
13940
  for (const name3 of names)
13328
- if (members.filter((member) => member.name === name3).length !== 1)
13941
+ if (memberCounts.get(name3) !== 1)
13329
13942
  throw new Error(
13330
13943
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
13331
13944
  );
@@ -13402,14 +14015,25 @@ function linkGuestImages(options) {
13402
14015
  }
13403
14016
  const archives = /* @__PURE__ */ new Map();
13404
14017
  const memberBytes = /* @__PURE__ */ new Map();
14018
+ const objectBytes = /* @__PURE__ */ new Map();
13405
14019
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
13406
14020
  const providerSymbol = "__peach_dlsym_from_image";
13407
14021
  const readSelected = (item) => {
13408
- 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
+ }
13409
14030
  let byName = memberBytes.get(item.artifact);
13410
14031
  if (!byName) {
13411
- const members = readArMembers(import_node_fs24.default.readFileSync(item.artifact));
13412
- 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
+ }
13413
14037
  byName = /* @__PURE__ */ new Map();
13414
14038
  for (const member of members)
13415
14039
  if (!byName.has(member.name))
@@ -13433,7 +14057,13 @@ function linkGuestImages(options) {
13433
14057
  `--why-extract=${whyPath}`,
13434
14058
  `--Map=${mapPath}`
13435
14059
  ]);
13436
- 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
+ );
13437
14067
  };
13438
14068
  const needsProvider = (item) => {
13439
14069
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -13473,7 +14103,7 @@ function linkGuestImages(options) {
13473
14103
  )
13474
14104
  ]);
13475
14105
  const originalOwnership = identity(plan);
13476
- const resolved = options.resolvePlan(selected, plan);
14106
+ const resolved = options.resolvePlan(selected, plan, readSelected);
13477
14107
  if (identity(resolved) !== originalOwnership)
13478
14108
  throw new Error("resolved guest scopes changed input ownership");
13479
14109
  plan = resolved;
@@ -13527,6 +14157,7 @@ function linkGuestImages(options) {
13527
14157
  }
13528
14158
  }
13529
14159
  let discoveryRegions;
14160
+ let liveSymbols;
13530
14161
  if (discoveryProjection && options.projection) {
13531
14162
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options.projection.image]]);
13532
14163
  for (const item of selected)
@@ -13535,10 +14166,15 @@ function linkGuestImages(options) {
13535
14166
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
13536
14167
  );
13537
14168
  const wasm = import_node_fs24.default.readFileSync(discovery);
14169
+ liveSymbols = /* @__PURE__ */ new Set();
13538
14170
  discoveryRegions = guestProjectionRegionCounts(
13539
14171
  plan.images.length,
13540
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
14172
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
14173
+ collectSymbols: liveSymbols
14174
+ })
13541
14175
  );
14176
+ } else {
14177
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
13542
14178
  }
13543
14179
  const ledger = createGuestImageLedger({
13544
14180
  images: plan.images.map((image) => ({
@@ -13547,7 +14183,7 @@ function linkGuestImages(options) {
13547
14183
  })),
13548
14184
  callers: plan.callers,
13549
14185
  symbols: plan.symbols,
13550
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
14186
+ liveSymbols,
13551
14187
  commandLineSymbols: commandLineSymbols(args),
13552
14188
  directBindings: plan.directBindings,
13553
14189
  registerAppTables: sdkCallers !== void 0,
@@ -13679,7 +14315,8 @@ function linkGuestImages(options) {
13679
14315
  const selectedInputs = selectedGuestManifestInputs(
13680
14316
  plan,
13681
14317
  selected,
13682
- projection.identities
14318
+ projection.identities,
14319
+ readSelected
13683
14320
  );
13684
14321
  const images = projection.images.map(
13685
14322
  (image) => createGuestImageManifest({
@@ -13689,6 +14326,9 @@ function linkGuestImages(options) {
13689
14326
  regions: []
13690
14327
  })
13691
14328
  );
14329
+ objectBytes.clear();
14330
+ memberBytes.clear();
14331
+ archives.clear();
13692
14332
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
13693
14333
  const regionsBefore = discoveryRegions;
13694
14334
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs24.default.readFileSync(ledgerObject)], 0);
@@ -13782,10 +14422,47 @@ ${changed.join("\n")}`
13782
14422
  }
13783
14423
  function linkedMapSymbols(lines) {
13784
14424
  const names = /* @__PURE__ */ new Set();
13785
- const symbol = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
13786
14425
  for (const line of lines) {
13787
- const match = symbol.exec(line);
13788
- 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));
13789
14466
  }
13790
14467
  return names;
13791
14468
  }
@@ -13884,7 +14561,7 @@ function discoverGuestLinkInputs(options) {
13884
14561
  import_node_fs24.default.mkdirSync(options.directory, { recursive: true });
13885
14562
  const why = import_node_path24.default.join(options.directory, "preselection-why.txt");
13886
14563
  const response = import_node_path24.default.join(options.directory, "preselection.rsp");
13887
- 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");
13888
14565
  const flags = [
13889
14566
  ...withOutput(args, output, true),
13890
14567
  ...options.objects,
@@ -13982,7 +14659,7 @@ function prepareGuestRuntimeInputs(options) {
13982
14659
  });
13983
14660
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
13984
14661
  }
13985
- function selectedGuestSymbolInputs(plan, selected) {
14662
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
13986
14663
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
13987
14664
  const archives = /* @__PURE__ */ new Map();
13988
14665
  const symbols = /* @__PURE__ */ new Set();
@@ -13998,22 +14675,27 @@ function selectedGuestSymbolInputs(plan, selected) {
13998
14675
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
13999
14676
  let bytes;
14000
14677
  let name3 = item.artifact;
14001
- if (item.member === null) bytes = import_node_fs24.default.readFileSync(item.artifact);
14002
- else {
14003
- let members = archives.get(item.artifact);
14004
- if (!members) {
14005
- members = Map.groupBy(
14006
- readArMembers(import_node_fs24.default.readFileSync(item.artifact)),
14007
- (member) => member.name
14008
- );
14009
- 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;
14010
14698
  }
14011
- const matching = members.get(item.member) ?? [];
14012
- if (matching.length !== 1)
14013
- throw new Error(
14014
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
14015
- );
14016
- bytes = matching[0].bytes;
14017
14699
  name3 += `(${item.member})`;
14018
14700
  }
14019
14701
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -14026,9 +14708,9 @@ function selectedGuestSymbolInputs(plan, selected) {
14026
14708
  for (const symbol of names.tags) tags.add(symbol);
14027
14709
  for (const symbol of names.defined) {
14028
14710
  definitions.add(symbol);
14029
- const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14711
+ let objects = definitionObjects.get(symbol);
14712
+ if (!objects) definitionObjects.set(symbol, objects = /* @__PURE__ */ new Set());
14030
14713
  objects.add(name3);
14031
- definitionObjects.set(symbol, objects);
14032
14714
  }
14033
14715
  }
14034
14716
  return {
@@ -14049,7 +14731,7 @@ function verifyGuestSymbolScopes(options) {
14049
14731
  if (!symbols.length) return { bindings: [], directBindings: [] };
14050
14732
  import_node_fs24.default.mkdirSync(options.directory, { recursive: true });
14051
14733
  const response = import_node_path24.default.join(options.directory, "scope-trace.rsp");
14052
- 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");
14053
14735
  const args = [
14054
14736
  ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
14055
14737
  ...options.objects,
@@ -14067,55 +14749,76 @@ function verifyGuestSymbolScopes(options) {
14067
14749
  import_node_fs24.default.closeSync(traceOutput);
14068
14750
  }
14069
14751
  const records = /* @__PURE__ */ new Map();
14070
- const consume = (line) => {
14071
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
14072
- if (!match) return;
14073
- const [, object3, kind, symbol] = match;
14074
- if (!requested.has(symbol)) return;
14075
- if (options.hostImports.has(symbol)) return;
14076
- const record = records.get(symbol) ?? {
14077
- references: /* @__PURE__ */ new Map(),
14078
- providers: /* @__PURE__ */ new Map(),
14079
- physicalModule: false
14080
- };
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);
14081
14770
  if (object3 === "<internal>") {
14082
- if (kind === "definition of") record.physicalModule = true;
14771
+ if (!isRef) record.physicalModule = true;
14083
14772
  } else {
14084
14773
  const image = options.owners.get(object3);
14085
14774
  if (image === void 0)
14086
14775
  throw new Error(`traced guest object has no owner ${object3}`);
14087
- (kind === "reference to" ? record.references : record.providers).set(
14088
- object3,
14089
- image
14090
- );
14776
+ (isRef ? record.references : record.providers).set(object3, image);
14091
14777
  }
14092
- records.set(symbol, record);
14093
- };
14094
- for (const line of guestLinkLines(tracePath)) consume(line);
14778
+ }
14095
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);
14096
14784
  const result = [];
14097
14785
  const directBindings = [];
14098
14786
  for (const symbol of symbols) {
14099
14787
  const record = records.get(symbol);
14100
14788
  if (!record || !record.references.size) continue;
14101
14789
  if (!record.providers.size && options.hostImports.has(symbol)) continue;
14102
- const startupReferences = [...record.references].filter(
14103
- ([object3]) => options.startupObjects.has(object3) && options.weakReferences.get(object3)?.has(symbol)
14104
- );
14105
- const otherReferences = [...record.references].filter(
14106
- ([object3]) => !startupReferences.some(([startup]) => startup === object3)
14107
- );
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
+ }
14108
14802
  for (const [, caller] of startupReferences)
14109
14803
  if (!callers.has(caller))
14110
14804
  throw new Error(`guest image has no caller scope ${caller}`);
14111
14805
  if (startupReferences.length && !record.physicalModule) {
14112
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14113
- 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)
14114
14809
  throw new Error(`ambiguous startup provider ${symbol}`);
14115
- if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object3) => !candidates.has(object3)))
14116
- 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}`);
14117
14820
  if (record.providers.size === 1) {
14118
- const [providerObject, providerImage] = [...record.providers][0];
14821
+ const [providerObject, providerImage] = record.providers.entries().next().value;
14119
14822
  if (options.weakDefinitions.get(providerObject)?.has(symbol))
14120
14823
  throw new Error(`weak startup provider ${symbol}`);
14121
14824
  for (const [object3] of startupReferences)
@@ -14123,28 +14826,34 @@ function verifyGuestSymbolScopes(options) {
14123
14826
  }
14124
14827
  if (!otherReferences.length) continue;
14125
14828
  }
14126
- if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
14127
- (object3) => options.weakReferences.get(object3)?.has(symbol)
14128
- ))
14129
- continue;
14829
+ if (!record.providers.size && !record.physicalModule && allWeakRefs) continue;
14130
14830
  const providerImages = new Set(record.providers.values());
14131
- const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
14132
- (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) {
14133
14837
  const image = options.owners.get(object3);
14134
- 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
+ }
14135
14846
  }
14136
- );
14137
- const copyImages = new Set(copies.map((copy) => copy.image));
14138
- const strongImages = new Set(
14139
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
14140
- );
14847
+ }
14141
14848
  const interposed = !record.physicalModule && copyImages.size > 1;
14142
14849
  const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
14143
14850
  if (!providerCount) continue;
14144
14851
  if (providerCount !== 1)
14145
14852
  throw new Error(`guest symbol has ambiguous provider ${symbol}`);
14146
- const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
14147
- 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;
14148
14857
  for (const [object3, caller] of scopedReferences) {
14149
14858
  const scope = callers.get(caller);
14150
14859
  if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
@@ -14152,18 +14861,35 @@ function verifyGuestSymbolScopes(options) {
14152
14861
  result.push({ symbol, caller, provider: { kind: "physical-module" } });
14153
14862
  continue;
14154
14863
  }
14155
- 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
+ }
14156
14886
  if (provider === void 0) {
14157
14887
  if (options.weakReferences.get(object3)?.has(symbol)) continue;
14158
14888
  throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
14159
14889
  }
14160
14890
  if (caller === provider) continue;
14161
- if ([...options.definitionObjects.get(symbol) ?? []].some(
14162
- (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
14163
- ))
14164
- continue;
14165
- if (!scope.includes(provider)) {
14166
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14891
+ if (weakDefinerImages?.has(caller)) continue;
14892
+ if (!callerSets.get(caller).has(provider)) {
14167
14893
  const traced = [...record.providers.keys()];
14168
14894
  const strongTraced = traced.filter(
14169
14895
  (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
@@ -14171,16 +14897,17 @@ function verifyGuestSymbolScopes(options) {
14171
14897
  const providers = strongTraced.length === 1 ? strongTraced : traced;
14172
14898
  if (options.weakReferences.get(object3)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
14173
14899
  continue;
14174
- 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(
14175
14902
  (definer) => options.weakDefinitions.get(definer)?.has(symbol)
14176
14903
  );
14177
- const strongCandidates = [...candidates].filter(
14904
+ const strongCandidates = [...candidateSet].filter(
14178
14905
  (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
14179
14906
  );
14180
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
14181
- 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
14182
14909
  // scope, the root image and its dependency closure, as in elf.
14183
- 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]))))
14184
14911
  throw new Error(
14185
14912
  `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
14186
14913
  );
@@ -18291,9 +19018,9 @@ async function compileGuestLink(options) {
18291
19018
  }
18292
19019
  };
18293
19020
  },
18294
- resolvePlan: (selected, plan) => {
19021
+ resolvePlan: (selected, plan, readSelected) => {
18295
19022
  if (!prepared) throw new Error("guest runtime selection is unavailable");
18296
- const scope = selectedGuestSymbolInputs(plan, selected);
19023
+ const scope = selectedGuestSymbolInputs(plan, selected, readSelected);
18297
19024
  const owners = new Map(scope.owners);
18298
19025
  owners.set(import_node_path37.default.join(directory, "projection-discovery.o"), 0);
18299
19026
  const providersByImage = Map.groupBy(scope.owners, ([, image]) => image);
@@ -26169,7 +26896,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
26169
26896
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
26170
26897
  MULTI_MANIFEST_VERSION = 76;
26171
26898
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
26172
- compilerSourceDigest = true ? "6433b1a7f6d99095c2a444c33cfbf4bc62bedbf18b40e3415e37cd83e450f0df" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
26899
+ compilerSourceDigest = true ? "7b91fa4405159335b5484c82700e001e4c27abf15621b724ea8af4edea693f66" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
26173
26900
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
26174
26901
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
26175
26902
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));