peachsim 0.1.2589 → 0.1.2591

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +1490 -534
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-6FUOY6FX.mjs → acorn-EMX4WZ72.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-33SCXU3Y.mjs → chunk-4QHHRGO4.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-Y4PV4HZB.mjs → chunk-7627LKJK.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-M4KUWGU3.mjs → chunk-AKKHSVJ4.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-MKSOJCRT.mjs → chunk-EGKH2L6J.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-5EFD2VBY.mjs → chunk-ILWFGZWW.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-57FFWABF.mjs → chunk-J676B57D.mjs} +5 -5
  33. package/dist-lib/esm-chunks/{chunk-JLOJZF2Y.mjs → chunk-JHXDM3YU.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-464CBA5U.mjs → chunk-MC6NMYWY.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-CRIYVOMB.mjs → chunk-NX23AMX4.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-EAIFG4MQ.mjs → chunk-Q4NA6PUR.mjs} +3 -3
  37. package/dist-lib/esm-chunks/{chunk-47K4QPVA.mjs → chunk-QBMFX3J2.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-FQQ2DMXS.mjs → chunk-RKQZGWX2.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-5QWQDXXD.mjs → chunk-SOAYP72T.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-XTKKROVU.mjs → chunk-TFG4LZ5T.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-KFHCRS5K.mjs → chunk-UIVXVMS5.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-BSAAJR25.mjs → chunk-UYJXLDCG.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-FMWEI6OI.mjs → chunk-VD27WNCT.mjs} +4 -4
  44. package/dist-lib/esm-chunks/{chunk-3VNUC4DT.mjs → chunk-VF5WVB3D.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-WQ73RKJY.mjs → chunk-VRVXRZI4.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-L3OSVIGA.mjs → chunk-VYZ5DC3M.mjs} +1359 -487
  47. package/dist-lib/esm-chunks/{chunk-I22LAVD5.mjs → chunk-YR6DNV76.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-PUBH3EXI.mjs → chunk-ZL5N6ENT.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-T5QIJTEV.mjs → metro-layout-parser-ANKZARNW.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-AWTZHPDM.mjs → swift-package-prebuilt-4N5CXBOZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-MGTJTVKU.mjs → swift-sdk-app-module-5IUSRXYA.mjs} +151 -67
  52. package/dist-lib/esm-chunks/{swift-sdk-image-JABGF3ZR.mjs → swift-sdk-image-7T2LMQS5.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-RJRJ3EFU.mjs → swift-sdk-image-producer-7QJ3BF6E.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1489 -533
  55. package/dist-lib/expo-swift-metadata.cjs +1 -1
  56. package/dist-lib/expo-swift-metadata.mjs +7 -7
  57. package/dist-lib/home-paths.cjs +1 -1
  58. package/dist-lib/host/bridge-host.cjs +1518 -557
  59. package/dist-lib/host/fetch-proxy-handler.cjs +4 -4
  60. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  61. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  62. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  63. package/dist-lib/host/websocket-proxy.cjs +1 -1
  64. package/dist-lib/index.cjs +1 -1
  65. package/dist-lib/kotlin-host.cjs +1 -1
  66. package/dist-lib/menu.cjs +1 -1
  67. package/dist-lib/menu.mjs +3 -3
  68. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  69. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  70. package/dist-lib/metro-production-bundle.cjs +1 -1
  71. package/dist-lib/metro-production-bundle.mjs +4 -4
  72. package/dist-lib/native-app-identity-project.cjs +2 -2
  73. package/dist-lib/native-app-identity-project.mjs +16 -16
  74. package/dist-lib/native-app-identity.cjs +1 -1
  75. package/dist-lib/native-app-identity.mjs +6 -6
  76. package/dist-lib/native-firebase-metadata.cjs +1 -1
  77. package/dist-lib/native-firebase-metadata.mjs +3 -3
  78. package/dist-lib/pdfium-raster.cjs +1 -1
  79. package/dist-lib/pdfium-raster.mjs +2 -2
  80. package/dist-lib/plist.cjs +1 -1
  81. package/dist-lib/plist.mjs +3 -3
  82. package/dist-lib/profiles.cjs +1 -1
  83. package/dist-lib/public-brand.cjs +1 -1
  84. package/dist-lib/public-origins-lib-esm.json +81 -81
  85. package/dist-lib/public-origins-lib.json +69 -69
  86. package/dist-lib/react-native-host-modules.cjs +1 -1
  87. package/dist-lib/react-native-host-modules.mjs +2 -2
  88. package/dist-lib/reap-browser.cjs +1 -1
  89. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  90. package/dist-lib/sdk.cjs +1 -1
  91. package/dist-lib/sdk.mjs +8 -8
  92. package/dist-lib/skills.cjs +1520 -559
  93. package/dist-lib/swift-compile.cjs +1486 -530
  94. package/dist-lib/swift-compile.mjs +10 -10
  95. package/dist-lib/swift-package.cjs +1 -1
  96. package/dist-lib/swift-package.mjs +3 -3
  97. package/dist-lib/swift-submit.cjs +1 -1
  98. package/dist-lib/swift-submit.mjs +6 -6
  99. package/dist-lib/swift-svg-raster.cjs +1 -1
  100. package/dist-lib/swift-svg-raster.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +1 -1
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/kotlin/sdk.tar.gz +0 -0
  126. package/package.json +1 -1
  127. package/src/swift-guest-compile.ts +43 -10
  128. package/src/swift-guest-dyld-table.ts +9 -2
  129. package/src/swift-guest-image-ledger.ts +403 -208
  130. package/src/swift-guest-link.ts +258 -113
  131. package/src/swift-guest-linked-spans.ts +217 -28
  132. package/src/swift-guest-manifest.ts +24 -13
  133. package/src/swift-guest-projection-storage.ts +6 -8
  134. package/src/swift-guest-projection.ts +7 -6
  135. package/src/swift-guest-source-inputs.ts +158 -30
  136. package/src/swift-sdk-app-module.ts +146 -59
  137. package/src/swift-sdk-image-map.ts +137 -35
  138. package/src/swift-wasm-prune.ts +263 -85
  139. package/src/swiftGuestImageContract.ts +1 -1
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2589 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2591 | (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;
@@ -23829,24 +23829,56 @@ function layout(bytes, readData = true, requireExports = true) {
23829
23829
  const code = sections.get(10);
23830
23830
  if (code) {
23831
23831
  let pos = code[0];
23832
- let count;
23833
- [count, pos] = number(bytes, pos);
23832
+ const codeStart = code[0];
23833
+ const codeEnd = code[1];
23834
+ let count = 0;
23835
+ {
23836
+ let shift = 0;
23837
+ for (; ; ) {
23838
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
23839
+ const byte = bytes[pos++];
23840
+ count += (byte & 127) * 2 ** shift;
23841
+ if (!(byte & 128)) break;
23842
+ shift += 7;
23843
+ }
23844
+ }
23834
23845
  for (let i = 0; i < count; i++) {
23835
23846
  const prefix = pos;
23836
- let size2;
23837
- [size2, pos] = number(bytes, pos);
23838
- functionsByCodeOffset.set(prefix - code[0], imports2 + i);
23847
+ let size2 = 0;
23848
+ const b0 = bytes[pos++];
23849
+ if (b0 < 128) {
23850
+ size2 = b0;
23851
+ } else {
23852
+ size2 = b0 & 127;
23853
+ let shift = 7;
23854
+ for (; ; ) {
23855
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
23856
+ const byte = bytes[pos++];
23857
+ size2 += (byte & 127) * 2 ** shift;
23858
+ if (!(byte & 128)) break;
23859
+ shift += 7;
23860
+ }
23861
+ }
23862
+ functionsByCodeOffset.set(prefix - codeStart, imports2 + i);
23839
23863
  if (imports2 + i === startFunction) startup = bytes.subarray(pos, pos + size2);
23840
23864
  pos += size2;
23841
- if (pos > code[1]) throw new Error("invalid wasm code");
23865
+ if (pos > codeEnd) throw new Error("invalid wasm code");
23842
23866
  }
23843
- if (pos !== code[1]) throw new Error("invalid wasm code section");
23867
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
23844
23868
  }
23845
23869
  const functionsByTableSlot = /* @__PURE__ */ new Map();
23846
23870
  const elements = sections.get(9);
23847
23871
  if (elements) {
23848
23872
  let pos = elements[0];
23873
+ const elemEnd = elements[1];
23849
23874
  const read = () => {
23875
+ if (pos < elemEnd) {
23876
+ const b0 = bytes[pos];
23877
+ if (b0 < 128) {
23878
+ pos++;
23879
+ return b0;
23880
+ }
23881
+ }
23850
23882
  const [value, next] = number(bytes, pos);
23851
23883
  pos = next;
23852
23884
  return value;
@@ -23876,7 +23908,7 @@ function layout(bytes, readData = true, requireExports = true) {
23876
23908
  functionsByTableSlot.set(slot, read());
23877
23909
  }
23878
23910
  }
23879
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
23911
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
23880
23912
  }
23881
23913
  const data = [];
23882
23914
  const passive = /* @__PURE__ */ new Map();
@@ -23941,36 +23973,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
23941
23973
  length: segment3.bytes.length
23942
23974
  }));
23943
23975
  }
23944
- function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
23976
+ function isMapSpace(code) {
23977
+ return code === 32 || code >= 9 && code <= 13;
23978
+ }
23979
+ function isMapHex(code) {
23980
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
23981
+ }
23982
+ function mapHexDigit(code) {
23983
+ return code <= 57 ? code - 48 : code - 87;
23984
+ }
23985
+ function* stringLines(text7) {
23986
+ let start = 0;
23987
+ for (let end = text7.indexOf("\n"); end !== -1; end = text7.indexOf("\n", start)) {
23988
+ yield text7.slice(start, end);
23989
+ start = end + 1;
23990
+ }
23991
+ yield text7.slice(start);
23992
+ }
23993
+ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
23945
23994
  const unchanged = before === after;
23946
23995
  const original = layout(before, !unchanged, !importsLayout);
23947
23996
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
23997
+ const collectSymbols = extra?.collectSymbols;
23998
+ const trackedObject = extra?.trackedObject;
23999
+ const trackedObjectOwner = extra?.trackedObjectOwner;
24000
+ const trackedLinearSpans = extra?.trackedLinearSpans;
24001
+ const hasSectionOwners = sectionOwners.size > 0;
23948
24002
  let codeOffset;
23949
24003
  let outputSection = "";
23950
24004
  const codeOwners = /* @__PURE__ */ new Map();
23951
24005
  const pieces = [];
23952
- for (const line of typeof map2 === "string" ? map2.split("\n") : map2) {
23953
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
23954
- if (!match) continue;
23955
- const [, address, offset, size2, indent2, source] = match;
23956
- if (address === "-" && indent2 === " ") {
23957
- outputSection = source;
23958
- if (source === "CODE") codeOffset = parseInt(offset, 16);
24006
+ const lines = typeof map2 === "string" ? stringLines(map2) : map2;
24007
+ for (const line of lines) {
24008
+ const lineLen = line.length;
24009
+ let pos = 0;
24010
+ let onlySpaces = true;
24011
+ while (pos < lineLen) {
24012
+ const ch = line.charCodeAt(pos);
24013
+ if (!isMapSpace(ch)) break;
24014
+ if (ch !== 32) onlySpaces = false;
24015
+ pos++;
24016
+ }
24017
+ const leadingSpaces = pos;
24018
+ if (pos >= lineLen) continue;
24019
+ const addrStart = pos;
24020
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
24021
+ const addrEnd = pos;
24022
+ if (pos >= lineLen) continue;
24023
+ const s1 = pos;
24024
+ while (pos < lineLen) {
24025
+ const ch = line.charCodeAt(pos);
24026
+ if (!isMapSpace(ch)) break;
24027
+ if (ch !== 32) onlySpaces = false;
24028
+ pos++;
24029
+ }
24030
+ if (pos === s1 || pos >= lineLen) continue;
24031
+ const offStart = pos;
24032
+ let offsetVal = 0;
24033
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
24034
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
24035
+ }
24036
+ if (pos === offStart || pos >= lineLen) continue;
24037
+ const s2 = pos;
24038
+ while (pos < lineLen) {
24039
+ const ch = line.charCodeAt(pos);
24040
+ if (!isMapSpace(ch)) break;
24041
+ if (ch !== 32) onlySpaces = false;
24042
+ pos++;
24043
+ }
24044
+ if (pos === s2 || pos >= lineLen) continue;
24045
+ const sizeStart = pos;
24046
+ let sizeVal = 0;
24047
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
24048
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
24049
+ }
24050
+ if (pos === sizeStart || pos >= lineLen) continue;
24051
+ const indentStart = pos;
24052
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
24053
+ const indentLen = pos - indentStart;
24054
+ if (indentLen === 0 || pos >= lineLen) continue;
24055
+ const firstCh = line.charCodeAt(pos);
24056
+ if (isMapSpace(firstCh)) continue;
24057
+ const sourceStart = pos;
24058
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
24059
+ let symEnd = sourceStart + 1;
24060
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
24061
+ collectSymbols.add(line.slice(sourceStart, symEnd));
24062
+ }
24063
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
24064
+ if (isDash && indentLen === 1) {
24065
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
24066
+ outputSection = line.slice(sourceStart);
24067
+ if (outputSection === "CODE") codeOffset = offsetVal;
23959
24068
  continue;
23960
24069
  }
23961
- const separator = source.indexOf(":(");
24070
+ if (sizeVal === 0) continue;
24071
+ const separator = line.indexOf(":(", sourceStart);
23962
24072
  if (separator < 0) continue;
23963
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
23964
- const length = parseInt(size2, 16);
23965
- if (!length) continue;
23966
- if (address !== "-") {
23967
- if (outputSection === "DATA")
23968
- pieces.push({ image, address: parseInt(address, 16), length });
24073
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
24074
+ let hasLineSep = false;
24075
+ for (let i = sourceStart; i < lineLen; i++) {
24076
+ const ch = line.charCodeAt(i);
24077
+ if (ch === 8232 || ch === 8233) {
24078
+ hasLineSep = true;
24079
+ break;
24080
+ }
24081
+ }
24082
+ if (hasLineSep) continue;
24083
+ const objectPath = line.slice(sourceStart, separator);
24084
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
24085
+ if (image === void 0) image = owners.get(objectPath);
24086
+ if (!isDash) {
24087
+ if (outputSection === "DATA") {
24088
+ let addressVal = 0;
24089
+ let allHex = true;
24090
+ for (let i = addrStart; i < addrEnd; i++) {
24091
+ const ch = line.charCodeAt(i);
24092
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
24093
+ else {
24094
+ allHex = false;
24095
+ break;
24096
+ }
24097
+ }
24098
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
24099
+ pieces.push({
24100
+ image,
24101
+ address: addressVal,
24102
+ length: sizeVal,
24103
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
24104
+ });
24105
+ }
23969
24106
  continue;
23970
24107
  }
23971
24108
  if (image === void 0 || outputSection !== "CODE") continue;
23972
24109
  if (codeOffset === void 0) throw new Error("link map has no code section");
23973
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
24110
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
23974
24111
  if (index === void 0) throw new Error("link map function has no wasm body");
23975
24112
  const existing = codeOwners.get(index);
23976
24113
  if (existing !== void 0 && existing !== image)
@@ -23979,12 +24116,23 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
23979
24116
  }
23980
24117
  pieces.sort((a, b) => a.address - b.address);
23981
24118
  const spans = [];
23982
- for (const [index, { image, address, length }] of pieces.entries()) {
23983
- if (image === void 0) continue;
24119
+ for (let index = 0; index < pieces.length; index++) {
24120
+ const piece = pieces[index];
24121
+ const { image, address, length, tracked } = piece;
24122
+ if (image === void 0 && !tracked) continue;
23984
24123
  let next = index + 1;
23985
24124
  while (next < pieces.length && pieces[next].address < address + length) next++;
23986
24125
  const end = pieces[next]?.address ?? address + length;
23987
- spans.push({ image, space: "linear-memory", address, length: end - address });
24126
+ const spanLength = end - address;
24127
+ if (image !== void 0)
24128
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
24129
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
24130
+ trackedLinearSpans.push({
24131
+ image: trackedObjectOwner,
24132
+ space: "linear-memory",
24133
+ address,
24134
+ length: spanLength
24135
+ });
23988
24136
  }
23989
24137
  const optimizedOwners = /* @__PURE__ */ new Map();
23990
24138
  const dataAt = (module2, start, length) => {
@@ -24023,7 +24171,7 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
24023
24171
  throw new Error(`optimization changed linked data at ${span.address}`);
24024
24172
  }
24025
24173
  let previous;
24026
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
24174
+ for (const span of spans) {
24027
24175
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
24028
24176
  throw new Error("linked data belongs to multiple images");
24029
24177
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -24205,6 +24353,20 @@ var init_swift_guest_linked_spans = __esm({
24205
24353
  });
24206
24354
 
24207
24355
  // src/swift-sdk-image-map.ts
24356
+ function isHexChar(code) {
24357
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
24358
+ }
24359
+ function hexDigit(code) {
24360
+ return code <= 57 ? code - 48 : code - 87;
24361
+ }
24362
+ function hasLineBreak(line, from) {
24363
+ if (line.indexOf("\r", from) >= 0) return true;
24364
+ for (let i = from; i < line.length; i++) {
24365
+ const ch = line.charCodeAt(i);
24366
+ if (ch === 8232 || ch === 8233) return true;
24367
+ }
24368
+ return false;
24369
+ }
24208
24370
  function readWasmLinkMap(file, partition) {
24209
24371
  const segments = /* @__PURE__ */ new Map();
24210
24372
  const data = [];
@@ -24212,48 +24374,117 @@ function readWasmLinkMap(file, partition) {
24212
24374
  let kind = "";
24213
24375
  let segment3 = "";
24214
24376
  let previous;
24215
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
24216
24377
  for (const line of guestLinkLines(file)) {
24217
- const symbol2 = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
24218
- if (symbol2) {
24219
- previous?.symbols.push({
24220
- name: symbol2[3],
24221
- address: hex(symbol2[1]),
24222
- size: parseInt(symbol2[2], 16)
24223
- });
24378
+ const length = line.length;
24379
+ let pos = 0;
24380
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24381
+ if (pos >= length) continue;
24382
+ const leadingSpaces = pos;
24383
+ let address = -1;
24384
+ if (line.charCodeAt(pos) === 45) {
24385
+ pos++;
24386
+ } else {
24387
+ const start = pos;
24388
+ let value = 0;
24389
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
24390
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
24391
+ }
24392
+ if (pos === start) continue;
24393
+ address = value;
24394
+ }
24395
+ const s1 = pos;
24396
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24397
+ if (pos === s1 || pos >= length) continue;
24398
+ const offStart = pos;
24399
+ let offset = 0;
24400
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
24401
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
24402
+ }
24403
+ if (pos === offStart) continue;
24404
+ const s2 = pos;
24405
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24406
+ if (pos === s2 || pos >= length) continue;
24407
+ const sizeStart = pos;
24408
+ let size2 = 0;
24409
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
24410
+ size2 = size2 * 16 + hexDigit(line.charCodeAt(pos++));
24411
+ }
24412
+ if (pos === sizeStart || pos >= length) continue;
24413
+ const indentStart = pos;
24414
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24415
+ const indent2 = pos - indentStart;
24416
+ if (indent2 === 0 || pos >= length) continue;
24417
+ if (indent2 === 17) {
24418
+ if (previous) {
24419
+ const first = line.charCodeAt(pos);
24420
+ if (first > 32 && !hasLineBreak(line, pos)) {
24421
+ previous.symbols.push({
24422
+ name: line.slice(pos),
24423
+ address,
24424
+ size: size2
24425
+ });
24426
+ }
24427
+ }
24224
24428
  continue;
24225
24429
  }
24226
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
24227
- if (output) {
24228
- kind = output[1];
24430
+ if (indent2 === 1) {
24431
+ let hasWhitespace = false;
24432
+ for (let i = pos; i < length; i++) {
24433
+ const ch = line.charCodeAt(i);
24434
+ if (ch <= 32) {
24435
+ hasWhitespace = true;
24436
+ break;
24437
+ }
24438
+ }
24439
+ if (hasWhitespace) continue;
24440
+ if (address < 0 && leadingSpaces > 0) {
24441
+ kind = line.slice(pos);
24442
+ } else if (kind === "DATA" && address >= 0) {
24443
+ segment3 = line.slice(pos);
24444
+ segments.set(segment3, { address, size: size2 });
24445
+ }
24229
24446
  continue;
24230
24447
  }
24231
- if (kind === "DATA") {
24232
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
24233
- if (top) {
24234
- segment3 = top[3];
24235
- segments.set(segment3, { address: hex(top[1]), size: parseInt(top[2], 16) });
24236
- continue;
24448
+ if (indent2 === 9 && (kind === "DATA" || kind === "CODE")) {
24449
+ const first = line.charCodeAt(pos);
24450
+ if (first !== 47 && first !== 60) continue;
24451
+ if (hasLineBreak(line, pos)) continue;
24452
+ const name3 = line.slice(pos);
24453
+ let filePath = name3;
24454
+ let section2 = "";
24455
+ if (name3.charCodeAt(name3.length - 1) === 41) {
24456
+ const splitAt = name3.indexOf(":(");
24457
+ if (splitAt >= 0) {
24458
+ filePath = name3.slice(0, splitAt);
24459
+ section2 = name3.slice(splitAt + 2, -1);
24460
+ }
24461
+ }
24462
+ let objectName;
24463
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
24464
+ const open = filePath.lastIndexOf("(");
24465
+ if (open >= 0 && open + 1 < filePath.length - 1) {
24466
+ const close = filePath.indexOf(")", open + 1);
24467
+ if (close === filePath.length - 1) {
24468
+ objectName = filePath.slice(open + 1, -1);
24469
+ }
24470
+ }
24471
+ }
24472
+ if (objectName === void 0) objectName = (0, import_node_path27.basename)(filePath);
24473
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
24474
+ objectName = objectName.replace(/^lib\w*?__/, "");
24237
24475
  }
24476
+ previous = {
24477
+ inputFile: filePath,
24478
+ segment: segment3,
24479
+ address,
24480
+ offset,
24481
+ size: size2,
24482
+ object: objectName,
24483
+ section: section2,
24484
+ symbols: []
24485
+ };
24486
+ (kind === "DATA" ? data : code).push(previous);
24238
24487
  }
24239
- if (kind !== "DATA" && kind !== "CODE") continue;
24240
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
24241
- if (!input) continue;
24242
- const name3 = input[4];
24243
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
24244
- const path138 = split ? split[1] : name3;
24245
- const member = /\(([^()]+)\)$/.exec(path138);
24246
- previous = {
24247
- inputFile: path138,
24248
- segment: segment3,
24249
- address: hex(input[1]),
24250
- offset: parseInt(input[2], 16),
24251
- size: parseInt(input[3], 16),
24252
- object: (member ? member[1] : (0, import_node_path27.basename)(path138)).replace(/^lib\w*?__/, ""),
24253
- section: split ? split[2] : "",
24254
- symbols: []
24255
- };
24256
- (kind === "DATA" ? data : code).push(previous);
24257
24488
  }
24258
24489
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
24259
24490
  }
@@ -25399,6 +25630,7 @@ function patchSwiftrtObject(src) {
25399
25630
  return buf;
25400
25631
  }
25401
25632
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25633
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
25402
25634
  let pos = 8;
25403
25635
  let numImportFuncs = 0;
25404
25636
  let importsDlsym = false;
@@ -25434,10 +25666,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25434
25666
  let [cnt, cp] = readULEB2(buf, p);
25435
25667
  for (let i = 0; i < cnt; i++) {
25436
25668
  const [mLen, m2] = readULEB2(buf, cp);
25437
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
25669
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
25438
25670
  cp = m2 + mLen;
25439
25671
  const [fLen, f2] = readULEB2(buf, cp);
25440
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
25672
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
25441
25673
  cp = f2 + fLen;
25442
25674
  const kind = buf[cp++];
25443
25675
  if (kind === 0) {
@@ -25517,7 +25749,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25517
25749
  }
25518
25750
  } else if (id === 0) {
25519
25751
  const [nLen, np] = readULEB2(buf, p);
25520
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
25752
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
25521
25753
  const cp = np + nLen;
25522
25754
  if (name3 === "linking") {
25523
25755
  let [, lp] = readULEB2(buf, cp);
@@ -25530,7 +25762,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25530
25762
  let cur = p2;
25531
25763
  for (let i = 0; i < cnt; i++) {
25532
25764
  const [sLen, s2] = readULEB2(buf, cur);
25533
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
25765
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
25534
25766
  cur = s2 + sLen;
25535
25767
  const [, s3] = readULEB2(buf, cur);
25536
25768
  const [fl, s4] = readULEB2(buf, s3);
@@ -25570,7 +25802,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25570
25802
  let sName = "";
25571
25803
  if (!isUndef || isExplicitName) {
25572
25804
  const [sLen, c4] = readULEB2(buf, cur);
25573
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
25805
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
25574
25806
  cur = c4 + sLen;
25575
25807
  } else if (kind === 0) {
25576
25808
  sName = importFuncNames[el] ?? "";
@@ -25586,7 +25818,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25586
25818
  symNames.push(sName);
25587
25819
  } else if (kind === 1) {
25588
25820
  const [sLen, c3] = readULEB2(buf, cur);
25589
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
25821
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
25590
25822
  cur = c3 + sLen;
25591
25823
  if (!isUndef) {
25592
25824
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -25701,9 +25933,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25701
25933
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
25702
25934
  let ownerSymIdx = -1;
25703
25935
  const topList = segTopSyms.get(lo);
25704
- if (topList) {
25705
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
25706
- if (owner) ownerSymIdx = owner.symIdx;
25936
+ if (topList && topList.length > 0) {
25937
+ let tLo = 0;
25938
+ let tHi = topList.length - 1;
25939
+ while (tLo <= tHi) {
25940
+ const tMid = tLo + tHi >> 1;
25941
+ const top = topList[tMid];
25942
+ if (offInSeg < top.off) {
25943
+ tHi = tMid - 1;
25944
+ } else if (offInSeg >= top.end) {
25945
+ tLo = tMid + 1;
25946
+ } else {
25947
+ ownerSymIdx = top.symIdx;
25948
+ break;
25949
+ }
25950
+ }
25707
25951
  }
25708
25952
  if (ownerSymIdx !== -1) {
25709
25953
  let list2 = symDataRelocs.get(ownerSymIdx);
@@ -25958,54 +26202,151 @@ function localizeDefinedWasmSymbols(bytes, names) {
25958
26202
  return output;
25959
26203
  }
25960
26204
  function guestWasmSymbols(bytes) {
25961
- const object7 = parseWasmObjectBytes("", bytes, false);
26205
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
26206
+ let cur = 8;
26207
+ const readU = () => {
26208
+ const b0 = bytes[cur++];
26209
+ if (b0 < 128) return b0;
26210
+ let res = b0 & 127;
26211
+ let shift = 7;
26212
+ while (true) {
26213
+ const byte = bytes[cur++];
26214
+ res |= (byte & 127) << shift;
26215
+ if ((byte & 128) === 0) return res;
26216
+ shift += 7;
26217
+ }
26218
+ };
26219
+ let importsDlsym = false;
26220
+ const importFuncNames = [];
26221
+ const importFuncModules = [];
26222
+ const importGlobalNames = [];
26223
+ const importTableNames = [];
26224
+ const importEventNames = [];
26225
+ const undefinedSyms = /* @__PURE__ */ new Set();
26226
+ const tags = /* @__PURE__ */ new Set();
26227
+ const globals = /* @__PURE__ */ new Set();
26228
+ const hostImports = /* @__PURE__ */ new Set();
26229
+ const weakUndefined = /* @__PURE__ */ new Set();
26230
+ const defined = /* @__PURE__ */ new Set();
26231
+ const weakDefined = /* @__PURE__ */ new Set();
26232
+ while (cur < bytes.length) {
26233
+ const id = bytes[cur++];
26234
+ const sz = readU();
26235
+ const end = cur + sz;
26236
+ if (id === 2) {
26237
+ const cnt = readU();
26238
+ for (let i = 0; i < cnt; i++) {
26239
+ const mLen = readU();
26240
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
26241
+ cur += mLen;
26242
+ const fLen = readU();
26243
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
26244
+ cur += fLen;
26245
+ const kind = bytes[cur++];
26246
+ if (kind === 0) {
26247
+ readU();
26248
+ importFuncNames.push(fName);
26249
+ importFuncModules.push(mName);
26250
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
26251
+ } else if (kind === 1) {
26252
+ cur++;
26253
+ const fl = readU();
26254
+ readU();
26255
+ if (fl & 1) readU();
26256
+ importTableNames.push(fName);
26257
+ } else if (kind === 2) {
26258
+ const fl = readU();
26259
+ readU();
26260
+ if (fl & 1) readU();
26261
+ } else if (kind === 3) {
26262
+ cur += 2;
26263
+ importGlobalNames.push(fName);
26264
+ } else if (kind === 4) {
26265
+ cur++;
26266
+ readU();
26267
+ importEventNames.push(fName);
26268
+ }
26269
+ }
26270
+ } else if (id === 0) {
26271
+ const nLen = readU();
26272
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
26273
+ cur += nLen;
26274
+ readU();
26275
+ while (cur < end) {
26276
+ const subId = bytes[cur++];
26277
+ const subLen = readU();
26278
+ const subEnd = cur + subLen;
26279
+ if (subId === 8) {
26280
+ const cnt = readU();
26281
+ for (let i = 0; i < cnt; i++) {
26282
+ const kind = bytes[cur++];
26283
+ const fl = readU();
26284
+ const isUndef = (fl & 16) !== 0;
26285
+ const isExplicitName = (fl & 64) !== 0;
26286
+ let sName = "";
26287
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
26288
+ const el = readU();
26289
+ if (!isUndef || isExplicitName) {
26290
+ const sLen = readU();
26291
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
26292
+ cur += sLen;
26293
+ } else if (kind === 0) {
26294
+ sName = importFuncNames[el] ?? "";
26295
+ } else if (kind === 2) {
26296
+ sName = importGlobalNames[el] ?? "";
26297
+ } else if (kind === 4) {
26298
+ sName = importEventNames[el] ?? "";
26299
+ } else if (kind === 5) {
26300
+ sName = importTableNames[el] ?? "";
26301
+ }
26302
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
26303
+ hostImports.add(sName);
26304
+ } else if (kind === 1) {
26305
+ const sLen = readU();
26306
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
26307
+ cur += sLen;
26308
+ if (!isUndef) {
26309
+ readU();
26310
+ readU();
26311
+ readU();
26312
+ }
26313
+ } else if (kind === 3) {
26314
+ readU();
26315
+ }
26316
+ if (sName) {
26317
+ if (isUndef) {
26318
+ undefinedSyms.add(sName);
26319
+ if ((fl & 19) === 17) weakUndefined.add(sName);
26320
+ } else if ((fl & 3) !== 2) {
26321
+ defined.add(sName);
26322
+ if ((fl & 19) === 1) weakDefined.add(sName);
26323
+ }
26324
+ if (kind === 4) tags.add(sName);
26325
+ else if (kind === 2 || kind === 5) globals.add(sName);
26326
+ }
26327
+ }
26328
+ break;
26329
+ }
26330
+ cur = subEnd;
26331
+ }
26332
+ break;
26333
+ }
26334
+ }
26335
+ cur = end;
26336
+ }
25962
26337
  return {
25963
- importsDlsym: object7.importsDlsym,
25964
- undefined: [
25965
- ...new Set(
25966
- object7.symNames.filter(
25967
- (name3, index) => name3 && (object7.symFlags[index] & 16) !== 0
25968
- )
25969
- )
25970
- ],
26338
+ importsDlsym,
26339
+ undefined: [...undefinedSyms],
25971
26340
  // a wasm tag is one module entity unified by name across the link, as the
25972
26341
  // main module owns it for dynamic images, so no image scope applies.
25973
- tags: [
25974
- ...new Set(
25975
- object7.symNames.filter((name3, index) => name3 && object7.symKind[index] === 4)
25976
- )
25977
- ],
25978
- globals: [
25979
- ...new Set(
25980
- object7.symNames.filter(
25981
- (name3, index) => name3 && (object7.symKind[index] === 2 || object7.symKind[index] === 5)
25982
- )
25983
- )
25984
- ],
26342
+ tags: [...tags],
26343
+ globals: [...globals],
25985
26344
  // an undefined function imported from a module other than env is supplied
25986
26345
  // by the host, whatever linker symbol names it.
25987
- hostImports: [...object7.hostImportNames],
25988
- weakUndefined: [
25989
- ...new Set(
25990
- object7.symNames.filter(
25991
- (name3, index) => name3 && (object7.symFlags[index] & 19) === 17
25992
- )
25993
- )
25994
- ],
25995
- defined: [
25996
- ...new Set(
25997
- object7.symNames.filter(
25998
- (name3, index) => name3 && (object7.symFlags[index] & 16) === 0 && (object7.symFlags[index] & 3) !== 2
25999
- )
26000
- )
26001
- ],
26002
- weakDefined: [
26003
- ...new Set(
26004
- object7.symNames.filter(
26005
- (name3, index) => name3 && (object7.symFlags[index] & 19) === 1
26006
- )
26007
- )
26008
- ]
26346
+ hostImports: [...hostImports],
26347
+ weakUndefined: [...weakUndefined],
26348
+ defined: [...defined],
26349
+ weakDefined: [...weakDefined]
26009
26350
  };
26010
26351
  }
26011
26352
  function sdkObjectName(archive, member, ordinal) {
@@ -26522,9 +26863,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26522
26863
  for (const entry of waiting) tryActivateConformance(entry);
26523
26864
  }
26524
26865
  };
26866
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
26525
26867
  const checkProtocolTrigger = (rawSymName) => {
26526
26868
  if (!rawSymName) return;
26527
26869
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
26870
+ if (checkedProtocolTriggers.has(sName)) return;
26871
+ checkedProtocolTriggers.add(sName);
26528
26872
  if (knownProtocols.has(sName)) {
26529
26873
  markProtocolLive(sName);
26530
26874
  return;
@@ -26557,6 +26901,43 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26557
26901
  }
26558
26902
  }
26559
26903
  };
26904
+ const typeIndexes = /* @__PURE__ */ new Map();
26905
+ const getTypeIndex = (obj) => {
26906
+ let idx = typeIndexes.get(obj);
26907
+ if (idx) return idx;
26908
+ const mnByPrefix = /* @__PURE__ */ new Map();
26909
+ for (let i = 0; i < obj.symNames.length; i++) {
26910
+ const name3 = obj.symNames[i];
26911
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
26912
+ const pref = name3.slice(0, -2);
26913
+ let list2 = mnByPrefix.get(pref);
26914
+ if (!list2) mnByPrefix.set(pref, list2 = []);
26915
+ list2.push(i);
26916
+ }
26917
+ }
26918
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
26919
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
26920
+ let list2 = objcRegByPrefix.get(p);
26921
+ if (!list2) objcRegByPrefix.set(p, list2 = []);
26922
+ list2.push(lf);
26923
+ }
26924
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
26925
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
26926
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
26927
+ let list2 = objcClassByPrefix.get(p);
26928
+ if (!list2) objcClassByPrefix.set(p, list2 = []);
26929
+ list2.push(classSym.slice("._OBJC_CLASS_".length));
26930
+ }
26931
+ let minPrefLen = Infinity;
26932
+ let maxPrefLen = 0;
26933
+ for (const p of obj.typePrefixesInObj) {
26934
+ if (p.length < minPrefLen) minPrefLen = p.length;
26935
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
26936
+ }
26937
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
26938
+ typeIndexes.set(obj, idx);
26939
+ return idx;
26940
+ };
26560
26941
  const markTypeLive = (obj, pref) => {
26561
26942
  const set2 = liveTypes.get(obj);
26562
26943
  if (set2.has(pref)) return;
@@ -26570,22 +26951,10 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26570
26951
  const outer = pref.slice(0, n);
26571
26952
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
26572
26953
  }
26573
- const mnName = `${pref}Mn`;
26574
- for (let i = 0; i < obj.symNames.length; i++) {
26575
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
26576
- activateSymbolInObj(obj, i);
26577
- }
26578
- }
26579
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
26580
- if (p === pref) {
26581
- markFuncLive(obj, lf);
26582
- }
26583
- }
26584
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
26585
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
26586
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
26587
- }
26588
- }
26954
+ const idx = getTypeIndex(obj);
26955
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
26956
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
26957
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
26589
26958
  };
26590
26959
  const checkTypeTrigger = (obj, rawSymName) => {
26591
26960
  if (!rawSymName) return;
@@ -26610,11 +26979,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26610
26979
  }
26611
26980
  }
26612
26981
  }
26613
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
26614
- for (const pref of obj.typePrefixesInObj) {
26615
- if (sName.startsWith(pref)) {
26616
- markTypeLive(obj, pref);
26617
- }
26982
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
26983
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
26984
+ const hi = Math.min(sName.length, maxPrefLen);
26985
+ for (let n = minPrefLen; n <= hi; n++) {
26986
+ const cand = sName.slice(0, n);
26987
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
26618
26988
  }
26619
26989
  }
26620
26990
  };
@@ -26707,7 +27077,8 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26707
27077
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
26708
27078
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
26709
27079
  for (const name3 of obj.symNames) {
26710
- const loaded4 = name3?.match(/^_c_(\w+)__load$/)?.[1];
27080
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
27081
+ const loaded4 = name3.match(/^_c_(\w+)__load$/)?.[1];
26711
27082
  if (!loaded4) continue;
26712
27083
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded4}`);
26713
27084
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -26855,14 +27226,30 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26855
27226
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
26856
27227
  const range3 = obj.segPayloadRanges[segIdx];
26857
27228
  if (!range3) return;
27229
+ const [rangeStart, rangeEnd] = range3;
27230
+ if (rangeEnd - rangeStart < 4) return;
26858
27231
  let bytes = objectBytes.get(obj);
26859
27232
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs29.default.readFileSync(obj.file));
26860
- const text7 = bytes.toString("latin1", range3[0], range3[1]);
26861
- for (const match of text7.matchAll(/So(\d+)/g)) {
26862
- const start = match.index + 2 + match[1].length;
26863
- const length = Number(match[1]);
26864
- if (text7[start + length] !== "C") continue;
26865
- const symbol2 = `._OBJC_CLASS_${text7.slice(start, start + length)}`;
27233
+ let pos = rangeStart;
27234
+ while (pos < rangeEnd - 3) {
27235
+ const at = bytes.indexOf("So", pos);
27236
+ if (at < 0 || at >= rangeEnd - 2) break;
27237
+ let digitEnd = at + 2;
27238
+ let length = 0;
27239
+ while (digitEnd < rangeEnd) {
27240
+ const ch = bytes[digitEnd];
27241
+ if (ch < 48 || ch > 57) break;
27242
+ length = length * 10 + (ch - 48);
27243
+ digitEnd++;
27244
+ }
27245
+ if (digitEnd === at + 2) {
27246
+ pos = at + 2;
27247
+ continue;
27248
+ }
27249
+ pos = digitEnd;
27250
+ const nameEnd = digitEnd + length;
27251
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
27252
+ const symbol2 = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
26866
27253
  for (const provider of lazyProviders.get(symbol2) ?? []) {
26867
27254
  eagerDynamicObjects.add(provider);
26868
27255
  extractObject(provider);
@@ -27839,6 +28226,10 @@ var init_nativeDyldTableContract = __esm({
27839
28226
 
27840
28227
  // src/swift-guest-image-ledger.ts
27841
28228
  function readNumber(bytes, position) {
28229
+ if (position < bytes.length) {
28230
+ const first = bytes[position];
28231
+ if (first < 128) return [first, position + 1];
28232
+ }
27842
28233
  let value = 0;
27843
28234
  let shift = 0;
27844
28235
  for (; ; ) {
@@ -27850,6 +28241,7 @@ function readNumber(bytes, position) {
27850
28241
  }
27851
28242
  }
27852
28243
  function encodeNumber(value) {
28244
+ if (value < 128) return Buffer.from([value]);
27853
28245
  const bytes = [];
27854
28246
  do {
27855
28247
  let byte = value % 128;
@@ -27871,6 +28263,9 @@ function encodedString(value) {
27871
28263
  const bytes = Buffer.from(value);
27872
28264
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
27873
28265
  }
28266
+ function isWasmMagic(bytes) {
28267
+ 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;
28268
+ }
27874
28269
  function llvmType(value) {
27875
28270
  switch (value) {
27876
28271
  case 127:
@@ -27886,11 +28281,12 @@ function llvmType(value) {
27886
28281
  }
27887
28282
  }
27888
28283
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options2 = {}) {
27889
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
27890
- throw new Error("expected wasm object");
28284
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
28285
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
27891
28286
  const { sdkLookupOnly, sdkProduct } = options2;
27892
28287
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
27893
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
28288
+ const rewrite = binding !== void 0;
28289
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
27894
28290
  const types2 = [];
27895
28291
  const functionTypes = [];
27896
28292
  const definitions = [];
@@ -27904,45 +28300,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27904
28300
  const usedSymbols = /* @__PURE__ */ new Set();
27905
28301
  let position = 8;
27906
28302
  while (position < bytes.length) {
28303
+ const headerStart2 = position;
27907
28304
  const id = bytes[position++];
27908
- const [size2, start] = readNumber(bytes, position);
28305
+ let size2 = 0;
28306
+ if (position < bytes.length && bytes[position] < 128) {
28307
+ size2 = bytes[position++];
28308
+ } else {
28309
+ const [val, next] = readNumber(bytes, position);
28310
+ size2 = val;
28311
+ position = next;
28312
+ }
28313
+ const start = position;
27909
28314
  const end = start + size2;
27910
28315
  if (end > bytes.length) throw new Error("invalid wasm section");
27911
28316
  position = end;
27912
- if (!sections && id > 3) continue;
27913
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size2);
27914
- let offset = 0;
28317
+ if (id > 3) {
28318
+ if (sections) sections.push(bytes.subarray(headerStart2, end));
28319
+ continue;
28320
+ }
28321
+ let offset = start;
27915
28322
  const number3 = () => {
27916
- const [value, next] = readNumber(section2, offset);
27917
- offset = next;
27918
- return value;
28323
+ if (offset < end) {
28324
+ const first = bytes[offset];
28325
+ if (first < 128) {
28326
+ offset++;
28327
+ return first;
28328
+ }
28329
+ }
28330
+ let value = 0;
28331
+ let shift = 0;
28332
+ for (; ; ) {
28333
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
28334
+ const byte = bytes[offset++];
28335
+ value += (byte & 127) * 2 ** shift;
28336
+ if (!(byte & 128)) return value;
28337
+ shift += 7;
28338
+ }
27919
28339
  };
27920
28340
  const string7 = () => {
27921
- const [value, next] = readString(section2, offset);
27922
- offset = next;
28341
+ const length = number3();
28342
+ const strEnd = offset + length;
28343
+ if (strEnd > end) throw new Error("invalid wasm string");
28344
+ const value = rawBuf.toString("utf8", offset, strEnd);
28345
+ offset = strEnd;
27923
28346
  return value;
27924
28347
  };
28348
+ let rewrittenSection;
27925
28349
  if (id === 1) {
27926
28350
  const count = number3();
27927
28351
  for (let i = 0; i < count; i++) {
27928
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
28352
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
27929
28353
  const parameterCount = number3();
27930
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
27931
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
27932
- offset += parameterCount;
28354
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
28355
+ const parameters = new Array(parameterCount);
28356
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
27933
28357
  const resultCount = number3();
27934
- const results = [...section2.subarray(offset, offset + resultCount)];
27935
- if (results.length !== resultCount) throw new Error("invalid wasm type");
27936
- offset += resultCount;
28358
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
28359
+ const results = new Array(resultCount);
28360
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
27937
28361
  types2.push({ parameters, results });
27938
28362
  }
27939
28363
  } else if (id === 2) {
27940
28364
  const count = number3();
27941
- const imports2 = sections ? [encodeNumber(count)] : void 0;
28365
+ const importWriter = rewrite ? new ByteWriter(size2 + 64) : void 0;
28366
+ importWriter?.uleb(count);
27942
28367
  for (let i = 0; i < count; i++) {
27943
28368
  const module2 = string7();
27944
28369
  const name3 = string7();
27945
- const kind = section2[offset++];
28370
+ const kind = bytes[offset++];
27946
28371
  const typeStart = offset;
27947
28372
  let functionType2 = -1;
27948
28373
  if (kind === 0) {
@@ -27950,7 +28375,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27950
28375
  functionTypes.push(functionType2);
27951
28376
  functionImportNames.push(name3);
27952
28377
  } else if (kind === 1) {
27953
- const referenceType = section2[offset++];
28378
+ const referenceType = bytes[offset++];
27954
28379
  if (referenceType !== 112 && referenceType !== 111)
27955
28380
  throw new Error("unsupported table type");
27956
28381
  const flags = number3();
@@ -27969,11 +28394,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27969
28394
  } else throw new Error("unsupported wasm import");
27970
28395
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
27971
28396
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
27972
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
27973
- if (module2 === "env" && kind === 0 && names.has(name3)) {
27974
- const type = types2[functionType2];
27975
- if (!type) throw new Error(`missing import type for ${name3}`);
27976
- functionImports.set(name3, type);
28397
+ if (!rewrite) {
28398
+ if (module2 === "env" && names.has(name3)) {
28399
+ usedSymbols.add(name3);
28400
+ if (kind === 0) {
28401
+ const type = types2[functionType2];
28402
+ if (!type) throw new Error(`missing import type for ${name3}`);
28403
+ functionImports.set(name3, type);
28404
+ }
28405
+ }
27977
28406
  }
27978
28407
  if (isDlsym || isDlerror) {
27979
28408
  const type = types2[functionType2];
@@ -27983,17 +28412,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27983
28412
  }
27984
28413
  if (isDlsym) usesDlsym = true;
27985
28414
  if (isDlerror) usesDlerror = true;
27986
- imports2?.push(
27987
- encodedString(module2),
27988
- encodedString(
27989
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
27990
- ),
27991
- Buffer.from([kind]),
27992
- section2.subarray(typeStart, offset)
27993
- );
28415
+ if (importWriter && binding) {
28416
+ importWriter.string(module2);
28417
+ importWriter.string(
28418
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
28419
+ );
28420
+ importWriter.byte(kind);
28421
+ importWriter.bytes(bytes, typeStart, offset);
28422
+ }
27994
28423
  }
27995
- if (offset !== section2.length) throw new Error("invalid wasm import section");
27996
- if (imports2) section2 = Buffer.concat(imports2);
28424
+ if (offset !== end) throw new Error("invalid wasm import section");
28425
+ if (importWriter) rewrittenSection = importWriter.finish();
27997
28426
  } else if (id === 3) {
27998
28427
  const count = number3();
27999
28428
  for (let i = 0; i < count; i++) functionTypes.push(number3());
@@ -28002,43 +28431,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28002
28431
  if (sectionName === "linking") {
28003
28432
  const version2 = number3();
28004
28433
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
28005
- const subsections = [];
28434
+ const subsections = rewrite ? [] : void 0;
28006
28435
  let objcLoader;
28007
- while (offset < section2.length) {
28008
- const kind = section2[offset++];
28436
+ while (offset < end) {
28437
+ const kind = bytes[offset++];
28009
28438
  const length = number3();
28010
28439
  const stop = offset + length;
28011
- if (stop > section2.length) throw new Error("invalid linking subsection");
28012
- let content = section2.subarray(offset, stop);
28013
- if (kind === 7 && !sdkLookupOnly) {
28014
- const groups = [];
28440
+ if (stop > end) throw new Error("invalid linking subsection");
28441
+ const contentStart = offset;
28442
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
28443
+ const comdatWriter = new ByteWriter(length + 64);
28015
28444
  const count = number3();
28016
- groups.push(encodeNumber(count));
28445
+ comdatWriter.uleb(count);
28017
28446
  for (let i = 0; i < count; i++) {
28018
28447
  const group = string7();
28019
28448
  const begin = offset;
28020
28449
  number3();
28021
28450
  const members2 = number3();
28022
28451
  for (let member = 0; member < members2 * 2; member++) number3();
28023
- groups.push(
28024
- encodedString(
28025
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
28026
- ),
28027
- section2.subarray(begin, offset)
28452
+ comdatWriter.string(
28453
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
28028
28454
  );
28455
+ comdatWriter.bytes(bytes, begin, offset);
28029
28456
  }
28030
28457
  if (offset !== stop) throw new Error("invalid comdat subsection");
28031
- content = Buffer.concat(groups);
28032
- }
28033
- if (kind === 8) {
28034
- const entries2 = [];
28035
- const extraEntries = [];
28458
+ const buf = comdatWriter.finish();
28459
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
28460
+ } else if (kind === 8) {
28461
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
28462
+ let extraWriter;
28036
28463
  const count = number3();
28037
- entries2.push(encodeNumber(count));
28038
28464
  let added = 0;
28039
28465
  for (let i = 0; i < count; i++) {
28040
28466
  const begin = offset;
28041
- const symbolKind = section2[offset++];
28467
+ const symbolKind = bytes[offset++];
28042
28468
  const flags = number3();
28043
28469
  const flagsEnd = offset;
28044
28470
  let index = -1;
@@ -28066,25 +28492,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28066
28492
  }
28067
28493
  } else if (symbolKind === 3) number3();
28068
28494
  else throw new Error("unsupported wasm symbol kind");
28069
- if (symbolKind === 0)
28495
+ if (!rewrite && symbolKind === 0)
28070
28496
  functionSymbols[i] = name3 || functionImportNames[index];
28071
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
28497
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
28072
28498
  objcLoader = i;
28073
28499
  }
28074
28500
  const alias = names.get(name3);
28075
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
28076
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
28077
- entries2.push(
28078
- section2.subarray(begin, nameStart),
28079
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
28080
- section2.subarray(nameEnd, offset)
28081
- );
28082
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
28083
- entries2.push(
28084
- section2.subarray(begin, nameStart),
28085
- encodedString(binding(name3)),
28086
- section2.subarray(nameEnd, offset)
28087
- );
28501
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
28502
+ usedSymbols.add(name3);
28503
+ if (entryWriter && binding) {
28504
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
28505
+ entryWriter.bytes(bytes, begin, nameStart);
28506
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
28507
+ entryWriter.bytes(bytes, nameEnd, offset);
28508
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
28509
+ entryWriter.bytes(bytes, begin, nameStart);
28510
+ entryWriter.string(binding(name3));
28511
+ entryWriter.bytes(bytes, nameEnd, offset);
28512
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
28513
+ if (symbolKind !== 0 && symbolKind !== 1)
28514
+ throw new Error(`unsupported symbol ${name3}`);
28515
+ if (preserveCanonical.has(name3)) {
28516
+ entryWriter.bytes(bytes, begin, offset);
28517
+ extraWriter ??= new ByteWriter(256);
28518
+ extraWriter.byte(bytes[begin]);
28519
+ extraWriter.uleb(flags & ~32);
28520
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
28521
+ extraWriter.string(alias);
28522
+ extraWriter.bytes(bytes, nameEnd, offset);
28523
+ added++;
28524
+ } else {
28525
+ entryWriter.bytes(bytes, begin, nameStart);
28526
+ entryWriter.string(alias);
28527
+ entryWriter.bytes(bytes, nameEnd, offset);
28528
+ }
28529
+ } else {
28530
+ entryWriter.bytes(bytes, begin, offset);
28531
+ }
28088
28532
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
28089
28533
  if (symbolKind !== 0 && symbolKind !== 1)
28090
28534
  throw new Error(`unsupported symbol ${name3}`);
@@ -28098,63 +28542,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28098
28542
  hidden: (flags & 4) !== 0,
28099
28543
  type
28100
28544
  });
28101
- if (preserveCanonical.has(name3)) {
28102
- entries2.push(section2.subarray(begin, offset));
28103
- extraEntries.push(
28104
- section2.subarray(begin, begin + 1),
28105
- encodeNumber(flags & ~32),
28106
- section2.subarray(flagsEnd, nameStart),
28107
- encodedString(alias),
28108
- section2.subarray(nameEnd, offset)
28109
- );
28110
- added++;
28111
- } else {
28112
- entries2.push(
28113
- section2.subarray(begin, nameStart),
28114
- encodedString(alias),
28115
- section2.subarray(nameEnd, offset)
28116
- );
28117
- }
28118
- } else entries2.push(section2.subarray(begin, offset));
28545
+ }
28119
28546
  }
28120
28547
  if (offset !== stop) throw new Error("invalid symbol subsection");
28121
- entries2[0] = encodeNumber(count + added);
28122
- content = Buffer.concat([...entries2, ...extraEntries]);
28548
+ if (entryWriter) {
28549
+ const countBytes = encodeNumber(count + added);
28550
+ const entryBuf = entryWriter.finish();
28551
+ if (extraWriter) {
28552
+ const extraBuf = extraWriter.finish();
28553
+ subsections.push({
28554
+ kind,
28555
+ parts: [countBytes, entryBuf, extraBuf],
28556
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
28557
+ });
28558
+ } else {
28559
+ subsections.push({
28560
+ kind,
28561
+ parts: [countBytes, entryBuf],
28562
+ byteLength: countBytes.length + entryBuf.length
28563
+ });
28564
+ }
28565
+ }
28566
+ } else if (subsections) {
28567
+ subsections.push({
28568
+ kind,
28569
+ parts: [bytes.subarray(contentStart, stop)],
28570
+ byteLength: length
28571
+ });
28123
28572
  }
28124
28573
  offset = stop;
28125
- subsections.push({ kind, content });
28126
- }
28127
- const parts = [encodedString(sectionName), encodeNumber(version2)];
28128
- for (const subsection of subsections) {
28129
- let content = subsection.content;
28130
- if (subsection.kind === 6 && objcLoader !== void 0) {
28131
- const [count, entriesStart] = readNumber(content, 0);
28132
- const entries2 = [content.subarray(0, entriesStart)];
28133
- let entryStart = entriesStart;
28134
- for (let i = 0; i < count; i++) {
28135
- const [, symbolStart] = readNumber(content, entryStart);
28136
- const [symbol2, entryEnd] = readNumber(content, symbolStart);
28137
- if (symbol2 === objcLoader) entries2.push(encodeNumber(1));
28138
- entries2.push(
28139
- content.subarray(
28140
- symbol2 === objcLoader ? symbolStart : entryStart,
28141
- entryEnd
28142
- )
28143
- );
28144
- entryStart = entryEnd;
28574
+ }
28575
+ if (subsections) {
28576
+ const linkingWriter = new ByteWriter(size2 + 128);
28577
+ linkingWriter.string(sectionName);
28578
+ linkingWriter.uleb(version2);
28579
+ for (const subsection of subsections) {
28580
+ if (subsection.kind === 6 && objcLoader !== void 0) {
28581
+ const content = subsection.parts[0];
28582
+ const [count, entriesStart] = readNumber(content, 0);
28583
+ const initWriter = new ByteWriter(content.length + 16);
28584
+ initWriter.bytes(content, 0, entriesStart);
28585
+ let entryStart = entriesStart;
28586
+ for (let i = 0; i < count; i++) {
28587
+ const [, symbolStart] = readNumber(content, entryStart);
28588
+ const [symbol2, entryEnd] = readNumber(content, symbolStart);
28589
+ if (symbol2 === objcLoader) {
28590
+ initWriter.uleb(1);
28591
+ initWriter.bytes(content, symbolStart, entryEnd);
28592
+ } else {
28593
+ initWriter.bytes(content, entryStart, entryEnd);
28594
+ }
28595
+ entryStart = entryEnd;
28596
+ }
28597
+ if (entryStart !== content.length)
28598
+ throw new Error("invalid init functions subsection");
28599
+ const initBuf = initWriter.finish();
28600
+ linkingWriter.byte(subsection.kind);
28601
+ linkingWriter.uleb(initBuf.length);
28602
+ linkingWriter.bytes(initBuf);
28603
+ } else {
28604
+ linkingWriter.byte(subsection.kind);
28605
+ linkingWriter.uleb(subsection.byteLength);
28606
+ for (const part of subsection.parts) linkingWriter.bytes(part);
28145
28607
  }
28146
- if (entryStart !== content.length)
28147
- throw new Error("invalid init functions subsection");
28148
- content = Buffer.concat(entries2);
28149
28608
  }
28150
- parts.push(
28151
- Buffer.from([subsection.kind]),
28152
- encodeNumber(content.length),
28153
- content
28154
- );
28609
+ rewrittenSection = linkingWriter.finish();
28155
28610
  }
28156
- section2 = Buffer.concat(parts);
28157
- } else if (!sections && sectionName.startsWith("reloc.")) {
28611
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
28158
28612
  number3();
28159
28613
  for (let count = number3(); count > 0; count--) {
28160
28614
  const type = number3();
@@ -28164,18 +28618,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28164
28618
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
28165
28619
  addressTaken.add(name3);
28166
28620
  }
28167
- if (offset !== section2.length)
28168
- throw new Error(`invalid relocation section ${sectionName}`);
28621
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
28622
+ }
28623
+ }
28624
+ if (sections) {
28625
+ if (rewrittenSection) {
28626
+ sections.push(
28627
+ Buffer.from([id]),
28628
+ encodeNumber(rewrittenSection.length),
28629
+ rewrittenSection
28630
+ );
28631
+ } else {
28632
+ sections.push(bytes.subarray(headerStart2, end));
28169
28633
  }
28170
28634
  }
28171
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
28172
28635
  }
28173
28636
  return {
28174
28637
  bytes: sections ? Buffer.concat(sections) : bytes,
28175
28638
  definitions,
28176
28639
  functionImports,
28177
28640
  usesDlsym,
28178
- usedSymbols: [...usedSymbols],
28641
+ usedSymbols,
28179
28642
  addressTaken: [...addressTaken]
28180
28643
  };
28181
28644
  }
@@ -28264,36 +28727,51 @@ function createGuestImageLedger(input) {
28264
28727
  }
28265
28728
  }
28266
28729
  }
28267
- const nameBytes = /* @__PURE__ */ new Map();
28268
- for (const definition2 of definitions)
28269
- if (!nameBytes.has(definition2.name))
28270
- nameBytes.set(definition2.name, Buffer.from(definition2.name));
28271
- definitions.sort(
28272
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
28273
- );
28730
+ let hasNonAscii = false;
28731
+ for (const definition2 of definitions) {
28732
+ const s = definition2.name;
28733
+ for (let i = 0; i < s.length; i++) {
28734
+ if (s.charCodeAt(i) > 127) {
28735
+ hasNonAscii = true;
28736
+ break;
28737
+ }
28738
+ }
28739
+ if (hasNonAscii) break;
28740
+ }
28741
+ if (hasNonAscii) {
28742
+ const nameBytes = /* @__PURE__ */ new Map();
28743
+ for (const definition2 of definitions)
28744
+ if (!nameBytes.has(definition2.name))
28745
+ nameBytes.set(definition2.name, Buffer.from(definition2.name));
28746
+ definitions.sort(
28747
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
28748
+ );
28749
+ } else {
28750
+ definitions.sort(
28751
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
28752
+ );
28753
+ }
28274
28754
  const preserveCanonical = /* @__PURE__ */ new Set();
28275
28755
  const definitionsByName = Map.groupBy(definitions, (definition2) => definition2.name);
28276
- for (const name3 of input.symbols) {
28756
+ if (symbolIndices.has("__cxa_throw")) {
28757
+ const name3 = "__cxa_throw";
28277
28758
  const matching2 = definitionsByName.get(name3) ?? [];
28278
- if (new Set(matching2.map((definition2) => definition2.image)).size < 2 || !matching2.some((definition2) => definition2.weak))
28279
- continue;
28280
- const weak = matching2.filter((definition2) => definition2.weak);
28281
- const strong = matching2.filter((definition2) => !definition2.weak);
28282
- if (name3 !== "__cxa_throw") continue;
28283
- if (weak.length !== 1 || strong.length !== 1)
28284
- throw new Error(`unsupported weak interposition for ${name3}`);
28285
- const [local] = weak;
28286
- const [runtime] = strong;
28287
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
28288
- throw new Error(`incompatible weak interposition for ${name3}`);
28289
- for (const caller of input.callers) {
28290
- const uses = caller.image === local.image || units.some(
28291
- (unit2) => unit2.image === caller.image && unit2.usedSymbols.includes(name3)
28292
- );
28293
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
28294
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
28759
+ if (new Set(matching2.map((definition2) => definition2.image)).size >= 2 && matching2.some((definition2) => definition2.weak)) {
28760
+ const weak = matching2.filter((definition2) => definition2.weak);
28761
+ const strong = matching2.filter((definition2) => !definition2.weak);
28762
+ if (weak.length !== 1 || strong.length !== 1)
28763
+ throw new Error(`unsupported weak interposition for ${name3}`);
28764
+ const [local] = weak;
28765
+ const [runtime] = strong;
28766
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
28767
+ throw new Error(`incompatible weak interposition for ${name3}`);
28768
+ for (const caller of input.callers) {
28769
+ const uses = caller.image === local.image || units.some((unit2) => unit2.image === caller.image && unit2.usedSymbols.has(name3));
28770
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
28771
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
28772
+ }
28773
+ preserveCanonical.add(name3);
28295
28774
  }
28296
- preserveCanonical.add(name3);
28297
28775
  }
28298
28776
  for (const name3 of [
28299
28777
  "dlsym",
@@ -28305,40 +28783,76 @@ function createGuestImageLedger(input) {
28305
28783
  ])
28306
28784
  preserveCanonical.add(name3);
28307
28785
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
28308
- const bindingsByImage = /* @__PURE__ */ new Map();
28309
- const definitionsByImage = Map.groupBy(definitions, (definition2) => definition2.image);
28786
+ const imageAliases = /* @__PURE__ */ new Map();
28787
+ const imageWeakNames = /* @__PURE__ */ new Map();
28788
+ const singleOwnerByName = /* @__PURE__ */ new Map();
28789
+ for (const definition2 of definitions) {
28790
+ let aliases = imageAliases.get(definition2.image);
28791
+ if (!aliases) imageAliases.set(definition2.image, aliases = /* @__PURE__ */ new Map());
28792
+ const existing = aliases.get(definition2.name);
28793
+ if (existing === void 0) {
28794
+ aliases.set(definition2.name, definition2.alias);
28795
+ if (definition2.weak) {
28796
+ let weak = imageWeakNames.get(definition2.image);
28797
+ if (!weak) imageWeakNames.set(definition2.image, weak = /* @__PURE__ */ new Set());
28798
+ weak.add(definition2.name);
28799
+ }
28800
+ const owner = singleOwnerByName.get(definition2.name);
28801
+ if (owner === void 0)
28802
+ singleOwnerByName.set(definition2.name, {
28803
+ image: definition2.image,
28804
+ alias: definition2.alias
28805
+ });
28806
+ else if (owner !== null && owner.image !== definition2.image)
28807
+ singleOwnerByName.set(definition2.name, null);
28808
+ } else if (!definition2.weak && imageWeakNames.get(definition2.image)?.has(definition2.name)) {
28809
+ aliases.set(definition2.name, definition2.alias);
28810
+ imageWeakNames.get(definition2.image).delete(definition2.name);
28811
+ const owner = singleOwnerByName.get(definition2.name);
28812
+ if (owner && owner.image === definition2.image) owner.alias = definition2.alias;
28813
+ }
28814
+ }
28815
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
28310
28816
  for (const caller of input.callers) {
28311
- const bindings = /* @__PURE__ */ new Map();
28312
- const seen = /* @__PURE__ */ new Map();
28313
28817
  const scope2 = [caller.image, ...caller.next];
28314
28818
  if (input.systemImage !== void 0 && !scope2.includes(input.systemImage))
28315
28819
  scope2.push(input.systemImage);
28316
- for (const image of scope2)
28317
- for (const definition2 of definitionsByImage.get(image) ?? []) {
28318
- const previous = seen.get(definition2.name);
28319
- if (previous?.image === definition2.image) {
28320
- if (previous.weak && !definition2.weak) {
28321
- seen.set(definition2.name, definition2);
28322
- if (!preserveCanonical.has(definition2.name))
28323
- bindings.set(definition2.name, definition2.alias);
28324
- }
28325
- continue;
28326
- }
28327
- if (!previous) {
28328
- seen.set(definition2.name, definition2);
28329
- if (!preserveCanonical.has(definition2.name))
28330
- bindings.set(definition2.name, definition2.alias);
28820
+ const scopeSet = new Set(scope2);
28821
+ const scopeMaps = [];
28822
+ const seenImages = /* @__PURE__ */ new Set();
28823
+ for (const image of scope2) {
28824
+ if (seenImages.has(image)) continue;
28825
+ seenImages.add(image);
28826
+ const aliases = imageAliases.get(image);
28827
+ if (aliases) scopeMaps.push(aliases);
28828
+ }
28829
+ const cache = /* @__PURE__ */ new Map();
28830
+ sharedLookupByImage.set(caller.image, (name3) => {
28831
+ if (preserveCanonical.has(name3)) return void 0;
28832
+ const single = singleOwnerByName.get(name3);
28833
+ if (single === void 0) return void 0;
28834
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
28835
+ const hit = cache.get(name3);
28836
+ if (hit !== void 0) return hit ?? void 0;
28837
+ for (const aliases of scopeMaps) {
28838
+ const alias = aliases.get(name3);
28839
+ if (alias !== void 0) {
28840
+ cache.set(name3, alias);
28841
+ return alias;
28331
28842
  }
28332
28843
  }
28333
- bindingsByImage.set(caller.image, bindings);
28844
+ cache.set(name3, null);
28845
+ return void 0;
28846
+ });
28334
28847
  }
28335
28848
  const startup = /* @__PURE__ */ new Map();
28849
+ const unitsByPath = new Map(units.map((unit2) => [unit2.object.path, unit2]));
28336
28850
  for (const binding of input.directBindings ?? []) {
28337
- const unit2 = units.find(({ object: object7 }) => object7.path === binding.object);
28851
+ const unit2 = unitsByPath.get(binding.object);
28338
28852
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
28339
28853
  (definition2) => definition2.object === binding.providerObject && definition2.image === binding.providerImage
28340
28854
  );
28341
- if (!unit2 || !unit2.usedSymbols.includes(binding.symbol) || matches.length !== 1)
28855
+ if (!unit2 || !unit2.usedSymbols.has(binding.symbol) || matches.length !== 1)
28342
28856
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
28343
28857
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
28344
28858
  if (bindings.has(binding.symbol))
@@ -28379,11 +28893,11 @@ function createGuestImageLedger(input) {
28379
28893
  }
28380
28894
  }
28381
28895
  const objects = units.map(({ image, object: object7, aliases, functionImports }) => {
28382
- const shared = bindingsByImage.get(image);
28896
+ const shared = sharedLookupByImage.get(image);
28383
28897
  const own2 = startup.get(object7.path);
28384
28898
  const bindings = new Map(own2);
28385
28899
  const weak = input.sdkWeakReferences?.get(object7.path);
28386
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
28900
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
28387
28901
  for (const [name3, type] of functionImports) {
28388
28902
  const alias = binding(name3);
28389
28903
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -28648,7 +29162,7 @@ function nameGuestImageAliases(wasm, symbols) {
28648
29162
  }
28649
29163
  return Buffer.concat(parts);
28650
29164
  }
28651
- var import_node_crypto16, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
29165
+ var import_node_crypto16, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
28652
29166
  var init_swift_guest_image_ledger = __esm({
28653
29167
  "src/swift-guest-image-ledger.ts"() {
28654
29168
  "use strict";
@@ -28656,6 +29170,57 @@ var init_swift_guest_image_ledger = __esm({
28656
29170
  init_nativeWasmContract();
28657
29171
  init_swift_sdk_image_wasm();
28658
29172
  init_swiftSdkLinkContract();
29173
+ ByteWriter = class {
29174
+ buf;
29175
+ pos = 0;
29176
+ constructor(initialCapacity = 256) {
29177
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
29178
+ }
29179
+ ensure(extra) {
29180
+ const needed = this.pos + extra;
29181
+ if (needed <= this.buf.length) return;
29182
+ let next = this.buf.length * 2;
29183
+ while (next < needed) next *= 2;
29184
+ const grown = Buffer.allocUnsafe(next);
29185
+ this.buf.copy(grown, 0, 0, this.pos);
29186
+ this.buf = grown;
29187
+ }
29188
+ byte(value) {
29189
+ this.ensure(1);
29190
+ this.buf[this.pos++] = value;
29191
+ }
29192
+ uleb(value) {
29193
+ this.ensure(10);
29194
+ let pos = this.pos;
29195
+ const buf = this.buf;
29196
+ do {
29197
+ let byte = value % 128;
29198
+ value = Math.floor(value / 128);
29199
+ if (value) byte |= 128;
29200
+ buf[pos++] = byte;
29201
+ } while (value);
29202
+ this.pos = pos;
29203
+ }
29204
+ bytes(source, start = 0, end = source.length) {
29205
+ const len = end - start;
29206
+ if (len <= 0) return;
29207
+ this.ensure(len);
29208
+ this.buf.set(source.subarray(start, end), this.pos);
29209
+ this.pos += len;
29210
+ }
29211
+ string(value) {
29212
+ const len = Buffer.byteLength(value, "utf8");
29213
+ this.uleb(len);
29214
+ if (len > 0) {
29215
+ this.ensure(len);
29216
+ this.buf.write(value, this.pos, len, "utf8");
29217
+ this.pos += len;
29218
+ }
29219
+ }
29220
+ finish() {
29221
+ return this.buf.subarray(0, this.pos);
29222
+ }
29223
+ };
28659
29224
  OBJC_INIT_RECORD = ".objc_init";
28660
29225
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
28661
29226
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -29107,8 +29672,11 @@ function moveGuestDyldTable(map2, wasm, symbols, bindingValues = /* @__PURE__ */
29107
29672
  function guestDyldValueRange(map2) {
29108
29673
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
29109
29674
  let found;
29110
- for (const line of map2.split("\n")) {
29111
- if (!line.endsWith(suffix)) continue;
29675
+ for (let at = map2.indexOf(suffix); at !== -1; at = map2.indexOf(suffix, at + suffix.length)) {
29676
+ const lineEnd = at + suffix.length;
29677
+ if (lineEnd < map2.length && map2.charCodeAt(lineEnd) !== 10) continue;
29678
+ const lineStart = map2.lastIndexOf("\n", at) + 1;
29679
+ const line = map2.slice(lineStart, lineEnd);
29112
29680
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
29113
29681
  if (!match) throw new Error("unreadable dyld values map line");
29114
29682
  if (found) throw new Error("link map has several dyld value sections");
@@ -29161,7 +29729,7 @@ var init_swift_guest_link_plan = __esm({
29161
29729
  });
29162
29730
 
29163
29731
  // src/swift-guest-manifest.ts
29164
- function selectedGuestManifestInputs(plan, selection, identities) {
29732
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
29165
29733
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
29166
29734
  const archives = /* @__PURE__ */ new Map();
29167
29735
  const images = /* @__PURE__ */ new Map();
@@ -29172,19 +29740,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
29172
29740
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
29173
29741
  let bytes;
29174
29742
  let memberIdentity = null;
29175
- if (item.member === null) bytes = (0, import_node_fs31.readFileSync)(item.artifact);
29176
- else {
29177
- let members2 = archives.get(item.artifact);
29178
- if (!members2) {
29179
- members2 = readArMembers((0, import_node_fs31.readFileSync)(item.artifact));
29180
- archives.set(item.artifact, members2);
29743
+ if (item.member === null) {
29744
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs31.readFileSync)(item.artifact);
29745
+ } else {
29746
+ if (readSelected) {
29747
+ bytes = readSelected(item);
29748
+ } else {
29749
+ let members2 = archives.get(item.artifact);
29750
+ if (!members2) {
29751
+ members2 = /* @__PURE__ */ new Map();
29752
+ for (const member of readArMembers((0, import_node_fs31.readFileSync)(item.artifact))) {
29753
+ let list2 = members2.get(member.name);
29754
+ if (!list2) members2.set(member.name, list2 = []);
29755
+ list2.push(member.bytes);
29756
+ }
29757
+ archives.set(item.artifact, members2);
29758
+ }
29759
+ const matching2 = members2.get(item.member);
29760
+ if (!matching2 || matching2.length !== 1)
29761
+ throw new Error(
29762
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
29763
+ );
29764
+ bytes = matching2[0];
29181
29765
  }
29182
- const matching2 = members2.filter((member) => member.name === item.member);
29183
- if (matching2.length !== 1)
29184
- throw new Error(
29185
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
29186
- );
29187
- bytes = matching2[0].bytes;
29188
29766
  const origin = artifact.memberOrigins?.get(item.member);
29189
29767
  if (artifact.memberOrigins && !origin)
29190
29768
  throw new Error(
@@ -29276,7 +29854,7 @@ var init_swift_guest_manifest = __esm({
29276
29854
  function isSwiftGuestImageManifest(value) {
29277
29855
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
29278
29856
  const text7 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
29279
- const name3 = (value2) => text7(value2) && new TextEncoder().encode(value2).length <= 16;
29857
+ const name3 = (value2) => text7(value2) && Buffer.byteLength(value2, "utf8") <= 16;
29280
29858
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
29281
29859
  if (!isRecord(value) || value.version !== 1 || !text7(value.id) || !text7(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))
29282
29860
  return false;
@@ -29590,27 +30168,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
29590
30168
  function finalizeGuestProjectionStorage(options2) {
29591
30169
  const owner = options2.owners.get(options2.projectionObject);
29592
30170
  if (owner === void 0) throw new Error("guest projection object has no image owner");
30171
+ const ranges = [];
29593
30172
  const spans = guestLinkedSpans(
29594
30173
  options2.map,
29595
30174
  options2.linked,
29596
30175
  options2.optimized,
29597
30176
  options2.owners,
29598
30177
  options2.sectionOwners,
29599
- options2.sdkSpans !== void 0
30178
+ options2.sdkSpans !== void 0,
30179
+ {
30180
+ trackedObject: options2.projectionObject,
30181
+ trackedObjectOwner: owner,
30182
+ trackedLinearSpans: ranges
30183
+ }
29600
30184
  );
29601
30185
  const images = planGuestProjectionRegions(
29602
30186
  options2.reserved.images,
29603
30187
  options2.reserved.capacities,
29604
30188
  options2.sdkSpans ? [...spans, ...options2.sdkSpans] : spans
29605
30189
  );
29606
- const ranges = guestLinkedSpans(
29607
- options2.map,
29608
- options2.linked,
29609
- options2.optimized,
29610
- /* @__PURE__ */ new Map([[options2.projectionObject, owner]]),
29611
- void 0,
29612
- options2.sdkSpans !== void 0
29613
- ).filter((span) => span.space === "linear-memory");
29614
30190
  const result = Buffer.from(options2.optimized);
29615
30191
  const data = guestWasmDataSegments(options2.optimized, options2.sdkSpans === void 0);
29616
30192
  const locations = /* @__PURE__ */ new Map();
@@ -30678,7 +31254,7 @@ function occurrences(plan, args) {
30678
31254
  throw new Error("guest plan does not match linker inputs");
30679
31255
  return found;
30680
31256
  }
30681
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
31257
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
30682
31258
  const rows = whyExtract.trimEnd().split("\n");
30683
31259
  if (rows.shift() !== "reference extracted symbol")
30684
31260
  throw new Error("invalid wasm-ld extraction report");
@@ -30693,8 +31269,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
30693
31269
  for (const file of extracted)
30694
31270
  if (!traced.has(file))
30695
31271
  throw new Error(`extracted guest input is absent from link trace ${file}`);
31272
+ const foundOccurrences = occurrences(plan, args);
31273
+ const archivePaths = /* @__PURE__ */ new Set();
31274
+ for (const { artifact } of foundOccurrences)
31275
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
31276
+ const tracedMembers = /* @__PURE__ */ new Map();
31277
+ if (archivePaths.size > 0) {
31278
+ const archivePrefixes = [...archivePaths].map(
31279
+ (archivePath) => [archivePath, `${archivePath}(`]
31280
+ );
31281
+ for (const item of traced) {
31282
+ if (!item.endsWith(")")) continue;
31283
+ const open = item.lastIndexOf("(");
31284
+ if (open > 0) {
31285
+ const archivePath = item.slice(0, open);
31286
+ if (archivePaths.has(archivePath)) {
31287
+ let list2 = tracedMembers.get(archivePath);
31288
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
31289
+ list2.push(item.slice(open + 1, -1));
31290
+ continue;
31291
+ }
31292
+ }
31293
+ for (const [archivePath, prefix] of archivePrefixes) {
31294
+ if (item.startsWith(prefix)) {
31295
+ let list2 = tracedMembers.get(archivePath);
31296
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
31297
+ list2.push(item.slice(prefix.length, -1));
31298
+ }
31299
+ }
31300
+ }
31301
+ }
30696
31302
  const result = [];
30697
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
31303
+ for (const { artifact, lazy, whole } of foundOccurrences) {
30698
31304
  if (artifact.kind === "object") {
30699
31305
  if (!lazy && !traced.has(artifact.path))
30700
31306
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -30702,15 +31308,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
30702
31308
  result.push({ artifact: artifact.path, member: null });
30703
31309
  continue;
30704
31310
  }
30705
- const prefix = `${artifact.path}(`;
30706
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
30707
- const members2 = readArMembers(import_node_fs34.default.readFileSync(artifact.path));
31311
+ const names = tracedMembers.get(artifact.path) ?? [];
31312
+ const nameSet = new Set(names);
31313
+ let members2 = archiveCache?.get(artifact.path);
31314
+ if (!members2) {
31315
+ members2 = readArMembers(import_node_fs34.default.readFileSync(artifact.path));
31316
+ archiveCache?.set(artifact.path, members2);
31317
+ }
31318
+ const memberCounts = /* @__PURE__ */ new Map();
30708
31319
  for (const member of members2) {
30709
- if (whole || names.includes(member.name))
31320
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
31321
+ if (whole || nameSet.has(member.name))
30710
31322
  result.push({ artifact: artifact.path, member: member.name });
30711
31323
  }
30712
31324
  for (const name3 of names)
30713
- if (members2.filter((member) => member.name === name3).length !== 1)
31325
+ if (memberCounts.get(name3) !== 1)
30714
31326
  throw new Error(
30715
31327
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
30716
31328
  );
@@ -30787,14 +31399,25 @@ function linkGuestImages(options2) {
30787
31399
  }
30788
31400
  const archives = /* @__PURE__ */ new Map();
30789
31401
  const memberBytes = /* @__PURE__ */ new Map();
31402
+ const objectBytes = /* @__PURE__ */ new Map();
30790
31403
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
30791
31404
  const providerSymbol = "__peach_dlsym_from_image";
30792
31405
  const readSelected = (item) => {
30793
- if (item.member === null) return import_node_fs34.default.readFileSync(item.artifact);
31406
+ if (item.member === null) {
31407
+ let bytes = objectBytes.get(item.artifact);
31408
+ if (!bytes) {
31409
+ bytes = import_node_fs34.default.readFileSync(item.artifact);
31410
+ objectBytes.set(item.artifact, bytes);
31411
+ }
31412
+ return bytes;
31413
+ }
30794
31414
  let byName2 = memberBytes.get(item.artifact);
30795
31415
  if (!byName2) {
30796
- const members2 = readArMembers(import_node_fs34.default.readFileSync(item.artifact));
30797
- archives.set(item.artifact, members2);
31416
+ let members2 = archives.get(item.artifact);
31417
+ if (!members2) {
31418
+ members2 = readArMembers(import_node_fs34.default.readFileSync(item.artifact));
31419
+ archives.set(item.artifact, members2);
31420
+ }
30798
31421
  byName2 = /* @__PURE__ */ new Map();
30799
31422
  for (const member of members2)
30800
31423
  if (!byName2.has(member.name))
@@ -30818,7 +31441,13 @@ function linkGuestImages(options2) {
30818
31441
  `--why-extract=${whyPath}`,
30819
31442
  `--Map=${mapPath}`
30820
31443
  ]);
30821
- return selectedGuestLinkInputs(plan, args, import_node_fs34.default.readFileSync(whyPath, "utf8"), trace);
31444
+ return selectedGuestLinkInputs(
31445
+ plan,
31446
+ args,
31447
+ import_node_fs34.default.readFileSync(whyPath, "utf8"),
31448
+ trace,
31449
+ archives
31450
+ );
30822
31451
  };
30823
31452
  const needsProvider = (item) => {
30824
31453
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -30858,7 +31487,7 @@ function linkGuestImages(options2) {
30858
31487
  )
30859
31488
  ]);
30860
31489
  const originalOwnership = identity2(plan);
30861
- const resolved = options2.resolvePlan(selected, plan);
31490
+ const resolved = options2.resolvePlan(selected, plan, readSelected);
30862
31491
  if (identity2(resolved) !== originalOwnership)
30863
31492
  throw new Error("resolved guest scopes changed input ownership");
30864
31493
  plan = resolved;
@@ -30912,6 +31541,7 @@ function linkGuestImages(options2) {
30912
31541
  }
30913
31542
  }
30914
31543
  let discoveryRegions;
31544
+ let liveSymbols;
30915
31545
  if (discoveryProjection && options2.projection) {
30916
31546
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options2.projection.image]]);
30917
31547
  for (const item of selected)
@@ -30920,10 +31550,15 @@ function linkGuestImages(options2) {
30920
31550
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
30921
31551
  );
30922
31552
  const wasm = import_node_fs34.default.readFileSync(discovery);
31553
+ liveSymbols = /* @__PURE__ */ new Set();
30923
31554
  discoveryRegions = guestProjectionRegionCounts(
30924
31555
  plan.images.length,
30925
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
31556
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
31557
+ collectSymbols: liveSymbols
31558
+ })
30926
31559
  );
31560
+ } else {
31561
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
30927
31562
  }
30928
31563
  const ledger = createGuestImageLedger({
30929
31564
  images: plan.images.map((image) => ({
@@ -30932,7 +31567,7 @@ function linkGuestImages(options2) {
30932
31567
  })),
30933
31568
  callers: plan.callers,
30934
31569
  symbols: plan.symbols,
30935
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
31570
+ liveSymbols,
30936
31571
  commandLineSymbols: commandLineSymbols(args),
30937
31572
  directBindings: plan.directBindings,
30938
31573
  registerAppTables: sdkCallers !== void 0,
@@ -31064,7 +31699,8 @@ function linkGuestImages(options2) {
31064
31699
  const selectedInputs = selectedGuestManifestInputs(
31065
31700
  plan,
31066
31701
  selected,
31067
- projection.identities
31702
+ projection.identities,
31703
+ readSelected
31068
31704
  );
31069
31705
  const images = projection.images.map(
31070
31706
  (image) => createGuestImageManifest({
@@ -31074,6 +31710,9 @@ function linkGuestImages(options2) {
31074
31710
  regions: []
31075
31711
  })
31076
31712
  );
31713
+ objectBytes.clear();
31714
+ memberBytes.clear();
31715
+ archives.clear();
31077
31716
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
31078
31717
  const regionsBefore = discoveryRegions;
31079
31718
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs34.default.readFileSync(ledgerObject)], 0);
@@ -31099,6 +31738,7 @@ function linkGuestImages(options2) {
31099
31738
  { stdio: "pipe" }
31100
31739
  );
31101
31740
  finalTrace = linkFinal(projectionObject, callerMap ? void 0 : layoutMap);
31741
+ if (sharedSdk) break;
31102
31742
  const wasm = import_node_fs34.default.readFileSync(finalOutput);
31103
31743
  const actual = guestProjectionRegionCounts(
31104
31744
  images.length,
@@ -31167,10 +31807,47 @@ ${changed.join("\n")}`
31167
31807
  }
31168
31808
  function linkedMapSymbols(lines) {
31169
31809
  const names = /* @__PURE__ */ new Set();
31170
- const symbol2 = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
31171
31810
  for (const line of lines) {
31172
- const match = symbol2.exec(line);
31173
- if (match) names.add(match[1]);
31811
+ const length = line.length;
31812
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
31813
+ let pos = 1;
31814
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31815
+ const c1 = pos;
31816
+ while (pos < length) {
31817
+ const ch = line.charCodeAt(pos);
31818
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
31819
+ pos++;
31820
+ }
31821
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
31822
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31823
+ const c2 = pos;
31824
+ while (pos < length) {
31825
+ const ch = line.charCodeAt(pos);
31826
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
31827
+ pos++;
31828
+ }
31829
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
31830
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31831
+ const c3 = pos;
31832
+ while (pos < length) {
31833
+ const ch = line.charCodeAt(pos);
31834
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
31835
+ pos++;
31836
+ }
31837
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
31838
+ const sStart = pos;
31839
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31840
+ if (pos - sStart < 9 || pos >= length) continue;
31841
+ const first = line.charCodeAt(pos);
31842
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
31843
+ continue;
31844
+ let end = pos + 1;
31845
+ while (end < length) {
31846
+ const ch = line.charCodeAt(end);
31847
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
31848
+ end++;
31849
+ }
31850
+ names.add(line.slice(pos, end));
31174
31851
  }
31175
31852
  return names;
31176
31853
  }
@@ -31269,7 +31946,7 @@ function discoverGuestLinkInputs(options2) {
31269
31946
  import_node_fs34.default.mkdirSync(options2.directory, { recursive: true });
31270
31947
  const why = import_node_path32.default.join(options2.directory, "preselection-why.txt");
31271
31948
  const response = import_node_path32.default.join(options2.directory, "preselection.rsp");
31272
- const output = import_node_path32.default.join(options2.directory, "preselection.wasm");
31949
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path32.default.join(options2.directory, "preselection.wasm");
31273
31950
  const flags = [
31274
31951
  ...withOutput(args, output, true),
31275
31952
  ...options2.objects,
@@ -31367,7 +32044,7 @@ function prepareGuestRuntimeInputs(options2) {
31367
32044
  });
31368
32045
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
31369
32046
  }
31370
- function selectedGuestSymbolInputs(plan, selected) {
32047
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
31371
32048
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
31372
32049
  const archives = /* @__PURE__ */ new Map();
31373
32050
  const symbols = /* @__PURE__ */ new Set();
@@ -31383,22 +32060,27 @@ function selectedGuestSymbolInputs(plan, selected) {
31383
32060
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
31384
32061
  let bytes;
31385
32062
  let name3 = item.artifact;
31386
- if (item.member === null) bytes = import_node_fs34.default.readFileSync(item.artifact);
31387
- else {
31388
- let members2 = archives.get(item.artifact);
31389
- if (!members2) {
31390
- members2 = Map.groupBy(
31391
- readArMembers(import_node_fs34.default.readFileSync(item.artifact)),
31392
- (member) => member.name
31393
- );
31394
- archives.set(item.artifact, members2);
32063
+ if (item.member === null) {
32064
+ bytes = readSelected ? readSelected(item) : import_node_fs34.default.readFileSync(item.artifact);
32065
+ } else {
32066
+ if (readSelected) {
32067
+ bytes = readSelected(item);
32068
+ } else {
32069
+ let members2 = archives.get(item.artifact);
32070
+ if (!members2) {
32071
+ members2 = Map.groupBy(
32072
+ readArMembers(import_node_fs34.default.readFileSync(item.artifact)),
32073
+ (member) => member.name
32074
+ );
32075
+ archives.set(item.artifact, members2);
32076
+ }
32077
+ const matching2 = members2.get(item.member) ?? [];
32078
+ if (matching2.length !== 1)
32079
+ throw new Error(
32080
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
32081
+ );
32082
+ bytes = matching2[0].bytes;
31395
32083
  }
31396
- const matching2 = members2.get(item.member) ?? [];
31397
- if (matching2.length !== 1)
31398
- throw new Error(
31399
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
31400
- );
31401
- bytes = matching2[0].bytes;
31402
32084
  name3 += `(${item.member})`;
31403
32085
  }
31404
32086
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -31411,9 +32093,9 @@ function selectedGuestSymbolInputs(plan, selected) {
31411
32093
  for (const symbol2 of names.tags) tags.add(symbol2);
31412
32094
  for (const symbol2 of names.defined) {
31413
32095
  definitions.add(symbol2);
31414
- const objects = definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
32096
+ let objects = definitionObjects.get(symbol2);
32097
+ if (!objects) definitionObjects.set(symbol2, objects = /* @__PURE__ */ new Set());
31415
32098
  objects.add(name3);
31416
- definitionObjects.set(symbol2, objects);
31417
32099
  }
31418
32100
  }
31419
32101
  return {
@@ -31434,7 +32116,7 @@ function verifyGuestSymbolScopes(options2) {
31434
32116
  if (!symbols.length) return { bindings: [], directBindings: [] };
31435
32117
  import_node_fs34.default.mkdirSync(options2.directory, { recursive: true });
31436
32118
  const response = import_node_path32.default.join(options2.directory, "scope-trace.rsp");
31437
- const output = import_node_path32.default.join(options2.directory, "scope-trace.wasm");
32119
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path32.default.join(options2.directory, "scope-trace.wasm");
31438
32120
  const args = [
31439
32121
  ...withOutput(normalizedGuestLinkArgs(options2.args), output, true),
31440
32122
  ...options2.objects,
@@ -31452,55 +32134,76 @@ function verifyGuestSymbolScopes(options2) {
31452
32134
  import_node_fs34.default.closeSync(traceOutput);
31453
32135
  }
31454
32136
  const records = /* @__PURE__ */ new Map();
31455
- const consume = (line) => {
31456
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
31457
- if (!match) return;
31458
- const [, object7, kind, symbol2] = match;
31459
- if (!requested.has(symbol2)) return;
31460
- if (options2.hostImports.has(symbol2)) return;
31461
- const record5 = records.get(symbol2) ?? {
31462
- references: /* @__PURE__ */ new Map(),
31463
- providers: /* @__PURE__ */ new Map(),
31464
- physicalModule: false
31465
- };
32137
+ for (const line of guestLinkLines(tracePath)) {
32138
+ const refSep = line.lastIndexOf(": reference to ");
32139
+ const defSep = line.lastIndexOf(": definition of ");
32140
+ if (refSep < 0 && defSep < 0) continue;
32141
+ const isRef = refSep > defSep;
32142
+ const sep3 = isRef ? refSep : defSep;
32143
+ const symbol2 = line.slice(sep3 + (isRef ? 15 : 16));
32144
+ if (!requested.has(symbol2) || options2.hostImports.has(symbol2)) continue;
32145
+ let record5 = records.get(symbol2);
32146
+ if (!record5) {
32147
+ record5 = {
32148
+ references: /* @__PURE__ */ new Map(),
32149
+ providers: /* @__PURE__ */ new Map(),
32150
+ physicalModule: false
32151
+ };
32152
+ records.set(symbol2, record5);
32153
+ }
32154
+ const object7 = line.slice(0, sep3);
31466
32155
  if (object7 === "<internal>") {
31467
- if (kind === "definition of") record5.physicalModule = true;
32156
+ if (!isRef) record5.physicalModule = true;
31468
32157
  } else {
31469
32158
  const image = options2.owners.get(object7);
31470
32159
  if (image === void 0)
31471
32160
  throw new Error(`traced guest object has no owner ${object7}`);
31472
- (kind === "reference to" ? record5.references : record5.providers).set(
31473
- object7,
31474
- image
31475
- );
32161
+ (isRef ? record5.references : record5.providers).set(object7, image);
31476
32162
  }
31477
- records.set(symbol2, record5);
31478
- };
31479
- for (const line of guestLinkLines(tracePath)) consume(line);
32163
+ }
31480
32164
  const callers = new Map(options2.callers.map((caller) => [caller.image, caller.next]));
32165
+ const callerSets = new Map(
32166
+ options2.callers.map((caller) => [caller.image, new Set(caller.next)])
32167
+ );
32168
+ const rootScope = callerSets.get(0);
31481
32169
  const result = [];
31482
32170
  const directBindings = [];
31483
32171
  for (const symbol2 of symbols) {
31484
32172
  const record5 = records.get(symbol2);
31485
32173
  if (!record5 || !record5.references.size) continue;
31486
32174
  if (!record5.providers.size && options2.hostImports.has(symbol2)) continue;
31487
- const startupReferences = [...record5.references].filter(
31488
- ([object7]) => options2.startupObjects.has(object7) && options2.weakReferences.get(object7)?.has(symbol2)
31489
- );
31490
- const otherReferences = [...record5.references].filter(
31491
- ([object7]) => !startupReferences.some(([startup]) => startup === object7)
31492
- );
32175
+ const startupReferences = [];
32176
+ const otherReferences = [];
32177
+ let allWeakRefs = true;
32178
+ for (const [object7, caller] of record5.references) {
32179
+ const isWeakRef = options2.weakReferences.get(object7)?.has(symbol2) === true;
32180
+ if (!isWeakRef) allWeakRefs = false;
32181
+ if (isWeakRef && options2.startupObjects.has(object7)) {
32182
+ startupReferences.push([object7, caller]);
32183
+ } else {
32184
+ otherReferences.push([object7, caller]);
32185
+ }
32186
+ }
31493
32187
  for (const [, caller] of startupReferences)
31494
32188
  if (!callers.has(caller))
31495
32189
  throw new Error(`guest image has no caller scope ${caller}`);
31496
32190
  if (startupReferences.length && !record5.physicalModule) {
31497
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
31498
- if (candidates.size > 1 || record5.providers.size > 1)
32191
+ const candidates2 = options2.definitionObjects.get(symbol2);
32192
+ const candidateSize = candidates2?.size ?? 0;
32193
+ if (candidateSize > 1 || record5.providers.size > 1)
31499
32194
  throw new Error(`ambiguous startup provider ${symbol2}`);
31500
- if (candidates.size !== record5.providers.size || [...record5.providers.keys()].some((object7) => !candidates.has(object7)))
31501
- throw new Error(`unproven startup provider ${symbol2}`);
32195
+ let unproven = candidateSize !== record5.providers.size;
32196
+ if (!unproven && candidates2) {
32197
+ for (const object7 of record5.providers.keys()) {
32198
+ if (!candidates2.has(object7)) {
32199
+ unproven = true;
32200
+ break;
32201
+ }
32202
+ }
32203
+ }
32204
+ if (unproven) throw new Error(`unproven startup provider ${symbol2}`);
31502
32205
  if (record5.providers.size === 1) {
31503
- const [providerObject, providerImage] = [...record5.providers][0];
32206
+ const [providerObject, providerImage] = record5.providers.entries().next().value;
31504
32207
  if (options2.weakDefinitions.get(providerObject)?.has(symbol2))
31505
32208
  throw new Error(`weak startup provider ${symbol2}`);
31506
32209
  for (const [object7] of startupReferences)
@@ -31508,28 +32211,34 @@ function verifyGuestSymbolScopes(options2) {
31508
32211
  }
31509
32212
  if (!otherReferences.length) continue;
31510
32213
  }
31511
- if (!record5.providers.size && !record5.physicalModule && [...record5.references.keys()].every(
31512
- (object7) => options2.weakReferences.get(object7)?.has(symbol2)
31513
- ))
31514
- continue;
32214
+ if (!record5.providers.size && !record5.physicalModule && allWeakRefs) continue;
31515
32215
  const providerImages = new Set(record5.providers.values());
31516
- const copies = [...options2.definitionObjects.get(symbol2) ?? []].flatMap(
31517
- (object7) => {
32216
+ const candidates = options2.definitionObjects.get(symbol2);
32217
+ const copyImages = /* @__PURE__ */ new Set();
32218
+ const strongImages = /* @__PURE__ */ new Set();
32219
+ let weakDefinerImages;
32220
+ if (candidates) {
32221
+ for (const object7 of candidates) {
31518
32222
  const image = options2.owners.get(object7);
31519
- return image === void 0 ? [] : [{ image, weak: !!options2.weakDefinitions.get(object7)?.has(symbol2) }];
32223
+ if (image === void 0) continue;
32224
+ copyImages.add(image);
32225
+ if (options2.weakDefinitions.get(object7)?.has(symbol2)) {
32226
+ ;
32227
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
32228
+ } else {
32229
+ strongImages.add(image);
32230
+ }
31520
32231
  }
31521
- );
31522
- const copyImages = new Set(copies.map((copy) => copy.image));
31523
- const strongImages = new Set(
31524
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
31525
- );
32232
+ }
31526
32233
  const interposed = !record5.physicalModule && copyImages.size > 1;
31527
32234
  const providerCount = interposed ? 1 : providerImages.size + Number(record5.physicalModule);
31528
32235
  if (!providerCount) continue;
31529
32236
  if (providerCount !== 1)
31530
32237
  throw new Error(`guest symbol has ambiguous provider ${symbol2}`);
31531
- const scopedReferences = record5.physicalModule ? [...record5.references] : otherReferences;
31532
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
32238
+ const scopedReferences = record5.physicalModule ? record5.references : otherReferences;
32239
+ const firstProviderImage = providerImages.values().next().value;
32240
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
32241
+ let interposedByCaller;
31533
32242
  for (const [object7, caller] of scopedReferences) {
31534
32243
  const scope2 = callers.get(caller);
31535
32244
  if (!scope2) throw new Error(`guest image has no caller scope ${caller}`);
@@ -31537,18 +32246,35 @@ function verifyGuestSymbolScopes(options2) {
31537
32246
  result.push({ symbol: symbol2, caller, provider: { kind: "physical-module" } });
31538
32247
  continue;
31539
32248
  }
31540
- const provider = interposed ? [caller, ...scope2].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
32249
+ let provider;
32250
+ if (interposed) {
32251
+ if (interposedByCaller?.has(caller)) {
32252
+ provider = interposedByCaller.get(caller);
32253
+ } else {
32254
+ if (copyImages.has(caller)) {
32255
+ provider = caller;
32256
+ } else {
32257
+ for (const image of scope2) {
32258
+ if (copyImages.has(image)) {
32259
+ provider = image;
32260
+ break;
32261
+ }
32262
+ }
32263
+ if (provider === void 0) provider = uniqueProvider;
32264
+ }
32265
+ ;
32266
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
32267
+ }
32268
+ } else {
32269
+ provider = firstProviderImage;
32270
+ }
31541
32271
  if (provider === void 0) {
31542
32272
  if (options2.weakReferences.get(object7)?.has(symbol2)) continue;
31543
32273
  throw new Error(`guest scope ${caller} omits every provider of ${symbol2}`);
31544
32274
  }
31545
32275
  if (caller === provider) continue;
31546
- if ([...options2.definitionObjects.get(symbol2) ?? []].some(
31547
- (definer) => options2.owners.get(definer) === caller && options2.weakDefinitions.get(definer)?.has(symbol2)
31548
- ))
31549
- continue;
31550
- if (!scope2.includes(provider)) {
31551
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
32276
+ if (weakDefinerImages?.has(caller)) continue;
32277
+ if (!callerSets.get(caller).has(provider)) {
31552
32278
  const traced = [...record5.providers.keys()];
31553
32279
  const strongTraced = traced.filter(
31554
32280
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
@@ -31556,16 +32282,17 @@ function verifyGuestSymbolScopes(options2) {
31556
32282
  const providers = strongTraced.length === 1 ? strongTraced : traced;
31557
32283
  if (options2.weakReferences.get(object7)?.has(symbol2) && !providers.some((provider2) => options2.systemProviders.has(provider2)))
31558
32284
  continue;
31559
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
32285
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
32286
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
31560
32287
  (definer) => options2.weakDefinitions.get(definer)?.has(symbol2)
31561
32288
  );
31562
- const strongCandidates = [...candidates].filter(
32289
+ const strongCandidates = [...candidateSet].filter(
31563
32290
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
31564
32291
  );
31565
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
31566
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
32292
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
32293
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
31567
32294
  // scope, the root image and its dependency closure, as in elf.
31568
- provider === 0 || callers.get(0)?.includes(provider) || !options2.weakReferences.get(object7)?.has(symbol2) && options2.frameworkProviders.get(object7)?.has(providers[0]))))
32295
+ provider === 0 || rootScope?.has(provider) || !options2.weakReferences.get(object7)?.has(symbol2) && options2.frameworkProviders.get(object7)?.has(providers[0]))))
31569
32296
  throw new Error(
31570
32297
  `guest scope ${caller} omits traced provider ${provider} for ${symbol2}`
31571
32298
  );
@@ -31774,6 +32501,85 @@ function clangProducerStamp(file) {
31774
32501
  const stat = (0, import_node_fs35.statSync)(file, { bigint: true });
31775
32502
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
31776
32503
  }
32504
+ function clangBinaryStamp(file) {
32505
+ const stat = (0, import_node_fs35.statSync)(file, { bigint: true });
32506
+ return [file, stat.size, stat.mtimeNs].join(":");
32507
+ }
32508
+ function clangWrapperStamp(file) {
32509
+ return (0, import_node_crypto21.createHash)("sha256").update((0, import_node_fs35.readFileSync)(file)).digest("hex");
32510
+ }
32511
+ function clangArgsNeedCwd(args) {
32512
+ const pathFlags = /* @__PURE__ */ new Set([
32513
+ "-I",
32514
+ "-isystem",
32515
+ "-iquote",
32516
+ "-F",
32517
+ "-iframework",
32518
+ "-isysroot",
32519
+ "-o",
32520
+ "-MF"
32521
+ ]);
32522
+ const includeFlags = /* @__PURE__ */ new Set(["-include", "-imacros"]);
32523
+ const valueFlags = /* @__PURE__ */ new Set([
32524
+ "-x",
32525
+ "-target",
32526
+ "-MT",
32527
+ "-MQ",
32528
+ "-D",
32529
+ "-U",
32530
+ "-mllvm",
32531
+ "-Xclang",
32532
+ "-arch",
32533
+ "-std"
32534
+ ]);
32535
+ const prefixFlags = [
32536
+ "-I",
32537
+ "-F",
32538
+ "-isystem",
32539
+ "-iquote",
32540
+ "--sysroot=",
32541
+ "-fmodule-map-file=",
32542
+ "-fmodules-cache-path="
32543
+ ];
32544
+ const isRelativePath = (value) => value.length > 0 && !value.startsWith("/") && !value.startsWith("=/") && value !== "-";
32545
+ for (let i = 1; i < args.length; i++) {
32546
+ const arg = args[i];
32547
+ if (pathFlags.has(arg)) {
32548
+ if (isRelativePath(args[++i] ?? "")) return true;
32549
+ continue;
32550
+ }
32551
+ if (includeFlags.has(arg)) {
32552
+ const value = args[++i] ?? "";
32553
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs35.existsSync)(value))) return true;
32554
+ continue;
32555
+ }
32556
+ if (valueFlags.has(arg)) {
32557
+ i++;
32558
+ continue;
32559
+ }
32560
+ if (arg.startsWith("@")) {
32561
+ if (isRelativePath(arg.slice(1))) return true;
32562
+ continue;
32563
+ }
32564
+ if (arg.startsWith("-")) {
32565
+ if (arg.startsWith("-include") && arg.length > 8) {
32566
+ const value = arg.slice(8);
32567
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs35.existsSync)(value)))
32568
+ return true;
32569
+ continue;
32570
+ }
32571
+ for (const prefix of prefixFlags) {
32572
+ if (arg.startsWith(prefix) && arg.length > prefix.length) {
32573
+ if (isRelativePath(arg.slice(prefix.length))) return true;
32574
+ break;
32575
+ }
32576
+ }
32577
+ continue;
32578
+ }
32579
+ if (isRelativePath(arg)) return true;
32580
+ }
32581
+ return false;
32582
+ }
31777
32583
  function validateClangLinkOptions(flags) {
31778
32584
  for (let index = 0; index < flags.length; index++) {
31779
32585
  const flag = flags[index];
@@ -31853,7 +32659,7 @@ function sourceGuestClangLinkOptions(options2) {
31853
32659
  let clang;
31854
32660
  let clangStamp;
31855
32661
  let wrapperStamp;
31856
- for (const [index, file] of [...wanted].entries()) {
32662
+ for (const file of wanted) {
31857
32663
  const command = commands.get(file);
31858
32664
  if (!command) throw new Error(`missing source object producer ${file}`);
31859
32665
  if (command.tool === "shell") {
@@ -31867,12 +32673,12 @@ function sourceGuestClangLinkOptions(options2) {
31867
32673
  throw new Error(`unsupported source object producer ${file}`);
31868
32674
  const key2 = (0, import_node_crypto21.createHash)("sha256").update(
31869
32675
  JSON.stringify([
31870
- "clang-link-options/v1",
31871
- process.cwd(),
32676
+ "clang-link-options/v2",
32677
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
31872
32678
  driverEnvironment,
31873
32679
  command.args,
31874
- clangStamp ??= clangProducerStamp(clang),
31875
- compiler === clang ? null : wrapperStamp ??= clangProducerStamp(compiler),
32680
+ clangStamp ??= clangBinaryStamp(clang),
32681
+ compiler === clang ? null : wrapperStamp ??= clangWrapperStamp(compiler),
31876
32682
  clangProducerStamp(file)
31877
32683
  ])
31878
32684
  ).digest("hex");
@@ -31887,31 +32693,44 @@ function sourceGuestClangLinkOptions(options2) {
31887
32693
  continue;
31888
32694
  }
31889
32695
  result.set(file, []);
31890
- const args = command.args.slice(1).filter((arg) => arg !== "-c");
31891
32696
  const targetBuild = import_node_path33.default.relative(options2.buildDirectory, file).split(import_node_path33.default.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
31892
- const outputDirectory = import_node_path33.default.join(
31893
- options2.directory,
31894
- targetBuild ?? import_node_path33.default.basename(import_node_path33.default.dirname(file))
31895
- );
31896
- (0, import_node_fs35.mkdirSync)(outputDirectory, { recursive: true });
31897
- const output = import_node_path33.default.join(outputDirectory, `clang-link-${index}.ll`);
31898
- for (const flag of ["-o", "-MF"]) {
31899
- const index2 = args.lastIndexOf(flag);
31900
- if (index2 < 0 || index2 + 1 >= args.length)
31901
- throw new Error(`missing clang ${flag} for ${file}`);
31902
- args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
32697
+ const args = [];
32698
+ let sawOutput = false;
32699
+ let explicitModuleName = false;
32700
+ for (let i = 1; i < command.args.length; i++) {
32701
+ const arg = command.args[i];
32702
+ if (arg === "-c" || arg === "-MD" || arg === "-MMD" || arg === "-MP") continue;
32703
+ if (arg === "-MF" || arg === "-MT" || arg === "-MQ") {
32704
+ if (i + 1 >= command.args.length)
32705
+ throw new Error(`missing clang ${arg} for ${file}`);
32706
+ i++;
32707
+ continue;
32708
+ }
32709
+ if (arg === "-o") {
32710
+ if (i + 1 >= command.args.length) throw new Error(`missing clang -o for ${file}`);
32711
+ i++;
32712
+ args.push("-o", "-");
32713
+ sawOutput = true;
32714
+ continue;
32715
+ }
32716
+ if (arg.startsWith("-fmodule-name=")) explicitModuleName = true;
32717
+ args.push(arg);
32718
+ }
32719
+ if (!sawOutput) throw new Error(`missing clang -o for ${file}`);
32720
+ if (compiler !== clang && targetBuild && !explicitModuleName) {
32721
+ args.unshift(`-fmodule-name=${targetBuild.slice(0, -".build".length)}`);
31903
32722
  }
31904
32723
  replays.push({
31905
32724
  file,
31906
32725
  compiler: command.args[0],
31907
32726
  args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
31908
- output,
31909
32727
  cacheFile,
31910
32728
  key: key2
31911
32729
  });
31912
32730
  }
31913
32731
  if (replays.length === 0) return result;
31914
32732
  const plan = import_node_path33.default.join(options2.directory, "clang-link-replays.json");
32733
+ const resultsPath = import_node_path33.default.join(options2.directory, "clang-link-results.json");
31915
32734
  (0, import_node_fs35.writeFileSync)(
31916
32735
  plan,
31917
32736
  JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
@@ -31924,12 +32743,16 @@ function sourceGuestClangLinkOptions(options2) {
31924
32743
  ...process.env,
31925
32744
  [PEACH_FORKED_SCRIPT_ENV]: "1",
31926
32745
  PEACH_CLANG_REPLAYS: plan,
32746
+ PEACH_CLANG_RESULTS: resultsPath,
31927
32747
  PEACH_CLANG_JOBS: String(options2.jobs)
31928
32748
  }
31929
32749
  });
32750
+ const replayMetadata = JSON.parse((0, import_node_fs35.readFileSync)(resultsPath, "utf8"));
32751
+ if (!Array.isArray(replayMetadata) || replayMetadata.length !== replays.length || !replayMetadata.every((item) => typeof item === "string"))
32752
+ throw new Error("invalid clang link replay results");
31930
32753
  (0, import_node_fs35.mkdirSync)(cacheDirectory, { recursive: true });
31931
- for (const { file, output, cacheFile, key: key2 } of replays) {
31932
- const flags = clangIrLinkOptions((0, import_node_fs35.readFileSync)(output, "utf8"));
32754
+ for (const [index, { file, cacheFile, key: key2 }] of replays.entries()) {
32755
+ const flags = clangIrLinkOptions(replayMetadata[index]);
31933
32756
  validateClangLinkOptions(flags);
31934
32757
  const temporary = `${cacheFile}.${process.pid}`;
31935
32758
  (0, import_node_fs35.writeFileSync)(temporary, JSON.stringify({ key: key2, flags }));
@@ -32167,22 +32990,47 @@ var init_swift_guest_source_inputs = __esm({
32167
32990
  CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
32168
32991
  PARALLEL_REPLAY = `
32169
32992
  const { spawn } = require('node:child_process')
32170
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
32993
+ const fs = require('node:fs')
32994
+ const commands = JSON.parse(fs.readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
32995
+ const results = new Array(commands.length)
32171
32996
  let next = 0
32172
32997
  const run = () => {
32173
32998
  if (next >= commands.length) return Promise.resolve()
32174
- const [file, ...args] = commands[next++]
32999
+ const index = next++
33000
+ const [file, ...args] = commands[index]
32175
33001
  return new Promise((resolve, reject) => {
32176
- const child = spawn(file, args, { stdio: 'inherit' })
33002
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'inherit'] })
33003
+ const metadata = []
33004
+ let pending = ''
33005
+ child.stdout.setEncoding('utf8')
33006
+ child.stdout.on('data', (chunk) => {
33007
+ const text = pending + chunk
33008
+ let start = 0
33009
+ for (let nl = text.indexOf('\\n'); nl !== -1; nl = text.indexOf('\\n', start)) {
33010
+ if (text.charCodeAt(start) === 33) metadata.push(text.slice(start, nl))
33011
+ start = nl + 1
33012
+ }
33013
+ pending = text.slice(start)
33014
+ })
32177
33015
  child.on('error', reject)
32178
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
33016
+ child.on('close', (code) => {
33017
+ if (pending.charCodeAt(0) === 33) metadata.push(pending)
33018
+ if (code === 0) {
33019
+ results[index] = metadata.join('\\n')
33020
+ resolve()
33021
+ } else reject(new Error('clang link replay failed: ' + file))
33022
+ })
32179
33023
  }).then(run)
32180
33024
  }
32181
33025
  const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
32182
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
32183
- console.error(error.message)
32184
- process.exit(1)
32185
- })
33026
+ Promise.all(Array.from({ length: jobs }, run))
33027
+ .then(() => {
33028
+ fs.writeFileSync(process.env.PEACH_CLANG_RESULTS, JSON.stringify(results))
33029
+ })
33030
+ .catch((error) => {
33031
+ console.error(error.message)
33032
+ process.exit(1)
33033
+ })
32186
33034
  `;
32187
33035
  }
32188
33036
  });
@@ -35891,6 +36739,7 @@ __export(swift_sdk_app_module_exports, {
35891
36739
  readSwiftSdkUsage: () => readSwiftSdkUsage,
35892
36740
  selectSwiftSdkData: () => selectSwiftSdkData,
35893
36741
  swiftAppModuleInputs: () => swiftAppModuleInputs,
36742
+ swiftSdkProjectionSpans: () => swiftSdkProjectionSpans,
35894
36743
  writeSwiftSdkAppLink: () => writeSwiftSdkAppLink
35895
36744
  });
35896
36745
  async function buildSwiftAppModule(options2) {
@@ -36006,15 +36855,18 @@ async function compileSdkForwarders(inputs2, sdk2, toolchainBin, output, project
36006
36855
  index++;
36007
36856
  }
36008
36857
  const errno = tls.errno;
36858
+ let declaredErrno = false;
36009
36859
  for (const name3 of referenced) {
36010
36860
  const offset = tls[name3];
36011
36861
  if (offset === void 0 || defined.has(name3)) continue;
36012
36862
  if (errno === void 0 || signatures.__errno_location !== ":j")
36013
36863
  throw new Error("the sdk image has no errno to find its thread block by");
36014
- if (!lines.some((line) => line.startsWith("char *__peach_errno(")))
36864
+ if (!declaredErrno) {
36865
+ declaredErrno = true;
36015
36866
  lines.push(
36016
36867
  `__attribute__((import_module("env"), import_name("__errno_location"))) char *__peach_errno(void);`
36017
36868
  );
36869
+ }
36018
36870
  lines.push(
36019
36871
  `__attribute__((weak)) _Thread_local char t${index} __asm__(${literal3(name3)});`,
36020
36872
  `__attribute__((used)) long long h${index}(void) __asm__(${literal3(SDK_TLS_HELPER + name3)});`,
@@ -36390,6 +37242,20 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36390
37242
  symbols.filter((symbol2) => symbol2.kind === 0 && symbol2.name.startsWith(SDK_TLS_HELPER)).map((symbol2) => [symbol2.name.slice(SDK_TLS_HELPER.length), symbol2.index])
36391
37243
  );
36392
37244
  const segments = guestWasmDataSegments(bytes, false);
37245
+ const segmentsByOffset = [...segments].sort((a, b) => a.offset - b.offset);
37246
+ const segmentNameSet = new Set(segmentNames);
37247
+ const findSegmentByOffset = (at, size2) => {
37248
+ let lo = 0;
37249
+ let hi = segmentsByOffset.length - 1;
37250
+ while (lo <= hi) {
37251
+ const mid = lo + hi >> 1;
37252
+ const entry = segmentsByOffset[mid];
37253
+ if (at < entry.offset) hi = mid - 1;
37254
+ else if (at >= entry.offset + entry.length) lo = mid + 1;
37255
+ else return at + size2 <= entry.offset + entry.length ? entry : void 0;
37256
+ }
37257
+ return void 0;
37258
+ };
36393
37259
  const tdata = segmentNames.indexOf(".tdata");
36394
37260
  const tlsTemplate = tdata < 0 ? void 0 : passiveSegments(bytes)[tdata];
36395
37261
  const tlsStart = tlsTemplate && tlsTemplate.byteOffset - bytes.byteOffset;
@@ -36454,7 +37320,7 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36454
37320
  const encoding = width.width;
36455
37321
  if (kind === "address" && target.id === 11 && encoding === "u64" && addend === 0n) {
36456
37322
  const section2 = OBJC_SECTION_BOUNDARY.exec(name3)?.[1];
36457
- if (section2 && !segmentNames.includes(section2)) {
37323
+ if (section2 && !segmentNameSet.has(section2)) {
36458
37324
  bytes.fill(0, at, at + 8);
36459
37325
  continue;
36460
37326
  }
@@ -36466,9 +37332,7 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36466
37332
  if (tlsStart !== void 0 && at >= tlsStart && at < tlsStart + tlsTemplate.length)
36467
37333
  linkage.tls.push(at - tlsStart, size2, value);
36468
37334
  else {
36469
- const segment3 = segments.find(
36470
- (entry) => at >= entry.offset && at + size2 <= entry.offset + entry.length
36471
- );
37335
+ const segment3 = findSegmentByOffset(at, size2);
36472
37336
  if (!segment3)
36473
37337
  throw new Error(`Swift SDK relocation has no load address for ${name3}`);
36474
37338
  linkage.data.push(segment3.address + at - segment3.offset, size2, value);
@@ -36512,15 +37376,29 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36512
37376
  }
36513
37377
  }
36514
37378
  }
36515
- const entries2 = imports2.map((entry) => {
37379
+ const encodedNameBuf = (name3) => {
37380
+ const raw2 = Buffer.from(name3, "utf8");
37381
+ const len = uleb4(raw2.length);
37382
+ const out = Buffer.allocUnsafe(len.length + raw2.length);
37383
+ for (let i = 0; i < len.length; i++) out[i] = len[i];
37384
+ raw2.copy(out, len.length);
37385
+ return out;
37386
+ };
37387
+ const importParts = [];
37388
+ let importEntryCount = imports2.length + 1;
37389
+ for (const entry of imports2) {
36516
37390
  const slot = entry.kind === 0 && entry.module === "env" ? functionSlots.get(entry.name) : void 0;
36517
- return [
36518
- ...encodedName2(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
36519
- ...encodedName2(slot === void 0 ? entry.name : String(slot)),
36520
- ...bytes.subarray(entry.start, entry.end)
36521
- ];
36522
- });
36523
- entries2.push([...encodedName2("env"), ...encodedName2("__stack_pointer"), 3, 126, 1]);
37391
+ importParts.push(
37392
+ encodedNameBuf(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
37393
+ encodedNameBuf(slot === void 0 ? entry.name : String(slot)),
37394
+ bytes.subarray(entry.start, entry.end)
37395
+ );
37396
+ }
37397
+ importParts.push(
37398
+ encodedNameBuf("env"),
37399
+ encodedNameBuf("__stack_pointer"),
37400
+ Buffer.from([3, 126, 1])
37401
+ );
36524
37402
  const tags = sections.find((section2) => section2.id === 13);
36525
37403
  if (tags) {
36526
37404
  const r = wasmReader(bytes, tags.start);
@@ -36535,15 +37413,18 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36535
37413
  throw new Error(
36536
37414
  `Swift app defines an exception tag the sdk does not own: ${name3}`
36537
37415
  );
36538
- entries2.push([
36539
- ...encodedName2("env"),
36540
- ...encodedName2(name3),
36541
- 4,
36542
- ...bytes.subarray(start, r.at)
36543
- ]);
37416
+ importParts.push(
37417
+ encodedNameBuf("env"),
37418
+ encodedNameBuf(name3),
37419
+ Buffer.from([4]),
37420
+ bytes.subarray(start, r.at)
37421
+ );
37422
+ importEntryCount++;
36544
37423
  }
36545
37424
  }
36546
- const globals = [];
37425
+ const globalParts = [
37426
+ Buffer.from(uleb4(globalCount - 1 + syntheticGlobals.length))
37427
+ ];
36547
37428
  for (let index = 0; index < globalCount; index++) {
36548
37429
  const start = gr.at;
36549
37430
  const type = gr.byte();
@@ -36555,12 +37436,12 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36555
37436
  if (gr.byte() !== 11) throw new Error("app global initializer has no end");
36556
37437
  if (index === 0) continue;
36557
37438
  const value = got.get(index);
36558
- if (value === void 0) globals.push(...bytes.subarray(start, gr.at));
36559
- else globals.push(type, 1, type === 126 ? 66 : 65, 0, 11);
37439
+ if (value === void 0) globalParts.push(bytes.subarray(start, gr.at));
37440
+ else globalParts.push(Buffer.from([type, 1, type === 126 ? 66 : 65, 0, 11]));
36560
37441
  }
36561
37442
  for (const type of syntheticGlobals) {
36562
37443
  const zero = type === 125 ? [67, 0, 0, 0, 0] : type === 124 ? [68, 0, 0, 0, 0, 0, 0, 0, 0] : [type === 126 ? 66 : 65, 0];
36563
- globals.push(type, 1, ...zero, 11);
37444
+ globalParts.push(Buffer.from([type, 1, ...zero, 11]));
36564
37445
  }
36565
37446
  const exportSection = sections.find((s) => s.id === 7);
36566
37447
  if (!exportSection) throw new Error("app link has no exports");
@@ -36583,24 +37464,21 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36583
37464
  throw new Error("Swift app exceeds its reserved static memory range");
36584
37465
  }
36585
37466
  }
37467
+ const exportParts = [
37468
+ Buffer.from(uleb4(exportCount + 1 + got.size)),
37469
+ bytes.subarray(originalExportsStart, exportSection.end)
37470
+ ];
37471
+ for (const [index, value] of got) {
37472
+ exportParts.push(
37473
+ encodedNameBuf(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
37474
+ Buffer.from([3, ...uleb4(index)])
37475
+ );
37476
+ }
37477
+ exportParts.push(encodedNameBuf("__indirect_function_table"), Buffer.from([1, 0]));
36586
37478
  const replaced = /* @__PURE__ */ new Map([
36587
- [2, [...uleb4(entries2.length), ...entries2.flat()]],
36588
- [6, [...uleb4(globalCount - 1 + syntheticGlobals.length), ...globals]],
36589
- [
36590
- 7,
36591
- [
36592
- ...uleb4(exportCount + 1 + got.size),
36593
- ...bytes.subarray(originalExportsStart, exportSection.end),
36594
- ...[...got].flatMap(([index, value]) => [
36595
- ...encodedName2(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
36596
- 3,
36597
- ...uleb4(index)
36598
- ]),
36599
- ...encodedName2("__indirect_function_table"),
36600
- 1,
36601
- 0
36602
- ]
36603
- ]
37479
+ [2, Buffer.concat([Buffer.from(uleb4(importEntryCount)), ...importParts])],
37480
+ [6, Buffer.concat(globalParts)],
37481
+ [7, Buffer.concat(exportParts)]
36604
37482
  ]);
36605
37483
  const rebuiltCode = expanded.length ? expandSdkRelocations(
36606
37484
  bytes,
@@ -36612,9 +37490,13 @@ function resolveSdkReferences(source, sdk2, forwarders) {
36612
37490
  if (s === tags || s.name === "linking" || s.name?.startsWith("reloc.") || s.name === ".swift1_autolink_entries")
36613
37491
  continue;
36614
37492
  const payload = replaced.get(s.id);
36615
- parts.push(
36616
- s.id === 10 && rebuiltCode ? rebuiltCode : payload ? Uint8Array.from([s.id, ...uleb4(payload.length), ...payload]) : bytes.subarray(s.offset, s.end)
36617
- );
37493
+ if (s.id === 10 && rebuiltCode) {
37494
+ parts.push(rebuiltCode);
37495
+ } else if (payload) {
37496
+ parts.push(Buffer.from([s.id, ...uleb4(payload.length)]), payload);
37497
+ } else {
37498
+ parts.push(bytes.subarray(s.offset, s.end));
37499
+ }
36618
37500
  }
36619
37501
  return { bytes: Buffer.concat(parts), linkage };
36620
37502
  }
@@ -36712,6 +37594,49 @@ function readSwiftSdkUsage(mapFile, linkedFile, sdkObjects) {
36712
37594
  constructors: [...new Set(constructorKeys(map2, (0, import_node_fs44.readFileSync)(linkedFile)))]
36713
37595
  };
36714
37596
  }
37597
+ function swiftSdkProjectionSpans(sdk2, imageFor) {
37598
+ const { manifest, block: block2 } = readSwiftSdkManifest(sdk2);
37599
+ const guestObjects = manifest.guestObjects;
37600
+ if (!guestObjects) return [];
37601
+ const { strings: strings7 } = manifest;
37602
+ const fields = block2("pieces");
37603
+ const ordered = [];
37604
+ for (let i = 0; i < fields.length; i += SWIFT_SDK_PIECE_FIELDS) {
37605
+ const size2 = fields[i + 1];
37606
+ if (!size2) continue;
37607
+ ordered.push({
37608
+ address: fields[i],
37609
+ size: size2,
37610
+ object: strings7[fields[i + 3]]
37611
+ });
37612
+ }
37613
+ ordered.sort((a, b) => a.address - b.address);
37614
+ const imageOf = (object7) => {
37615
+ const product = guestObjects[object7]?.product;
37616
+ return product === void 0 ? void 0 : imageFor(object7, product);
37617
+ };
37618
+ const spans = [];
37619
+ for (let index = 0; index < ordered.length; index++) {
37620
+ const { object: object7, address, size: size2 } = ordered[index];
37621
+ const image = imageOf(object7);
37622
+ if (image === void 0) continue;
37623
+ let next = index + 1;
37624
+ while (next < ordered.length && ordered[next].address < address + size2) next++;
37625
+ const end = ordered[next]?.address ?? address + size2;
37626
+ spans.push({ image, space: "linear-memory", address, length: end - address });
37627
+ }
37628
+ const functionKeys = block2("functions");
37629
+ const slots = block2("functionSlots");
37630
+ for (let index = 0; index < functionKeys.length; index++) {
37631
+ const slot = slots[index];
37632
+ if (!slot) continue;
37633
+ const key2 = strings7[functionKeys[index]];
37634
+ const image = imageOf(key2.slice(0, key2.indexOf(":")));
37635
+ if (image !== void 0)
37636
+ spans.push({ image, space: "function-table", address: slot, length: 1 });
37637
+ }
37638
+ return spans;
37639
+ }
36715
37640
  function selectSwiftSdkData(sdk2, usage, linkage, projection) {
36716
37641
  const { manifest, block: block2, segments } = readSwiftSdkManifest(sdk2);
36717
37642
  const { strings: strings7 } = manifest;
@@ -36734,15 +37659,24 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
36734
37659
  });
36735
37660
  }
36736
37661
  const memory = new Map(segments.map((segment3) => [segment3.name, segment3]));
36737
- const read = (address2, size2) => {
37662
+ let lastSegment = segments[0];
37663
+ const segmentAt = (address2, size2) => {
37664
+ if (lastSegment && address2 >= lastSegment.address && address2 + size2 <= lastSegment.address + lastSegment.data.length)
37665
+ return lastSegment;
36738
37666
  for (const segment3 of segments)
36739
- if (address2 >= segment3.address && address2 + size2 <= segment3.address + segment3.data.length)
36740
- return segment3.data.subarray(
36741
- address2 - segment3.address,
36742
- address2 - segment3.address + size2
36743
- );
37667
+ if (address2 >= segment3.address && address2 + size2 <= segment3.address + segment3.data.length) {
37668
+ lastSegment = segment3;
37669
+ return segment3;
37670
+ }
36744
37671
  return void 0;
36745
37672
  };
37673
+ const read = (address2, size2) => {
37674
+ const segment3 = segmentAt(address2, size2);
37675
+ return segment3?.data.subarray(
37676
+ address2 - segment3.address,
37677
+ address2 - segment3.address + size2
37678
+ );
37679
+ };
36746
37680
  const appSectionsByObject = /* @__PURE__ */ new Map();
36747
37681
  const appSections = /* @__PURE__ */ new Set();
36748
37682
  const appSymbols = /* @__PURE__ */ new Set();
@@ -36848,9 +37782,7 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
36848
37782
  const classAddress = Number(
36849
37783
  new DataView(field.buffer, field.byteOffset, 8).getBigUint64(0, true)
36850
37784
  );
36851
- const segment3 = segments.find(
36852
- ({ address: address3, data }) => classAddress >= address3 && classAddress < address3 + data.length
36853
- );
37785
+ const segment3 = segmentAt(classAddress, 1);
36854
37786
  if (!segment3) continue;
36855
37787
  const start = classAddress - segment3.address;
36856
37788
  const end = segment3.data.indexOf(0, start);
@@ -37058,7 +37990,7 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
37058
37990
  if (current2)
37059
37991
  runs.push({
37060
37992
  address: current2.address,
37061
- bytes: Uint8Array.from(Buffer.concat(current2.parts))
37993
+ bytes: Buffer.concat(current2.parts)
37062
37994
  });
37063
37995
  };
37064
37996
  for (const piece of loaded4) {
@@ -37476,13 +38408,19 @@ async function compileGuestLink(options2) {
37476
38408
  const selectedSource = source.artifacts.filter(
37477
38409
  (artifact) => selected.has(import_node_path43.default.resolve(rewritten.get(artifact.path) ?? artifact.path))
37478
38410
  );
38411
+ const admittedCores = Number(process.env.TM_EXEC_CPU_CORES);
38412
+ const linuxMemory = process.env.TM_EXEC_ADMITTED === "1" && process.env.LINUX_BUILD_SCOPE ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX) : NaN;
38413
+ const clangReplayJobs = Number.isInteger(admittedCores) && admittedCores > 0 ? Math.min(
38414
+ admittedCores,
38415
+ Number.isSafeInteger(linuxMemory) && linuxMemory > 0 ? Math.max(options2.jobs, Math.floor(linuxMemory / (512 * 1024 ** 2))) : Math.max(options2.jobs, admittedCores)
38416
+ ) : options2.jobs;
37479
38417
  const clangOptions2 = sourceGuestClangLinkOptions({
37480
38418
  buildDirectory: options2.buildDirectory,
37481
38419
  directory: directory2,
37482
38420
  toolchainBin: options2.toolchainBin,
37483
38421
  swiftCompiler: options2.swiftCompiler,
37484
38422
  objects: selectedSource.map((artifact) => artifact.path),
37485
- jobs: options2.jobs
38423
+ jobs: clangReplayJobs
37486
38424
  });
37487
38425
  const links = sourceGuestRuntimeLinks({
37488
38426
  toolchainBin: options2.toolchainBin,
@@ -37584,9 +38522,9 @@ async function compileGuestLink(options2) {
37584
38522
  }
37585
38523
  };
37586
38524
  },
37587
- resolvePlan: (selected, plan) => {
38525
+ resolvePlan: (selected, plan, readSelected) => {
37588
38526
  if (!prepared) throw new Error("guest runtime selection is unavailable");
37589
- const scope2 = selectedGuestSymbolInputs(plan, selected);
38527
+ const scope2 = selectedGuestSymbolInputs(plan, selected, readSelected);
37590
38528
  const owners = new Map(scope2.owners);
37591
38529
  owners.set(import_node_path43.default.join(directory2, "projection-discovery.o"), 0);
37592
38530
  const providersByImage = Map.groupBy(scope2.owners, ([, image]) => image);
@@ -37664,7 +38602,8 @@ async function compileGuestLink(options2) {
37664
38602
  createSwiftSdkBinding: createSwiftSdkBinding2,
37665
38603
  finishSwiftAppModule: finishSwiftAppModule2,
37666
38604
  linkSwiftAppModule: linkSwiftAppModule2,
37667
- readSwiftSdkUsage: readSwiftSdkUsage2
38605
+ readSwiftSdkUsage: readSwiftSdkUsage2,
38606
+ swiftSdkProjectionSpans: swiftSdkProjectionSpans2
37668
38607
  } = await Promise.resolve().then(() => (init_swift_sdk_app_module(), swift_sdk_app_module_exports));
37669
38608
  const project2 = options2.project;
37670
38609
  const work = project2 ? (0, import_node_fs45.mkdtempSync)(import_node_path43.default.join(directory2, "app-module-")) : import_node_path43.default.join(directory2, "app-module");
@@ -37686,7 +38625,28 @@ async function compileGuestLink(options2) {
37686
38625
  }
37687
38626
  const usage = readSwiftSdkUsage2(result.mapPath, options2.output, sdkObjectKeys);
37688
38627
  const linkedModule = import_node_path43.default.join(work, "app.wasm");
38628
+ const sdkSpans = swiftSdkProjectionSpans2(
38629
+ sdk2,
38630
+ (object7, product) => sdkObjectImages.get(object7) ?? sdkProductImages.get(product)
38631
+ );
37689
38632
  let storage = reserved2;
38633
+ if (sdkSpans.length > 0) {
38634
+ const sdkCounts = guestProjectionRegionCounts(storage.images.length, sdkSpans);
38635
+ storage = reserveGuestProjectionStorage(
38636
+ storage.images,
38637
+ storage.capacities.map((capacity, index) => ({
38638
+ ...capacity,
38639
+ regions: capacity.regions + sdkCounts[index] + 16
38640
+ }))
38641
+ );
38642
+ const projectionSource = import_node_path43.default.join(work, "projection.c");
38643
+ (0, import_node_fs45.writeFileSync)(projectionSource, storage.source);
38644
+ (0, import_node_child_process27.execFileSync)(
38645
+ import_node_path43.default.join(options2.toolchainBin, "clang"),
38646
+ [...clangOptions, "-c", projectionSource, "-o", projectionObject],
38647
+ { stdio: "pipe" }
38648
+ );
38649
+ }
37690
38650
  for (; ; ) {
37691
38651
  const link = await linkSwiftAppModule2({
37692
38652
  objects: [...owners.keys()],
@@ -37724,11 +38684,7 @@ async function compileGuestLink(options2) {
37724
38684
  bindingRows.set((address - values.address) / 8, value);
37725
38685
  } else data.push(address, size2, value);
37726
38686
  }
37727
- const sdkSpans = [];
37728
- const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk2, usage, {
37729
- imageFor: (object7, product) => sdkObjectImages.get(object7) ?? sdkProductImages.get(product),
37730
- spans: sdkSpans
37731
- });
38687
+ const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk2, usage);
37732
38688
  const linked = (0, import_node_fs45.readFileSync)(
37733
38689
  project2 ? projectOutputFile(work, linkedModule, project2) : linkedModule
37734
38690
  );
@@ -45283,7 +46239,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
45283
46239
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
45284
46240
  MULTI_MANIFEST_VERSION = 76;
45285
46241
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
45286
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
46242
+ compilerSourceDigest = true ? "d4cf22b53d08266bf9bd0238bffe899805f62daeb3d628664ee351830e496cda" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
45287
46243
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
45288
46244
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
45289
46245
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));
@@ -85719,7 +86675,7 @@ var init_swift_standin_digest = __esm({
85719
86675
  STANDIN_DIGEST_ENTRYPOINTS = ["swift-standins.ts", "swift-objc-compile.ts"];
85720
86676
  SPECIFIER = /from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
85721
86677
  standinSourceDigest = (srcDir = __sootsim_import_meta_dirname) => sourceClosureDigest(srcDir, STANDIN_DIGEST_ENTRYPOINTS);
85722
- STANDIN_SOURCE_DIGEST = true ? "b4ec01293af51e43890fb5aa52c9dc6d240c73b8fe722cdaff952457b08d94ff" : standinSourceDigest();
86678
+ STANDIN_SOURCE_DIGEST = true ? "a8f701d93728e07278999e87ca0ce8629c73067b6c4382393bfa6705a275114b" : standinSourceDigest();
85723
86679
  }
85724
86680
  });
85725
86681
 
@@ -102163,7 +103119,7 @@ var init_nitro_superset = __esm({
102163
103119
  init_nitroContract();
102164
103120
  init_swift_standin_digest();
102165
103121
  NITRO_SUPERSET_ENTRY_NAME = "superset";
102166
- NITRO_COMPILER_DIGEST = true ? "59081cf672cb2bb9c125425cd97f2df60507acfc6de96f1525f18ddca39ff000" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
103122
+ NITRO_COMPILER_DIGEST = true ? "0ce63814b4a72a014a0388c3792cede09d8d1cae4f69a18e904584487588222d" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
102167
103123
  nitroSupersetLock = parseLock(nitro_superset_lock_default);
102168
103124
  nitroSupersetKey = (inputs2) => nativeEntryKey({ ...inputs2, compiler: NITRO_COMPILER_DIGEST });
102169
103125
  published = /* @__PURE__ */ new Map();
@@ -103030,7 +103986,7 @@ var init_expo_eager_seam_contract = __esm({
103030
103986
 
103031
103987
  // src/expo-native-compiler-digest.ts
103032
103988
  function expoNativeCompilerDigestValue() {
103033
- return true ? "bc9bf63858735336bd46e9b34db5ced39d682f7200bbbc3eafbf5470dae0018f" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
103989
+ return true ? "fac25d497603de6d36f5104099d949e505b050f78be3ed12989ae494db25b470" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
103034
103990
  }
103035
103991
  var import_node_crypto78;
103036
103992
  var init_expo_native_compiler_digest = __esm({