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;
@@ -26243,13 +26243,13 @@ var init_swift_standin_digest = __esm({
26243
26243
  STANDIN_DIGEST_ENTRYPOINTS = ["swift-standins.ts", "swift-objc-compile.ts"];
26244
26244
  SPECIFIER = /from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
26245
26245
  standinSourceDigest = (srcDir = __sootsim_import_meta_dirname) => sourceClosureDigest(srcDir, STANDIN_DIGEST_ENTRYPOINTS);
26246
- STANDIN_SOURCE_DIGEST = true ? "b4ec01293af51e43890fb5aa52c9dc6d240c73b8fe722cdaff952457b08d94ff" : standinSourceDigest();
26246
+ STANDIN_SOURCE_DIGEST = true ? "a8f701d93728e07278999e87ca0ce8629c73067b6c4382393bfa6705a275114b" : standinSourceDigest();
26247
26247
  }
26248
26248
  });
26249
26249
 
26250
26250
  // src/expo-native-compiler-digest.ts
26251
26251
  function expoNativeCompilerDigestValue() {
26252
- return true ? "bc9bf63858735336bd46e9b34db5ced39d682f7200bbbc3eafbf5470dae0018f" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
26252
+ return true ? "fac25d497603de6d36f5104099d949e505b050f78be3ed12989ae494db25b470" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
26253
26253
  }
26254
26254
  var import_node_crypto17;
26255
26255
  var init_expo_native_compiler_digest = __esm({
@@ -31115,24 +31115,56 @@ function layout(bytes, readData = true, requireExports = true) {
31115
31115
  const code = sections.get(10);
31116
31116
  if (code) {
31117
31117
  let pos = code[0];
31118
- let count;
31119
- [count, pos] = number(bytes, pos);
31118
+ const codeStart = code[0];
31119
+ const codeEnd = code[1];
31120
+ let count = 0;
31121
+ {
31122
+ let shift = 0;
31123
+ for (; ; ) {
31124
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
31125
+ const byte = bytes[pos++];
31126
+ count += (byte & 127) * 2 ** shift;
31127
+ if (!(byte & 128)) break;
31128
+ shift += 7;
31129
+ }
31130
+ }
31120
31131
  for (let i = 0; i < count; i++) {
31121
31132
  const prefix = pos;
31122
- let size2;
31123
- [size2, pos] = number(bytes, pos);
31124
- functionsByCodeOffset.set(prefix - code[0], imports2 + i);
31133
+ let size2 = 0;
31134
+ const b0 = bytes[pos++];
31135
+ if (b0 < 128) {
31136
+ size2 = b0;
31137
+ } else {
31138
+ size2 = b0 & 127;
31139
+ let shift = 7;
31140
+ for (; ; ) {
31141
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
31142
+ const byte = bytes[pos++];
31143
+ size2 += (byte & 127) * 2 ** shift;
31144
+ if (!(byte & 128)) break;
31145
+ shift += 7;
31146
+ }
31147
+ }
31148
+ functionsByCodeOffset.set(prefix - codeStart, imports2 + i);
31125
31149
  if (imports2 + i === startFunction) startup = bytes.subarray(pos, pos + size2);
31126
31150
  pos += size2;
31127
- if (pos > code[1]) throw new Error("invalid wasm code");
31151
+ if (pos > codeEnd) throw new Error("invalid wasm code");
31128
31152
  }
31129
- if (pos !== code[1]) throw new Error("invalid wasm code section");
31153
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
31130
31154
  }
31131
31155
  const functionsByTableSlot = /* @__PURE__ */ new Map();
31132
31156
  const elements = sections.get(9);
31133
31157
  if (elements) {
31134
31158
  let pos = elements[0];
31159
+ const elemEnd = elements[1];
31135
31160
  const read = () => {
31161
+ if (pos < elemEnd) {
31162
+ const b0 = bytes[pos];
31163
+ if (b0 < 128) {
31164
+ pos++;
31165
+ return b0;
31166
+ }
31167
+ }
31136
31168
  const [value, next] = number(bytes, pos);
31137
31169
  pos = next;
31138
31170
  return value;
@@ -31162,7 +31194,7 @@ function layout(bytes, readData = true, requireExports = true) {
31162
31194
  functionsByTableSlot.set(slot, read());
31163
31195
  }
31164
31196
  }
31165
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
31197
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
31166
31198
  }
31167
31199
  const data = [];
31168
31200
  const passive = /* @__PURE__ */ new Map();
@@ -31227,36 +31259,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
31227
31259
  length: segment2.bytes.length
31228
31260
  }));
31229
31261
  }
31230
- function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
31262
+ function isMapSpace(code) {
31263
+ return code === 32 || code >= 9 && code <= 13;
31264
+ }
31265
+ function isMapHex(code) {
31266
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
31267
+ }
31268
+ function mapHexDigit(code) {
31269
+ return code <= 57 ? code - 48 : code - 87;
31270
+ }
31271
+ function* stringLines(text7) {
31272
+ let start = 0;
31273
+ for (let end = text7.indexOf("\n"); end !== -1; end = text7.indexOf("\n", start)) {
31274
+ yield text7.slice(start, end);
31275
+ start = end + 1;
31276
+ }
31277
+ yield text7.slice(start);
31278
+ }
31279
+ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
31231
31280
  const unchanged = before === after;
31232
31281
  const original = layout(before, !unchanged, !importsLayout);
31233
31282
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
31283
+ const collectSymbols = extra?.collectSymbols;
31284
+ const trackedObject = extra?.trackedObject;
31285
+ const trackedObjectOwner = extra?.trackedObjectOwner;
31286
+ const trackedLinearSpans = extra?.trackedLinearSpans;
31287
+ const hasSectionOwners = sectionOwners.size > 0;
31234
31288
  let codeOffset;
31235
31289
  let outputSection = "";
31236
31290
  const codeOwners = /* @__PURE__ */ new Map();
31237
31291
  const pieces = [];
31238
- for (const line of typeof map2 === "string" ? map2.split("\n") : map2) {
31239
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
31240
- if (!match) continue;
31241
- const [, address, offset, size2, indent2, source] = match;
31242
- if (address === "-" && indent2 === " ") {
31243
- outputSection = source;
31244
- if (source === "CODE") codeOffset = parseInt(offset, 16);
31292
+ const lines = typeof map2 === "string" ? stringLines(map2) : map2;
31293
+ for (const line of lines) {
31294
+ const lineLen = line.length;
31295
+ let pos = 0;
31296
+ let onlySpaces = true;
31297
+ while (pos < lineLen) {
31298
+ const ch = line.charCodeAt(pos);
31299
+ if (!isMapSpace(ch)) break;
31300
+ if (ch !== 32) onlySpaces = false;
31301
+ pos++;
31302
+ }
31303
+ const leadingSpaces = pos;
31304
+ if (pos >= lineLen) continue;
31305
+ const addrStart = pos;
31306
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
31307
+ const addrEnd = pos;
31308
+ if (pos >= lineLen) continue;
31309
+ const s1 = pos;
31310
+ while (pos < lineLen) {
31311
+ const ch = line.charCodeAt(pos);
31312
+ if (!isMapSpace(ch)) break;
31313
+ if (ch !== 32) onlySpaces = false;
31314
+ pos++;
31315
+ }
31316
+ if (pos === s1 || pos >= lineLen) continue;
31317
+ const offStart = pos;
31318
+ let offsetVal = 0;
31319
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
31320
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
31321
+ }
31322
+ if (pos === offStart || pos >= lineLen) continue;
31323
+ const s2 = pos;
31324
+ while (pos < lineLen) {
31325
+ const ch = line.charCodeAt(pos);
31326
+ if (!isMapSpace(ch)) break;
31327
+ if (ch !== 32) onlySpaces = false;
31328
+ pos++;
31329
+ }
31330
+ if (pos === s2 || pos >= lineLen) continue;
31331
+ const sizeStart = pos;
31332
+ let sizeVal = 0;
31333
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
31334
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
31335
+ }
31336
+ if (pos === sizeStart || pos >= lineLen) continue;
31337
+ const indentStart = pos;
31338
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
31339
+ const indentLen = pos - indentStart;
31340
+ if (indentLen === 0 || pos >= lineLen) continue;
31341
+ const firstCh = line.charCodeAt(pos);
31342
+ if (isMapSpace(firstCh)) continue;
31343
+ const sourceStart = pos;
31344
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
31345
+ let symEnd = sourceStart + 1;
31346
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
31347
+ collectSymbols.add(line.slice(sourceStart, symEnd));
31348
+ }
31349
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
31350
+ if (isDash && indentLen === 1) {
31351
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
31352
+ outputSection = line.slice(sourceStart);
31353
+ if (outputSection === "CODE") codeOffset = offsetVal;
31245
31354
  continue;
31246
31355
  }
31247
- const separator = source.indexOf(":(");
31356
+ if (sizeVal === 0) continue;
31357
+ const separator = line.indexOf(":(", sourceStart);
31248
31358
  if (separator < 0) continue;
31249
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
31250
- const length = parseInt(size2, 16);
31251
- if (!length) continue;
31252
- if (address !== "-") {
31253
- if (outputSection === "DATA")
31254
- pieces.push({ image, address: parseInt(address, 16), length });
31359
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
31360
+ let hasLineSep = false;
31361
+ for (let i = sourceStart; i < lineLen; i++) {
31362
+ const ch = line.charCodeAt(i);
31363
+ if (ch === 8232 || ch === 8233) {
31364
+ hasLineSep = true;
31365
+ break;
31366
+ }
31367
+ }
31368
+ if (hasLineSep) continue;
31369
+ const objectPath = line.slice(sourceStart, separator);
31370
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
31371
+ if (image === void 0) image = owners.get(objectPath);
31372
+ if (!isDash) {
31373
+ if (outputSection === "DATA") {
31374
+ let addressVal = 0;
31375
+ let allHex = true;
31376
+ for (let i = addrStart; i < addrEnd; i++) {
31377
+ const ch = line.charCodeAt(i);
31378
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
31379
+ else {
31380
+ allHex = false;
31381
+ break;
31382
+ }
31383
+ }
31384
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
31385
+ pieces.push({
31386
+ image,
31387
+ address: addressVal,
31388
+ length: sizeVal,
31389
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
31390
+ });
31391
+ }
31255
31392
  continue;
31256
31393
  }
31257
31394
  if (image === void 0 || outputSection !== "CODE") continue;
31258
31395
  if (codeOffset === void 0) throw new Error("link map has no code section");
31259
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
31396
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
31260
31397
  if (index === void 0) throw new Error("link map function has no wasm body");
31261
31398
  const existing = codeOwners.get(index);
31262
31399
  if (existing !== void 0 && existing !== image)
@@ -31265,12 +31402,23 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
31265
31402
  }
31266
31403
  pieces.sort((a, b) => a.address - b.address);
31267
31404
  const spans = [];
31268
- for (const [index, { image, address, length }] of pieces.entries()) {
31269
- if (image === void 0) continue;
31405
+ for (let index = 0; index < pieces.length; index++) {
31406
+ const piece = pieces[index];
31407
+ const { image, address, length, tracked } = piece;
31408
+ if (image === void 0 && !tracked) continue;
31270
31409
  let next = index + 1;
31271
31410
  while (next < pieces.length && pieces[next].address < address + length) next++;
31272
31411
  const end = pieces[next]?.address ?? address + length;
31273
- spans.push({ image, space: "linear-memory", address, length: end - address });
31412
+ const spanLength = end - address;
31413
+ if (image !== void 0)
31414
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
31415
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
31416
+ trackedLinearSpans.push({
31417
+ image: trackedObjectOwner,
31418
+ space: "linear-memory",
31419
+ address,
31420
+ length: spanLength
31421
+ });
31274
31422
  }
31275
31423
  const optimizedOwners = /* @__PURE__ */ new Map();
31276
31424
  const dataAt = (module2, start, length) => {
@@ -31309,7 +31457,7 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
31309
31457
  throw new Error(`optimization changed linked data at ${span.address}`);
31310
31458
  }
31311
31459
  let previous;
31312
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
31460
+ for (const span of spans) {
31313
31461
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
31314
31462
  throw new Error("linked data belongs to multiple images");
31315
31463
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -31491,6 +31639,20 @@ var init_swift_guest_linked_spans = __esm({
31491
31639
  });
31492
31640
 
31493
31641
  // src/swift-sdk-image-map.ts
31642
+ function isHexChar(code) {
31643
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
31644
+ }
31645
+ function hexDigit(code) {
31646
+ return code <= 57 ? code - 48 : code - 87;
31647
+ }
31648
+ function hasLineBreak(line, from) {
31649
+ if (line.indexOf("\r", from) >= 0) return true;
31650
+ for (let i = from; i < line.length; i++) {
31651
+ const ch = line.charCodeAt(i);
31652
+ if (ch === 8232 || ch === 8233) return true;
31653
+ }
31654
+ return false;
31655
+ }
31494
31656
  function readWasmLinkMap(file, partition) {
31495
31657
  const segments = /* @__PURE__ */ new Map();
31496
31658
  const data = [];
@@ -31498,48 +31660,117 @@ function readWasmLinkMap(file, partition) {
31498
31660
  let kind = "";
31499
31661
  let segment2 = "";
31500
31662
  let previous;
31501
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
31502
31663
  for (const line of guestLinkLines(file)) {
31503
- const symbol2 = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
31504
- if (symbol2) {
31505
- previous?.symbols.push({
31506
- name: symbol2[3],
31507
- address: hex(symbol2[1]),
31508
- size: parseInt(symbol2[2], 16)
31509
- });
31664
+ const length = line.length;
31665
+ let pos = 0;
31666
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31667
+ if (pos >= length) continue;
31668
+ const leadingSpaces = pos;
31669
+ let address = -1;
31670
+ if (line.charCodeAt(pos) === 45) {
31671
+ pos++;
31672
+ } else {
31673
+ const start = pos;
31674
+ let value = 0;
31675
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
31676
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
31677
+ }
31678
+ if (pos === start) continue;
31679
+ address = value;
31680
+ }
31681
+ const s1 = pos;
31682
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31683
+ if (pos === s1 || pos >= length) continue;
31684
+ const offStart = pos;
31685
+ let offset = 0;
31686
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
31687
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
31688
+ }
31689
+ if (pos === offStart) continue;
31690
+ const s2 = pos;
31691
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31692
+ if (pos === s2 || pos >= length) continue;
31693
+ const sizeStart = pos;
31694
+ let size2 = 0;
31695
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
31696
+ size2 = size2 * 16 + hexDigit(line.charCodeAt(pos++));
31697
+ }
31698
+ if (pos === sizeStart || pos >= length) continue;
31699
+ const indentStart = pos;
31700
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31701
+ const indent2 = pos - indentStart;
31702
+ if (indent2 === 0 || pos >= length) continue;
31703
+ if (indent2 === 17) {
31704
+ if (previous) {
31705
+ const first = line.charCodeAt(pos);
31706
+ if (first > 32 && !hasLineBreak(line, pos)) {
31707
+ previous.symbols.push({
31708
+ name: line.slice(pos),
31709
+ address,
31710
+ size: size2
31711
+ });
31712
+ }
31713
+ }
31510
31714
  continue;
31511
31715
  }
31512
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
31513
- if (output) {
31514
- kind = output[1];
31716
+ if (indent2 === 1) {
31717
+ let hasWhitespace = false;
31718
+ for (let i = pos; i < length; i++) {
31719
+ const ch = line.charCodeAt(i);
31720
+ if (ch <= 32) {
31721
+ hasWhitespace = true;
31722
+ break;
31723
+ }
31724
+ }
31725
+ if (hasWhitespace) continue;
31726
+ if (address < 0 && leadingSpaces > 0) {
31727
+ kind = line.slice(pos);
31728
+ } else if (kind === "DATA" && address >= 0) {
31729
+ segment2 = line.slice(pos);
31730
+ segments.set(segment2, { address, size: size2 });
31731
+ }
31515
31732
  continue;
31516
31733
  }
31517
- if (kind === "DATA") {
31518
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
31519
- if (top) {
31520
- segment2 = top[3];
31521
- segments.set(segment2, { address: hex(top[1]), size: parseInt(top[2], 16) });
31522
- continue;
31734
+ if (indent2 === 9 && (kind === "DATA" || kind === "CODE")) {
31735
+ const first = line.charCodeAt(pos);
31736
+ if (first !== 47 && first !== 60) continue;
31737
+ if (hasLineBreak(line, pos)) continue;
31738
+ const name3 = line.slice(pos);
31739
+ let filePath = name3;
31740
+ let section2 = "";
31741
+ if (name3.charCodeAt(name3.length - 1) === 41) {
31742
+ const splitAt = name3.indexOf(":(");
31743
+ if (splitAt >= 0) {
31744
+ filePath = name3.slice(0, splitAt);
31745
+ section2 = name3.slice(splitAt + 2, -1);
31746
+ }
31747
+ }
31748
+ let objectName;
31749
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
31750
+ const open = filePath.lastIndexOf("(");
31751
+ if (open >= 0 && open + 1 < filePath.length - 1) {
31752
+ const close = filePath.indexOf(")", open + 1);
31753
+ if (close === filePath.length - 1) {
31754
+ objectName = filePath.slice(open + 1, -1);
31755
+ }
31756
+ }
31757
+ }
31758
+ if (objectName === void 0) objectName = (0, import_node_path42.basename)(filePath);
31759
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
31760
+ objectName = objectName.replace(/^lib\w*?__/, "");
31523
31761
  }
31762
+ previous = {
31763
+ inputFile: filePath,
31764
+ segment: segment2,
31765
+ address,
31766
+ offset,
31767
+ size: size2,
31768
+ object: objectName,
31769
+ section: section2,
31770
+ symbols: []
31771
+ };
31772
+ (kind === "DATA" ? data : code).push(previous);
31524
31773
  }
31525
- if (kind !== "DATA" && kind !== "CODE") continue;
31526
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
31527
- if (!input) continue;
31528
- const name3 = input[4];
31529
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
31530
- const path115 = split ? split[1] : name3;
31531
- const member = /\(([^()]+)\)$/.exec(path115);
31532
- previous = {
31533
- inputFile: path115,
31534
- segment: segment2,
31535
- address: hex(input[1]),
31536
- offset: parseInt(input[2], 16),
31537
- size: parseInt(input[3], 16),
31538
- object: (member ? member[1] : (0, import_node_path42.basename)(path115)).replace(/^lib\w*?__/, ""),
31539
- section: split ? split[2] : "",
31540
- symbols: []
31541
- };
31542
- (kind === "DATA" ? data : code).push(previous);
31543
31774
  }
31544
31775
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
31545
31776
  }
@@ -32685,6 +32916,7 @@ function patchSwiftrtObject(src) {
32685
32916
  return buf;
32686
32917
  }
32687
32918
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32919
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
32688
32920
  let pos = 8;
32689
32921
  let numImportFuncs = 0;
32690
32922
  let importsDlsym = false;
@@ -32720,10 +32952,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32720
32952
  let [cnt, cp] = readULEB2(buf, p);
32721
32953
  for (let i = 0; i < cnt; i++) {
32722
32954
  const [mLen, m2] = readULEB2(buf, cp);
32723
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
32955
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
32724
32956
  cp = m2 + mLen;
32725
32957
  const [fLen, f2] = readULEB2(buf, cp);
32726
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
32958
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
32727
32959
  cp = f2 + fLen;
32728
32960
  const kind = buf[cp++];
32729
32961
  if (kind === 0) {
@@ -32803,7 +33035,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32803
33035
  }
32804
33036
  } else if (id === 0) {
32805
33037
  const [nLen, np] = readULEB2(buf, p);
32806
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
33038
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
32807
33039
  const cp = np + nLen;
32808
33040
  if (name3 === "linking") {
32809
33041
  let [, lp] = readULEB2(buf, cp);
@@ -32816,7 +33048,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32816
33048
  let cur = p2;
32817
33049
  for (let i = 0; i < cnt; i++) {
32818
33050
  const [sLen, s2] = readULEB2(buf, cur);
32819
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
33051
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
32820
33052
  cur = s2 + sLen;
32821
33053
  const [, s3] = readULEB2(buf, cur);
32822
33054
  const [fl, s4] = readULEB2(buf, s3);
@@ -32856,7 +33088,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32856
33088
  let sName = "";
32857
33089
  if (!isUndef || isExplicitName) {
32858
33090
  const [sLen, c4] = readULEB2(buf, cur);
32859
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
33091
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
32860
33092
  cur = c4 + sLen;
32861
33093
  } else if (kind === 0) {
32862
33094
  sName = importFuncNames[el] ?? "";
@@ -32872,7 +33104,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32872
33104
  symNames.push(sName);
32873
33105
  } else if (kind === 1) {
32874
33106
  const [sLen, c3] = readULEB2(buf, cur);
32875
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
33107
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
32876
33108
  cur = c3 + sLen;
32877
33109
  if (!isUndef) {
32878
33110
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -32987,9 +33219,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
32987
33219
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
32988
33220
  let ownerSymIdx = -1;
32989
33221
  const topList = segTopSyms.get(lo);
32990
- if (topList) {
32991
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
32992
- if (owner) ownerSymIdx = owner.symIdx;
33222
+ if (topList && topList.length > 0) {
33223
+ let tLo = 0;
33224
+ let tHi = topList.length - 1;
33225
+ while (tLo <= tHi) {
33226
+ const tMid = tLo + tHi >> 1;
33227
+ const top = topList[tMid];
33228
+ if (offInSeg < top.off) {
33229
+ tHi = tMid - 1;
33230
+ } else if (offInSeg >= top.end) {
33231
+ tLo = tMid + 1;
33232
+ } else {
33233
+ ownerSymIdx = top.symIdx;
33234
+ break;
33235
+ }
33236
+ }
32993
33237
  }
32994
33238
  if (ownerSymIdx !== -1) {
32995
33239
  let list2 = symDataRelocs.get(ownerSymIdx);
@@ -33244,54 +33488,151 @@ function localizeDefinedWasmSymbols(bytes, names) {
33244
33488
  return output;
33245
33489
  }
33246
33490
  function guestWasmSymbols(bytes) {
33247
- const object7 = parseWasmObjectBytes("", bytes, false);
33491
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
33492
+ let cur = 8;
33493
+ const readU = () => {
33494
+ const b0 = bytes[cur++];
33495
+ if (b0 < 128) return b0;
33496
+ let res = b0 & 127;
33497
+ let shift = 7;
33498
+ while (true) {
33499
+ const byte = bytes[cur++];
33500
+ res |= (byte & 127) << shift;
33501
+ if ((byte & 128) === 0) return res;
33502
+ shift += 7;
33503
+ }
33504
+ };
33505
+ let importsDlsym = false;
33506
+ const importFuncNames = [];
33507
+ const importFuncModules = [];
33508
+ const importGlobalNames = [];
33509
+ const importTableNames = [];
33510
+ const importEventNames = [];
33511
+ const undefinedSyms = /* @__PURE__ */ new Set();
33512
+ const tags = /* @__PURE__ */ new Set();
33513
+ const globals = /* @__PURE__ */ new Set();
33514
+ const hostImports = /* @__PURE__ */ new Set();
33515
+ const weakUndefined = /* @__PURE__ */ new Set();
33516
+ const defined = /* @__PURE__ */ new Set();
33517
+ const weakDefined = /* @__PURE__ */ new Set();
33518
+ while (cur < bytes.length) {
33519
+ const id = bytes[cur++];
33520
+ const sz = readU();
33521
+ const end = cur + sz;
33522
+ if (id === 2) {
33523
+ const cnt = readU();
33524
+ for (let i = 0; i < cnt; i++) {
33525
+ const mLen = readU();
33526
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
33527
+ cur += mLen;
33528
+ const fLen = readU();
33529
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
33530
+ cur += fLen;
33531
+ const kind = bytes[cur++];
33532
+ if (kind === 0) {
33533
+ readU();
33534
+ importFuncNames.push(fName);
33535
+ importFuncModules.push(mName);
33536
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
33537
+ } else if (kind === 1) {
33538
+ cur++;
33539
+ const fl = readU();
33540
+ readU();
33541
+ if (fl & 1) readU();
33542
+ importTableNames.push(fName);
33543
+ } else if (kind === 2) {
33544
+ const fl = readU();
33545
+ readU();
33546
+ if (fl & 1) readU();
33547
+ } else if (kind === 3) {
33548
+ cur += 2;
33549
+ importGlobalNames.push(fName);
33550
+ } else if (kind === 4) {
33551
+ cur++;
33552
+ readU();
33553
+ importEventNames.push(fName);
33554
+ }
33555
+ }
33556
+ } else if (id === 0) {
33557
+ const nLen = readU();
33558
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
33559
+ cur += nLen;
33560
+ readU();
33561
+ while (cur < end) {
33562
+ const subId = bytes[cur++];
33563
+ const subLen = readU();
33564
+ const subEnd = cur + subLen;
33565
+ if (subId === 8) {
33566
+ const cnt = readU();
33567
+ for (let i = 0; i < cnt; i++) {
33568
+ const kind = bytes[cur++];
33569
+ const fl = readU();
33570
+ const isUndef = (fl & 16) !== 0;
33571
+ const isExplicitName = (fl & 64) !== 0;
33572
+ let sName = "";
33573
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
33574
+ const el = readU();
33575
+ if (!isUndef || isExplicitName) {
33576
+ const sLen = readU();
33577
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
33578
+ cur += sLen;
33579
+ } else if (kind === 0) {
33580
+ sName = importFuncNames[el] ?? "";
33581
+ } else if (kind === 2) {
33582
+ sName = importGlobalNames[el] ?? "";
33583
+ } else if (kind === 4) {
33584
+ sName = importEventNames[el] ?? "";
33585
+ } else if (kind === 5) {
33586
+ sName = importTableNames[el] ?? "";
33587
+ }
33588
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
33589
+ hostImports.add(sName);
33590
+ } else if (kind === 1) {
33591
+ const sLen = readU();
33592
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
33593
+ cur += sLen;
33594
+ if (!isUndef) {
33595
+ readU();
33596
+ readU();
33597
+ readU();
33598
+ }
33599
+ } else if (kind === 3) {
33600
+ readU();
33601
+ }
33602
+ if (sName) {
33603
+ if (isUndef) {
33604
+ undefinedSyms.add(sName);
33605
+ if ((fl & 19) === 17) weakUndefined.add(sName);
33606
+ } else if ((fl & 3) !== 2) {
33607
+ defined.add(sName);
33608
+ if ((fl & 19) === 1) weakDefined.add(sName);
33609
+ }
33610
+ if (kind === 4) tags.add(sName);
33611
+ else if (kind === 2 || kind === 5) globals.add(sName);
33612
+ }
33613
+ }
33614
+ break;
33615
+ }
33616
+ cur = subEnd;
33617
+ }
33618
+ break;
33619
+ }
33620
+ }
33621
+ cur = end;
33622
+ }
33248
33623
  return {
33249
- importsDlsym: object7.importsDlsym,
33250
- undefined: [
33251
- ...new Set(
33252
- object7.symNames.filter(
33253
- (name3, index) => name3 && (object7.symFlags[index] & 16) !== 0
33254
- )
33255
- )
33256
- ],
33624
+ importsDlsym,
33625
+ undefined: [...undefinedSyms],
33257
33626
  // a wasm tag is one module entity unified by name across the link, as the
33258
33627
  // main module owns it for dynamic images, so no image scope applies.
33259
- tags: [
33260
- ...new Set(
33261
- object7.symNames.filter((name3, index) => name3 && object7.symKind[index] === 4)
33262
- )
33263
- ],
33264
- globals: [
33265
- ...new Set(
33266
- object7.symNames.filter(
33267
- (name3, index) => name3 && (object7.symKind[index] === 2 || object7.symKind[index] === 5)
33268
- )
33269
- )
33270
- ],
33628
+ tags: [...tags],
33629
+ globals: [...globals],
33271
33630
  // an undefined function imported from a module other than env is supplied
33272
33631
  // by the host, whatever linker symbol names it.
33273
- hostImports: [...object7.hostImportNames],
33274
- weakUndefined: [
33275
- ...new Set(
33276
- object7.symNames.filter(
33277
- (name3, index) => name3 && (object7.symFlags[index] & 19) === 17
33278
- )
33279
- )
33280
- ],
33281
- defined: [
33282
- ...new Set(
33283
- object7.symNames.filter(
33284
- (name3, index) => name3 && (object7.symFlags[index] & 16) === 0 && (object7.symFlags[index] & 3) !== 2
33285
- )
33286
- )
33287
- ],
33288
- weakDefined: [
33289
- ...new Set(
33290
- object7.symNames.filter(
33291
- (name3, index) => name3 && (object7.symFlags[index] & 19) === 1
33292
- )
33293
- )
33294
- ]
33632
+ hostImports: [...hostImports],
33633
+ weakUndefined: [...weakUndefined],
33634
+ defined: [...defined],
33635
+ weakDefined: [...weakDefined]
33295
33636
  };
33296
33637
  }
33297
33638
  function sdkObjectName(archive, member, ordinal) {
@@ -33808,9 +34149,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
33808
34149
  for (const entry of waiting) tryActivateConformance(entry);
33809
34150
  }
33810
34151
  };
34152
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
33811
34153
  const checkProtocolTrigger = (rawSymName) => {
33812
34154
  if (!rawSymName) return;
33813
34155
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
34156
+ if (checkedProtocolTriggers.has(sName)) return;
34157
+ checkedProtocolTriggers.add(sName);
33814
34158
  if (knownProtocols.has(sName)) {
33815
34159
  markProtocolLive(sName);
33816
34160
  return;
@@ -33843,6 +34187,43 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
33843
34187
  }
33844
34188
  }
33845
34189
  };
34190
+ const typeIndexes = /* @__PURE__ */ new Map();
34191
+ const getTypeIndex = (obj) => {
34192
+ let idx = typeIndexes.get(obj);
34193
+ if (idx) return idx;
34194
+ const mnByPrefix = /* @__PURE__ */ new Map();
34195
+ for (let i = 0; i < obj.symNames.length; i++) {
34196
+ const name3 = obj.symNames[i];
34197
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
34198
+ const pref = name3.slice(0, -2);
34199
+ let list2 = mnByPrefix.get(pref);
34200
+ if (!list2) mnByPrefix.set(pref, list2 = []);
34201
+ list2.push(i);
34202
+ }
34203
+ }
34204
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
34205
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
34206
+ let list2 = objcRegByPrefix.get(p);
34207
+ if (!list2) objcRegByPrefix.set(p, list2 = []);
34208
+ list2.push(lf);
34209
+ }
34210
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
34211
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
34212
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
34213
+ let list2 = objcClassByPrefix.get(p);
34214
+ if (!list2) objcClassByPrefix.set(p, list2 = []);
34215
+ list2.push(classSym.slice("._OBJC_CLASS_".length));
34216
+ }
34217
+ let minPrefLen = Infinity;
34218
+ let maxPrefLen = 0;
34219
+ for (const p of obj.typePrefixesInObj) {
34220
+ if (p.length < minPrefLen) minPrefLen = p.length;
34221
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
34222
+ }
34223
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
34224
+ typeIndexes.set(obj, idx);
34225
+ return idx;
34226
+ };
33846
34227
  const markTypeLive = (obj, pref) => {
33847
34228
  const set2 = liveTypes.get(obj);
33848
34229
  if (set2.has(pref)) return;
@@ -33856,22 +34237,10 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
33856
34237
  const outer = pref.slice(0, n);
33857
34238
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
33858
34239
  }
33859
- const mnName = `${pref}Mn`;
33860
- for (let i = 0; i < obj.symNames.length; i++) {
33861
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
33862
- activateSymbolInObj(obj, i);
33863
- }
33864
- }
33865
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
33866
- if (p === pref) {
33867
- markFuncLive(obj, lf);
33868
- }
33869
- }
33870
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
33871
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
33872
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
33873
- }
33874
- }
34240
+ const idx = getTypeIndex(obj);
34241
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
34242
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
34243
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
33875
34244
  };
33876
34245
  const checkTypeTrigger = (obj, rawSymName) => {
33877
34246
  if (!rawSymName) return;
@@ -33896,11 +34265,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
33896
34265
  }
33897
34266
  }
33898
34267
  }
33899
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
33900
- for (const pref of obj.typePrefixesInObj) {
33901
- if (sName.startsWith(pref)) {
33902
- markTypeLive(obj, pref);
33903
- }
34268
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
34269
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
34270
+ const hi = Math.min(sName.length, maxPrefLen);
34271
+ for (let n = minPrefLen; n <= hi; n++) {
34272
+ const cand = sName.slice(0, n);
34273
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
33904
34274
  }
33905
34275
  }
33906
34276
  };
@@ -33993,7 +34363,8 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
33993
34363
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
33994
34364
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
33995
34365
  for (const name3 of obj.symNames) {
33996
- const loaded3 = name3?.match(/^_c_(\w+)__load$/)?.[1];
34366
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
34367
+ const loaded3 = name3.match(/^_c_(\w+)__load$/)?.[1];
33997
34368
  if (!loaded3) continue;
33998
34369
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded3}`);
33999
34370
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -34141,14 +34512,30 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
34141
34512
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
34142
34513
  const range3 = obj.segPayloadRanges[segIdx];
34143
34514
  if (!range3) return;
34515
+ const [rangeStart, rangeEnd] = range3;
34516
+ if (rangeEnd - rangeStart < 4) return;
34144
34517
  let bytes = objectBytes.get(obj);
34145
34518
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs44.default.readFileSync(obj.file));
34146
- const text7 = bytes.toString("latin1", range3[0], range3[1]);
34147
- for (const match of text7.matchAll(/So(\d+)/g)) {
34148
- const start = match.index + 2 + match[1].length;
34149
- const length = Number(match[1]);
34150
- if (text7[start + length] !== "C") continue;
34151
- const symbol2 = `._OBJC_CLASS_${text7.slice(start, start + length)}`;
34519
+ let pos = rangeStart;
34520
+ while (pos < rangeEnd - 3) {
34521
+ const at = bytes.indexOf("So", pos);
34522
+ if (at < 0 || at >= rangeEnd - 2) break;
34523
+ let digitEnd = at + 2;
34524
+ let length = 0;
34525
+ while (digitEnd < rangeEnd) {
34526
+ const ch = bytes[digitEnd];
34527
+ if (ch < 48 || ch > 57) break;
34528
+ length = length * 10 + (ch - 48);
34529
+ digitEnd++;
34530
+ }
34531
+ if (digitEnd === at + 2) {
34532
+ pos = at + 2;
34533
+ continue;
34534
+ }
34535
+ pos = digitEnd;
34536
+ const nameEnd = digitEnd + length;
34537
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
34538
+ const symbol2 = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
34152
34539
  for (const provider of lazyProviders.get(symbol2) ?? []) {
34153
34540
  eagerDynamicObjects.add(provider);
34154
34541
  extractObject(provider);
@@ -35125,6 +35512,10 @@ var init_nativeDyldTableContract = __esm({
35125
35512
 
35126
35513
  // src/swift-guest-image-ledger.ts
35127
35514
  function readNumber(bytes, position) {
35515
+ if (position < bytes.length) {
35516
+ const first = bytes[position];
35517
+ if (first < 128) return [first, position + 1];
35518
+ }
35128
35519
  let value = 0;
35129
35520
  let shift = 0;
35130
35521
  for (; ; ) {
@@ -35136,6 +35527,7 @@ function readNumber(bytes, position) {
35136
35527
  }
35137
35528
  }
35138
35529
  function encodeNumber(value) {
35530
+ if (value < 128) return Buffer.from([value]);
35139
35531
  const bytes = [];
35140
35532
  do {
35141
35533
  let byte = value % 128;
@@ -35157,6 +35549,9 @@ function encodedString(value) {
35157
35549
  const bytes = Buffer.from(value);
35158
35550
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
35159
35551
  }
35552
+ function isWasmMagic(bytes) {
35553
+ 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;
35554
+ }
35160
35555
  function llvmType(value) {
35161
35556
  switch (value) {
35162
35557
  case 127:
@@ -35172,11 +35567,12 @@ function llvmType(value) {
35172
35567
  }
35173
35568
  }
35174
35569
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options2 = {}) {
35175
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
35176
- throw new Error("expected wasm object");
35570
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
35571
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
35177
35572
  const { sdkLookupOnly, sdkProduct } = options2;
35178
35573
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
35179
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
35574
+ const rewrite = binding !== void 0;
35575
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
35180
35576
  const types2 = [];
35181
35577
  const functionTypes = [];
35182
35578
  const definitions = [];
@@ -35190,45 +35586,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35190
35586
  const usedSymbols = /* @__PURE__ */ new Set();
35191
35587
  let position = 8;
35192
35588
  while (position < bytes.length) {
35589
+ const headerStart2 = position;
35193
35590
  const id = bytes[position++];
35194
- const [size2, start] = readNumber(bytes, position);
35591
+ let size2 = 0;
35592
+ if (position < bytes.length && bytes[position] < 128) {
35593
+ size2 = bytes[position++];
35594
+ } else {
35595
+ const [val, next] = readNumber(bytes, position);
35596
+ size2 = val;
35597
+ position = next;
35598
+ }
35599
+ const start = position;
35195
35600
  const end = start + size2;
35196
35601
  if (end > bytes.length) throw new Error("invalid wasm section");
35197
35602
  position = end;
35198
- if (!sections && id > 3) continue;
35199
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size2);
35200
- let offset = 0;
35603
+ if (id > 3) {
35604
+ if (sections) sections.push(bytes.subarray(headerStart2, end));
35605
+ continue;
35606
+ }
35607
+ let offset = start;
35201
35608
  const number3 = () => {
35202
- const [value, next] = readNumber(section2, offset);
35203
- offset = next;
35204
- return value;
35609
+ if (offset < end) {
35610
+ const first = bytes[offset];
35611
+ if (first < 128) {
35612
+ offset++;
35613
+ return first;
35614
+ }
35615
+ }
35616
+ let value = 0;
35617
+ let shift = 0;
35618
+ for (; ; ) {
35619
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
35620
+ const byte = bytes[offset++];
35621
+ value += (byte & 127) * 2 ** shift;
35622
+ if (!(byte & 128)) return value;
35623
+ shift += 7;
35624
+ }
35205
35625
  };
35206
35626
  const string7 = () => {
35207
- const [value, next] = readString(section2, offset);
35208
- offset = next;
35627
+ const length = number3();
35628
+ const strEnd = offset + length;
35629
+ if (strEnd > end) throw new Error("invalid wasm string");
35630
+ const value = rawBuf.toString("utf8", offset, strEnd);
35631
+ offset = strEnd;
35209
35632
  return value;
35210
35633
  };
35634
+ let rewrittenSection;
35211
35635
  if (id === 1) {
35212
35636
  const count = number3();
35213
35637
  for (let i = 0; i < count; i++) {
35214
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
35638
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
35215
35639
  const parameterCount = number3();
35216
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
35217
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
35218
- offset += parameterCount;
35640
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
35641
+ const parameters = new Array(parameterCount);
35642
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
35219
35643
  const resultCount = number3();
35220
- const results = [...section2.subarray(offset, offset + resultCount)];
35221
- if (results.length !== resultCount) throw new Error("invalid wasm type");
35222
- offset += resultCount;
35644
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
35645
+ const results = new Array(resultCount);
35646
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
35223
35647
  types2.push({ parameters, results });
35224
35648
  }
35225
35649
  } else if (id === 2) {
35226
35650
  const count = number3();
35227
- const imports2 = sections ? [encodeNumber(count)] : void 0;
35651
+ const importWriter = rewrite ? new ByteWriter(size2 + 64) : void 0;
35652
+ importWriter?.uleb(count);
35228
35653
  for (let i = 0; i < count; i++) {
35229
35654
  const module2 = string7();
35230
35655
  const name3 = string7();
35231
- const kind = section2[offset++];
35656
+ const kind = bytes[offset++];
35232
35657
  const typeStart = offset;
35233
35658
  let functionType2 = -1;
35234
35659
  if (kind === 0) {
@@ -35236,7 +35661,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35236
35661
  functionTypes.push(functionType2);
35237
35662
  functionImportNames.push(name3);
35238
35663
  } else if (kind === 1) {
35239
- const referenceType = section2[offset++];
35664
+ const referenceType = bytes[offset++];
35240
35665
  if (referenceType !== 112 && referenceType !== 111)
35241
35666
  throw new Error("unsupported table type");
35242
35667
  const flags = number3();
@@ -35255,11 +35680,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35255
35680
  } else throw new Error("unsupported wasm import");
35256
35681
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
35257
35682
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
35258
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
35259
- if (module2 === "env" && kind === 0 && names.has(name3)) {
35260
- const type = types2[functionType2];
35261
- if (!type) throw new Error(`missing import type for ${name3}`);
35262
- functionImports.set(name3, type);
35683
+ if (!rewrite) {
35684
+ if (module2 === "env" && names.has(name3)) {
35685
+ usedSymbols.add(name3);
35686
+ if (kind === 0) {
35687
+ const type = types2[functionType2];
35688
+ if (!type) throw new Error(`missing import type for ${name3}`);
35689
+ functionImports.set(name3, type);
35690
+ }
35691
+ }
35263
35692
  }
35264
35693
  if (isDlsym || isDlerror) {
35265
35694
  const type = types2[functionType2];
@@ -35269,17 +35698,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35269
35698
  }
35270
35699
  if (isDlsym) usesDlsym = true;
35271
35700
  if (isDlerror) usesDlerror = true;
35272
- imports2?.push(
35273
- encodedString(module2),
35274
- encodedString(
35275
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
35276
- ),
35277
- Buffer.from([kind]),
35278
- section2.subarray(typeStart, offset)
35279
- );
35701
+ if (importWriter && binding) {
35702
+ importWriter.string(module2);
35703
+ importWriter.string(
35704
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
35705
+ );
35706
+ importWriter.byte(kind);
35707
+ importWriter.bytes(bytes, typeStart, offset);
35708
+ }
35280
35709
  }
35281
- if (offset !== section2.length) throw new Error("invalid wasm import section");
35282
- if (imports2) section2 = Buffer.concat(imports2);
35710
+ if (offset !== end) throw new Error("invalid wasm import section");
35711
+ if (importWriter) rewrittenSection = importWriter.finish();
35283
35712
  } else if (id === 3) {
35284
35713
  const count = number3();
35285
35714
  for (let i = 0; i < count; i++) functionTypes.push(number3());
@@ -35288,43 +35717,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35288
35717
  if (sectionName === "linking") {
35289
35718
  const version2 = number3();
35290
35719
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
35291
- const subsections = [];
35720
+ const subsections = rewrite ? [] : void 0;
35292
35721
  let objcLoader;
35293
- while (offset < section2.length) {
35294
- const kind = section2[offset++];
35722
+ while (offset < end) {
35723
+ const kind = bytes[offset++];
35295
35724
  const length = number3();
35296
35725
  const stop = offset + length;
35297
- if (stop > section2.length) throw new Error("invalid linking subsection");
35298
- let content = section2.subarray(offset, stop);
35299
- if (kind === 7 && !sdkLookupOnly) {
35300
- const groups = [];
35726
+ if (stop > end) throw new Error("invalid linking subsection");
35727
+ const contentStart = offset;
35728
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
35729
+ const comdatWriter = new ByteWriter(length + 64);
35301
35730
  const count = number3();
35302
- groups.push(encodeNumber(count));
35731
+ comdatWriter.uleb(count);
35303
35732
  for (let i = 0; i < count; i++) {
35304
35733
  const group = string7();
35305
35734
  const begin = offset;
35306
35735
  number3();
35307
35736
  const members2 = number3();
35308
35737
  for (let member = 0; member < members2 * 2; member++) number3();
35309
- groups.push(
35310
- encodedString(
35311
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
35312
- ),
35313
- section2.subarray(begin, offset)
35738
+ comdatWriter.string(
35739
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
35314
35740
  );
35741
+ comdatWriter.bytes(bytes, begin, offset);
35315
35742
  }
35316
35743
  if (offset !== stop) throw new Error("invalid comdat subsection");
35317
- content = Buffer.concat(groups);
35318
- }
35319
- if (kind === 8) {
35320
- const entries2 = [];
35321
- const extraEntries = [];
35744
+ const buf = comdatWriter.finish();
35745
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
35746
+ } else if (kind === 8) {
35747
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
35748
+ let extraWriter;
35322
35749
  const count = number3();
35323
- entries2.push(encodeNumber(count));
35324
35750
  let added = 0;
35325
35751
  for (let i = 0; i < count; i++) {
35326
35752
  const begin = offset;
35327
- const symbolKind = section2[offset++];
35753
+ const symbolKind = bytes[offset++];
35328
35754
  const flags = number3();
35329
35755
  const flagsEnd = offset;
35330
35756
  let index = -1;
@@ -35352,25 +35778,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35352
35778
  }
35353
35779
  } else if (symbolKind === 3) number3();
35354
35780
  else throw new Error("unsupported wasm symbol kind");
35355
- if (symbolKind === 0)
35781
+ if (!rewrite && symbolKind === 0)
35356
35782
  functionSymbols[i] = name3 || functionImportNames[index];
35357
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
35783
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
35358
35784
  objcLoader = i;
35359
35785
  }
35360
35786
  const alias = names.get(name3);
35361
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
35362
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
35363
- entries2.push(
35364
- section2.subarray(begin, nameStart),
35365
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
35366
- section2.subarray(nameEnd, offset)
35367
- );
35368
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
35369
- entries2.push(
35370
- section2.subarray(begin, nameStart),
35371
- encodedString(binding(name3)),
35372
- section2.subarray(nameEnd, offset)
35373
- );
35787
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
35788
+ usedSymbols.add(name3);
35789
+ if (entryWriter && binding) {
35790
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
35791
+ entryWriter.bytes(bytes, begin, nameStart);
35792
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
35793
+ entryWriter.bytes(bytes, nameEnd, offset);
35794
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
35795
+ entryWriter.bytes(bytes, begin, nameStart);
35796
+ entryWriter.string(binding(name3));
35797
+ entryWriter.bytes(bytes, nameEnd, offset);
35798
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
35799
+ if (symbolKind !== 0 && symbolKind !== 1)
35800
+ throw new Error(`unsupported symbol ${name3}`);
35801
+ if (preserveCanonical.has(name3)) {
35802
+ entryWriter.bytes(bytes, begin, offset);
35803
+ extraWriter ??= new ByteWriter(256);
35804
+ extraWriter.byte(bytes[begin]);
35805
+ extraWriter.uleb(flags & ~32);
35806
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
35807
+ extraWriter.string(alias);
35808
+ extraWriter.bytes(bytes, nameEnd, offset);
35809
+ added++;
35810
+ } else {
35811
+ entryWriter.bytes(bytes, begin, nameStart);
35812
+ entryWriter.string(alias);
35813
+ entryWriter.bytes(bytes, nameEnd, offset);
35814
+ }
35815
+ } else {
35816
+ entryWriter.bytes(bytes, begin, offset);
35817
+ }
35374
35818
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
35375
35819
  if (symbolKind !== 0 && symbolKind !== 1)
35376
35820
  throw new Error(`unsupported symbol ${name3}`);
@@ -35384,63 +35828,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35384
35828
  hidden: (flags & 4) !== 0,
35385
35829
  type
35386
35830
  });
35387
- if (preserveCanonical.has(name3)) {
35388
- entries2.push(section2.subarray(begin, offset));
35389
- extraEntries.push(
35390
- section2.subarray(begin, begin + 1),
35391
- encodeNumber(flags & ~32),
35392
- section2.subarray(flagsEnd, nameStart),
35393
- encodedString(alias),
35394
- section2.subarray(nameEnd, offset)
35395
- );
35396
- added++;
35397
- } else {
35398
- entries2.push(
35399
- section2.subarray(begin, nameStart),
35400
- encodedString(alias),
35401
- section2.subarray(nameEnd, offset)
35402
- );
35403
- }
35404
- } else entries2.push(section2.subarray(begin, offset));
35831
+ }
35405
35832
  }
35406
35833
  if (offset !== stop) throw new Error("invalid symbol subsection");
35407
- entries2[0] = encodeNumber(count + added);
35408
- content = Buffer.concat([...entries2, ...extraEntries]);
35834
+ if (entryWriter) {
35835
+ const countBytes = encodeNumber(count + added);
35836
+ const entryBuf = entryWriter.finish();
35837
+ if (extraWriter) {
35838
+ const extraBuf = extraWriter.finish();
35839
+ subsections.push({
35840
+ kind,
35841
+ parts: [countBytes, entryBuf, extraBuf],
35842
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
35843
+ });
35844
+ } else {
35845
+ subsections.push({
35846
+ kind,
35847
+ parts: [countBytes, entryBuf],
35848
+ byteLength: countBytes.length + entryBuf.length
35849
+ });
35850
+ }
35851
+ }
35852
+ } else if (subsections) {
35853
+ subsections.push({
35854
+ kind,
35855
+ parts: [bytes.subarray(contentStart, stop)],
35856
+ byteLength: length
35857
+ });
35409
35858
  }
35410
35859
  offset = stop;
35411
- subsections.push({ kind, content });
35412
- }
35413
- const parts = [encodedString(sectionName), encodeNumber(version2)];
35414
- for (const subsection of subsections) {
35415
- let content = subsection.content;
35416
- if (subsection.kind === 6 && objcLoader !== void 0) {
35417
- const [count, entriesStart] = readNumber(content, 0);
35418
- const entries2 = [content.subarray(0, entriesStart)];
35419
- let entryStart = entriesStart;
35420
- for (let i = 0; i < count; i++) {
35421
- const [, symbolStart] = readNumber(content, entryStart);
35422
- const [symbol2, entryEnd] = readNumber(content, symbolStart);
35423
- if (symbol2 === objcLoader) entries2.push(encodeNumber(1));
35424
- entries2.push(
35425
- content.subarray(
35426
- symbol2 === objcLoader ? symbolStart : entryStart,
35427
- entryEnd
35428
- )
35429
- );
35430
- entryStart = entryEnd;
35860
+ }
35861
+ if (subsections) {
35862
+ const linkingWriter = new ByteWriter(size2 + 128);
35863
+ linkingWriter.string(sectionName);
35864
+ linkingWriter.uleb(version2);
35865
+ for (const subsection of subsections) {
35866
+ if (subsection.kind === 6 && objcLoader !== void 0) {
35867
+ const content = subsection.parts[0];
35868
+ const [count, entriesStart] = readNumber(content, 0);
35869
+ const initWriter = new ByteWriter(content.length + 16);
35870
+ initWriter.bytes(content, 0, entriesStart);
35871
+ let entryStart = entriesStart;
35872
+ for (let i = 0; i < count; i++) {
35873
+ const [, symbolStart] = readNumber(content, entryStart);
35874
+ const [symbol2, entryEnd] = readNumber(content, symbolStart);
35875
+ if (symbol2 === objcLoader) {
35876
+ initWriter.uleb(1);
35877
+ initWriter.bytes(content, symbolStart, entryEnd);
35878
+ } else {
35879
+ initWriter.bytes(content, entryStart, entryEnd);
35880
+ }
35881
+ entryStart = entryEnd;
35882
+ }
35883
+ if (entryStart !== content.length)
35884
+ throw new Error("invalid init functions subsection");
35885
+ const initBuf = initWriter.finish();
35886
+ linkingWriter.byte(subsection.kind);
35887
+ linkingWriter.uleb(initBuf.length);
35888
+ linkingWriter.bytes(initBuf);
35889
+ } else {
35890
+ linkingWriter.byte(subsection.kind);
35891
+ linkingWriter.uleb(subsection.byteLength);
35892
+ for (const part of subsection.parts) linkingWriter.bytes(part);
35431
35893
  }
35432
- if (entryStart !== content.length)
35433
- throw new Error("invalid init functions subsection");
35434
- content = Buffer.concat(entries2);
35435
35894
  }
35436
- parts.push(
35437
- Buffer.from([subsection.kind]),
35438
- encodeNumber(content.length),
35439
- content
35440
- );
35895
+ rewrittenSection = linkingWriter.finish();
35441
35896
  }
35442
- section2 = Buffer.concat(parts);
35443
- } else if (!sections && sectionName.startsWith("reloc.")) {
35897
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
35444
35898
  number3();
35445
35899
  for (let count = number3(); count > 0; count--) {
35446
35900
  const type = number3();
@@ -35450,18 +35904,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
35450
35904
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
35451
35905
  addressTaken.add(name3);
35452
35906
  }
35453
- if (offset !== section2.length)
35454
- throw new Error(`invalid relocation section ${sectionName}`);
35907
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
35908
+ }
35909
+ }
35910
+ if (sections) {
35911
+ if (rewrittenSection) {
35912
+ sections.push(
35913
+ Buffer.from([id]),
35914
+ encodeNumber(rewrittenSection.length),
35915
+ rewrittenSection
35916
+ );
35917
+ } else {
35918
+ sections.push(bytes.subarray(headerStart2, end));
35455
35919
  }
35456
35920
  }
35457
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
35458
35921
  }
35459
35922
  return {
35460
35923
  bytes: sections ? Buffer.concat(sections) : bytes,
35461
35924
  definitions,
35462
35925
  functionImports,
35463
35926
  usesDlsym,
35464
- usedSymbols: [...usedSymbols],
35927
+ usedSymbols,
35465
35928
  addressTaken: [...addressTaken]
35466
35929
  };
35467
35930
  }
@@ -35550,36 +36013,51 @@ function createGuestImageLedger(input) {
35550
36013
  }
35551
36014
  }
35552
36015
  }
35553
- const nameBytes = /* @__PURE__ */ new Map();
35554
- for (const definition2 of definitions)
35555
- if (!nameBytes.has(definition2.name))
35556
- nameBytes.set(definition2.name, Buffer.from(definition2.name));
35557
- definitions.sort(
35558
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
35559
- );
36016
+ let hasNonAscii = false;
36017
+ for (const definition2 of definitions) {
36018
+ const s = definition2.name;
36019
+ for (let i = 0; i < s.length; i++) {
36020
+ if (s.charCodeAt(i) > 127) {
36021
+ hasNonAscii = true;
36022
+ break;
36023
+ }
36024
+ }
36025
+ if (hasNonAscii) break;
36026
+ }
36027
+ if (hasNonAscii) {
36028
+ const nameBytes = /* @__PURE__ */ new Map();
36029
+ for (const definition2 of definitions)
36030
+ if (!nameBytes.has(definition2.name))
36031
+ nameBytes.set(definition2.name, Buffer.from(definition2.name));
36032
+ definitions.sort(
36033
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
36034
+ );
36035
+ } else {
36036
+ definitions.sort(
36037
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
36038
+ );
36039
+ }
35560
36040
  const preserveCanonical = /* @__PURE__ */ new Set();
35561
36041
  const definitionsByName = Map.groupBy(definitions, (definition2) => definition2.name);
35562
- for (const name3 of input.symbols) {
36042
+ if (symbolIndices.has("__cxa_throw")) {
36043
+ const name3 = "__cxa_throw";
35563
36044
  const matching = definitionsByName.get(name3) ?? [];
35564
- if (new Set(matching.map((definition2) => definition2.image)).size < 2 || !matching.some((definition2) => definition2.weak))
35565
- continue;
35566
- const weak = matching.filter((definition2) => definition2.weak);
35567
- const strong = matching.filter((definition2) => !definition2.weak);
35568
- if (name3 !== "__cxa_throw") continue;
35569
- if (weak.length !== 1 || strong.length !== 1)
35570
- throw new Error(`unsupported weak interposition for ${name3}`);
35571
- const [local] = weak;
35572
- const [runtime] = strong;
35573
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
35574
- throw new Error(`incompatible weak interposition for ${name3}`);
35575
- for (const caller of input.callers) {
35576
- const uses = caller.image === local.image || units.some(
35577
- (unit2) => unit2.image === caller.image && unit2.usedSymbols.includes(name3)
35578
- );
35579
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
35580
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
36045
+ if (new Set(matching.map((definition2) => definition2.image)).size >= 2 && matching.some((definition2) => definition2.weak)) {
36046
+ const weak = matching.filter((definition2) => definition2.weak);
36047
+ const strong = matching.filter((definition2) => !definition2.weak);
36048
+ if (weak.length !== 1 || strong.length !== 1)
36049
+ throw new Error(`unsupported weak interposition for ${name3}`);
36050
+ const [local] = weak;
36051
+ const [runtime] = strong;
36052
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
36053
+ throw new Error(`incompatible weak interposition for ${name3}`);
36054
+ for (const caller of input.callers) {
36055
+ const uses = caller.image === local.image || units.some((unit2) => unit2.image === caller.image && unit2.usedSymbols.has(name3));
36056
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
36057
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
36058
+ }
36059
+ preserveCanonical.add(name3);
35581
36060
  }
35582
- preserveCanonical.add(name3);
35583
36061
  }
35584
36062
  for (const name3 of [
35585
36063
  "dlsym",
@@ -35591,40 +36069,76 @@ function createGuestImageLedger(input) {
35591
36069
  ])
35592
36070
  preserveCanonical.add(name3);
35593
36071
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
35594
- const bindingsByImage = /* @__PURE__ */ new Map();
35595
- const definitionsByImage = Map.groupBy(definitions, (definition2) => definition2.image);
36072
+ const imageAliases = /* @__PURE__ */ new Map();
36073
+ const imageWeakNames = /* @__PURE__ */ new Map();
36074
+ const singleOwnerByName = /* @__PURE__ */ new Map();
36075
+ for (const definition2 of definitions) {
36076
+ let aliases = imageAliases.get(definition2.image);
36077
+ if (!aliases) imageAliases.set(definition2.image, aliases = /* @__PURE__ */ new Map());
36078
+ const existing = aliases.get(definition2.name);
36079
+ if (existing === void 0) {
36080
+ aliases.set(definition2.name, definition2.alias);
36081
+ if (definition2.weak) {
36082
+ let weak = imageWeakNames.get(definition2.image);
36083
+ if (!weak) imageWeakNames.set(definition2.image, weak = /* @__PURE__ */ new Set());
36084
+ weak.add(definition2.name);
36085
+ }
36086
+ const owner = singleOwnerByName.get(definition2.name);
36087
+ if (owner === void 0)
36088
+ singleOwnerByName.set(definition2.name, {
36089
+ image: definition2.image,
36090
+ alias: definition2.alias
36091
+ });
36092
+ else if (owner !== null && owner.image !== definition2.image)
36093
+ singleOwnerByName.set(definition2.name, null);
36094
+ } else if (!definition2.weak && imageWeakNames.get(definition2.image)?.has(definition2.name)) {
36095
+ aliases.set(definition2.name, definition2.alias);
36096
+ imageWeakNames.get(definition2.image).delete(definition2.name);
36097
+ const owner = singleOwnerByName.get(definition2.name);
36098
+ if (owner && owner.image === definition2.image) owner.alias = definition2.alias;
36099
+ }
36100
+ }
36101
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
35596
36102
  for (const caller of input.callers) {
35597
- const bindings = /* @__PURE__ */ new Map();
35598
- const seen = /* @__PURE__ */ new Map();
35599
36103
  const scope2 = [caller.image, ...caller.next];
35600
36104
  if (input.systemImage !== void 0 && !scope2.includes(input.systemImage))
35601
36105
  scope2.push(input.systemImage);
35602
- for (const image of scope2)
35603
- for (const definition2 of definitionsByImage.get(image) ?? []) {
35604
- const previous = seen.get(definition2.name);
35605
- if (previous?.image === definition2.image) {
35606
- if (previous.weak && !definition2.weak) {
35607
- seen.set(definition2.name, definition2);
35608
- if (!preserveCanonical.has(definition2.name))
35609
- bindings.set(definition2.name, definition2.alias);
35610
- }
35611
- continue;
35612
- }
35613
- if (!previous) {
35614
- seen.set(definition2.name, definition2);
35615
- if (!preserveCanonical.has(definition2.name))
35616
- bindings.set(definition2.name, definition2.alias);
36106
+ const scopeSet = new Set(scope2);
36107
+ const scopeMaps = [];
36108
+ const seenImages = /* @__PURE__ */ new Set();
36109
+ for (const image of scope2) {
36110
+ if (seenImages.has(image)) continue;
36111
+ seenImages.add(image);
36112
+ const aliases = imageAliases.get(image);
36113
+ if (aliases) scopeMaps.push(aliases);
36114
+ }
36115
+ const cache = /* @__PURE__ */ new Map();
36116
+ sharedLookupByImage.set(caller.image, (name3) => {
36117
+ if (preserveCanonical.has(name3)) return void 0;
36118
+ const single = singleOwnerByName.get(name3);
36119
+ if (single === void 0) return void 0;
36120
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
36121
+ const hit = cache.get(name3);
36122
+ if (hit !== void 0) return hit ?? void 0;
36123
+ for (const aliases of scopeMaps) {
36124
+ const alias = aliases.get(name3);
36125
+ if (alias !== void 0) {
36126
+ cache.set(name3, alias);
36127
+ return alias;
35617
36128
  }
35618
36129
  }
35619
- bindingsByImage.set(caller.image, bindings);
36130
+ cache.set(name3, null);
36131
+ return void 0;
36132
+ });
35620
36133
  }
35621
36134
  const startup = /* @__PURE__ */ new Map();
36135
+ const unitsByPath = new Map(units.map((unit2) => [unit2.object.path, unit2]));
35622
36136
  for (const binding of input.directBindings ?? []) {
35623
- const unit2 = units.find(({ object: object7 }) => object7.path === binding.object);
36137
+ const unit2 = unitsByPath.get(binding.object);
35624
36138
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
35625
36139
  (definition2) => definition2.object === binding.providerObject && definition2.image === binding.providerImage
35626
36140
  );
35627
- if (!unit2 || !unit2.usedSymbols.includes(binding.symbol) || matches.length !== 1)
36141
+ if (!unit2 || !unit2.usedSymbols.has(binding.symbol) || matches.length !== 1)
35628
36142
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
35629
36143
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
35630
36144
  if (bindings.has(binding.symbol))
@@ -35665,11 +36179,11 @@ function createGuestImageLedger(input) {
35665
36179
  }
35666
36180
  }
35667
36181
  const objects = units.map(({ image, object: object7, aliases, functionImports }) => {
35668
- const shared = bindingsByImage.get(image);
36182
+ const shared = sharedLookupByImage.get(image);
35669
36183
  const own2 = startup.get(object7.path);
35670
36184
  const bindings = new Map(own2);
35671
36185
  const weak = input.sdkWeakReferences?.get(object7.path);
35672
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
36186
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
35673
36187
  for (const [name3, type] of functionImports) {
35674
36188
  const alias = binding(name3);
35675
36189
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -35934,7 +36448,7 @@ function nameGuestImageAliases(wasm, symbols) {
35934
36448
  }
35935
36449
  return Buffer.concat(parts);
35936
36450
  }
35937
- var import_node_crypto26, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
36451
+ var import_node_crypto26, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
35938
36452
  var init_swift_guest_image_ledger = __esm({
35939
36453
  "src/swift-guest-image-ledger.ts"() {
35940
36454
  "use strict";
@@ -35942,6 +36456,57 @@ var init_swift_guest_image_ledger = __esm({
35942
36456
  init_nativeWasmContract();
35943
36457
  init_swift_sdk_image_wasm();
35944
36458
  init_swiftSdkLinkContract();
36459
+ ByteWriter = class {
36460
+ buf;
36461
+ pos = 0;
36462
+ constructor(initialCapacity = 256) {
36463
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
36464
+ }
36465
+ ensure(extra) {
36466
+ const needed = this.pos + extra;
36467
+ if (needed <= this.buf.length) return;
36468
+ let next = this.buf.length * 2;
36469
+ while (next < needed) next *= 2;
36470
+ const grown = Buffer.allocUnsafe(next);
36471
+ this.buf.copy(grown, 0, 0, this.pos);
36472
+ this.buf = grown;
36473
+ }
36474
+ byte(value) {
36475
+ this.ensure(1);
36476
+ this.buf[this.pos++] = value;
36477
+ }
36478
+ uleb(value) {
36479
+ this.ensure(10);
36480
+ let pos = this.pos;
36481
+ const buf = this.buf;
36482
+ do {
36483
+ let byte = value % 128;
36484
+ value = Math.floor(value / 128);
36485
+ if (value) byte |= 128;
36486
+ buf[pos++] = byte;
36487
+ } while (value);
36488
+ this.pos = pos;
36489
+ }
36490
+ bytes(source, start = 0, end = source.length) {
36491
+ const len = end - start;
36492
+ if (len <= 0) return;
36493
+ this.ensure(len);
36494
+ this.buf.set(source.subarray(start, end), this.pos);
36495
+ this.pos += len;
36496
+ }
36497
+ string(value) {
36498
+ const len = Buffer.byteLength(value, "utf8");
36499
+ this.uleb(len);
36500
+ if (len > 0) {
36501
+ this.ensure(len);
36502
+ this.buf.write(value, this.pos, len, "utf8");
36503
+ this.pos += len;
36504
+ }
36505
+ }
36506
+ finish() {
36507
+ return this.buf.subarray(0, this.pos);
36508
+ }
36509
+ };
35945
36510
  OBJC_INIT_RECORD = ".objc_init";
35946
36511
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
35947
36512
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -36393,8 +36958,11 @@ function moveGuestDyldTable(map2, wasm, symbols, bindingValues = /* @__PURE__ */
36393
36958
  function guestDyldValueRange(map2) {
36394
36959
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
36395
36960
  let found;
36396
- for (const line of map2.split("\n")) {
36397
- if (!line.endsWith(suffix)) continue;
36961
+ for (let at = map2.indexOf(suffix); at !== -1; at = map2.indexOf(suffix, at + suffix.length)) {
36962
+ const lineEnd = at + suffix.length;
36963
+ if (lineEnd < map2.length && map2.charCodeAt(lineEnd) !== 10) continue;
36964
+ const lineStart = map2.lastIndexOf("\n", at) + 1;
36965
+ const line = map2.slice(lineStart, lineEnd);
36398
36966
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
36399
36967
  if (!match) throw new Error("unreadable dyld values map line");
36400
36968
  if (found) throw new Error("link map has several dyld value sections");
@@ -36447,7 +37015,7 @@ var init_swift_guest_link_plan = __esm({
36447
37015
  });
36448
37016
 
36449
37017
  // src/swift-guest-manifest.ts
36450
- function selectedGuestManifestInputs(plan, selection, identities) {
37018
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
36451
37019
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
36452
37020
  const archives = /* @__PURE__ */ new Map();
36453
37021
  const images = /* @__PURE__ */ new Map();
@@ -36458,19 +37026,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
36458
37026
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
36459
37027
  let bytes;
36460
37028
  let memberIdentity = null;
36461
- if (item.member === null) bytes = (0, import_node_fs46.readFileSync)(item.artifact);
36462
- else {
36463
- let members2 = archives.get(item.artifact);
36464
- if (!members2) {
36465
- members2 = readArMembers((0, import_node_fs46.readFileSync)(item.artifact));
36466
- archives.set(item.artifact, members2);
37029
+ if (item.member === null) {
37030
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs46.readFileSync)(item.artifact);
37031
+ } else {
37032
+ if (readSelected) {
37033
+ bytes = readSelected(item);
37034
+ } else {
37035
+ let members2 = archives.get(item.artifact);
37036
+ if (!members2) {
37037
+ members2 = /* @__PURE__ */ new Map();
37038
+ for (const member of readArMembers((0, import_node_fs46.readFileSync)(item.artifact))) {
37039
+ let list2 = members2.get(member.name);
37040
+ if (!list2) members2.set(member.name, list2 = []);
37041
+ list2.push(member.bytes);
37042
+ }
37043
+ archives.set(item.artifact, members2);
37044
+ }
37045
+ const matching = members2.get(item.member);
37046
+ if (!matching || matching.length !== 1)
37047
+ throw new Error(
37048
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
37049
+ );
37050
+ bytes = matching[0];
36467
37051
  }
36468
- const matching = members2.filter((member) => member.name === item.member);
36469
- if (matching.length !== 1)
36470
- throw new Error(
36471
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
36472
- );
36473
- bytes = matching[0].bytes;
36474
37052
  const origin = artifact.memberOrigins?.get(item.member);
36475
37053
  if (artifact.memberOrigins && !origin)
36476
37054
  throw new Error(
@@ -36562,7 +37140,7 @@ var init_swift_guest_manifest = __esm({
36562
37140
  function isSwiftGuestImageManifest(value) {
36563
37141
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
36564
37142
  const text7 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
36565
- const name3 = (value2) => text7(value2) && new TextEncoder().encode(value2).length <= 16;
37143
+ const name3 = (value2) => text7(value2) && Buffer.byteLength(value2, "utf8") <= 16;
36566
37144
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
36567
37145
  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))
36568
37146
  return false;
@@ -36876,27 +37454,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
36876
37454
  function finalizeGuestProjectionStorage(options2) {
36877
37455
  const owner = options2.owners.get(options2.projectionObject);
36878
37456
  if (owner === void 0) throw new Error("guest projection object has no image owner");
37457
+ const ranges = [];
36879
37458
  const spans = guestLinkedSpans(
36880
37459
  options2.map,
36881
37460
  options2.linked,
36882
37461
  options2.optimized,
36883
37462
  options2.owners,
36884
37463
  options2.sectionOwners,
36885
- options2.sdkSpans !== void 0
37464
+ options2.sdkSpans !== void 0,
37465
+ {
37466
+ trackedObject: options2.projectionObject,
37467
+ trackedObjectOwner: owner,
37468
+ trackedLinearSpans: ranges
37469
+ }
36886
37470
  );
36887
37471
  const images = planGuestProjectionRegions(
36888
37472
  options2.reserved.images,
36889
37473
  options2.reserved.capacities,
36890
37474
  options2.sdkSpans ? [...spans, ...options2.sdkSpans] : spans
36891
37475
  );
36892
- const ranges = guestLinkedSpans(
36893
- options2.map,
36894
- options2.linked,
36895
- options2.optimized,
36896
- /* @__PURE__ */ new Map([[options2.projectionObject, owner]]),
36897
- void 0,
36898
- options2.sdkSpans !== void 0
36899
- ).filter((span) => span.space === "linear-memory");
36900
37476
  const result = Buffer.from(options2.optimized);
36901
37477
  const data = guestWasmDataSegments(options2.optimized, options2.sdkSpans === void 0);
36902
37478
  const locations = /* @__PURE__ */ new Map();
@@ -37964,7 +38540,7 @@ function occurrences(plan, args) {
37964
38540
  throw new Error("guest plan does not match linker inputs");
37965
38541
  return found;
37966
38542
  }
37967
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
38543
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
37968
38544
  const rows = whyExtract.trimEnd().split("\n");
37969
38545
  if (rows.shift() !== "reference extracted symbol")
37970
38546
  throw new Error("invalid wasm-ld extraction report");
@@ -37979,8 +38555,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
37979
38555
  for (const file of extracted)
37980
38556
  if (!traced.has(file))
37981
38557
  throw new Error(`extracted guest input is absent from link trace ${file}`);
38558
+ const foundOccurrences = occurrences(plan, args);
38559
+ const archivePaths = /* @__PURE__ */ new Set();
38560
+ for (const { artifact } of foundOccurrences)
38561
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
38562
+ const tracedMembers = /* @__PURE__ */ new Map();
38563
+ if (archivePaths.size > 0) {
38564
+ const archivePrefixes = [...archivePaths].map(
38565
+ (archivePath) => [archivePath, `${archivePath}(`]
38566
+ );
38567
+ for (const item of traced) {
38568
+ if (!item.endsWith(")")) continue;
38569
+ const open = item.lastIndexOf("(");
38570
+ if (open > 0) {
38571
+ const archivePath = item.slice(0, open);
38572
+ if (archivePaths.has(archivePath)) {
38573
+ let list2 = tracedMembers.get(archivePath);
38574
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
38575
+ list2.push(item.slice(open + 1, -1));
38576
+ continue;
38577
+ }
38578
+ }
38579
+ for (const [archivePath, prefix] of archivePrefixes) {
38580
+ if (item.startsWith(prefix)) {
38581
+ let list2 = tracedMembers.get(archivePath);
38582
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
38583
+ list2.push(item.slice(prefix.length, -1));
38584
+ }
38585
+ }
38586
+ }
38587
+ }
37982
38588
  const result = [];
37983
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
38589
+ for (const { artifact, lazy, whole } of foundOccurrences) {
37984
38590
  if (artifact.kind === "object") {
37985
38591
  if (!lazy && !traced.has(artifact.path))
37986
38592
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -37988,15 +38594,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
37988
38594
  result.push({ artifact: artifact.path, member: null });
37989
38595
  continue;
37990
38596
  }
37991
- const prefix = `${artifact.path}(`;
37992
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
37993
- const members2 = readArMembers(import_node_fs49.default.readFileSync(artifact.path));
38597
+ const names = tracedMembers.get(artifact.path) ?? [];
38598
+ const nameSet = new Set(names);
38599
+ let members2 = archiveCache?.get(artifact.path);
38600
+ if (!members2) {
38601
+ members2 = readArMembers(import_node_fs49.default.readFileSync(artifact.path));
38602
+ archiveCache?.set(artifact.path, members2);
38603
+ }
38604
+ const memberCounts = /* @__PURE__ */ new Map();
37994
38605
  for (const member of members2) {
37995
- if (whole || names.includes(member.name))
38606
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
38607
+ if (whole || nameSet.has(member.name))
37996
38608
  result.push({ artifact: artifact.path, member: member.name });
37997
38609
  }
37998
38610
  for (const name3 of names)
37999
- if (members2.filter((member) => member.name === name3).length !== 1)
38611
+ if (memberCounts.get(name3) !== 1)
38000
38612
  throw new Error(
38001
38613
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
38002
38614
  );
@@ -38073,14 +38685,25 @@ function linkGuestImages(options2) {
38073
38685
  }
38074
38686
  const archives = /* @__PURE__ */ new Map();
38075
38687
  const memberBytes = /* @__PURE__ */ new Map();
38688
+ const objectBytes = /* @__PURE__ */ new Map();
38076
38689
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
38077
38690
  const providerSymbol = "__peach_dlsym_from_image";
38078
38691
  const readSelected = (item) => {
38079
- if (item.member === null) return import_node_fs49.default.readFileSync(item.artifact);
38692
+ if (item.member === null) {
38693
+ let bytes = objectBytes.get(item.artifact);
38694
+ if (!bytes) {
38695
+ bytes = import_node_fs49.default.readFileSync(item.artifact);
38696
+ objectBytes.set(item.artifact, bytes);
38697
+ }
38698
+ return bytes;
38699
+ }
38080
38700
  let byName2 = memberBytes.get(item.artifact);
38081
38701
  if (!byName2) {
38082
- const members2 = readArMembers(import_node_fs49.default.readFileSync(item.artifact));
38083
- archives.set(item.artifact, members2);
38702
+ let members2 = archives.get(item.artifact);
38703
+ if (!members2) {
38704
+ members2 = readArMembers(import_node_fs49.default.readFileSync(item.artifact));
38705
+ archives.set(item.artifact, members2);
38706
+ }
38084
38707
  byName2 = /* @__PURE__ */ new Map();
38085
38708
  for (const member of members2)
38086
38709
  if (!byName2.has(member.name))
@@ -38104,7 +38727,13 @@ function linkGuestImages(options2) {
38104
38727
  `--why-extract=${whyPath}`,
38105
38728
  `--Map=${mapPath}`
38106
38729
  ]);
38107
- return selectedGuestLinkInputs(plan, args, import_node_fs49.default.readFileSync(whyPath, "utf8"), trace);
38730
+ return selectedGuestLinkInputs(
38731
+ plan,
38732
+ args,
38733
+ import_node_fs49.default.readFileSync(whyPath, "utf8"),
38734
+ trace,
38735
+ archives
38736
+ );
38108
38737
  };
38109
38738
  const needsProvider = (item) => {
38110
38739
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -38144,7 +38773,7 @@ function linkGuestImages(options2) {
38144
38773
  )
38145
38774
  ]);
38146
38775
  const originalOwnership = identity2(plan);
38147
- const resolved = options2.resolvePlan(selected, plan);
38776
+ const resolved = options2.resolvePlan(selected, plan, readSelected);
38148
38777
  if (identity2(resolved) !== originalOwnership)
38149
38778
  throw new Error("resolved guest scopes changed input ownership");
38150
38779
  plan = resolved;
@@ -38198,6 +38827,7 @@ function linkGuestImages(options2) {
38198
38827
  }
38199
38828
  }
38200
38829
  let discoveryRegions;
38830
+ let liveSymbols;
38201
38831
  if (discoveryProjection && options2.projection) {
38202
38832
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options2.projection.image]]);
38203
38833
  for (const item of selected)
@@ -38206,10 +38836,15 @@ function linkGuestImages(options2) {
38206
38836
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
38207
38837
  );
38208
38838
  const wasm = import_node_fs49.default.readFileSync(discovery);
38839
+ liveSymbols = /* @__PURE__ */ new Set();
38209
38840
  discoveryRegions = guestProjectionRegionCounts(
38210
38841
  plan.images.length,
38211
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
38842
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
38843
+ collectSymbols: liveSymbols
38844
+ })
38212
38845
  );
38846
+ } else {
38847
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
38213
38848
  }
38214
38849
  const ledger = createGuestImageLedger({
38215
38850
  images: plan.images.map((image) => ({
@@ -38218,7 +38853,7 @@ function linkGuestImages(options2) {
38218
38853
  })),
38219
38854
  callers: plan.callers,
38220
38855
  symbols: plan.symbols,
38221
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
38856
+ liveSymbols,
38222
38857
  commandLineSymbols: commandLineSymbols(args),
38223
38858
  directBindings: plan.directBindings,
38224
38859
  registerAppTables: sdkCallers !== void 0,
@@ -38350,7 +38985,8 @@ function linkGuestImages(options2) {
38350
38985
  const selectedInputs = selectedGuestManifestInputs(
38351
38986
  plan,
38352
38987
  selected,
38353
- projection.identities
38988
+ projection.identities,
38989
+ readSelected
38354
38990
  );
38355
38991
  const images = projection.images.map(
38356
38992
  (image) => createGuestImageManifest({
@@ -38360,6 +38996,9 @@ function linkGuestImages(options2) {
38360
38996
  regions: []
38361
38997
  })
38362
38998
  );
38999
+ objectBytes.clear();
39000
+ memberBytes.clear();
39001
+ archives.clear();
38363
39002
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
38364
39003
  const regionsBefore = discoveryRegions;
38365
39004
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs49.default.readFileSync(ledgerObject)], 0);
@@ -38385,6 +39024,7 @@ function linkGuestImages(options2) {
38385
39024
  { stdio: "pipe" }
38386
39025
  );
38387
39026
  finalTrace = linkFinal(projectionObject, callerMap ? void 0 : layoutMap);
39027
+ if (sharedSdk) break;
38388
39028
  const wasm = import_node_fs49.default.readFileSync(finalOutput);
38389
39029
  const actual = guestProjectionRegionCounts(
38390
39030
  images.length,
@@ -38453,10 +39093,47 @@ ${changed.join("\n")}`
38453
39093
  }
38454
39094
  function linkedMapSymbols(lines) {
38455
39095
  const names = /* @__PURE__ */ new Set();
38456
- const symbol2 = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
38457
39096
  for (const line of lines) {
38458
- const match = symbol2.exec(line);
38459
- if (match) names.add(match[1]);
39097
+ const length = line.length;
39098
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
39099
+ let pos = 1;
39100
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
39101
+ const c1 = pos;
39102
+ while (pos < length) {
39103
+ const ch = line.charCodeAt(pos);
39104
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
39105
+ pos++;
39106
+ }
39107
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
39108
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
39109
+ const c2 = pos;
39110
+ while (pos < length) {
39111
+ const ch = line.charCodeAt(pos);
39112
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
39113
+ pos++;
39114
+ }
39115
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
39116
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
39117
+ const c3 = pos;
39118
+ while (pos < length) {
39119
+ const ch = line.charCodeAt(pos);
39120
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
39121
+ pos++;
39122
+ }
39123
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
39124
+ const sStart = pos;
39125
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
39126
+ if (pos - sStart < 9 || pos >= length) continue;
39127
+ const first = line.charCodeAt(pos);
39128
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
39129
+ continue;
39130
+ let end = pos + 1;
39131
+ while (end < length) {
39132
+ const ch = line.charCodeAt(end);
39133
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
39134
+ end++;
39135
+ }
39136
+ names.add(line.slice(pos, end));
38460
39137
  }
38461
39138
  return names;
38462
39139
  }
@@ -38555,7 +39232,7 @@ function discoverGuestLinkInputs(options2) {
38555
39232
  import_node_fs49.default.mkdirSync(options2.directory, { recursive: true });
38556
39233
  const why = import_node_path47.default.join(options2.directory, "preselection-why.txt");
38557
39234
  const response = import_node_path47.default.join(options2.directory, "preselection.rsp");
38558
- const output = import_node_path47.default.join(options2.directory, "preselection.wasm");
39235
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path47.default.join(options2.directory, "preselection.wasm");
38559
39236
  const flags = [
38560
39237
  ...withOutput(args, output, true),
38561
39238
  ...options2.objects,
@@ -38653,7 +39330,7 @@ function prepareGuestRuntimeInputs(options2) {
38653
39330
  });
38654
39331
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
38655
39332
  }
38656
- function selectedGuestSymbolInputs(plan, selected) {
39333
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
38657
39334
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
38658
39335
  const archives = /* @__PURE__ */ new Map();
38659
39336
  const symbols = /* @__PURE__ */ new Set();
@@ -38669,22 +39346,27 @@ function selectedGuestSymbolInputs(plan, selected) {
38669
39346
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
38670
39347
  let bytes;
38671
39348
  let name3 = item.artifact;
38672
- if (item.member === null) bytes = import_node_fs49.default.readFileSync(item.artifact);
38673
- else {
38674
- let members2 = archives.get(item.artifact);
38675
- if (!members2) {
38676
- members2 = Map.groupBy(
38677
- readArMembers(import_node_fs49.default.readFileSync(item.artifact)),
38678
- (member) => member.name
38679
- );
38680
- archives.set(item.artifact, members2);
39349
+ if (item.member === null) {
39350
+ bytes = readSelected ? readSelected(item) : import_node_fs49.default.readFileSync(item.artifact);
39351
+ } else {
39352
+ if (readSelected) {
39353
+ bytes = readSelected(item);
39354
+ } else {
39355
+ let members2 = archives.get(item.artifact);
39356
+ if (!members2) {
39357
+ members2 = Map.groupBy(
39358
+ readArMembers(import_node_fs49.default.readFileSync(item.artifact)),
39359
+ (member) => member.name
39360
+ );
39361
+ archives.set(item.artifact, members2);
39362
+ }
39363
+ const matching = members2.get(item.member) ?? [];
39364
+ if (matching.length !== 1)
39365
+ throw new Error(
39366
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
39367
+ );
39368
+ bytes = matching[0].bytes;
38681
39369
  }
38682
- const matching = members2.get(item.member) ?? [];
38683
- if (matching.length !== 1)
38684
- throw new Error(
38685
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
38686
- );
38687
- bytes = matching[0].bytes;
38688
39370
  name3 += `(${item.member})`;
38689
39371
  }
38690
39372
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -38697,9 +39379,9 @@ function selectedGuestSymbolInputs(plan, selected) {
38697
39379
  for (const symbol2 of names.tags) tags.add(symbol2);
38698
39380
  for (const symbol2 of names.defined) {
38699
39381
  definitions.add(symbol2);
38700
- const objects = definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
39382
+ let objects = definitionObjects.get(symbol2);
39383
+ if (!objects) definitionObjects.set(symbol2, objects = /* @__PURE__ */ new Set());
38701
39384
  objects.add(name3);
38702
- definitionObjects.set(symbol2, objects);
38703
39385
  }
38704
39386
  }
38705
39387
  return {
@@ -38720,7 +39402,7 @@ function verifyGuestSymbolScopes(options2) {
38720
39402
  if (!symbols.length) return { bindings: [], directBindings: [] };
38721
39403
  import_node_fs49.default.mkdirSync(options2.directory, { recursive: true });
38722
39404
  const response = import_node_path47.default.join(options2.directory, "scope-trace.rsp");
38723
- const output = import_node_path47.default.join(options2.directory, "scope-trace.wasm");
39405
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path47.default.join(options2.directory, "scope-trace.wasm");
38724
39406
  const args = [
38725
39407
  ...withOutput(normalizedGuestLinkArgs(options2.args), output, true),
38726
39408
  ...options2.objects,
@@ -38738,55 +39420,76 @@ function verifyGuestSymbolScopes(options2) {
38738
39420
  import_node_fs49.default.closeSync(traceOutput);
38739
39421
  }
38740
39422
  const records = /* @__PURE__ */ new Map();
38741
- const consume = (line) => {
38742
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
38743
- if (!match) return;
38744
- const [, object7, kind, symbol2] = match;
38745
- if (!requested.has(symbol2)) return;
38746
- if (options2.hostImports.has(symbol2)) return;
38747
- const record4 = records.get(symbol2) ?? {
38748
- references: /* @__PURE__ */ new Map(),
38749
- providers: /* @__PURE__ */ new Map(),
38750
- physicalModule: false
38751
- };
39423
+ for (const line of guestLinkLines(tracePath)) {
39424
+ const refSep = line.lastIndexOf(": reference to ");
39425
+ const defSep = line.lastIndexOf(": definition of ");
39426
+ if (refSep < 0 && defSep < 0) continue;
39427
+ const isRef = refSep > defSep;
39428
+ const sep2 = isRef ? refSep : defSep;
39429
+ const symbol2 = line.slice(sep2 + (isRef ? 15 : 16));
39430
+ if (!requested.has(symbol2) || options2.hostImports.has(symbol2)) continue;
39431
+ let record4 = records.get(symbol2);
39432
+ if (!record4) {
39433
+ record4 = {
39434
+ references: /* @__PURE__ */ new Map(),
39435
+ providers: /* @__PURE__ */ new Map(),
39436
+ physicalModule: false
39437
+ };
39438
+ records.set(symbol2, record4);
39439
+ }
39440
+ const object7 = line.slice(0, sep2);
38752
39441
  if (object7 === "<internal>") {
38753
- if (kind === "definition of") record4.physicalModule = true;
39442
+ if (!isRef) record4.physicalModule = true;
38754
39443
  } else {
38755
39444
  const image = options2.owners.get(object7);
38756
39445
  if (image === void 0)
38757
39446
  throw new Error(`traced guest object has no owner ${object7}`);
38758
- (kind === "reference to" ? record4.references : record4.providers).set(
38759
- object7,
38760
- image
38761
- );
39447
+ (isRef ? record4.references : record4.providers).set(object7, image);
38762
39448
  }
38763
- records.set(symbol2, record4);
38764
- };
38765
- for (const line of guestLinkLines(tracePath)) consume(line);
39449
+ }
38766
39450
  const callers = new Map(options2.callers.map((caller) => [caller.image, caller.next]));
39451
+ const callerSets = new Map(
39452
+ options2.callers.map((caller) => [caller.image, new Set(caller.next)])
39453
+ );
39454
+ const rootScope = callerSets.get(0);
38767
39455
  const result = [];
38768
39456
  const directBindings = [];
38769
39457
  for (const symbol2 of symbols) {
38770
39458
  const record4 = records.get(symbol2);
38771
39459
  if (!record4 || !record4.references.size) continue;
38772
39460
  if (!record4.providers.size && options2.hostImports.has(symbol2)) continue;
38773
- const startupReferences = [...record4.references].filter(
38774
- ([object7]) => options2.startupObjects.has(object7) && options2.weakReferences.get(object7)?.has(symbol2)
38775
- );
38776
- const otherReferences = [...record4.references].filter(
38777
- ([object7]) => !startupReferences.some(([startup]) => startup === object7)
38778
- );
39461
+ const startupReferences = [];
39462
+ const otherReferences = [];
39463
+ let allWeakRefs = true;
39464
+ for (const [object7, caller] of record4.references) {
39465
+ const isWeakRef = options2.weakReferences.get(object7)?.has(symbol2) === true;
39466
+ if (!isWeakRef) allWeakRefs = false;
39467
+ if (isWeakRef && options2.startupObjects.has(object7)) {
39468
+ startupReferences.push([object7, caller]);
39469
+ } else {
39470
+ otherReferences.push([object7, caller]);
39471
+ }
39472
+ }
38779
39473
  for (const [, caller] of startupReferences)
38780
39474
  if (!callers.has(caller))
38781
39475
  throw new Error(`guest image has no caller scope ${caller}`);
38782
39476
  if (startupReferences.length && !record4.physicalModule) {
38783
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
38784
- if (candidates.size > 1 || record4.providers.size > 1)
39477
+ const candidates2 = options2.definitionObjects.get(symbol2);
39478
+ const candidateSize = candidates2?.size ?? 0;
39479
+ if (candidateSize > 1 || record4.providers.size > 1)
38785
39480
  throw new Error(`ambiguous startup provider ${symbol2}`);
38786
- if (candidates.size !== record4.providers.size || [...record4.providers.keys()].some((object7) => !candidates.has(object7)))
38787
- throw new Error(`unproven startup provider ${symbol2}`);
39481
+ let unproven = candidateSize !== record4.providers.size;
39482
+ if (!unproven && candidates2) {
39483
+ for (const object7 of record4.providers.keys()) {
39484
+ if (!candidates2.has(object7)) {
39485
+ unproven = true;
39486
+ break;
39487
+ }
39488
+ }
39489
+ }
39490
+ if (unproven) throw new Error(`unproven startup provider ${symbol2}`);
38788
39491
  if (record4.providers.size === 1) {
38789
- const [providerObject, providerImage] = [...record4.providers][0];
39492
+ const [providerObject, providerImage] = record4.providers.entries().next().value;
38790
39493
  if (options2.weakDefinitions.get(providerObject)?.has(symbol2))
38791
39494
  throw new Error(`weak startup provider ${symbol2}`);
38792
39495
  for (const [object7] of startupReferences)
@@ -38794,28 +39497,34 @@ function verifyGuestSymbolScopes(options2) {
38794
39497
  }
38795
39498
  if (!otherReferences.length) continue;
38796
39499
  }
38797
- if (!record4.providers.size && !record4.physicalModule && [...record4.references.keys()].every(
38798
- (object7) => options2.weakReferences.get(object7)?.has(symbol2)
38799
- ))
38800
- continue;
39500
+ if (!record4.providers.size && !record4.physicalModule && allWeakRefs) continue;
38801
39501
  const providerImages = new Set(record4.providers.values());
38802
- const copies = [...options2.definitionObjects.get(symbol2) ?? []].flatMap(
38803
- (object7) => {
39502
+ const candidates = options2.definitionObjects.get(symbol2);
39503
+ const copyImages = /* @__PURE__ */ new Set();
39504
+ const strongImages = /* @__PURE__ */ new Set();
39505
+ let weakDefinerImages;
39506
+ if (candidates) {
39507
+ for (const object7 of candidates) {
38804
39508
  const image = options2.owners.get(object7);
38805
- return image === void 0 ? [] : [{ image, weak: !!options2.weakDefinitions.get(object7)?.has(symbol2) }];
39509
+ if (image === void 0) continue;
39510
+ copyImages.add(image);
39511
+ if (options2.weakDefinitions.get(object7)?.has(symbol2)) {
39512
+ ;
39513
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
39514
+ } else {
39515
+ strongImages.add(image);
39516
+ }
38806
39517
  }
38807
- );
38808
- const copyImages = new Set(copies.map((copy) => copy.image));
38809
- const strongImages = new Set(
38810
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
38811
- );
39518
+ }
38812
39519
  const interposed = !record4.physicalModule && copyImages.size > 1;
38813
39520
  const providerCount = interposed ? 1 : providerImages.size + Number(record4.physicalModule);
38814
39521
  if (!providerCount) continue;
38815
39522
  if (providerCount !== 1)
38816
39523
  throw new Error(`guest symbol has ambiguous provider ${symbol2}`);
38817
- const scopedReferences = record4.physicalModule ? [...record4.references] : otherReferences;
38818
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
39524
+ const scopedReferences = record4.physicalModule ? record4.references : otherReferences;
39525
+ const firstProviderImage = providerImages.values().next().value;
39526
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
39527
+ let interposedByCaller;
38819
39528
  for (const [object7, caller] of scopedReferences) {
38820
39529
  const scope2 = callers.get(caller);
38821
39530
  if (!scope2) throw new Error(`guest image has no caller scope ${caller}`);
@@ -38823,18 +39532,35 @@ function verifyGuestSymbolScopes(options2) {
38823
39532
  result.push({ symbol: symbol2, caller, provider: { kind: "physical-module" } });
38824
39533
  continue;
38825
39534
  }
38826
- const provider = interposed ? [caller, ...scope2].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
39535
+ let provider;
39536
+ if (interposed) {
39537
+ if (interposedByCaller?.has(caller)) {
39538
+ provider = interposedByCaller.get(caller);
39539
+ } else {
39540
+ if (copyImages.has(caller)) {
39541
+ provider = caller;
39542
+ } else {
39543
+ for (const image of scope2) {
39544
+ if (copyImages.has(image)) {
39545
+ provider = image;
39546
+ break;
39547
+ }
39548
+ }
39549
+ if (provider === void 0) provider = uniqueProvider;
39550
+ }
39551
+ ;
39552
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
39553
+ }
39554
+ } else {
39555
+ provider = firstProviderImage;
39556
+ }
38827
39557
  if (provider === void 0) {
38828
39558
  if (options2.weakReferences.get(object7)?.has(symbol2)) continue;
38829
39559
  throw new Error(`guest scope ${caller} omits every provider of ${symbol2}`);
38830
39560
  }
38831
39561
  if (caller === provider) continue;
38832
- if ([...options2.definitionObjects.get(symbol2) ?? []].some(
38833
- (definer) => options2.owners.get(definer) === caller && options2.weakDefinitions.get(definer)?.has(symbol2)
38834
- ))
38835
- continue;
38836
- if (!scope2.includes(provider)) {
38837
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
39562
+ if (weakDefinerImages?.has(caller)) continue;
39563
+ if (!callerSets.get(caller).has(provider)) {
38838
39564
  const traced = [...record4.providers.keys()];
38839
39565
  const strongTraced = traced.filter(
38840
39566
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
@@ -38842,16 +39568,17 @@ function verifyGuestSymbolScopes(options2) {
38842
39568
  const providers = strongTraced.length === 1 ? strongTraced : traced;
38843
39569
  if (options2.weakReferences.get(object7)?.has(symbol2) && !providers.some((provider2) => options2.systemProviders.has(provider2)))
38844
39570
  continue;
38845
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
39571
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
39572
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
38846
39573
  (definer) => options2.weakDefinitions.get(definer)?.has(symbol2)
38847
39574
  );
38848
- const strongCandidates = [...candidates].filter(
39575
+ const strongCandidates = [...candidateSet].filter(
38849
39576
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
38850
39577
  );
38851
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
38852
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
39578
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
39579
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
38853
39580
  // scope, the root image and its dependency closure, as in elf.
38854
- provider === 0 || callers.get(0)?.includes(provider) || !options2.weakReferences.get(object7)?.has(symbol2) && options2.frameworkProviders.get(object7)?.has(providers[0]))))
39581
+ provider === 0 || rootScope?.has(provider) || !options2.weakReferences.get(object7)?.has(symbol2) && options2.frameworkProviders.get(object7)?.has(providers[0]))))
38855
39582
  throw new Error(
38856
39583
  `guest scope ${caller} omits traced provider ${provider} for ${symbol2}`
38857
39584
  );
@@ -39051,6 +39778,85 @@ function clangProducerStamp(file) {
39051
39778
  const stat = (0, import_node_fs50.statSync)(file, { bigint: true });
39052
39779
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
39053
39780
  }
39781
+ function clangBinaryStamp(file) {
39782
+ const stat = (0, import_node_fs50.statSync)(file, { bigint: true });
39783
+ return [file, stat.size, stat.mtimeNs].join(":");
39784
+ }
39785
+ function clangWrapperStamp(file) {
39786
+ return (0, import_node_crypto31.createHash)("sha256").update((0, import_node_fs50.readFileSync)(file)).digest("hex");
39787
+ }
39788
+ function clangArgsNeedCwd(args) {
39789
+ const pathFlags = /* @__PURE__ */ new Set([
39790
+ "-I",
39791
+ "-isystem",
39792
+ "-iquote",
39793
+ "-F",
39794
+ "-iframework",
39795
+ "-isysroot",
39796
+ "-o",
39797
+ "-MF"
39798
+ ]);
39799
+ const includeFlags = /* @__PURE__ */ new Set(["-include", "-imacros"]);
39800
+ const valueFlags = /* @__PURE__ */ new Set([
39801
+ "-x",
39802
+ "-target",
39803
+ "-MT",
39804
+ "-MQ",
39805
+ "-D",
39806
+ "-U",
39807
+ "-mllvm",
39808
+ "-Xclang",
39809
+ "-arch",
39810
+ "-std"
39811
+ ]);
39812
+ const prefixFlags = [
39813
+ "-I",
39814
+ "-F",
39815
+ "-isystem",
39816
+ "-iquote",
39817
+ "--sysroot=",
39818
+ "-fmodule-map-file=",
39819
+ "-fmodules-cache-path="
39820
+ ];
39821
+ const isRelativePath = (value) => value.length > 0 && !value.startsWith("/") && !value.startsWith("=/") && value !== "-";
39822
+ for (let i = 1; i < args.length; i++) {
39823
+ const arg = args[i];
39824
+ if (pathFlags.has(arg)) {
39825
+ if (isRelativePath(args[++i] ?? "")) return true;
39826
+ continue;
39827
+ }
39828
+ if (includeFlags.has(arg)) {
39829
+ const value = args[++i] ?? "";
39830
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs50.existsSync)(value))) return true;
39831
+ continue;
39832
+ }
39833
+ if (valueFlags.has(arg)) {
39834
+ i++;
39835
+ continue;
39836
+ }
39837
+ if (arg.startsWith("@")) {
39838
+ if (isRelativePath(arg.slice(1))) return true;
39839
+ continue;
39840
+ }
39841
+ if (arg.startsWith("-")) {
39842
+ if (arg.startsWith("-include") && arg.length > 8) {
39843
+ const value = arg.slice(8);
39844
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs50.existsSync)(value)))
39845
+ return true;
39846
+ continue;
39847
+ }
39848
+ for (const prefix of prefixFlags) {
39849
+ if (arg.startsWith(prefix) && arg.length > prefix.length) {
39850
+ if (isRelativePath(arg.slice(prefix.length))) return true;
39851
+ break;
39852
+ }
39853
+ }
39854
+ continue;
39855
+ }
39856
+ if (isRelativePath(arg)) return true;
39857
+ }
39858
+ return false;
39859
+ }
39054
39860
  function validateClangLinkOptions(flags) {
39055
39861
  for (let index = 0; index < flags.length; index++) {
39056
39862
  const flag = flags[index];
@@ -39130,7 +39936,7 @@ function sourceGuestClangLinkOptions(options2) {
39130
39936
  let clang;
39131
39937
  let clangStamp;
39132
39938
  let wrapperStamp;
39133
- for (const [index, file] of [...wanted].entries()) {
39939
+ for (const file of wanted) {
39134
39940
  const command = commands.get(file);
39135
39941
  if (!command) throw new Error(`missing source object producer ${file}`);
39136
39942
  if (command.tool === "shell") {
@@ -39144,12 +39950,12 @@ function sourceGuestClangLinkOptions(options2) {
39144
39950
  throw new Error(`unsupported source object producer ${file}`);
39145
39951
  const key2 = (0, import_node_crypto31.createHash)("sha256").update(
39146
39952
  JSON.stringify([
39147
- "clang-link-options/v1",
39148
- process.cwd(),
39953
+ "clang-link-options/v2",
39954
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
39149
39955
  driverEnvironment,
39150
39956
  command.args,
39151
- clangStamp ??= clangProducerStamp(clang),
39152
- compiler === clang ? null : wrapperStamp ??= clangProducerStamp(compiler),
39957
+ clangStamp ??= clangBinaryStamp(clang),
39958
+ compiler === clang ? null : wrapperStamp ??= clangWrapperStamp(compiler),
39153
39959
  clangProducerStamp(file)
39154
39960
  ])
39155
39961
  ).digest("hex");
@@ -39164,31 +39970,44 @@ function sourceGuestClangLinkOptions(options2) {
39164
39970
  continue;
39165
39971
  }
39166
39972
  result.set(file, []);
39167
- const args = command.args.slice(1).filter((arg) => arg !== "-c");
39168
39973
  const targetBuild = import_node_path48.default.relative(options2.buildDirectory, file).split(import_node_path48.default.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
39169
- const outputDirectory = import_node_path48.default.join(
39170
- options2.directory,
39171
- targetBuild ?? import_node_path48.default.basename(import_node_path48.default.dirname(file))
39172
- );
39173
- (0, import_node_fs50.mkdirSync)(outputDirectory, { recursive: true });
39174
- const output = import_node_path48.default.join(outputDirectory, `clang-link-${index}.ll`);
39175
- for (const flag of ["-o", "-MF"]) {
39176
- const index2 = args.lastIndexOf(flag);
39177
- if (index2 < 0 || index2 + 1 >= args.length)
39178
- throw new Error(`missing clang ${flag} for ${file}`);
39179
- args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
39974
+ const args = [];
39975
+ let sawOutput = false;
39976
+ let explicitModuleName = false;
39977
+ for (let i = 1; i < command.args.length; i++) {
39978
+ const arg = command.args[i];
39979
+ if (arg === "-c" || arg === "-MD" || arg === "-MMD" || arg === "-MP") continue;
39980
+ if (arg === "-MF" || arg === "-MT" || arg === "-MQ") {
39981
+ if (i + 1 >= command.args.length)
39982
+ throw new Error(`missing clang ${arg} for ${file}`);
39983
+ i++;
39984
+ continue;
39985
+ }
39986
+ if (arg === "-o") {
39987
+ if (i + 1 >= command.args.length) throw new Error(`missing clang -o for ${file}`);
39988
+ i++;
39989
+ args.push("-o", "-");
39990
+ sawOutput = true;
39991
+ continue;
39992
+ }
39993
+ if (arg.startsWith("-fmodule-name=")) explicitModuleName = true;
39994
+ args.push(arg);
39995
+ }
39996
+ if (!sawOutput) throw new Error(`missing clang -o for ${file}`);
39997
+ if (compiler !== clang && targetBuild && !explicitModuleName) {
39998
+ args.unshift(`-fmodule-name=${targetBuild.slice(0, -".build".length)}`);
39180
39999
  }
39181
40000
  replays.push({
39182
40001
  file,
39183
40002
  compiler: command.args[0],
39184
40003
  args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
39185
- output,
39186
40004
  cacheFile,
39187
40005
  key: key2
39188
40006
  });
39189
40007
  }
39190
40008
  if (replays.length === 0) return result;
39191
40009
  const plan = import_node_path48.default.join(options2.directory, "clang-link-replays.json");
40010
+ const resultsPath = import_node_path48.default.join(options2.directory, "clang-link-results.json");
39192
40011
  (0, import_node_fs50.writeFileSync)(
39193
40012
  plan,
39194
40013
  JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
@@ -39201,12 +40020,16 @@ function sourceGuestClangLinkOptions(options2) {
39201
40020
  ...process.env,
39202
40021
  [PEACH_FORKED_SCRIPT_ENV]: "1",
39203
40022
  PEACH_CLANG_REPLAYS: plan,
40023
+ PEACH_CLANG_RESULTS: resultsPath,
39204
40024
  PEACH_CLANG_JOBS: String(options2.jobs)
39205
40025
  }
39206
40026
  });
40027
+ const replayMetadata = JSON.parse((0, import_node_fs50.readFileSync)(resultsPath, "utf8"));
40028
+ if (!Array.isArray(replayMetadata) || replayMetadata.length !== replays.length || !replayMetadata.every((item) => typeof item === "string"))
40029
+ throw new Error("invalid clang link replay results");
39207
40030
  (0, import_node_fs50.mkdirSync)(cacheDirectory, { recursive: true });
39208
- for (const { file, output, cacheFile, key: key2 } of replays) {
39209
- const flags = clangIrLinkOptions((0, import_node_fs50.readFileSync)(output, "utf8"));
40031
+ for (const [index, { file, cacheFile, key: key2 }] of replays.entries()) {
40032
+ const flags = clangIrLinkOptions(replayMetadata[index]);
39210
40033
  validateClangLinkOptions(flags);
39211
40034
  const temporary = `${cacheFile}.${process.pid}`;
39212
40035
  (0, import_node_fs50.writeFileSync)(temporary, JSON.stringify({ key: key2, flags }));
@@ -39444,22 +40267,47 @@ var init_swift_guest_source_inputs = __esm({
39444
40267
  CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
39445
40268
  PARALLEL_REPLAY = `
39446
40269
  const { spawn } = require('node:child_process')
39447
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
40270
+ const fs = require('node:fs')
40271
+ const commands = JSON.parse(fs.readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
40272
+ const results = new Array(commands.length)
39448
40273
  let next = 0
39449
40274
  const run = () => {
39450
40275
  if (next >= commands.length) return Promise.resolve()
39451
- const [file, ...args] = commands[next++]
40276
+ const index = next++
40277
+ const [file, ...args] = commands[index]
39452
40278
  return new Promise((resolve, reject) => {
39453
- const child = spawn(file, args, { stdio: 'inherit' })
40279
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'inherit'] })
40280
+ const metadata = []
40281
+ let pending = ''
40282
+ child.stdout.setEncoding('utf8')
40283
+ child.stdout.on('data', (chunk) => {
40284
+ const text = pending + chunk
40285
+ let start = 0
40286
+ for (let nl = text.indexOf('\\n'); nl !== -1; nl = text.indexOf('\\n', start)) {
40287
+ if (text.charCodeAt(start) === 33) metadata.push(text.slice(start, nl))
40288
+ start = nl + 1
40289
+ }
40290
+ pending = text.slice(start)
40291
+ })
39454
40292
  child.on('error', reject)
39455
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
40293
+ child.on('close', (code) => {
40294
+ if (pending.charCodeAt(0) === 33) metadata.push(pending)
40295
+ if (code === 0) {
40296
+ results[index] = metadata.join('\\n')
40297
+ resolve()
40298
+ } else reject(new Error('clang link replay failed: ' + file))
40299
+ })
39456
40300
  }).then(run)
39457
40301
  }
39458
40302
  const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
39459
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
39460
- console.error(error.message)
39461
- process.exit(1)
39462
- })
40303
+ Promise.all(Array.from({ length: jobs }, run))
40304
+ .then(() => {
40305
+ fs.writeFileSync(process.env.PEACH_CLANG_RESULTS, JSON.stringify(results))
40306
+ })
40307
+ .catch((error) => {
40308
+ console.error(error.message)
40309
+ process.exit(1)
40310
+ })
39463
40311
  `;
39464
40312
  }
39465
40313
  });
@@ -43020,6 +43868,7 @@ __export(swift_sdk_app_module_exports, {
43020
43868
  readSwiftSdkUsage: () => readSwiftSdkUsage,
43021
43869
  selectSwiftSdkData: () => selectSwiftSdkData,
43022
43870
  swiftAppModuleInputs: () => swiftAppModuleInputs,
43871
+ swiftSdkProjectionSpans: () => swiftSdkProjectionSpans,
43023
43872
  writeSwiftSdkAppLink: () => writeSwiftSdkAppLink
43024
43873
  });
43025
43874
  async function buildSwiftAppModule(options2) {
@@ -43135,15 +43984,18 @@ async function compileSdkForwarders(inputs2, sdk2, toolchainBin, output, project
43135
43984
  index++;
43136
43985
  }
43137
43986
  const errno = tls.errno;
43987
+ let declaredErrno = false;
43138
43988
  for (const name3 of referenced) {
43139
43989
  const offset = tls[name3];
43140
43990
  if (offset === void 0 || defined.has(name3)) continue;
43141
43991
  if (errno === void 0 || signatures.__errno_location !== ":j")
43142
43992
  throw new Error("the sdk image has no errno to find its thread block by");
43143
- if (!lines.some((line) => line.startsWith("char *__peach_errno(")))
43993
+ if (!declaredErrno) {
43994
+ declaredErrno = true;
43144
43995
  lines.push(
43145
43996
  `__attribute__((import_module("env"), import_name("__errno_location"))) char *__peach_errno(void);`
43146
43997
  );
43998
+ }
43147
43999
  lines.push(
43148
44000
  `__attribute__((weak)) _Thread_local char t${index} __asm__(${literal2(name3)});`,
43149
44001
  `__attribute__((used)) long long h${index}(void) __asm__(${literal2(SDK_TLS_HELPER + name3)});`,
@@ -43519,6 +44371,20 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43519
44371
  symbols.filter((symbol2) => symbol2.kind === 0 && symbol2.name.startsWith(SDK_TLS_HELPER)).map((symbol2) => [symbol2.name.slice(SDK_TLS_HELPER.length), symbol2.index])
43520
44372
  );
43521
44373
  const segments = guestWasmDataSegments(bytes, false);
44374
+ const segmentsByOffset = [...segments].sort((a, b) => a.offset - b.offset);
44375
+ const segmentNameSet = new Set(segmentNames);
44376
+ const findSegmentByOffset = (at, size2) => {
44377
+ let lo = 0;
44378
+ let hi = segmentsByOffset.length - 1;
44379
+ while (lo <= hi) {
44380
+ const mid = lo + hi >> 1;
44381
+ const entry = segmentsByOffset[mid];
44382
+ if (at < entry.offset) hi = mid - 1;
44383
+ else if (at >= entry.offset + entry.length) lo = mid + 1;
44384
+ else return at + size2 <= entry.offset + entry.length ? entry : void 0;
44385
+ }
44386
+ return void 0;
44387
+ };
43522
44388
  const tdata = segmentNames.indexOf(".tdata");
43523
44389
  const tlsTemplate = tdata < 0 ? void 0 : passiveSegments(bytes)[tdata];
43524
44390
  const tlsStart = tlsTemplate && tlsTemplate.byteOffset - bytes.byteOffset;
@@ -43583,7 +44449,7 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43583
44449
  const encoding = width.width;
43584
44450
  if (kind === "address" && target.id === 11 && encoding === "u64" && addend === 0n) {
43585
44451
  const section2 = OBJC_SECTION_BOUNDARY.exec(name3)?.[1];
43586
- if (section2 && !segmentNames.includes(section2)) {
44452
+ if (section2 && !segmentNameSet.has(section2)) {
43587
44453
  bytes.fill(0, at, at + 8);
43588
44454
  continue;
43589
44455
  }
@@ -43595,9 +44461,7 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43595
44461
  if (tlsStart !== void 0 && at >= tlsStart && at < tlsStart + tlsTemplate.length)
43596
44462
  linkage.tls.push(at - tlsStart, size2, value);
43597
44463
  else {
43598
- const segment2 = segments.find(
43599
- (entry) => at >= entry.offset && at + size2 <= entry.offset + entry.length
43600
- );
44464
+ const segment2 = findSegmentByOffset(at, size2);
43601
44465
  if (!segment2)
43602
44466
  throw new Error(`Swift SDK relocation has no load address for ${name3}`);
43603
44467
  linkage.data.push(segment2.address + at - segment2.offset, size2, value);
@@ -43641,15 +44505,29 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43641
44505
  }
43642
44506
  }
43643
44507
  }
43644
- const entries2 = imports2.map((entry) => {
44508
+ const encodedNameBuf = (name3) => {
44509
+ const raw2 = Buffer.from(name3, "utf8");
44510
+ const len = uleb4(raw2.length);
44511
+ const out = Buffer.allocUnsafe(len.length + raw2.length);
44512
+ for (let i = 0; i < len.length; i++) out[i] = len[i];
44513
+ raw2.copy(out, len.length);
44514
+ return out;
44515
+ };
44516
+ const importParts = [];
44517
+ let importEntryCount = imports2.length + 1;
44518
+ for (const entry of imports2) {
43645
44519
  const slot = entry.kind === 0 && entry.module === "env" ? functionSlots.get(entry.name) : void 0;
43646
- return [
43647
- ...encodedName2(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
43648
- ...encodedName2(slot === void 0 ? entry.name : String(slot)),
43649
- ...bytes.subarray(entry.start, entry.end)
43650
- ];
43651
- });
43652
- entries2.push([...encodedName2("env"), ...encodedName2("__stack_pointer"), 3, 126, 1]);
44520
+ importParts.push(
44521
+ encodedNameBuf(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
44522
+ encodedNameBuf(slot === void 0 ? entry.name : String(slot)),
44523
+ bytes.subarray(entry.start, entry.end)
44524
+ );
44525
+ }
44526
+ importParts.push(
44527
+ encodedNameBuf("env"),
44528
+ encodedNameBuf("__stack_pointer"),
44529
+ Buffer.from([3, 126, 1])
44530
+ );
43653
44531
  const tags = sections.find((section2) => section2.id === 13);
43654
44532
  if (tags) {
43655
44533
  const r = wasmReader(bytes, tags.start);
@@ -43664,15 +44542,18 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43664
44542
  throw new Error(
43665
44543
  `Swift app defines an exception tag the sdk does not own: ${name3}`
43666
44544
  );
43667
- entries2.push([
43668
- ...encodedName2("env"),
43669
- ...encodedName2(name3),
43670
- 4,
43671
- ...bytes.subarray(start, r.at)
43672
- ]);
44545
+ importParts.push(
44546
+ encodedNameBuf("env"),
44547
+ encodedNameBuf(name3),
44548
+ Buffer.from([4]),
44549
+ bytes.subarray(start, r.at)
44550
+ );
44551
+ importEntryCount++;
43673
44552
  }
43674
44553
  }
43675
- const globals = [];
44554
+ const globalParts = [
44555
+ Buffer.from(uleb4(globalCount - 1 + syntheticGlobals.length))
44556
+ ];
43676
44557
  for (let index = 0; index < globalCount; index++) {
43677
44558
  const start = gr.at;
43678
44559
  const type = gr.byte();
@@ -43684,12 +44565,12 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43684
44565
  if (gr.byte() !== 11) throw new Error("app global initializer has no end");
43685
44566
  if (index === 0) continue;
43686
44567
  const value = got.get(index);
43687
- if (value === void 0) globals.push(...bytes.subarray(start, gr.at));
43688
- else globals.push(type, 1, type === 126 ? 66 : 65, 0, 11);
44568
+ if (value === void 0) globalParts.push(bytes.subarray(start, gr.at));
44569
+ else globalParts.push(Buffer.from([type, 1, type === 126 ? 66 : 65, 0, 11]));
43689
44570
  }
43690
44571
  for (const type of syntheticGlobals) {
43691
44572
  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];
43692
- globals.push(type, 1, ...zero, 11);
44573
+ globalParts.push(Buffer.from([type, 1, ...zero, 11]));
43693
44574
  }
43694
44575
  const exportSection = sections.find((s) => s.id === 7);
43695
44576
  if (!exportSection) throw new Error("app link has no exports");
@@ -43712,24 +44593,21 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43712
44593
  throw new Error("Swift app exceeds its reserved static memory range");
43713
44594
  }
43714
44595
  }
44596
+ const exportParts = [
44597
+ Buffer.from(uleb4(exportCount + 1 + got.size)),
44598
+ bytes.subarray(originalExportsStart, exportSection.end)
44599
+ ];
44600
+ for (const [index, value] of got) {
44601
+ exportParts.push(
44602
+ encodedNameBuf(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
44603
+ Buffer.from([3, ...uleb4(index)])
44604
+ );
44605
+ }
44606
+ exportParts.push(encodedNameBuf("__indirect_function_table"), Buffer.from([1, 0]));
43715
44607
  const replaced = /* @__PURE__ */ new Map([
43716
- [2, [...uleb4(entries2.length), ...entries2.flat()]],
43717
- [6, [...uleb4(globalCount - 1 + syntheticGlobals.length), ...globals]],
43718
- [
43719
- 7,
43720
- [
43721
- ...uleb4(exportCount + 1 + got.size),
43722
- ...bytes.subarray(originalExportsStart, exportSection.end),
43723
- ...[...got].flatMap(([index, value]) => [
43724
- ...encodedName2(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
43725
- 3,
43726
- ...uleb4(index)
43727
- ]),
43728
- ...encodedName2("__indirect_function_table"),
43729
- 1,
43730
- 0
43731
- ]
43732
- ]
44608
+ [2, Buffer.concat([Buffer.from(uleb4(importEntryCount)), ...importParts])],
44609
+ [6, Buffer.concat(globalParts)],
44610
+ [7, Buffer.concat(exportParts)]
43733
44611
  ]);
43734
44612
  const rebuiltCode = expanded.length ? expandSdkRelocations(
43735
44613
  bytes,
@@ -43741,9 +44619,13 @@ function resolveSdkReferences(source, sdk2, forwarders) {
43741
44619
  if (s === tags || s.name === "linking" || s.name?.startsWith("reloc.") || s.name === ".swift1_autolink_entries")
43742
44620
  continue;
43743
44621
  const payload = replaced.get(s.id);
43744
- parts.push(
43745
- s.id === 10 && rebuiltCode ? rebuiltCode : payload ? Uint8Array.from([s.id, ...uleb4(payload.length), ...payload]) : bytes.subarray(s.offset, s.end)
43746
- );
44622
+ if (s.id === 10 && rebuiltCode) {
44623
+ parts.push(rebuiltCode);
44624
+ } else if (payload) {
44625
+ parts.push(Buffer.from([s.id, ...uleb4(payload.length)]), payload);
44626
+ } else {
44627
+ parts.push(bytes.subarray(s.offset, s.end));
44628
+ }
43747
44629
  }
43748
44630
  return { bytes: Buffer.concat(parts), linkage };
43749
44631
  }
@@ -43841,6 +44723,49 @@ function readSwiftSdkUsage(mapFile, linkedFile, sdkObjects) {
43841
44723
  constructors: [...new Set(constructorKeys(map2, (0, import_node_fs59.readFileSync)(linkedFile)))]
43842
44724
  };
43843
44725
  }
44726
+ function swiftSdkProjectionSpans(sdk2, imageFor) {
44727
+ const { manifest, block: block2 } = readSwiftSdkManifest(sdk2);
44728
+ const guestObjects = manifest.guestObjects;
44729
+ if (!guestObjects) return [];
44730
+ const { strings: strings5 } = manifest;
44731
+ const fields = block2("pieces");
44732
+ const ordered = [];
44733
+ for (let i = 0; i < fields.length; i += SWIFT_SDK_PIECE_FIELDS) {
44734
+ const size2 = fields[i + 1];
44735
+ if (!size2) continue;
44736
+ ordered.push({
44737
+ address: fields[i],
44738
+ size: size2,
44739
+ object: strings5[fields[i + 3]]
44740
+ });
44741
+ }
44742
+ ordered.sort((a, b) => a.address - b.address);
44743
+ const imageOf = (object7) => {
44744
+ const product = guestObjects[object7]?.product;
44745
+ return product === void 0 ? void 0 : imageFor(object7, product);
44746
+ };
44747
+ const spans = [];
44748
+ for (let index = 0; index < ordered.length; index++) {
44749
+ const { object: object7, address, size: size2 } = ordered[index];
44750
+ const image = imageOf(object7);
44751
+ if (image === void 0) continue;
44752
+ let next = index + 1;
44753
+ while (next < ordered.length && ordered[next].address < address + size2) next++;
44754
+ const end = ordered[next]?.address ?? address + size2;
44755
+ spans.push({ image, space: "linear-memory", address, length: end - address });
44756
+ }
44757
+ const functionKeys = block2("functions");
44758
+ const slots = block2("functionSlots");
44759
+ for (let index = 0; index < functionKeys.length; index++) {
44760
+ const slot = slots[index];
44761
+ if (!slot) continue;
44762
+ const key2 = strings5[functionKeys[index]];
44763
+ const image = imageOf(key2.slice(0, key2.indexOf(":")));
44764
+ if (image !== void 0)
44765
+ spans.push({ image, space: "function-table", address: slot, length: 1 });
44766
+ }
44767
+ return spans;
44768
+ }
43844
44769
  function selectSwiftSdkData(sdk2, usage, linkage, projection) {
43845
44770
  const { manifest, block: block2, segments } = readSwiftSdkManifest(sdk2);
43846
44771
  const { strings: strings5 } = manifest;
@@ -43863,15 +44788,24 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
43863
44788
  });
43864
44789
  }
43865
44790
  const memory = new Map(segments.map((segment2) => [segment2.name, segment2]));
43866
- const read = (address2, size2) => {
44791
+ let lastSegment = segments[0];
44792
+ const segmentAt = (address2, size2) => {
44793
+ if (lastSegment && address2 >= lastSegment.address && address2 + size2 <= lastSegment.address + lastSegment.data.length)
44794
+ return lastSegment;
43867
44795
  for (const segment2 of segments)
43868
- if (address2 >= segment2.address && address2 + size2 <= segment2.address + segment2.data.length)
43869
- return segment2.data.subarray(
43870
- address2 - segment2.address,
43871
- address2 - segment2.address + size2
43872
- );
44796
+ if (address2 >= segment2.address && address2 + size2 <= segment2.address + segment2.data.length) {
44797
+ lastSegment = segment2;
44798
+ return segment2;
44799
+ }
43873
44800
  return void 0;
43874
44801
  };
44802
+ const read = (address2, size2) => {
44803
+ const segment2 = segmentAt(address2, size2);
44804
+ return segment2?.data.subarray(
44805
+ address2 - segment2.address,
44806
+ address2 - segment2.address + size2
44807
+ );
44808
+ };
43875
44809
  const appSectionsByObject = /* @__PURE__ */ new Map();
43876
44810
  const appSections = /* @__PURE__ */ new Set();
43877
44811
  const appSymbols = /* @__PURE__ */ new Set();
@@ -43977,9 +44911,7 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
43977
44911
  const classAddress = Number(
43978
44912
  new DataView(field.buffer, field.byteOffset, 8).getBigUint64(0, true)
43979
44913
  );
43980
- const segment2 = segments.find(
43981
- ({ address: address3, data }) => classAddress >= address3 && classAddress < address3 + data.length
43982
- );
44914
+ const segment2 = segmentAt(classAddress, 1);
43983
44915
  if (!segment2) continue;
43984
44916
  const start = classAddress - segment2.address;
43985
44917
  const end = segment2.data.indexOf(0, start);
@@ -44187,7 +45119,7 @@ function selectSwiftSdkData(sdk2, usage, linkage, projection) {
44187
45119
  if (current2)
44188
45120
  runs.push({
44189
45121
  address: current2.address,
44190
- bytes: Uint8Array.from(Buffer.concat(current2.parts))
45122
+ bytes: Buffer.concat(current2.parts)
44191
45123
  });
44192
45124
  };
44193
45125
  for (const piece of loaded3) {
@@ -44605,13 +45537,19 @@ async function compileGuestLink(options2) {
44605
45537
  const selectedSource = source.artifacts.filter(
44606
45538
  (artifact) => selected.has(import_node_path58.default.resolve(rewritten.get(artifact.path) ?? artifact.path))
44607
45539
  );
45540
+ const admittedCores = Number(process.env.TM_EXEC_CPU_CORES);
45541
+ const linuxMemory = process.env.TM_EXEC_ADMITTED === "1" && process.env.LINUX_BUILD_SCOPE ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX) : NaN;
45542
+ const clangReplayJobs = Number.isInteger(admittedCores) && admittedCores > 0 ? Math.min(
45543
+ admittedCores,
45544
+ Number.isSafeInteger(linuxMemory) && linuxMemory > 0 ? Math.max(options2.jobs, Math.floor(linuxMemory / (512 * 1024 ** 2))) : Math.max(options2.jobs, admittedCores)
45545
+ ) : options2.jobs;
44608
45546
  const clangOptions2 = sourceGuestClangLinkOptions({
44609
45547
  buildDirectory: options2.buildDirectory,
44610
45548
  directory: directory2,
44611
45549
  toolchainBin: options2.toolchainBin,
44612
45550
  swiftCompiler: options2.swiftCompiler,
44613
45551
  objects: selectedSource.map((artifact) => artifact.path),
44614
- jobs: options2.jobs
45552
+ jobs: clangReplayJobs
44615
45553
  });
44616
45554
  const links = sourceGuestRuntimeLinks({
44617
45555
  toolchainBin: options2.toolchainBin,
@@ -44713,9 +45651,9 @@ async function compileGuestLink(options2) {
44713
45651
  }
44714
45652
  };
44715
45653
  },
44716
- resolvePlan: (selected, plan) => {
45654
+ resolvePlan: (selected, plan, readSelected) => {
44717
45655
  if (!prepared) throw new Error("guest runtime selection is unavailable");
44718
- const scope2 = selectedGuestSymbolInputs(plan, selected);
45656
+ const scope2 = selectedGuestSymbolInputs(plan, selected, readSelected);
44719
45657
  const owners = new Map(scope2.owners);
44720
45658
  owners.set(import_node_path58.default.join(directory2, "projection-discovery.o"), 0);
44721
45659
  const providersByImage = Map.groupBy(scope2.owners, ([, image]) => image);
@@ -44793,7 +45731,8 @@ async function compileGuestLink(options2) {
44793
45731
  createSwiftSdkBinding: createSwiftSdkBinding2,
44794
45732
  finishSwiftAppModule: finishSwiftAppModule2,
44795
45733
  linkSwiftAppModule: linkSwiftAppModule2,
44796
- readSwiftSdkUsage: readSwiftSdkUsage2
45734
+ readSwiftSdkUsage: readSwiftSdkUsage2,
45735
+ swiftSdkProjectionSpans: swiftSdkProjectionSpans2
44797
45736
  } = await Promise.resolve().then(() => (init_swift_sdk_app_module(), swift_sdk_app_module_exports));
44798
45737
  const project = options2.project;
44799
45738
  const work = project ? (0, import_node_fs60.mkdtempSync)(import_node_path58.default.join(directory2, "app-module-")) : import_node_path58.default.join(directory2, "app-module");
@@ -44815,7 +45754,28 @@ async function compileGuestLink(options2) {
44815
45754
  }
44816
45755
  const usage = readSwiftSdkUsage2(result.mapPath, options2.output, sdkObjectKeys);
44817
45756
  const linkedModule = import_node_path58.default.join(work, "app.wasm");
45757
+ const sdkSpans = swiftSdkProjectionSpans2(
45758
+ sdk2,
45759
+ (object7, product) => sdkObjectImages.get(object7) ?? sdkProductImages.get(product)
45760
+ );
44818
45761
  let storage = reserved2;
45762
+ if (sdkSpans.length > 0) {
45763
+ const sdkCounts = guestProjectionRegionCounts(storage.images.length, sdkSpans);
45764
+ storage = reserveGuestProjectionStorage(
45765
+ storage.images,
45766
+ storage.capacities.map((capacity, index) => ({
45767
+ ...capacity,
45768
+ regions: capacity.regions + sdkCounts[index] + 16
45769
+ }))
45770
+ );
45771
+ const projectionSource = import_node_path58.default.join(work, "projection.c");
45772
+ (0, import_node_fs60.writeFileSync)(projectionSource, storage.source);
45773
+ (0, import_node_child_process33.execFileSync)(
45774
+ import_node_path58.default.join(options2.toolchainBin, "clang"),
45775
+ [...clangOptions, "-c", projectionSource, "-o", projectionObject],
45776
+ { stdio: "pipe" }
45777
+ );
45778
+ }
44819
45779
  for (; ; ) {
44820
45780
  const link = await linkSwiftAppModule2({
44821
45781
  objects: [...owners.keys()],
@@ -44853,11 +45813,7 @@ async function compileGuestLink(options2) {
44853
45813
  bindingRows.set((address - values.address) / 8, value);
44854
45814
  } else data.push(address, size2, value);
44855
45815
  }
44856
- const sdkSpans = [];
44857
- const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk2, usage, {
44858
- imageFor: (object7, product) => sdkObjectImages.get(object7) ?? sdkProductImages.get(product),
44859
- spans: sdkSpans
44860
- });
45816
+ const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk2, usage);
44861
45817
  const linked = (0, import_node_fs60.readFileSync)(
44862
45818
  project ? projectOutputFile(work, linkedModule, project) : linkedModule
44863
45819
  );
@@ -52394,7 +53350,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
52394
53350
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
52395
53351
  MULTI_MANIFEST_VERSION = 76;
52396
53352
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
52397
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
53353
+ compilerSourceDigest = true ? "d4cf22b53d08266bf9bd0238bffe899805f62daeb3d628664ee351830e496cda" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
52398
53354
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
52399
53355
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
52400
53356
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));