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;
@@ -6192,24 +6192,56 @@ function layout(bytes, readData = true, requireExports = true) {
6192
6192
  const code = sections.get(10);
6193
6193
  if (code) {
6194
6194
  let pos = code[0];
6195
- let count;
6196
- [count, pos] = number(bytes, pos);
6195
+ const codeStart = code[0];
6196
+ const codeEnd = code[1];
6197
+ let count = 0;
6198
+ {
6199
+ let shift = 0;
6200
+ for (; ; ) {
6201
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
6202
+ const byte = bytes[pos++];
6203
+ count += (byte & 127) * 2 ** shift;
6204
+ if (!(byte & 128)) break;
6205
+ shift += 7;
6206
+ }
6207
+ }
6197
6208
  for (let i = 0; i < count; i++) {
6198
6209
  const prefix = pos;
6199
- let size;
6200
- [size, pos] = number(bytes, pos);
6201
- functionsByCodeOffset.set(prefix - code[0], imports + i);
6210
+ let size = 0;
6211
+ const b0 = bytes[pos++];
6212
+ if (b0 < 128) {
6213
+ size = b0;
6214
+ } else {
6215
+ size = b0 & 127;
6216
+ let shift = 7;
6217
+ for (; ; ) {
6218
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
6219
+ const byte = bytes[pos++];
6220
+ size += (byte & 127) * 2 ** shift;
6221
+ if (!(byte & 128)) break;
6222
+ shift += 7;
6223
+ }
6224
+ }
6225
+ functionsByCodeOffset.set(prefix - codeStart, imports + i);
6202
6226
  if (imports + i === startFunction) startup = bytes.subarray(pos, pos + size);
6203
6227
  pos += size;
6204
- if (pos > code[1]) throw new Error("invalid wasm code");
6228
+ if (pos > codeEnd) throw new Error("invalid wasm code");
6205
6229
  }
6206
- if (pos !== code[1]) throw new Error("invalid wasm code section");
6230
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
6207
6231
  }
6208
6232
  const functionsByTableSlot = /* @__PURE__ */ new Map();
6209
6233
  const elements = sections.get(9);
6210
6234
  if (elements) {
6211
6235
  let pos = elements[0];
6236
+ const elemEnd = elements[1];
6212
6237
  const read = () => {
6238
+ if (pos < elemEnd) {
6239
+ const b0 = bytes[pos];
6240
+ if (b0 < 128) {
6241
+ pos++;
6242
+ return b0;
6243
+ }
6244
+ }
6213
6245
  const [value, next] = number(bytes, pos);
6214
6246
  pos = next;
6215
6247
  return value;
@@ -6239,7 +6271,7 @@ function layout(bytes, readData = true, requireExports = true) {
6239
6271
  functionsByTableSlot.set(slot, read());
6240
6272
  }
6241
6273
  }
6242
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
6274
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
6243
6275
  }
6244
6276
  const data = [];
6245
6277
  const passive = /* @__PURE__ */ new Map();
@@ -6304,36 +6336,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
6304
6336
  length: segment.bytes.length
6305
6337
  }));
6306
6338
  }
6307
- function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
6339
+ function isMapSpace(code) {
6340
+ return code === 32 || code >= 9 && code <= 13;
6341
+ }
6342
+ function isMapHex(code) {
6343
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
6344
+ }
6345
+ function mapHexDigit(code) {
6346
+ return code <= 57 ? code - 48 : code - 87;
6347
+ }
6348
+ function* stringLines(text2) {
6349
+ let start = 0;
6350
+ for (let end = text2.indexOf("\n"); end !== -1; end = text2.indexOf("\n", start)) {
6351
+ yield text2.slice(start, end);
6352
+ start = end + 1;
6353
+ }
6354
+ yield text2.slice(start);
6355
+ }
6356
+ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
6308
6357
  const unchanged = before === after;
6309
6358
  const original = layout(before, !unchanged, !importsLayout);
6310
6359
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
6360
+ const collectSymbols = extra?.collectSymbols;
6361
+ const trackedObject = extra?.trackedObject;
6362
+ const trackedObjectOwner = extra?.trackedObjectOwner;
6363
+ const trackedLinearSpans = extra?.trackedLinearSpans;
6364
+ const hasSectionOwners = sectionOwners.size > 0;
6311
6365
  let codeOffset;
6312
6366
  let outputSection = "";
6313
6367
  const codeOwners = /* @__PURE__ */ new Map();
6314
6368
  const pieces = [];
6315
- for (const line of typeof map === "string" ? map.split("\n") : map) {
6316
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
6317
- if (!match) continue;
6318
- const [, address, offset, size, indent, source] = match;
6319
- if (address === "-" && indent === " ") {
6320
- outputSection = source;
6321
- if (source === "CODE") codeOffset = parseInt(offset, 16);
6369
+ const lines = typeof map === "string" ? stringLines(map) : map;
6370
+ for (const line of lines) {
6371
+ const lineLen = line.length;
6372
+ let pos = 0;
6373
+ let onlySpaces = true;
6374
+ while (pos < lineLen) {
6375
+ const ch = line.charCodeAt(pos);
6376
+ if (!isMapSpace(ch)) break;
6377
+ if (ch !== 32) onlySpaces = false;
6378
+ pos++;
6379
+ }
6380
+ const leadingSpaces = pos;
6381
+ if (pos >= lineLen) continue;
6382
+ const addrStart = pos;
6383
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
6384
+ const addrEnd = pos;
6385
+ if (pos >= lineLen) continue;
6386
+ const s1 = pos;
6387
+ while (pos < lineLen) {
6388
+ const ch = line.charCodeAt(pos);
6389
+ if (!isMapSpace(ch)) break;
6390
+ if (ch !== 32) onlySpaces = false;
6391
+ pos++;
6392
+ }
6393
+ if (pos === s1 || pos >= lineLen) continue;
6394
+ const offStart = pos;
6395
+ let offsetVal = 0;
6396
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
6397
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
6398
+ }
6399
+ if (pos === offStart || pos >= lineLen) continue;
6400
+ const s2 = pos;
6401
+ while (pos < lineLen) {
6402
+ const ch = line.charCodeAt(pos);
6403
+ if (!isMapSpace(ch)) break;
6404
+ if (ch !== 32) onlySpaces = false;
6405
+ pos++;
6406
+ }
6407
+ if (pos === s2 || pos >= lineLen) continue;
6408
+ const sizeStart = pos;
6409
+ let sizeVal = 0;
6410
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
6411
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
6412
+ }
6413
+ if (pos === sizeStart || pos >= lineLen) continue;
6414
+ const indentStart = pos;
6415
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
6416
+ const indentLen = pos - indentStart;
6417
+ if (indentLen === 0 || pos >= lineLen) continue;
6418
+ const firstCh = line.charCodeAt(pos);
6419
+ if (isMapSpace(firstCh)) continue;
6420
+ const sourceStart = pos;
6421
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
6422
+ let symEnd = sourceStart + 1;
6423
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
6424
+ collectSymbols.add(line.slice(sourceStart, symEnd));
6425
+ }
6426
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
6427
+ if (isDash && indentLen === 1) {
6428
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
6429
+ outputSection = line.slice(sourceStart);
6430
+ if (outputSection === "CODE") codeOffset = offsetVal;
6322
6431
  continue;
6323
6432
  }
6324
- const separator = source.indexOf(":(");
6433
+ if (sizeVal === 0) continue;
6434
+ const separator = line.indexOf(":(", sourceStart);
6325
6435
  if (separator < 0) continue;
6326
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
6327
- const length = parseInt(size, 16);
6328
- if (!length) continue;
6329
- if (address !== "-") {
6330
- if (outputSection === "DATA")
6331
- pieces.push({ image, address: parseInt(address, 16), length });
6436
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
6437
+ let hasLineSep = false;
6438
+ for (let i = sourceStart; i < lineLen; i++) {
6439
+ const ch = line.charCodeAt(i);
6440
+ if (ch === 8232 || ch === 8233) {
6441
+ hasLineSep = true;
6442
+ break;
6443
+ }
6444
+ }
6445
+ if (hasLineSep) continue;
6446
+ const objectPath = line.slice(sourceStart, separator);
6447
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
6448
+ if (image === void 0) image = owners.get(objectPath);
6449
+ if (!isDash) {
6450
+ if (outputSection === "DATA") {
6451
+ let addressVal = 0;
6452
+ let allHex = true;
6453
+ for (let i = addrStart; i < addrEnd; i++) {
6454
+ const ch = line.charCodeAt(i);
6455
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
6456
+ else {
6457
+ allHex = false;
6458
+ break;
6459
+ }
6460
+ }
6461
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
6462
+ pieces.push({
6463
+ image,
6464
+ address: addressVal,
6465
+ length: sizeVal,
6466
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
6467
+ });
6468
+ }
6332
6469
  continue;
6333
6470
  }
6334
6471
  if (image === void 0 || outputSection !== "CODE") continue;
6335
6472
  if (codeOffset === void 0) throw new Error("link map has no code section");
6336
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
6473
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
6337
6474
  if (index === void 0) throw new Error("link map function has no wasm body");
6338
6475
  const existing = codeOwners.get(index);
6339
6476
  if (existing !== void 0 && existing !== image)
@@ -6342,12 +6479,23 @@ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE
6342
6479
  }
6343
6480
  pieces.sort((a, b) => a.address - b.address);
6344
6481
  const spans = [];
6345
- for (const [index, { image, address, length }] of pieces.entries()) {
6346
- if (image === void 0) continue;
6482
+ for (let index = 0; index < pieces.length; index++) {
6483
+ const piece = pieces[index];
6484
+ const { image, address, length, tracked } = piece;
6485
+ if (image === void 0 && !tracked) continue;
6347
6486
  let next = index + 1;
6348
6487
  while (next < pieces.length && pieces[next].address < address + length) next++;
6349
6488
  const end = pieces[next]?.address ?? address + length;
6350
- spans.push({ image, space: "linear-memory", address, length: end - address });
6489
+ const spanLength = end - address;
6490
+ if (image !== void 0)
6491
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
6492
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
6493
+ trackedLinearSpans.push({
6494
+ image: trackedObjectOwner,
6495
+ space: "linear-memory",
6496
+ address,
6497
+ length: spanLength
6498
+ });
6351
6499
  }
6352
6500
  const optimizedOwners = /* @__PURE__ */ new Map();
6353
6501
  const dataAt = (module2, start, length) => {
@@ -6386,7 +6534,7 @@ function guestLinkedSpans(map, before, after, owners, sectionOwners = /* @__PURE
6386
6534
  throw new Error(`optimization changed linked data at ${span.address}`);
6387
6535
  }
6388
6536
  let previous;
6389
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
6537
+ for (const span of spans) {
6390
6538
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
6391
6539
  throw new Error("linked data belongs to multiple images");
6392
6540
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -6568,6 +6716,20 @@ var init_swift_guest_linked_spans = __esm({
6568
6716
  });
6569
6717
 
6570
6718
  // src/swift-sdk-image-map.ts
6719
+ function isHexChar(code) {
6720
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
6721
+ }
6722
+ function hexDigit(code) {
6723
+ return code <= 57 ? code - 48 : code - 87;
6724
+ }
6725
+ function hasLineBreak(line, from) {
6726
+ if (line.indexOf("\r", from) >= 0) return true;
6727
+ for (let i = from; i < line.length; i++) {
6728
+ const ch = line.charCodeAt(i);
6729
+ if (ch === 8232 || ch === 8233) return true;
6730
+ }
6731
+ return false;
6732
+ }
6571
6733
  function readWasmLinkMap(file, partition) {
6572
6734
  const segments = /* @__PURE__ */ new Map();
6573
6735
  const data = [];
@@ -6575,48 +6737,117 @@ function readWasmLinkMap(file, partition) {
6575
6737
  let kind = "";
6576
6738
  let segment = "";
6577
6739
  let previous;
6578
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
6579
6740
  for (const line of guestLinkLines(file)) {
6580
- const symbol = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
6581
- if (symbol) {
6582
- previous?.symbols.push({
6583
- name: symbol[3],
6584
- address: hex(symbol[1]),
6585
- size: parseInt(symbol[2], 16)
6586
- });
6741
+ const length = line.length;
6742
+ let pos = 0;
6743
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6744
+ if (pos >= length) continue;
6745
+ const leadingSpaces = pos;
6746
+ let address = -1;
6747
+ if (line.charCodeAt(pos) === 45) {
6748
+ pos++;
6749
+ } else {
6750
+ const start = pos;
6751
+ let value = 0;
6752
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
6753
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
6754
+ }
6755
+ if (pos === start) continue;
6756
+ address = value;
6757
+ }
6758
+ const s1 = pos;
6759
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6760
+ if (pos === s1 || pos >= length) continue;
6761
+ const offStart = pos;
6762
+ let offset = 0;
6763
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
6764
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
6765
+ }
6766
+ if (pos === offStart) continue;
6767
+ const s2 = pos;
6768
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6769
+ if (pos === s2 || pos >= length) continue;
6770
+ const sizeStart = pos;
6771
+ let size = 0;
6772
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
6773
+ size = size * 16 + hexDigit(line.charCodeAt(pos++));
6774
+ }
6775
+ if (pos === sizeStart || pos >= length) continue;
6776
+ const indentStart = pos;
6777
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
6778
+ const indent = pos - indentStart;
6779
+ if (indent === 0 || pos >= length) continue;
6780
+ if (indent === 17) {
6781
+ if (previous) {
6782
+ const first = line.charCodeAt(pos);
6783
+ if (first > 32 && !hasLineBreak(line, pos)) {
6784
+ previous.symbols.push({
6785
+ name: line.slice(pos),
6786
+ address,
6787
+ size
6788
+ });
6789
+ }
6790
+ }
6587
6791
  continue;
6588
6792
  }
6589
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
6590
- if (output) {
6591
- kind = output[1];
6793
+ if (indent === 1) {
6794
+ let hasWhitespace = false;
6795
+ for (let i = pos; i < length; i++) {
6796
+ const ch = line.charCodeAt(i);
6797
+ if (ch <= 32) {
6798
+ hasWhitespace = true;
6799
+ break;
6800
+ }
6801
+ }
6802
+ if (hasWhitespace) continue;
6803
+ if (address < 0 && leadingSpaces > 0) {
6804
+ kind = line.slice(pos);
6805
+ } else if (kind === "DATA" && address >= 0) {
6806
+ segment = line.slice(pos);
6807
+ segments.set(segment, { address, size });
6808
+ }
6592
6809
  continue;
6593
6810
  }
6594
- if (kind === "DATA") {
6595
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
6596
- if (top) {
6597
- segment = top[3];
6598
- segments.set(segment, { address: hex(top[1]), size: parseInt(top[2], 16) });
6599
- continue;
6811
+ if (indent === 9 && (kind === "DATA" || kind === "CODE")) {
6812
+ const first = line.charCodeAt(pos);
6813
+ if (first !== 47 && first !== 60) continue;
6814
+ if (hasLineBreak(line, pos)) continue;
6815
+ const name3 = line.slice(pos);
6816
+ let filePath = name3;
6817
+ let section2 = "";
6818
+ if (name3.charCodeAt(name3.length - 1) === 41) {
6819
+ const splitAt = name3.indexOf(":(");
6820
+ if (splitAt >= 0) {
6821
+ filePath = name3.slice(0, splitAt);
6822
+ section2 = name3.slice(splitAt + 2, -1);
6823
+ }
6824
+ }
6825
+ let objectName;
6826
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
6827
+ const open = filePath.lastIndexOf("(");
6828
+ if (open >= 0 && open + 1 < filePath.length - 1) {
6829
+ const close = filePath.indexOf(")", open + 1);
6830
+ if (close === filePath.length - 1) {
6831
+ objectName = filePath.slice(open + 1, -1);
6832
+ }
6833
+ }
6834
+ }
6835
+ if (objectName === void 0) objectName = (0, import_node_path16.basename)(filePath);
6836
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
6837
+ objectName = objectName.replace(/^lib\w*?__/, "");
6600
6838
  }
6839
+ previous = {
6840
+ inputFile: filePath,
6841
+ segment,
6842
+ address,
6843
+ offset,
6844
+ size,
6845
+ object: objectName,
6846
+ section: section2,
6847
+ symbols: []
6848
+ };
6849
+ (kind === "DATA" ? data : code).push(previous);
6601
6850
  }
6602
- if (kind !== "DATA" && kind !== "CODE") continue;
6603
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
6604
- if (!input) continue;
6605
- const name3 = input[4];
6606
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
6607
- const path42 = split ? split[1] : name3;
6608
- const member = /\(([^()]+)\)$/.exec(path42);
6609
- previous = {
6610
- inputFile: path42,
6611
- segment,
6612
- address: hex(input[1]),
6613
- offset: parseInt(input[2], 16),
6614
- size: parseInt(input[3], 16),
6615
- object: (member ? member[1] : (0, import_node_path16.basename)(path42)).replace(/^lib\w*?__/, ""),
6616
- section: split ? split[2] : "",
6617
- symbols: []
6618
- };
6619
- (kind === "DATA" ? data : code).push(previous);
6620
6851
  }
6621
6852
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
6622
6853
  }
@@ -7762,6 +7993,7 @@ function patchSwiftrtObject(src) {
7762
7993
  return buf;
7763
7994
  }
7764
7995
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7996
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
7765
7997
  let pos = 8;
7766
7998
  let numImportFuncs = 0;
7767
7999
  let importsDlsym = false;
@@ -7797,10 +8029,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7797
8029
  let [cnt, cp] = readULEB2(buf, p);
7798
8030
  for (let i = 0; i < cnt; i++) {
7799
8031
  const [mLen, m2] = readULEB2(buf, cp);
7800
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
8032
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
7801
8033
  cp = m2 + mLen;
7802
8034
  const [fLen, f2] = readULEB2(buf, cp);
7803
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
8035
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
7804
8036
  cp = f2 + fLen;
7805
8037
  const kind = buf[cp++];
7806
8038
  if (kind === 0) {
@@ -7880,7 +8112,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7880
8112
  }
7881
8113
  } else if (id === 0) {
7882
8114
  const [nLen, np] = readULEB2(buf, p);
7883
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
8115
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
7884
8116
  const cp = np + nLen;
7885
8117
  if (name3 === "linking") {
7886
8118
  let [, lp] = readULEB2(buf, cp);
@@ -7893,7 +8125,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7893
8125
  let cur = p2;
7894
8126
  for (let i = 0; i < cnt; i++) {
7895
8127
  const [sLen, s2] = readULEB2(buf, cur);
7896
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
8128
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
7897
8129
  cur = s2 + sLen;
7898
8130
  const [, s3] = readULEB2(buf, cur);
7899
8131
  const [fl, s4] = readULEB2(buf, s3);
@@ -7933,7 +8165,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7933
8165
  let sName = "";
7934
8166
  if (!isUndef || isExplicitName) {
7935
8167
  const [sLen, c4] = readULEB2(buf, cur);
7936
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
8168
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
7937
8169
  cur = c4 + sLen;
7938
8170
  } else if (kind === 0) {
7939
8171
  sName = importFuncNames[el] ?? "";
@@ -7949,7 +8181,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
7949
8181
  symNames.push(sName);
7950
8182
  } else if (kind === 1) {
7951
8183
  const [sLen, c3] = readULEB2(buf, cur);
7952
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
8184
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
7953
8185
  cur = c3 + sLen;
7954
8186
  if (!isUndef) {
7955
8187
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -8064,9 +8296,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
8064
8296
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
8065
8297
  let ownerSymIdx = -1;
8066
8298
  const topList = segTopSyms.get(lo);
8067
- if (topList) {
8068
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
8069
- if (owner) ownerSymIdx = owner.symIdx;
8299
+ if (topList && topList.length > 0) {
8300
+ let tLo = 0;
8301
+ let tHi = topList.length - 1;
8302
+ while (tLo <= tHi) {
8303
+ const tMid = tLo + tHi >> 1;
8304
+ const top = topList[tMid];
8305
+ if (offInSeg < top.off) {
8306
+ tHi = tMid - 1;
8307
+ } else if (offInSeg >= top.end) {
8308
+ tLo = tMid + 1;
8309
+ } else {
8310
+ ownerSymIdx = top.symIdx;
8311
+ break;
8312
+ }
8313
+ }
8070
8314
  }
8071
8315
  if (ownerSymIdx !== -1) {
8072
8316
  let list = symDataRelocs.get(ownerSymIdx);
@@ -8304,54 +8548,151 @@ function parseWasmObjectCached(file, isDist, entries2) {
8304
8548
  return parsed;
8305
8549
  }
8306
8550
  function guestWasmSymbols(bytes) {
8307
- const object3 = parseWasmObjectBytes("", bytes, false);
8551
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
8552
+ let cur = 8;
8553
+ const readU = () => {
8554
+ const b0 = bytes[cur++];
8555
+ if (b0 < 128) return b0;
8556
+ let res = b0 & 127;
8557
+ let shift = 7;
8558
+ while (true) {
8559
+ const byte = bytes[cur++];
8560
+ res |= (byte & 127) << shift;
8561
+ if ((byte & 128) === 0) return res;
8562
+ shift += 7;
8563
+ }
8564
+ };
8565
+ let importsDlsym = false;
8566
+ const importFuncNames = [];
8567
+ const importFuncModules = [];
8568
+ const importGlobalNames = [];
8569
+ const importTableNames = [];
8570
+ const importEventNames = [];
8571
+ const undefinedSyms = /* @__PURE__ */ new Set();
8572
+ const tags = /* @__PURE__ */ new Set();
8573
+ const globals = /* @__PURE__ */ new Set();
8574
+ const hostImports = /* @__PURE__ */ new Set();
8575
+ const weakUndefined = /* @__PURE__ */ new Set();
8576
+ const defined = /* @__PURE__ */ new Set();
8577
+ const weakDefined = /* @__PURE__ */ new Set();
8578
+ while (cur < bytes.length) {
8579
+ const id = bytes[cur++];
8580
+ const sz = readU();
8581
+ const end = cur + sz;
8582
+ if (id === 2) {
8583
+ const cnt = readU();
8584
+ for (let i = 0; i < cnt; i++) {
8585
+ const mLen = readU();
8586
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
8587
+ cur += mLen;
8588
+ const fLen = readU();
8589
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
8590
+ cur += fLen;
8591
+ const kind = bytes[cur++];
8592
+ if (kind === 0) {
8593
+ readU();
8594
+ importFuncNames.push(fName);
8595
+ importFuncModules.push(mName);
8596
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
8597
+ } else if (kind === 1) {
8598
+ cur++;
8599
+ const fl = readU();
8600
+ readU();
8601
+ if (fl & 1) readU();
8602
+ importTableNames.push(fName);
8603
+ } else if (kind === 2) {
8604
+ const fl = readU();
8605
+ readU();
8606
+ if (fl & 1) readU();
8607
+ } else if (kind === 3) {
8608
+ cur += 2;
8609
+ importGlobalNames.push(fName);
8610
+ } else if (kind === 4) {
8611
+ cur++;
8612
+ readU();
8613
+ importEventNames.push(fName);
8614
+ }
8615
+ }
8616
+ } else if (id === 0) {
8617
+ const nLen = readU();
8618
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
8619
+ cur += nLen;
8620
+ readU();
8621
+ while (cur < end) {
8622
+ const subId = bytes[cur++];
8623
+ const subLen = readU();
8624
+ const subEnd = cur + subLen;
8625
+ if (subId === 8) {
8626
+ const cnt = readU();
8627
+ for (let i = 0; i < cnt; i++) {
8628
+ const kind = bytes[cur++];
8629
+ const fl = readU();
8630
+ const isUndef = (fl & 16) !== 0;
8631
+ const isExplicitName = (fl & 64) !== 0;
8632
+ let sName = "";
8633
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
8634
+ const el = readU();
8635
+ if (!isUndef || isExplicitName) {
8636
+ const sLen = readU();
8637
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
8638
+ cur += sLen;
8639
+ } else if (kind === 0) {
8640
+ sName = importFuncNames[el] ?? "";
8641
+ } else if (kind === 2) {
8642
+ sName = importGlobalNames[el] ?? "";
8643
+ } else if (kind === 4) {
8644
+ sName = importEventNames[el] ?? "";
8645
+ } else if (kind === 5) {
8646
+ sName = importTableNames[el] ?? "";
8647
+ }
8648
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
8649
+ hostImports.add(sName);
8650
+ } else if (kind === 1) {
8651
+ const sLen = readU();
8652
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
8653
+ cur += sLen;
8654
+ if (!isUndef) {
8655
+ readU();
8656
+ readU();
8657
+ readU();
8658
+ }
8659
+ } else if (kind === 3) {
8660
+ readU();
8661
+ }
8662
+ if (sName) {
8663
+ if (isUndef) {
8664
+ undefinedSyms.add(sName);
8665
+ if ((fl & 19) === 17) weakUndefined.add(sName);
8666
+ } else if ((fl & 3) !== 2) {
8667
+ defined.add(sName);
8668
+ if ((fl & 19) === 1) weakDefined.add(sName);
8669
+ }
8670
+ if (kind === 4) tags.add(sName);
8671
+ else if (kind === 2 || kind === 5) globals.add(sName);
8672
+ }
8673
+ }
8674
+ break;
8675
+ }
8676
+ cur = subEnd;
8677
+ }
8678
+ break;
8679
+ }
8680
+ }
8681
+ cur = end;
8682
+ }
8308
8683
  return {
8309
- importsDlsym: object3.importsDlsym,
8310
- undefined: [
8311
- ...new Set(
8312
- object3.symNames.filter(
8313
- (name3, index) => name3 && (object3.symFlags[index] & 16) !== 0
8314
- )
8315
- )
8316
- ],
8684
+ importsDlsym,
8685
+ undefined: [...undefinedSyms],
8317
8686
  // a wasm tag is one module entity unified by name across the link, as the
8318
8687
  // main module owns it for dynamic images, so no image scope applies.
8319
- tags: [
8320
- ...new Set(
8321
- object3.symNames.filter((name3, index) => name3 && object3.symKind[index] === 4)
8322
- )
8323
- ],
8324
- globals: [
8325
- ...new Set(
8326
- object3.symNames.filter(
8327
- (name3, index) => name3 && (object3.symKind[index] === 2 || object3.symKind[index] === 5)
8328
- )
8329
- )
8330
- ],
8688
+ tags: [...tags],
8689
+ globals: [...globals],
8331
8690
  // an undefined function imported from a module other than env is supplied
8332
8691
  // by the host, whatever linker symbol names it.
8333
- hostImports: [...object3.hostImportNames],
8334
- weakUndefined: [
8335
- ...new Set(
8336
- object3.symNames.filter(
8337
- (name3, index) => name3 && (object3.symFlags[index] & 19) === 17
8338
- )
8339
- )
8340
- ],
8341
- defined: [
8342
- ...new Set(
8343
- object3.symNames.filter(
8344
- (name3, index) => name3 && (object3.symFlags[index] & 16) === 0 && (object3.symFlags[index] & 3) !== 2
8345
- )
8346
- )
8347
- ],
8348
- weakDefined: [
8349
- ...new Set(
8350
- object3.symNames.filter(
8351
- (name3, index) => name3 && (object3.symFlags[index] & 19) === 1
8352
- )
8353
- )
8354
- ]
8692
+ hostImports: [...hostImports],
8693
+ weakUndefined: [...weakUndefined],
8694
+ defined: [...defined],
8695
+ weakDefined: [...weakDefined]
8355
8696
  };
8356
8697
  }
8357
8698
  function sdkObjectName(archive, member, ordinal) {
@@ -8868,9 +9209,12 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8868
9209
  for (const entry of waiting) tryActivateConformance(entry);
8869
9210
  }
8870
9211
  };
9212
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
8871
9213
  const checkProtocolTrigger = (rawSymName) => {
8872
9214
  if (!rawSymName) return;
8873
9215
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
9216
+ if (checkedProtocolTriggers.has(sName)) return;
9217
+ checkedProtocolTriggers.add(sName);
8874
9218
  if (knownProtocols.has(sName)) {
8875
9219
  markProtocolLive(sName);
8876
9220
  return;
@@ -8903,6 +9247,43 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8903
9247
  }
8904
9248
  }
8905
9249
  };
9250
+ const typeIndexes = /* @__PURE__ */ new Map();
9251
+ const getTypeIndex = (obj) => {
9252
+ let idx = typeIndexes.get(obj);
9253
+ if (idx) return idx;
9254
+ const mnByPrefix = /* @__PURE__ */ new Map();
9255
+ for (let i = 0; i < obj.symNames.length; i++) {
9256
+ const name3 = obj.symNames[i];
9257
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
9258
+ const pref = name3.slice(0, -2);
9259
+ let list = mnByPrefix.get(pref);
9260
+ if (!list) mnByPrefix.set(pref, list = []);
9261
+ list.push(i);
9262
+ }
9263
+ }
9264
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
9265
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
9266
+ let list = objcRegByPrefix.get(p);
9267
+ if (!list) objcRegByPrefix.set(p, list = []);
9268
+ list.push(lf);
9269
+ }
9270
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
9271
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
9272
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
9273
+ let list = objcClassByPrefix.get(p);
9274
+ if (!list) objcClassByPrefix.set(p, list = []);
9275
+ list.push(classSym.slice("._OBJC_CLASS_".length));
9276
+ }
9277
+ let minPrefLen = Infinity;
9278
+ let maxPrefLen = 0;
9279
+ for (const p of obj.typePrefixesInObj) {
9280
+ if (p.length < minPrefLen) minPrefLen = p.length;
9281
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
9282
+ }
9283
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
9284
+ typeIndexes.set(obj, idx);
9285
+ return idx;
9286
+ };
8906
9287
  const markTypeLive = (obj, pref) => {
8907
9288
  const set = liveTypes.get(obj);
8908
9289
  if (set.has(pref)) return;
@@ -8916,22 +9297,10 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8916
9297
  const outer = pref.slice(0, n);
8917
9298
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
8918
9299
  }
8919
- const mnName = `${pref}Mn`;
8920
- for (let i = 0; i < obj.symNames.length; i++) {
8921
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
8922
- activateSymbolInObj(obj, i);
8923
- }
8924
- }
8925
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
8926
- if (p === pref) {
8927
- markFuncLive(obj, lf);
8928
- }
8929
- }
8930
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
8931
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
8932
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
8933
- }
8934
- }
9300
+ const idx = getTypeIndex(obj);
9301
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
9302
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
9303
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
8935
9304
  };
8936
9305
  const checkTypeTrigger = (obj, rawSymName) => {
8937
9306
  if (!rawSymName) return;
@@ -8956,11 +9325,12 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
8956
9325
  }
8957
9326
  }
8958
9327
  }
8959
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
8960
- for (const pref of obj.typePrefixesInObj) {
8961
- if (sName.startsWith(pref)) {
8962
- markTypeLive(obj, pref);
8963
- }
9328
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
9329
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
9330
+ const hi = Math.min(sName.length, maxPrefLen);
9331
+ for (let n = minPrefLen; n <= hi; n++) {
9332
+ const cand = sName.slice(0, n);
9333
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
8964
9334
  }
8965
9335
  }
8966
9336
  };
@@ -9053,7 +9423,8 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
9053
9423
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
9054
9424
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
9055
9425
  for (const name3 of obj.symNames) {
9056
- const loaded = name3?.match(/^_c_(\w+)__load$/)?.[1];
9426
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
9427
+ const loaded = name3.match(/^_c_(\w+)__load$/)?.[1];
9057
9428
  if (!loaded) continue;
9058
9429
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded}`);
9059
9430
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -9201,14 +9572,30 @@ function pruneSwiftWasmLink(directory, toolchainBin, moduleRoot, staticClangTarg
9201
9572
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
9202
9573
  const range = obj.segPayloadRanges[segIdx];
9203
9574
  if (!range) return;
9575
+ const [rangeStart, rangeEnd] = range;
9576
+ if (rangeEnd - rangeStart < 4) return;
9204
9577
  let bytes = objectBytes.get(obj);
9205
9578
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs16.default.readFileSync(obj.file));
9206
- const text2 = bytes.toString("latin1", range[0], range[1]);
9207
- for (const match of text2.matchAll(/So(\d+)/g)) {
9208
- const start = match.index + 2 + match[1].length;
9209
- const length = Number(match[1]);
9210
- if (text2[start + length] !== "C") continue;
9211
- const symbol = `._OBJC_CLASS_${text2.slice(start, start + length)}`;
9579
+ let pos = rangeStart;
9580
+ while (pos < rangeEnd - 3) {
9581
+ const at = bytes.indexOf("So", pos);
9582
+ if (at < 0 || at >= rangeEnd - 2) break;
9583
+ let digitEnd = at + 2;
9584
+ let length = 0;
9585
+ while (digitEnd < rangeEnd) {
9586
+ const ch = bytes[digitEnd];
9587
+ if (ch < 48 || ch > 57) break;
9588
+ length = length * 10 + (ch - 48);
9589
+ digitEnd++;
9590
+ }
9591
+ if (digitEnd === at + 2) {
9592
+ pos = at + 2;
9593
+ continue;
9594
+ }
9595
+ pos = digitEnd;
9596
+ const nameEnd = digitEnd + length;
9597
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
9598
+ const symbol = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
9212
9599
  for (const provider of lazyProviders.get(symbol) ?? []) {
9213
9600
  eagerDynamicObjects.add(provider);
9214
9601
  extractObject(provider);
@@ -10145,6 +10532,10 @@ var init_nativeDyldTableContract = __esm({
10145
10532
 
10146
10533
  // src/swift-guest-image-ledger.ts
10147
10534
  function readNumber(bytes, position) {
10535
+ if (position < bytes.length) {
10536
+ const first = bytes[position];
10537
+ if (first < 128) return [first, position + 1];
10538
+ }
10148
10539
  let value = 0;
10149
10540
  let shift = 0;
10150
10541
  for (; ; ) {
@@ -10156,6 +10547,7 @@ function readNumber(bytes, position) {
10156
10547
  }
10157
10548
  }
10158
10549
  function encodeNumber(value) {
10550
+ if (value < 128) return Buffer.from([value]);
10159
10551
  const bytes = [];
10160
10552
  do {
10161
10553
  let byte = value % 128;
@@ -10177,6 +10569,9 @@ function encodedString(value) {
10177
10569
  const bytes = Buffer.from(value);
10178
10570
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
10179
10571
  }
10572
+ function isWasmMagic(bytes) {
10573
+ return bytes.length >= 8 && bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115 && bytes[3] === 109 && bytes[4] === 1 && bytes[5] === 0 && bytes[6] === 0 && bytes[7] === 0;
10574
+ }
10180
10575
  function llvmType(value) {
10181
10576
  switch (value) {
10182
10577
  case 127:
@@ -10192,11 +10587,12 @@ function llvmType(value) {
10192
10587
  }
10193
10588
  }
10194
10589
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options = {}) {
10195
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
10196
- throw new Error("expected wasm object");
10590
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
10591
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
10197
10592
  const { sdkLookupOnly, sdkProduct } = options;
10198
10593
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
10199
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
10594
+ const rewrite = binding !== void 0;
10595
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
10200
10596
  const types = [];
10201
10597
  const functionTypes = [];
10202
10598
  const definitions = [];
@@ -10210,45 +10606,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10210
10606
  const usedSymbols = /* @__PURE__ */ new Set();
10211
10607
  let position = 8;
10212
10608
  while (position < bytes.length) {
10609
+ const headerStart = position;
10213
10610
  const id = bytes[position++];
10214
- const [size, start] = readNumber(bytes, position);
10611
+ let size = 0;
10612
+ if (position < bytes.length && bytes[position] < 128) {
10613
+ size = bytes[position++];
10614
+ } else {
10615
+ const [val, next] = readNumber(bytes, position);
10616
+ size = val;
10617
+ position = next;
10618
+ }
10619
+ const start = position;
10215
10620
  const end = start + size;
10216
10621
  if (end > bytes.length) throw new Error("invalid wasm section");
10217
10622
  position = end;
10218
- if (!sections && id > 3) continue;
10219
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size);
10220
- let offset = 0;
10623
+ if (id > 3) {
10624
+ if (sections) sections.push(bytes.subarray(headerStart, end));
10625
+ continue;
10626
+ }
10627
+ let offset = start;
10221
10628
  const number3 = () => {
10222
- const [value, next] = readNumber(section2, offset);
10223
- offset = next;
10224
- return value;
10629
+ if (offset < end) {
10630
+ const first = bytes[offset];
10631
+ if (first < 128) {
10632
+ offset++;
10633
+ return first;
10634
+ }
10635
+ }
10636
+ let value = 0;
10637
+ let shift = 0;
10638
+ for (; ; ) {
10639
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
10640
+ const byte = bytes[offset++];
10641
+ value += (byte & 127) * 2 ** shift;
10642
+ if (!(byte & 128)) return value;
10643
+ shift += 7;
10644
+ }
10225
10645
  };
10226
10646
  const string4 = () => {
10227
- const [value, next] = readString(section2, offset);
10228
- offset = next;
10647
+ const length = number3();
10648
+ const strEnd = offset + length;
10649
+ if (strEnd > end) throw new Error("invalid wasm string");
10650
+ const value = rawBuf.toString("utf8", offset, strEnd);
10651
+ offset = strEnd;
10229
10652
  return value;
10230
10653
  };
10654
+ let rewrittenSection;
10231
10655
  if (id === 1) {
10232
10656
  const count = number3();
10233
10657
  for (let i = 0; i < count; i++) {
10234
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
10658
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
10235
10659
  const parameterCount = number3();
10236
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
10237
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
10238
- offset += parameterCount;
10660
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
10661
+ const parameters = new Array(parameterCount);
10662
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
10239
10663
  const resultCount = number3();
10240
- const results = [...section2.subarray(offset, offset + resultCount)];
10241
- if (results.length !== resultCount) throw new Error("invalid wasm type");
10242
- offset += resultCount;
10664
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
10665
+ const results = new Array(resultCount);
10666
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
10243
10667
  types.push({ parameters, results });
10244
10668
  }
10245
10669
  } else if (id === 2) {
10246
10670
  const count = number3();
10247
- const imports = sections ? [encodeNumber(count)] : void 0;
10671
+ const importWriter = rewrite ? new ByteWriter(size + 64) : void 0;
10672
+ importWriter?.uleb(count);
10248
10673
  for (let i = 0; i < count; i++) {
10249
10674
  const module2 = string4();
10250
10675
  const name3 = string4();
10251
- const kind = section2[offset++];
10676
+ const kind = bytes[offset++];
10252
10677
  const typeStart = offset;
10253
10678
  let functionType = -1;
10254
10679
  if (kind === 0) {
@@ -10256,7 +10681,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10256
10681
  functionTypes.push(functionType);
10257
10682
  functionImportNames.push(name3);
10258
10683
  } else if (kind === 1) {
10259
- const referenceType = section2[offset++];
10684
+ const referenceType = bytes[offset++];
10260
10685
  if (referenceType !== 112 && referenceType !== 111)
10261
10686
  throw new Error("unsupported table type");
10262
10687
  const flags = number3();
@@ -10275,11 +10700,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10275
10700
  } else throw new Error("unsupported wasm import");
10276
10701
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
10277
10702
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
10278
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
10279
- if (module2 === "env" && kind === 0 && names.has(name3)) {
10280
- const type = types[functionType];
10281
- if (!type) throw new Error(`missing import type for ${name3}`);
10282
- functionImports.set(name3, type);
10703
+ if (!rewrite) {
10704
+ if (module2 === "env" && names.has(name3)) {
10705
+ usedSymbols.add(name3);
10706
+ if (kind === 0) {
10707
+ const type = types[functionType];
10708
+ if (!type) throw new Error(`missing import type for ${name3}`);
10709
+ functionImports.set(name3, type);
10710
+ }
10711
+ }
10283
10712
  }
10284
10713
  if (isDlsym || isDlerror) {
10285
10714
  const type = types[functionType];
@@ -10289,17 +10718,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10289
10718
  }
10290
10719
  if (isDlsym) usesDlsym = true;
10291
10720
  if (isDlerror) usesDlerror = true;
10292
- imports?.push(
10293
- encodedString(module2),
10294
- encodedString(
10295
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
10296
- ),
10297
- Buffer.from([kind]),
10298
- section2.subarray(typeStart, offset)
10299
- );
10721
+ if (importWriter && binding) {
10722
+ importWriter.string(module2);
10723
+ importWriter.string(
10724
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
10725
+ );
10726
+ importWriter.byte(kind);
10727
+ importWriter.bytes(bytes, typeStart, offset);
10728
+ }
10300
10729
  }
10301
- if (offset !== section2.length) throw new Error("invalid wasm import section");
10302
- if (imports) section2 = Buffer.concat(imports);
10730
+ if (offset !== end) throw new Error("invalid wasm import section");
10731
+ if (importWriter) rewrittenSection = importWriter.finish();
10303
10732
  } else if (id === 3) {
10304
10733
  const count = number3();
10305
10734
  for (let i = 0; i < count; i++) functionTypes.push(number3());
@@ -10308,43 +10737,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10308
10737
  if (sectionName === "linking") {
10309
10738
  const version2 = number3();
10310
10739
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
10311
- const subsections = [];
10740
+ const subsections = rewrite ? [] : void 0;
10312
10741
  let objcLoader;
10313
- while (offset < section2.length) {
10314
- const kind = section2[offset++];
10742
+ while (offset < end) {
10743
+ const kind = bytes[offset++];
10315
10744
  const length = number3();
10316
10745
  const stop = offset + length;
10317
- if (stop > section2.length) throw new Error("invalid linking subsection");
10318
- let content = section2.subarray(offset, stop);
10319
- if (kind === 7 && !sdkLookupOnly) {
10320
- const groups = [];
10746
+ if (stop > end) throw new Error("invalid linking subsection");
10747
+ const contentStart = offset;
10748
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
10749
+ const comdatWriter = new ByteWriter(length + 64);
10321
10750
  const count = number3();
10322
- groups.push(encodeNumber(count));
10751
+ comdatWriter.uleb(count);
10323
10752
  for (let i = 0; i < count; i++) {
10324
10753
  const group = string4();
10325
10754
  const begin = offset;
10326
10755
  number3();
10327
10756
  const members = number3();
10328
10757
  for (let member = 0; member < members * 2; member++) number3();
10329
- groups.push(
10330
- encodedString(
10331
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
10332
- ),
10333
- section2.subarray(begin, offset)
10758
+ comdatWriter.string(
10759
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
10334
10760
  );
10761
+ comdatWriter.bytes(bytes, begin, offset);
10335
10762
  }
10336
10763
  if (offset !== stop) throw new Error("invalid comdat subsection");
10337
- content = Buffer.concat(groups);
10338
- }
10339
- if (kind === 8) {
10340
- const entries2 = [];
10341
- const extraEntries = [];
10764
+ const buf = comdatWriter.finish();
10765
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
10766
+ } else if (kind === 8) {
10767
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
10768
+ let extraWriter;
10342
10769
  const count = number3();
10343
- entries2.push(encodeNumber(count));
10344
10770
  let added = 0;
10345
10771
  for (let i = 0; i < count; i++) {
10346
10772
  const begin = offset;
10347
- const symbolKind = section2[offset++];
10773
+ const symbolKind = bytes[offset++];
10348
10774
  const flags = number3();
10349
10775
  const flagsEnd = offset;
10350
10776
  let index = -1;
@@ -10372,25 +10798,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10372
10798
  }
10373
10799
  } else if (symbolKind === 3) number3();
10374
10800
  else throw new Error("unsupported wasm symbol kind");
10375
- if (symbolKind === 0)
10801
+ if (!rewrite && symbolKind === 0)
10376
10802
  functionSymbols[i] = name3 || functionImportNames[index];
10377
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
10803
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
10378
10804
  objcLoader = i;
10379
10805
  }
10380
10806
  const alias = names.get(name3);
10381
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
10382
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
10383
- entries2.push(
10384
- section2.subarray(begin, nameStart),
10385
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
10386
- section2.subarray(nameEnd, offset)
10387
- );
10388
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
10389
- entries2.push(
10390
- section2.subarray(begin, nameStart),
10391
- encodedString(binding(name3)),
10392
- section2.subarray(nameEnd, offset)
10393
- );
10807
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
10808
+ usedSymbols.add(name3);
10809
+ if (entryWriter && binding) {
10810
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
10811
+ entryWriter.bytes(bytes, begin, nameStart);
10812
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
10813
+ entryWriter.bytes(bytes, nameEnd, offset);
10814
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
10815
+ entryWriter.bytes(bytes, begin, nameStart);
10816
+ entryWriter.string(binding(name3));
10817
+ entryWriter.bytes(bytes, nameEnd, offset);
10818
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
10819
+ if (symbolKind !== 0 && symbolKind !== 1)
10820
+ throw new Error(`unsupported symbol ${name3}`);
10821
+ if (preserveCanonical.has(name3)) {
10822
+ entryWriter.bytes(bytes, begin, offset);
10823
+ extraWriter ??= new ByteWriter(256);
10824
+ extraWriter.byte(bytes[begin]);
10825
+ extraWriter.uleb(flags & ~32);
10826
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
10827
+ extraWriter.string(alias);
10828
+ extraWriter.bytes(bytes, nameEnd, offset);
10829
+ added++;
10830
+ } else {
10831
+ entryWriter.bytes(bytes, begin, nameStart);
10832
+ entryWriter.string(alias);
10833
+ entryWriter.bytes(bytes, nameEnd, offset);
10834
+ }
10835
+ } else {
10836
+ entryWriter.bytes(bytes, begin, offset);
10837
+ }
10394
10838
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
10395
10839
  if (symbolKind !== 0 && symbolKind !== 1)
10396
10840
  throw new Error(`unsupported symbol ${name3}`);
@@ -10404,63 +10848,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10404
10848
  hidden: (flags & 4) !== 0,
10405
10849
  type
10406
10850
  });
10407
- if (preserveCanonical.has(name3)) {
10408
- entries2.push(section2.subarray(begin, offset));
10409
- extraEntries.push(
10410
- section2.subarray(begin, begin + 1),
10411
- encodeNumber(flags & ~32),
10412
- section2.subarray(flagsEnd, nameStart),
10413
- encodedString(alias),
10414
- section2.subarray(nameEnd, offset)
10415
- );
10416
- added++;
10417
- } else {
10418
- entries2.push(
10419
- section2.subarray(begin, nameStart),
10420
- encodedString(alias),
10421
- section2.subarray(nameEnd, offset)
10422
- );
10423
- }
10424
- } else entries2.push(section2.subarray(begin, offset));
10851
+ }
10425
10852
  }
10426
10853
  if (offset !== stop) throw new Error("invalid symbol subsection");
10427
- entries2[0] = encodeNumber(count + added);
10428
- content = Buffer.concat([...entries2, ...extraEntries]);
10854
+ if (entryWriter) {
10855
+ const countBytes = encodeNumber(count + added);
10856
+ const entryBuf = entryWriter.finish();
10857
+ if (extraWriter) {
10858
+ const extraBuf = extraWriter.finish();
10859
+ subsections.push({
10860
+ kind,
10861
+ parts: [countBytes, entryBuf, extraBuf],
10862
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
10863
+ });
10864
+ } else {
10865
+ subsections.push({
10866
+ kind,
10867
+ parts: [countBytes, entryBuf],
10868
+ byteLength: countBytes.length + entryBuf.length
10869
+ });
10870
+ }
10871
+ }
10872
+ } else if (subsections) {
10873
+ subsections.push({
10874
+ kind,
10875
+ parts: [bytes.subarray(contentStart, stop)],
10876
+ byteLength: length
10877
+ });
10429
10878
  }
10430
10879
  offset = stop;
10431
- subsections.push({ kind, content });
10432
10880
  }
10433
- const parts = [encodedString(sectionName), encodeNumber(version2)];
10434
- for (const subsection of subsections) {
10435
- let content = subsection.content;
10436
- if (subsection.kind === 6 && objcLoader !== void 0) {
10437
- const [count, entriesStart] = readNumber(content, 0);
10438
- const entries2 = [content.subarray(0, entriesStart)];
10439
- let entryStart = entriesStart;
10440
- for (let i = 0; i < count; i++) {
10441
- const [, symbolStart] = readNumber(content, entryStart);
10442
- const [symbol, entryEnd] = readNumber(content, symbolStart);
10443
- if (symbol === objcLoader) entries2.push(encodeNumber(1));
10444
- entries2.push(
10445
- content.subarray(
10446
- symbol === objcLoader ? symbolStart : entryStart,
10447
- entryEnd
10448
- )
10449
- );
10450
- entryStart = entryEnd;
10881
+ if (subsections) {
10882
+ const linkingWriter = new ByteWriter(size + 128);
10883
+ linkingWriter.string(sectionName);
10884
+ linkingWriter.uleb(version2);
10885
+ for (const subsection of subsections) {
10886
+ if (subsection.kind === 6 && objcLoader !== void 0) {
10887
+ const content = subsection.parts[0];
10888
+ const [count, entriesStart] = readNumber(content, 0);
10889
+ const initWriter = new ByteWriter(content.length + 16);
10890
+ initWriter.bytes(content, 0, entriesStart);
10891
+ let entryStart = entriesStart;
10892
+ for (let i = 0; i < count; i++) {
10893
+ const [, symbolStart] = readNumber(content, entryStart);
10894
+ const [symbol, entryEnd] = readNumber(content, symbolStart);
10895
+ if (symbol === objcLoader) {
10896
+ initWriter.uleb(1);
10897
+ initWriter.bytes(content, symbolStart, entryEnd);
10898
+ } else {
10899
+ initWriter.bytes(content, entryStart, entryEnd);
10900
+ }
10901
+ entryStart = entryEnd;
10902
+ }
10903
+ if (entryStart !== content.length)
10904
+ throw new Error("invalid init functions subsection");
10905
+ const initBuf = initWriter.finish();
10906
+ linkingWriter.byte(subsection.kind);
10907
+ linkingWriter.uleb(initBuf.length);
10908
+ linkingWriter.bytes(initBuf);
10909
+ } else {
10910
+ linkingWriter.byte(subsection.kind);
10911
+ linkingWriter.uleb(subsection.byteLength);
10912
+ for (const part of subsection.parts) linkingWriter.bytes(part);
10451
10913
  }
10452
- if (entryStart !== content.length)
10453
- throw new Error("invalid init functions subsection");
10454
- content = Buffer.concat(entries2);
10455
10914
  }
10456
- parts.push(
10457
- Buffer.from([subsection.kind]),
10458
- encodeNumber(content.length),
10459
- content
10460
- );
10915
+ rewrittenSection = linkingWriter.finish();
10461
10916
  }
10462
- section2 = Buffer.concat(parts);
10463
- } else if (!sections && sectionName.startsWith("reloc.")) {
10917
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
10464
10918
  number3();
10465
10919
  for (let count = number3(); count > 0; count--) {
10466
10920
  const type = number3();
@@ -10470,18 +10924,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
10470
10924
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
10471
10925
  addressTaken.add(name3);
10472
10926
  }
10473
- if (offset !== section2.length)
10474
- throw new Error(`invalid relocation section ${sectionName}`);
10927
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
10928
+ }
10929
+ }
10930
+ if (sections) {
10931
+ if (rewrittenSection) {
10932
+ sections.push(
10933
+ Buffer.from([id]),
10934
+ encodeNumber(rewrittenSection.length),
10935
+ rewrittenSection
10936
+ );
10937
+ } else {
10938
+ sections.push(bytes.subarray(headerStart, end));
10475
10939
  }
10476
10940
  }
10477
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
10478
10941
  }
10479
10942
  return {
10480
10943
  bytes: sections ? Buffer.concat(sections) : bytes,
10481
10944
  definitions,
10482
10945
  functionImports,
10483
10946
  usesDlsym,
10484
- usedSymbols: [...usedSymbols],
10947
+ usedSymbols,
10485
10948
  addressTaken: [...addressTaken]
10486
10949
  };
10487
10950
  }
@@ -10570,36 +11033,51 @@ function createGuestImageLedger(input) {
10570
11033
  }
10571
11034
  }
10572
11035
  }
10573
- const nameBytes = /* @__PURE__ */ new Map();
10574
- for (const definition of definitions)
10575
- if (!nameBytes.has(definition.name))
10576
- nameBytes.set(definition.name, Buffer.from(definition.name));
10577
- definitions.sort(
10578
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
10579
- );
11036
+ let hasNonAscii = false;
11037
+ for (const definition of definitions) {
11038
+ const s = definition.name;
11039
+ for (let i = 0; i < s.length; i++) {
11040
+ if (s.charCodeAt(i) > 127) {
11041
+ hasNonAscii = true;
11042
+ break;
11043
+ }
11044
+ }
11045
+ if (hasNonAscii) break;
11046
+ }
11047
+ if (hasNonAscii) {
11048
+ const nameBytes = /* @__PURE__ */ new Map();
11049
+ for (const definition of definitions)
11050
+ if (!nameBytes.has(definition.name))
11051
+ nameBytes.set(definition.name, Buffer.from(definition.name));
11052
+ definitions.sort(
11053
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
11054
+ );
11055
+ } else {
11056
+ definitions.sort(
11057
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
11058
+ );
11059
+ }
10580
11060
  const preserveCanonical = /* @__PURE__ */ new Set();
10581
11061
  const definitionsByName = Map.groupBy(definitions, (definition) => definition.name);
10582
- for (const name3 of input.symbols) {
11062
+ if (symbolIndices.has("__cxa_throw")) {
11063
+ const name3 = "__cxa_throw";
10583
11064
  const matching = definitionsByName.get(name3) ?? [];
10584
- if (new Set(matching.map((definition) => definition.image)).size < 2 || !matching.some((definition) => definition.weak))
10585
- continue;
10586
- const weak = matching.filter((definition) => definition.weak);
10587
- const strong = matching.filter((definition) => !definition.weak);
10588
- if (name3 !== "__cxa_throw") continue;
10589
- if (weak.length !== 1 || strong.length !== 1)
10590
- throw new Error(`unsupported weak interposition for ${name3}`);
10591
- const [local] = weak;
10592
- const [runtime] = strong;
10593
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
10594
- throw new Error(`incompatible weak interposition for ${name3}`);
10595
- for (const caller of input.callers) {
10596
- const uses = caller.image === local.image || units.some(
10597
- (unit) => unit.image === caller.image && unit.usedSymbols.includes(name3)
10598
- );
10599
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
10600
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
11065
+ if (new Set(matching.map((definition) => definition.image)).size >= 2 && matching.some((definition) => definition.weak)) {
11066
+ const weak = matching.filter((definition) => definition.weak);
11067
+ const strong = matching.filter((definition) => !definition.weak);
11068
+ if (weak.length !== 1 || strong.length !== 1)
11069
+ throw new Error(`unsupported weak interposition for ${name3}`);
11070
+ const [local] = weak;
11071
+ const [runtime] = strong;
11072
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
11073
+ throw new Error(`incompatible weak interposition for ${name3}`);
11074
+ for (const caller of input.callers) {
11075
+ const uses = caller.image === local.image || units.some((unit) => unit.image === caller.image && unit.usedSymbols.has(name3));
11076
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
11077
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
11078
+ }
11079
+ preserveCanonical.add(name3);
10601
11080
  }
10602
- preserveCanonical.add(name3);
10603
11081
  }
10604
11082
  for (const name3 of [
10605
11083
  "dlsym",
@@ -10611,40 +11089,76 @@ function createGuestImageLedger(input) {
10611
11089
  ])
10612
11090
  preserveCanonical.add(name3);
10613
11091
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
10614
- const bindingsByImage = /* @__PURE__ */ new Map();
10615
- const definitionsByImage = Map.groupBy(definitions, (definition) => definition.image);
11092
+ const imageAliases = /* @__PURE__ */ new Map();
11093
+ const imageWeakNames = /* @__PURE__ */ new Map();
11094
+ const singleOwnerByName = /* @__PURE__ */ new Map();
11095
+ for (const definition of definitions) {
11096
+ let aliases = imageAliases.get(definition.image);
11097
+ if (!aliases) imageAliases.set(definition.image, aliases = /* @__PURE__ */ new Map());
11098
+ const existing = aliases.get(definition.name);
11099
+ if (existing === void 0) {
11100
+ aliases.set(definition.name, definition.alias);
11101
+ if (definition.weak) {
11102
+ let weak = imageWeakNames.get(definition.image);
11103
+ if (!weak) imageWeakNames.set(definition.image, weak = /* @__PURE__ */ new Set());
11104
+ weak.add(definition.name);
11105
+ }
11106
+ const owner = singleOwnerByName.get(definition.name);
11107
+ if (owner === void 0)
11108
+ singleOwnerByName.set(definition.name, {
11109
+ image: definition.image,
11110
+ alias: definition.alias
11111
+ });
11112
+ else if (owner !== null && owner.image !== definition.image)
11113
+ singleOwnerByName.set(definition.name, null);
11114
+ } else if (!definition.weak && imageWeakNames.get(definition.image)?.has(definition.name)) {
11115
+ aliases.set(definition.name, definition.alias);
11116
+ imageWeakNames.get(definition.image).delete(definition.name);
11117
+ const owner = singleOwnerByName.get(definition.name);
11118
+ if (owner && owner.image === definition.image) owner.alias = definition.alias;
11119
+ }
11120
+ }
11121
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
10616
11122
  for (const caller of input.callers) {
10617
- const bindings = /* @__PURE__ */ new Map();
10618
- const seen = /* @__PURE__ */ new Map();
10619
11123
  const scope = [caller.image, ...caller.next];
10620
11124
  if (input.systemImage !== void 0 && !scope.includes(input.systemImage))
10621
11125
  scope.push(input.systemImage);
10622
- for (const image of scope)
10623
- for (const definition of definitionsByImage.get(image) ?? []) {
10624
- const previous = seen.get(definition.name);
10625
- if (previous?.image === definition.image) {
10626
- if (previous.weak && !definition.weak) {
10627
- seen.set(definition.name, definition);
10628
- if (!preserveCanonical.has(definition.name))
10629
- bindings.set(definition.name, definition.alias);
10630
- }
10631
- continue;
10632
- }
10633
- if (!previous) {
10634
- seen.set(definition.name, definition);
10635
- if (!preserveCanonical.has(definition.name))
10636
- bindings.set(definition.name, definition.alias);
11126
+ const scopeSet = new Set(scope);
11127
+ const scopeMaps = [];
11128
+ const seenImages = /* @__PURE__ */ new Set();
11129
+ for (const image of scope) {
11130
+ if (seenImages.has(image)) continue;
11131
+ seenImages.add(image);
11132
+ const aliases = imageAliases.get(image);
11133
+ if (aliases) scopeMaps.push(aliases);
11134
+ }
11135
+ const cache = /* @__PURE__ */ new Map();
11136
+ sharedLookupByImage.set(caller.image, (name3) => {
11137
+ if (preserveCanonical.has(name3)) return void 0;
11138
+ const single = singleOwnerByName.get(name3);
11139
+ if (single === void 0) return void 0;
11140
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
11141
+ const hit = cache.get(name3);
11142
+ if (hit !== void 0) return hit ?? void 0;
11143
+ for (const aliases of scopeMaps) {
11144
+ const alias = aliases.get(name3);
11145
+ if (alias !== void 0) {
11146
+ cache.set(name3, alias);
11147
+ return alias;
10637
11148
  }
10638
11149
  }
10639
- bindingsByImage.set(caller.image, bindings);
11150
+ cache.set(name3, null);
11151
+ return void 0;
11152
+ });
10640
11153
  }
10641
11154
  const startup = /* @__PURE__ */ new Map();
11155
+ const unitsByPath = new Map(units.map((unit) => [unit.object.path, unit]));
10642
11156
  for (const binding of input.directBindings ?? []) {
10643
- const unit = units.find(({ object: object3 }) => object3.path === binding.object);
11157
+ const unit = unitsByPath.get(binding.object);
10644
11158
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
10645
11159
  (definition) => definition.object === binding.providerObject && definition.image === binding.providerImage
10646
11160
  );
10647
- if (!unit || !unit.usedSymbols.includes(binding.symbol) || matches.length !== 1)
11161
+ if (!unit || !unit.usedSymbols.has(binding.symbol) || matches.length !== 1)
10648
11162
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
10649
11163
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
10650
11164
  if (bindings.has(binding.symbol))
@@ -10685,11 +11199,11 @@ function createGuestImageLedger(input) {
10685
11199
  }
10686
11200
  }
10687
11201
  const objects = units.map(({ image, object: object3, aliases, functionImports }) => {
10688
- const shared = bindingsByImage.get(image);
11202
+ const shared = sharedLookupByImage.get(image);
10689
11203
  const own = startup.get(object3.path);
10690
11204
  const bindings = new Map(own);
10691
11205
  const weak = input.sdkWeakReferences?.get(object3.path);
10692
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
11206
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
10693
11207
  for (const [name3, type] of functionImports) {
10694
11208
  const alias = binding(name3);
10695
11209
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -10954,7 +11468,7 @@ function nameGuestImageAliases(wasm, symbols) {
10954
11468
  }
10955
11469
  return Buffer.concat(parts);
10956
11470
  }
10957
- var import_node_crypto10, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
11471
+ var import_node_crypto10, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
10958
11472
  var init_swift_guest_image_ledger = __esm({
10959
11473
  "src/swift-guest-image-ledger.ts"() {
10960
11474
  "use strict";
@@ -10962,6 +11476,57 @@ var init_swift_guest_image_ledger = __esm({
10962
11476
  init_nativeWasmContract();
10963
11477
  init_swift_sdk_image_wasm();
10964
11478
  init_swiftSdkLinkContract();
11479
+ ByteWriter = class {
11480
+ buf;
11481
+ pos = 0;
11482
+ constructor(initialCapacity = 256) {
11483
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
11484
+ }
11485
+ ensure(extra) {
11486
+ const needed = this.pos + extra;
11487
+ if (needed <= this.buf.length) return;
11488
+ let next = this.buf.length * 2;
11489
+ while (next < needed) next *= 2;
11490
+ const grown = Buffer.allocUnsafe(next);
11491
+ this.buf.copy(grown, 0, 0, this.pos);
11492
+ this.buf = grown;
11493
+ }
11494
+ byte(value) {
11495
+ this.ensure(1);
11496
+ this.buf[this.pos++] = value;
11497
+ }
11498
+ uleb(value) {
11499
+ this.ensure(10);
11500
+ let pos = this.pos;
11501
+ const buf = this.buf;
11502
+ do {
11503
+ let byte = value % 128;
11504
+ value = Math.floor(value / 128);
11505
+ if (value) byte |= 128;
11506
+ buf[pos++] = byte;
11507
+ } while (value);
11508
+ this.pos = pos;
11509
+ }
11510
+ bytes(source, start = 0, end = source.length) {
11511
+ const len = end - start;
11512
+ if (len <= 0) return;
11513
+ this.ensure(len);
11514
+ this.buf.set(source.subarray(start, end), this.pos);
11515
+ this.pos += len;
11516
+ }
11517
+ string(value) {
11518
+ const len = Buffer.byteLength(value, "utf8");
11519
+ this.uleb(len);
11520
+ if (len > 0) {
11521
+ this.ensure(len);
11522
+ this.buf.write(value, this.pos, len, "utf8");
11523
+ this.pos += len;
11524
+ }
11525
+ }
11526
+ finish() {
11527
+ return this.buf.subarray(0, this.pos);
11528
+ }
11529
+ };
10965
11530
  OBJC_INIT_RECORD = ".objc_init";
10966
11531
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
10967
11532
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -11405,8 +11970,11 @@ function moveGuestDyldTable(map, wasm, symbols, bindingValues = /* @__PURE__ */
11405
11970
  function guestDyldValueRange(map) {
11406
11971
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
11407
11972
  let found;
11408
- for (const line of map.split("\n")) {
11409
- if (!line.endsWith(suffix)) continue;
11973
+ for (let at = map.indexOf(suffix); at !== -1; at = map.indexOf(suffix, at + suffix.length)) {
11974
+ const lineEnd = at + suffix.length;
11975
+ if (lineEnd < map.length && map.charCodeAt(lineEnd) !== 10) continue;
11976
+ const lineStart = map.lastIndexOf("\n", at) + 1;
11977
+ const line = map.slice(lineStart, lineEnd);
11410
11978
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
11411
11979
  if (!match) throw new Error("unreadable dyld values map line");
11412
11980
  if (found) throw new Error("link map has several dyld value sections");
@@ -11444,7 +12012,7 @@ var init_swift_guest_link_plan = __esm({
11444
12012
  });
11445
12013
 
11446
12014
  // src/swift-guest-manifest.ts
11447
- function selectedGuestManifestInputs(plan, selection, identities) {
12015
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
11448
12016
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
11449
12017
  const archives = /* @__PURE__ */ new Map();
11450
12018
  const images = /* @__PURE__ */ new Map();
@@ -11455,19 +12023,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
11455
12023
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
11456
12024
  let bytes;
11457
12025
  let memberIdentity = null;
11458
- if (item.member === null) bytes = (0, import_node_fs18.readFileSync)(item.artifact);
11459
- else {
11460
- let members = archives.get(item.artifact);
11461
- if (!members) {
11462
- members = readArMembers((0, import_node_fs18.readFileSync)(item.artifact));
11463
- archives.set(item.artifact, members);
12026
+ if (item.member === null) {
12027
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs18.readFileSync)(item.artifact);
12028
+ } else {
12029
+ if (readSelected) {
12030
+ bytes = readSelected(item);
12031
+ } else {
12032
+ let members = archives.get(item.artifact);
12033
+ if (!members) {
12034
+ members = /* @__PURE__ */ new Map();
12035
+ for (const member of readArMembers((0, import_node_fs18.readFileSync)(item.artifact))) {
12036
+ let list = members.get(member.name);
12037
+ if (!list) members.set(member.name, list = []);
12038
+ list.push(member.bytes);
12039
+ }
12040
+ archives.set(item.artifact, members);
12041
+ }
12042
+ const matching = members.get(item.member);
12043
+ if (!matching || matching.length !== 1)
12044
+ throw new Error(
12045
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
12046
+ );
12047
+ bytes = matching[0];
11464
12048
  }
11465
- const matching = members.filter((member) => member.name === item.member);
11466
- if (matching.length !== 1)
11467
- throw new Error(
11468
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
11469
- );
11470
- bytes = matching[0].bytes;
11471
12049
  const origin = artifact.memberOrigins?.get(item.member);
11472
12050
  if (artifact.memberOrigins && !origin)
11473
12051
  throw new Error(
@@ -11559,7 +12137,7 @@ var init_swift_guest_manifest = __esm({
11559
12137
  function isSwiftGuestImageManifest(value) {
11560
12138
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
11561
12139
  const text2 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
11562
- const name3 = (value2) => text2(value2) && new TextEncoder().encode(value2).length <= 16;
12140
+ const name3 = (value2) => text2(value2) && Buffer.byteLength(value2, "utf8") <= 16;
11563
12141
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
11564
12142
  if (!isRecord(value) || value.version !== 1 || !text2(value.id) || !text2(value.installName) || value.resourceBundlePath !== void 0 && !isSwiftBundlePath(value.resourceBundlePath) || value.fileType !== "executable" && value.fileType !== "dylib" || !isRecord(value.target) || value.target.triple !== SWIFT_WASM_TRIPLE || value.target.pointerWidth !== 64 || value.target.byteOrder !== "little" || value.target.cpuType !== -1 || value.target.cpuSubtype !== 0 || typeof value.inputsSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.inputsSha256) || value.uuid !== value.inputsSha256.slice(0, 32) || !isRecord(value.buildVersion) || !uint(value.buildVersion.platform, 4294967295) || !version2(value.buildVersion.minimum) || !version2(value.buildVersion.sdk) || !Array.isArray(value.regions))
11565
12143
  return false;
@@ -11873,27 +12451,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
11873
12451
  function finalizeGuestProjectionStorage(options) {
11874
12452
  const owner = options.owners.get(options.projectionObject);
11875
12453
  if (owner === void 0) throw new Error("guest projection object has no image owner");
12454
+ const ranges = [];
11876
12455
  const spans = guestLinkedSpans(
11877
12456
  options.map,
11878
12457
  options.linked,
11879
12458
  options.optimized,
11880
12459
  options.owners,
11881
12460
  options.sectionOwners,
11882
- options.sdkSpans !== void 0
12461
+ options.sdkSpans !== void 0,
12462
+ {
12463
+ trackedObject: options.projectionObject,
12464
+ trackedObjectOwner: owner,
12465
+ trackedLinearSpans: ranges
12466
+ }
11883
12467
  );
11884
12468
  const images = planGuestProjectionRegions(
11885
12469
  options.reserved.images,
11886
12470
  options.reserved.capacities,
11887
12471
  options.sdkSpans ? [...spans, ...options.sdkSpans] : spans
11888
12472
  );
11889
- const ranges = guestLinkedSpans(
11890
- options.map,
11891
- options.linked,
11892
- options.optimized,
11893
- /* @__PURE__ */ new Map([[options.projectionObject, owner]]),
11894
- void 0,
11895
- options.sdkSpans !== void 0
11896
- ).filter((span) => span.space === "linear-memory");
11897
12473
  const result = Buffer.from(options.optimized);
11898
12474
  const data = guestWasmDataSegments(options.optimized, options.sdkSpans === void 0);
11899
12475
  const locations = /* @__PURE__ */ new Map();
@@ -13294,7 +13870,7 @@ function occurrences(plan, args) {
13294
13870
  throw new Error("guest plan does not match linker inputs");
13295
13871
  return found;
13296
13872
  }
13297
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13873
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
13298
13874
  const rows = whyExtract.trimEnd().split("\n");
13299
13875
  if (rows.shift() !== "reference extracted symbol")
13300
13876
  throw new Error("invalid wasm-ld extraction report");
@@ -13309,8 +13885,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13309
13885
  for (const file of extracted)
13310
13886
  if (!traced.has(file))
13311
13887
  throw new Error(`extracted guest input is absent from link trace ${file}`);
13888
+ const foundOccurrences = occurrences(plan, args);
13889
+ const archivePaths = /* @__PURE__ */ new Set();
13890
+ for (const { artifact } of foundOccurrences)
13891
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
13892
+ const tracedMembers = /* @__PURE__ */ new Map();
13893
+ if (archivePaths.size > 0) {
13894
+ const archivePrefixes = [...archivePaths].map(
13895
+ (archivePath) => [archivePath, `${archivePath}(`]
13896
+ );
13897
+ for (const item of traced) {
13898
+ if (!item.endsWith(")")) continue;
13899
+ const open = item.lastIndexOf("(");
13900
+ if (open > 0) {
13901
+ const archivePath = item.slice(0, open);
13902
+ if (archivePaths.has(archivePath)) {
13903
+ let list = tracedMembers.get(archivePath);
13904
+ if (!list) tracedMembers.set(archivePath, list = []);
13905
+ list.push(item.slice(open + 1, -1));
13906
+ continue;
13907
+ }
13908
+ }
13909
+ for (const [archivePath, prefix] of archivePrefixes) {
13910
+ if (item.startsWith(prefix)) {
13911
+ let list = tracedMembers.get(archivePath);
13912
+ if (!list) tracedMembers.set(archivePath, list = []);
13913
+ list.push(item.slice(prefix.length, -1));
13914
+ }
13915
+ }
13916
+ }
13917
+ }
13312
13918
  const result = [];
13313
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
13919
+ for (const { artifact, lazy, whole } of foundOccurrences) {
13314
13920
  if (artifact.kind === "object") {
13315
13921
  if (!lazy && !traced.has(artifact.path))
13316
13922
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -13318,15 +13924,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
13318
13924
  result.push({ artifact: artifact.path, member: null });
13319
13925
  continue;
13320
13926
  }
13321
- const prefix = `${artifact.path}(`;
13322
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
13323
- const members = readArMembers(import_node_fs24.default.readFileSync(artifact.path));
13927
+ const names = tracedMembers.get(artifact.path) ?? [];
13928
+ const nameSet = new Set(names);
13929
+ let members = archiveCache?.get(artifact.path);
13930
+ if (!members) {
13931
+ members = readArMembers(import_node_fs24.default.readFileSync(artifact.path));
13932
+ archiveCache?.set(artifact.path, members);
13933
+ }
13934
+ const memberCounts = /* @__PURE__ */ new Map();
13324
13935
  for (const member of members) {
13325
- if (whole || names.includes(member.name))
13936
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
13937
+ if (whole || nameSet.has(member.name))
13326
13938
  result.push({ artifact: artifact.path, member: member.name });
13327
13939
  }
13328
13940
  for (const name3 of names)
13329
- if (members.filter((member) => member.name === name3).length !== 1)
13941
+ if (memberCounts.get(name3) !== 1)
13330
13942
  throw new Error(
13331
13943
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
13332
13944
  );
@@ -13403,14 +14015,25 @@ function linkGuestImages(options) {
13403
14015
  }
13404
14016
  const archives = /* @__PURE__ */ new Map();
13405
14017
  const memberBytes = /* @__PURE__ */ new Map();
14018
+ const objectBytes = /* @__PURE__ */ new Map();
13406
14019
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
13407
14020
  const providerSymbol = "__peach_dlsym_from_image";
13408
14021
  const readSelected = (item) => {
13409
- if (item.member === null) return import_node_fs24.default.readFileSync(item.artifact);
14022
+ if (item.member === null) {
14023
+ let bytes = objectBytes.get(item.artifact);
14024
+ if (!bytes) {
14025
+ bytes = import_node_fs24.default.readFileSync(item.artifact);
14026
+ objectBytes.set(item.artifact, bytes);
14027
+ }
14028
+ return bytes;
14029
+ }
13410
14030
  let byName = memberBytes.get(item.artifact);
13411
14031
  if (!byName) {
13412
- const members = readArMembers(import_node_fs24.default.readFileSync(item.artifact));
13413
- archives.set(item.artifact, members);
14032
+ let members = archives.get(item.artifact);
14033
+ if (!members) {
14034
+ members = readArMembers(import_node_fs24.default.readFileSync(item.artifact));
14035
+ archives.set(item.artifact, members);
14036
+ }
13414
14037
  byName = /* @__PURE__ */ new Map();
13415
14038
  for (const member of members)
13416
14039
  if (!byName.has(member.name))
@@ -13434,7 +14057,13 @@ function linkGuestImages(options) {
13434
14057
  `--why-extract=${whyPath}`,
13435
14058
  `--Map=${mapPath}`
13436
14059
  ]);
13437
- return selectedGuestLinkInputs(plan, args, import_node_fs24.default.readFileSync(whyPath, "utf8"), trace);
14060
+ return selectedGuestLinkInputs(
14061
+ plan,
14062
+ args,
14063
+ import_node_fs24.default.readFileSync(whyPath, "utf8"),
14064
+ trace,
14065
+ archives
14066
+ );
13438
14067
  };
13439
14068
  const needsProvider = (item) => {
13440
14069
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -13474,7 +14103,7 @@ function linkGuestImages(options) {
13474
14103
  )
13475
14104
  ]);
13476
14105
  const originalOwnership = identity(plan);
13477
- const resolved = options.resolvePlan(selected, plan);
14106
+ const resolved = options.resolvePlan(selected, plan, readSelected);
13478
14107
  if (identity(resolved) !== originalOwnership)
13479
14108
  throw new Error("resolved guest scopes changed input ownership");
13480
14109
  plan = resolved;
@@ -13528,6 +14157,7 @@ function linkGuestImages(options) {
13528
14157
  }
13529
14158
  }
13530
14159
  let discoveryRegions;
14160
+ let liveSymbols;
13531
14161
  if (discoveryProjection && options.projection) {
13532
14162
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options.projection.image]]);
13533
14163
  for (const item of selected)
@@ -13536,10 +14166,15 @@ function linkGuestImages(options) {
13536
14166
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
13537
14167
  );
13538
14168
  const wasm = import_node_fs24.default.readFileSync(discovery);
14169
+ liveSymbols = /* @__PURE__ */ new Set();
13539
14170
  discoveryRegions = guestProjectionRegionCounts(
13540
14171
  plan.images.length,
13541
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
14172
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
14173
+ collectSymbols: liveSymbols
14174
+ })
13542
14175
  );
14176
+ } else {
14177
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
13543
14178
  }
13544
14179
  const ledger = createGuestImageLedger({
13545
14180
  images: plan.images.map((image) => ({
@@ -13548,7 +14183,7 @@ function linkGuestImages(options) {
13548
14183
  })),
13549
14184
  callers: plan.callers,
13550
14185
  symbols: plan.symbols,
13551
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
14186
+ liveSymbols,
13552
14187
  commandLineSymbols: commandLineSymbols(args),
13553
14188
  directBindings: plan.directBindings,
13554
14189
  registerAppTables: sdkCallers !== void 0,
@@ -13680,7 +14315,8 @@ function linkGuestImages(options) {
13680
14315
  const selectedInputs = selectedGuestManifestInputs(
13681
14316
  plan,
13682
14317
  selected,
13683
- projection.identities
14318
+ projection.identities,
14319
+ readSelected
13684
14320
  );
13685
14321
  const images = projection.images.map(
13686
14322
  (image) => createGuestImageManifest({
@@ -13690,6 +14326,9 @@ function linkGuestImages(options) {
13690
14326
  regions: []
13691
14327
  })
13692
14328
  );
14329
+ objectBytes.clear();
14330
+ memberBytes.clear();
14331
+ archives.clear();
13693
14332
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
13694
14333
  const regionsBefore = discoveryRegions;
13695
14334
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs24.default.readFileSync(ledgerObject)], 0);
@@ -13715,6 +14354,7 @@ function linkGuestImages(options) {
13715
14354
  { stdio: "pipe" }
13716
14355
  );
13717
14356
  finalTrace = linkFinal(projectionObject, callerMap ? void 0 : layoutMap);
14357
+ if (sharedSdk) break;
13718
14358
  const wasm = import_node_fs24.default.readFileSync(finalOutput);
13719
14359
  const actual = guestProjectionRegionCounts(
13720
14360
  images.length,
@@ -13783,10 +14423,47 @@ ${changed.join("\n")}`
13783
14423
  }
13784
14424
  function linkedMapSymbols(lines) {
13785
14425
  const names = /* @__PURE__ */ new Set();
13786
- const symbol = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
13787
14426
  for (const line of lines) {
13788
- const match = symbol.exec(line);
13789
- if (match) names.add(match[1]);
14427
+ const length = line.length;
14428
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
14429
+ let pos = 1;
14430
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14431
+ const c1 = pos;
14432
+ while (pos < length) {
14433
+ const ch = line.charCodeAt(pos);
14434
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
14435
+ pos++;
14436
+ }
14437
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
14438
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14439
+ const c2 = pos;
14440
+ while (pos < length) {
14441
+ const ch = line.charCodeAt(pos);
14442
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
14443
+ pos++;
14444
+ }
14445
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
14446
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14447
+ const c3 = pos;
14448
+ while (pos < length) {
14449
+ const ch = line.charCodeAt(pos);
14450
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
14451
+ pos++;
14452
+ }
14453
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
14454
+ const sStart = pos;
14455
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
14456
+ if (pos - sStart < 9 || pos >= length) continue;
14457
+ const first = line.charCodeAt(pos);
14458
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
14459
+ continue;
14460
+ let end = pos + 1;
14461
+ while (end < length) {
14462
+ const ch = line.charCodeAt(end);
14463
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
14464
+ end++;
14465
+ }
14466
+ names.add(line.slice(pos, end));
13790
14467
  }
13791
14468
  return names;
13792
14469
  }
@@ -13885,7 +14562,7 @@ function discoverGuestLinkInputs(options) {
13885
14562
  import_node_fs24.default.mkdirSync(options.directory, { recursive: true });
13886
14563
  const why = import_node_path24.default.join(options.directory, "preselection-why.txt");
13887
14564
  const response = import_node_path24.default.join(options.directory, "preselection.rsp");
13888
- const output = import_node_path24.default.join(options.directory, "preselection.wasm");
14565
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path24.default.join(options.directory, "preselection.wasm");
13889
14566
  const flags = [
13890
14567
  ...withOutput(args, output, true),
13891
14568
  ...options.objects,
@@ -13983,7 +14660,7 @@ function prepareGuestRuntimeInputs(options) {
13983
14660
  });
13984
14661
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
13985
14662
  }
13986
- function selectedGuestSymbolInputs(plan, selected) {
14663
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
13987
14664
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
13988
14665
  const archives = /* @__PURE__ */ new Map();
13989
14666
  const symbols = /* @__PURE__ */ new Set();
@@ -13999,22 +14676,27 @@ function selectedGuestSymbolInputs(plan, selected) {
13999
14676
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
14000
14677
  let bytes;
14001
14678
  let name3 = item.artifact;
14002
- if (item.member === null) bytes = import_node_fs24.default.readFileSync(item.artifact);
14003
- else {
14004
- let members = archives.get(item.artifact);
14005
- if (!members) {
14006
- members = Map.groupBy(
14007
- readArMembers(import_node_fs24.default.readFileSync(item.artifact)),
14008
- (member) => member.name
14009
- );
14010
- archives.set(item.artifact, members);
14679
+ if (item.member === null) {
14680
+ bytes = readSelected ? readSelected(item) : import_node_fs24.default.readFileSync(item.artifact);
14681
+ } else {
14682
+ if (readSelected) {
14683
+ bytes = readSelected(item);
14684
+ } else {
14685
+ let members = archives.get(item.artifact);
14686
+ if (!members) {
14687
+ members = Map.groupBy(
14688
+ readArMembers(import_node_fs24.default.readFileSync(item.artifact)),
14689
+ (member) => member.name
14690
+ );
14691
+ archives.set(item.artifact, members);
14692
+ }
14693
+ const matching = members.get(item.member) ?? [];
14694
+ if (matching.length !== 1)
14695
+ throw new Error(
14696
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
14697
+ );
14698
+ bytes = matching[0].bytes;
14011
14699
  }
14012
- const matching = members.get(item.member) ?? [];
14013
- if (matching.length !== 1)
14014
- throw new Error(
14015
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
14016
- );
14017
- bytes = matching[0].bytes;
14018
14700
  name3 += `(${item.member})`;
14019
14701
  }
14020
14702
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -14027,9 +14709,9 @@ function selectedGuestSymbolInputs(plan, selected) {
14027
14709
  for (const symbol of names.tags) tags.add(symbol);
14028
14710
  for (const symbol of names.defined) {
14029
14711
  definitions.add(symbol);
14030
- const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14712
+ let objects = definitionObjects.get(symbol);
14713
+ if (!objects) definitionObjects.set(symbol, objects = /* @__PURE__ */ new Set());
14031
14714
  objects.add(name3);
14032
- definitionObjects.set(symbol, objects);
14033
14715
  }
14034
14716
  }
14035
14717
  return {
@@ -14050,7 +14732,7 @@ function verifyGuestSymbolScopes(options) {
14050
14732
  if (!symbols.length) return { bindings: [], directBindings: [] };
14051
14733
  import_node_fs24.default.mkdirSync(options.directory, { recursive: true });
14052
14734
  const response = import_node_path24.default.join(options.directory, "scope-trace.rsp");
14053
- const output = import_node_path24.default.join(options.directory, "scope-trace.wasm");
14735
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path24.default.join(options.directory, "scope-trace.wasm");
14054
14736
  const args = [
14055
14737
  ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
14056
14738
  ...options.objects,
@@ -14068,55 +14750,76 @@ function verifyGuestSymbolScopes(options) {
14068
14750
  import_node_fs24.default.closeSync(traceOutput);
14069
14751
  }
14070
14752
  const records = /* @__PURE__ */ new Map();
14071
- const consume = (line) => {
14072
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
14073
- if (!match) return;
14074
- const [, object3, kind, symbol] = match;
14075
- if (!requested.has(symbol)) return;
14076
- if (options.hostImports.has(symbol)) return;
14077
- const record = records.get(symbol) ?? {
14078
- references: /* @__PURE__ */ new Map(),
14079
- providers: /* @__PURE__ */ new Map(),
14080
- physicalModule: false
14081
- };
14753
+ for (const line of guestLinkLines(tracePath)) {
14754
+ const refSep = line.lastIndexOf(": reference to ");
14755
+ const defSep = line.lastIndexOf(": definition of ");
14756
+ if (refSep < 0 && defSep < 0) continue;
14757
+ const isRef = refSep > defSep;
14758
+ const sep = isRef ? refSep : defSep;
14759
+ const symbol = line.slice(sep + (isRef ? 15 : 16));
14760
+ if (!requested.has(symbol) || options.hostImports.has(symbol)) continue;
14761
+ let record = records.get(symbol);
14762
+ if (!record) {
14763
+ record = {
14764
+ references: /* @__PURE__ */ new Map(),
14765
+ providers: /* @__PURE__ */ new Map(),
14766
+ physicalModule: false
14767
+ };
14768
+ records.set(symbol, record);
14769
+ }
14770
+ const object3 = line.slice(0, sep);
14082
14771
  if (object3 === "<internal>") {
14083
- if (kind === "definition of") record.physicalModule = true;
14772
+ if (!isRef) record.physicalModule = true;
14084
14773
  } else {
14085
14774
  const image = options.owners.get(object3);
14086
14775
  if (image === void 0)
14087
14776
  throw new Error(`traced guest object has no owner ${object3}`);
14088
- (kind === "reference to" ? record.references : record.providers).set(
14089
- object3,
14090
- image
14091
- );
14777
+ (isRef ? record.references : record.providers).set(object3, image);
14092
14778
  }
14093
- records.set(symbol, record);
14094
- };
14095
- for (const line of guestLinkLines(tracePath)) consume(line);
14779
+ }
14096
14780
  const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]));
14781
+ const callerSets = new Map(
14782
+ options.callers.map((caller) => [caller.image, new Set(caller.next)])
14783
+ );
14784
+ const rootScope = callerSets.get(0);
14097
14785
  const result = [];
14098
14786
  const directBindings = [];
14099
14787
  for (const symbol of symbols) {
14100
14788
  const record = records.get(symbol);
14101
14789
  if (!record || !record.references.size) continue;
14102
14790
  if (!record.providers.size && options.hostImports.has(symbol)) continue;
14103
- const startupReferences = [...record.references].filter(
14104
- ([object3]) => options.startupObjects.has(object3) && options.weakReferences.get(object3)?.has(symbol)
14105
- );
14106
- const otherReferences = [...record.references].filter(
14107
- ([object3]) => !startupReferences.some(([startup]) => startup === object3)
14108
- );
14791
+ const startupReferences = [];
14792
+ const otherReferences = [];
14793
+ let allWeakRefs = true;
14794
+ for (const [object3, caller] of record.references) {
14795
+ const isWeakRef = options.weakReferences.get(object3)?.has(symbol) === true;
14796
+ if (!isWeakRef) allWeakRefs = false;
14797
+ if (isWeakRef && options.startupObjects.has(object3)) {
14798
+ startupReferences.push([object3, caller]);
14799
+ } else {
14800
+ otherReferences.push([object3, caller]);
14801
+ }
14802
+ }
14109
14803
  for (const [, caller] of startupReferences)
14110
14804
  if (!callers.has(caller))
14111
14805
  throw new Error(`guest image has no caller scope ${caller}`);
14112
14806
  if (startupReferences.length && !record.physicalModule) {
14113
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14114
- if (candidates.size > 1 || record.providers.size > 1)
14807
+ const candidates2 = options.definitionObjects.get(symbol);
14808
+ const candidateSize = candidates2?.size ?? 0;
14809
+ if (candidateSize > 1 || record.providers.size > 1)
14115
14810
  throw new Error(`ambiguous startup provider ${symbol}`);
14116
- if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object3) => !candidates.has(object3)))
14117
- throw new Error(`unproven startup provider ${symbol}`);
14811
+ let unproven = candidateSize !== record.providers.size;
14812
+ if (!unproven && candidates2) {
14813
+ for (const object3 of record.providers.keys()) {
14814
+ if (!candidates2.has(object3)) {
14815
+ unproven = true;
14816
+ break;
14817
+ }
14818
+ }
14819
+ }
14820
+ if (unproven) throw new Error(`unproven startup provider ${symbol}`);
14118
14821
  if (record.providers.size === 1) {
14119
- const [providerObject, providerImage] = [...record.providers][0];
14822
+ const [providerObject, providerImage] = record.providers.entries().next().value;
14120
14823
  if (options.weakDefinitions.get(providerObject)?.has(symbol))
14121
14824
  throw new Error(`weak startup provider ${symbol}`);
14122
14825
  for (const [object3] of startupReferences)
@@ -14124,28 +14827,34 @@ function verifyGuestSymbolScopes(options) {
14124
14827
  }
14125
14828
  if (!otherReferences.length) continue;
14126
14829
  }
14127
- if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
14128
- (object3) => options.weakReferences.get(object3)?.has(symbol)
14129
- ))
14130
- continue;
14830
+ if (!record.providers.size && !record.physicalModule && allWeakRefs) continue;
14131
14831
  const providerImages = new Set(record.providers.values());
14132
- const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
14133
- (object3) => {
14832
+ const candidates = options.definitionObjects.get(symbol);
14833
+ const copyImages = /* @__PURE__ */ new Set();
14834
+ const strongImages = /* @__PURE__ */ new Set();
14835
+ let weakDefinerImages;
14836
+ if (candidates) {
14837
+ for (const object3 of candidates) {
14134
14838
  const image = options.owners.get(object3);
14135
- return image === void 0 ? [] : [{ image, weak: !!options.weakDefinitions.get(object3)?.has(symbol) }];
14839
+ if (image === void 0) continue;
14840
+ copyImages.add(image);
14841
+ if (options.weakDefinitions.get(object3)?.has(symbol)) {
14842
+ ;
14843
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
14844
+ } else {
14845
+ strongImages.add(image);
14846
+ }
14136
14847
  }
14137
- );
14138
- const copyImages = new Set(copies.map((copy) => copy.image));
14139
- const strongImages = new Set(
14140
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
14141
- );
14848
+ }
14142
14849
  const interposed = !record.physicalModule && copyImages.size > 1;
14143
14850
  const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
14144
14851
  if (!providerCount) continue;
14145
14852
  if (providerCount !== 1)
14146
14853
  throw new Error(`guest symbol has ambiguous provider ${symbol}`);
14147
- const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
14148
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
14854
+ const scopedReferences = record.physicalModule ? record.references : otherReferences;
14855
+ const firstProviderImage = providerImages.values().next().value;
14856
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
14857
+ let interposedByCaller;
14149
14858
  for (const [object3, caller] of scopedReferences) {
14150
14859
  const scope = callers.get(caller);
14151
14860
  if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
@@ -14153,18 +14862,35 @@ function verifyGuestSymbolScopes(options) {
14153
14862
  result.push({ symbol, caller, provider: { kind: "physical-module" } });
14154
14863
  continue;
14155
14864
  }
14156
- const provider = interposed ? [caller, ...scope].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
14865
+ let provider;
14866
+ if (interposed) {
14867
+ if (interposedByCaller?.has(caller)) {
14868
+ provider = interposedByCaller.get(caller);
14869
+ } else {
14870
+ if (copyImages.has(caller)) {
14871
+ provider = caller;
14872
+ } else {
14873
+ for (const image of scope) {
14874
+ if (copyImages.has(image)) {
14875
+ provider = image;
14876
+ break;
14877
+ }
14878
+ }
14879
+ if (provider === void 0) provider = uniqueProvider;
14880
+ }
14881
+ ;
14882
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
14883
+ }
14884
+ } else {
14885
+ provider = firstProviderImage;
14886
+ }
14157
14887
  if (provider === void 0) {
14158
14888
  if (options.weakReferences.get(object3)?.has(symbol)) continue;
14159
14889
  throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
14160
14890
  }
14161
14891
  if (caller === provider) continue;
14162
- if ([...options.definitionObjects.get(symbol) ?? []].some(
14163
- (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
14164
- ))
14165
- continue;
14166
- if (!scope.includes(provider)) {
14167
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
14892
+ if (weakDefinerImages?.has(caller)) continue;
14893
+ if (!callerSets.get(caller).has(provider)) {
14168
14894
  const traced = [...record.providers.keys()];
14169
14895
  const strongTraced = traced.filter(
14170
14896
  (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
@@ -14172,16 +14898,17 @@ function verifyGuestSymbolScopes(options) {
14172
14898
  const providers = strongTraced.length === 1 ? strongTraced : traced;
14173
14899
  if (options.weakReferences.get(object3)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
14174
14900
  continue;
14175
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
14901
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
14902
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
14176
14903
  (definer) => options.weakDefinitions.get(definer)?.has(symbol)
14177
14904
  );
14178
- const strongCandidates = [...candidates].filter(
14905
+ const strongCandidates = [...candidateSet].filter(
14179
14906
  (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
14180
14907
  );
14181
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
14182
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
14908
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
14909
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
14183
14910
  // scope, the root image and its dependency closure, as in elf.
14184
- provider === 0 || callers.get(0)?.includes(provider) || !options.weakReferences.get(object3)?.has(symbol) && options.frameworkProviders.get(object3)?.has(providers[0]))))
14911
+ provider === 0 || rootScope?.has(provider) || !options.weakReferences.get(object3)?.has(symbol) && options.frameworkProviders.get(object3)?.has(providers[0]))))
14185
14912
  throw new Error(
14186
14913
  `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
14187
14914
  );
@@ -14390,6 +15117,85 @@ function clangProducerStamp(file) {
14390
15117
  const stat = (0, import_node_fs25.statSync)(file, { bigint: true });
14391
15118
  return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
14392
15119
  }
15120
+ function clangBinaryStamp(file) {
15121
+ const stat = (0, import_node_fs25.statSync)(file, { bigint: true });
15122
+ return [file, stat.size, stat.mtimeNs].join(":");
15123
+ }
15124
+ function clangWrapperStamp(file) {
15125
+ return (0, import_node_crypto17.createHash)("sha256").update((0, import_node_fs25.readFileSync)(file)).digest("hex");
15126
+ }
15127
+ function clangArgsNeedCwd(args) {
15128
+ const pathFlags = /* @__PURE__ */ new Set([
15129
+ "-I",
15130
+ "-isystem",
15131
+ "-iquote",
15132
+ "-F",
15133
+ "-iframework",
15134
+ "-isysroot",
15135
+ "-o",
15136
+ "-MF"
15137
+ ]);
15138
+ const includeFlags = /* @__PURE__ */ new Set(["-include", "-imacros"]);
15139
+ const valueFlags = /* @__PURE__ */ new Set([
15140
+ "-x",
15141
+ "-target",
15142
+ "-MT",
15143
+ "-MQ",
15144
+ "-D",
15145
+ "-U",
15146
+ "-mllvm",
15147
+ "-Xclang",
15148
+ "-arch",
15149
+ "-std"
15150
+ ]);
15151
+ const prefixFlags = [
15152
+ "-I",
15153
+ "-F",
15154
+ "-isystem",
15155
+ "-iquote",
15156
+ "--sysroot=",
15157
+ "-fmodule-map-file=",
15158
+ "-fmodules-cache-path="
15159
+ ];
15160
+ const isRelativePath = (value) => value.length > 0 && !value.startsWith("/") && !value.startsWith("=/") && value !== "-";
15161
+ for (let i = 1; i < args.length; i++) {
15162
+ const arg = args[i];
15163
+ if (pathFlags.has(arg)) {
15164
+ if (isRelativePath(args[++i] ?? "")) return true;
15165
+ continue;
15166
+ }
15167
+ if (includeFlags.has(arg)) {
15168
+ const value = args[++i] ?? "";
15169
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs25.existsSync)(value))) return true;
15170
+ continue;
15171
+ }
15172
+ if (valueFlags.has(arg)) {
15173
+ i++;
15174
+ continue;
15175
+ }
15176
+ if (arg.startsWith("@")) {
15177
+ if (isRelativePath(arg.slice(1))) return true;
15178
+ continue;
15179
+ }
15180
+ if (arg.startsWith("-")) {
15181
+ if (arg.startsWith("-include") && arg.length > 8) {
15182
+ const value = arg.slice(8);
15183
+ if (isRelativePath(value) && (value.includes("/") || (0, import_node_fs25.existsSync)(value)))
15184
+ return true;
15185
+ continue;
15186
+ }
15187
+ for (const prefix of prefixFlags) {
15188
+ if (arg.startsWith(prefix) && arg.length > prefix.length) {
15189
+ if (isRelativePath(arg.slice(prefix.length))) return true;
15190
+ break;
15191
+ }
15192
+ }
15193
+ continue;
15194
+ }
15195
+ if (isRelativePath(arg)) return true;
15196
+ }
15197
+ return false;
15198
+ }
14393
15199
  function validateClangLinkOptions(flags) {
14394
15200
  for (let index = 0; index < flags.length; index++) {
14395
15201
  const flag = flags[index];
@@ -14469,7 +15275,7 @@ function sourceGuestClangLinkOptions(options) {
14469
15275
  let clang;
14470
15276
  let clangStamp;
14471
15277
  let wrapperStamp;
14472
- for (const [index, file] of [...wanted].entries()) {
15278
+ for (const file of wanted) {
14473
15279
  const command = commands.get(file);
14474
15280
  if (!command) throw new Error(`missing source object producer ${file}`);
14475
15281
  if (command.tool === "shell") {
@@ -14483,12 +15289,12 @@ function sourceGuestClangLinkOptions(options) {
14483
15289
  throw new Error(`unsupported source object producer ${file}`);
14484
15290
  const key = (0, import_node_crypto17.createHash)("sha256").update(
14485
15291
  JSON.stringify([
14486
- "clang-link-options/v1",
14487
- process.cwd(),
15292
+ "clang-link-options/v2",
15293
+ clangArgsNeedCwd(command.args) ? process.cwd() : null,
14488
15294
  driverEnvironment,
14489
15295
  command.args,
14490
- clangStamp ??= clangProducerStamp(clang),
14491
- compiler === clang ? null : wrapperStamp ??= clangProducerStamp(compiler),
15296
+ clangStamp ??= clangBinaryStamp(clang),
15297
+ compiler === clang ? null : wrapperStamp ??= clangWrapperStamp(compiler),
14492
15298
  clangProducerStamp(file)
14493
15299
  ])
14494
15300
  ).digest("hex");
@@ -14503,31 +15309,44 @@ function sourceGuestClangLinkOptions(options) {
14503
15309
  continue;
14504
15310
  }
14505
15311
  result.set(file, []);
14506
- const args = command.args.slice(1).filter((arg) => arg !== "-c");
14507
15312
  const targetBuild = import_node_path25.default.relative(options.buildDirectory, file).split(import_node_path25.default.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
14508
- const outputDirectory = import_node_path25.default.join(
14509
- options.directory,
14510
- targetBuild ?? import_node_path25.default.basename(import_node_path25.default.dirname(file))
14511
- );
14512
- (0, import_node_fs25.mkdirSync)(outputDirectory, { recursive: true });
14513
- const output = import_node_path25.default.join(outputDirectory, `clang-link-${index}.ll`);
14514
- for (const flag of ["-o", "-MF"]) {
14515
- const index2 = args.lastIndexOf(flag);
14516
- if (index2 < 0 || index2 + 1 >= args.length)
14517
- throw new Error(`missing clang ${flag} for ${file}`);
14518
- args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
15313
+ const args = [];
15314
+ let sawOutput = false;
15315
+ let explicitModuleName = false;
15316
+ for (let i = 1; i < command.args.length; i++) {
15317
+ const arg = command.args[i];
15318
+ if (arg === "-c" || arg === "-MD" || arg === "-MMD" || arg === "-MP") continue;
15319
+ if (arg === "-MF" || arg === "-MT" || arg === "-MQ") {
15320
+ if (i + 1 >= command.args.length)
15321
+ throw new Error(`missing clang ${arg} for ${file}`);
15322
+ i++;
15323
+ continue;
15324
+ }
15325
+ if (arg === "-o") {
15326
+ if (i + 1 >= command.args.length) throw new Error(`missing clang -o for ${file}`);
15327
+ i++;
15328
+ args.push("-o", "-");
15329
+ sawOutput = true;
15330
+ continue;
15331
+ }
15332
+ if (arg.startsWith("-fmodule-name=")) explicitModuleName = true;
15333
+ args.push(arg);
15334
+ }
15335
+ if (!sawOutput) throw new Error(`missing clang -o for ${file}`);
15336
+ if (compiler !== clang && targetBuild && !explicitModuleName) {
15337
+ args.unshift(`-fmodule-name=${targetBuild.slice(0, -".build".length)}`);
14519
15338
  }
14520
15339
  replays.push({
14521
15340
  file,
14522
15341
  compiler: command.args[0],
14523
15342
  args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
14524
- output,
14525
15343
  cacheFile,
14526
15344
  key
14527
15345
  });
14528
15346
  }
14529
15347
  if (replays.length === 0) return result;
14530
15348
  const plan = import_node_path25.default.join(options.directory, "clang-link-replays.json");
15349
+ const resultsPath = import_node_path25.default.join(options.directory, "clang-link-results.json");
14531
15350
  (0, import_node_fs25.writeFileSync)(
14532
15351
  plan,
14533
15352
  JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
@@ -14540,12 +15359,16 @@ function sourceGuestClangLinkOptions(options) {
14540
15359
  ...process.env,
14541
15360
  [PEACH_FORKED_SCRIPT_ENV]: "1",
14542
15361
  PEACH_CLANG_REPLAYS: plan,
15362
+ PEACH_CLANG_RESULTS: resultsPath,
14543
15363
  PEACH_CLANG_JOBS: String(options.jobs)
14544
15364
  }
14545
15365
  });
15366
+ const replayMetadata = JSON.parse((0, import_node_fs25.readFileSync)(resultsPath, "utf8"));
15367
+ if (!Array.isArray(replayMetadata) || replayMetadata.length !== replays.length || !replayMetadata.every((item) => typeof item === "string"))
15368
+ throw new Error("invalid clang link replay results");
14546
15369
  (0, import_node_fs25.mkdirSync)(cacheDirectory, { recursive: true });
14547
- for (const { file, output, cacheFile, key } of replays) {
14548
- const flags = clangIrLinkOptions((0, import_node_fs25.readFileSync)(output, "utf8"));
15370
+ for (const [index, { file, cacheFile, key }] of replays.entries()) {
15371
+ const flags = clangIrLinkOptions(replayMetadata[index]);
14549
15372
  validateClangLinkOptions(flags);
14550
15373
  const temporary = `${cacheFile}.${process.pid}`;
14551
15374
  (0, import_node_fs25.writeFileSync)(temporary, JSON.stringify({ key, flags }));
@@ -14783,22 +15606,47 @@ var init_swift_guest_source_inputs = __esm({
14783
15606
  CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
14784
15607
  PARALLEL_REPLAY = `
14785
15608
  const { spawn } = require('node:child_process')
14786
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
15609
+ const fs = require('node:fs')
15610
+ const commands = JSON.parse(fs.readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
15611
+ const results = new Array(commands.length)
14787
15612
  let next = 0
14788
15613
  const run = () => {
14789
15614
  if (next >= commands.length) return Promise.resolve()
14790
- const [file, ...args] = commands[next++]
15615
+ const index = next++
15616
+ const [file, ...args] = commands[index]
14791
15617
  return new Promise((resolve, reject) => {
14792
- const child = spawn(file, args, { stdio: 'inherit' })
15618
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'inherit'] })
15619
+ const metadata = []
15620
+ let pending = ''
15621
+ child.stdout.setEncoding('utf8')
15622
+ child.stdout.on('data', (chunk) => {
15623
+ const text = pending + chunk
15624
+ let start = 0
15625
+ for (let nl = text.indexOf('\\n'); nl !== -1; nl = text.indexOf('\\n', start)) {
15626
+ if (text.charCodeAt(start) === 33) metadata.push(text.slice(start, nl))
15627
+ start = nl + 1
15628
+ }
15629
+ pending = text.slice(start)
15630
+ })
14793
15631
  child.on('error', reject)
14794
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
15632
+ child.on('close', (code) => {
15633
+ if (pending.charCodeAt(0) === 33) metadata.push(pending)
15634
+ if (code === 0) {
15635
+ results[index] = metadata.join('\\n')
15636
+ resolve()
15637
+ } else reject(new Error('clang link replay failed: ' + file))
15638
+ })
14795
15639
  }).then(run)
14796
15640
  }
14797
15641
  const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
14798
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
14799
- console.error(error.message)
14800
- process.exit(1)
14801
- })
15642
+ Promise.all(Array.from({ length: jobs }, run))
15643
+ .then(() => {
15644
+ fs.writeFileSync(process.env.PEACH_CLANG_RESULTS, JSON.stringify(results))
15645
+ })
15646
+ .catch((error) => {
15647
+ console.error(error.message)
15648
+ process.exit(1)
15649
+ })
14802
15650
  `;
14803
15651
  }
14804
15652
  });
@@ -16599,6 +17447,7 @@ __export(swift_sdk_app_module_exports, {
16599
17447
  readSwiftSdkUsage: () => readSwiftSdkUsage,
16600
17448
  selectSwiftSdkData: () => selectSwiftSdkData,
16601
17449
  swiftAppModuleInputs: () => swiftAppModuleInputs,
17450
+ swiftSdkProjectionSpans: () => swiftSdkProjectionSpans,
16602
17451
  writeSwiftSdkAppLink: () => writeSwiftSdkAppLink
16603
17452
  });
16604
17453
  async function buildSwiftAppModule(options) {
@@ -16714,15 +17563,18 @@ async function compileSdkForwarders(inputs, sdk, toolchainBin, output, project,
16714
17563
  index++;
16715
17564
  }
16716
17565
  const errno = tls.errno;
17566
+ let declaredErrno = false;
16717
17567
  for (const name3 of referenced) {
16718
17568
  const offset = tls[name3];
16719
17569
  if (offset === void 0 || defined.has(name3)) continue;
16720
17570
  if (errno === void 0 || signatures.__errno_location !== ":j")
16721
17571
  throw new Error("the sdk image has no errno to find its thread block by");
16722
- if (!lines.some((line) => line.startsWith("char *__peach_errno(")))
17572
+ if (!declaredErrno) {
17573
+ declaredErrno = true;
16723
17574
  lines.push(
16724
17575
  `__attribute__((import_module("env"), import_name("__errno_location"))) char *__peach_errno(void);`
16725
17576
  );
17577
+ }
16726
17578
  lines.push(
16727
17579
  `__attribute__((weak)) _Thread_local char t${index} __asm__(${literal2(name3)});`,
16728
17580
  `__attribute__((used)) long long h${index}(void) __asm__(${literal2(SDK_TLS_HELPER + name3)});`,
@@ -17098,6 +17950,20 @@ function resolveSdkReferences(source, sdk, forwarders) {
17098
17950
  symbols.filter((symbol) => symbol.kind === 0 && symbol.name.startsWith(SDK_TLS_HELPER)).map((symbol) => [symbol.name.slice(SDK_TLS_HELPER.length), symbol.index])
17099
17951
  );
17100
17952
  const segments = guestWasmDataSegments(bytes, false);
17953
+ const segmentsByOffset = [...segments].sort((a, b) => a.offset - b.offset);
17954
+ const segmentNameSet = new Set(segmentNames);
17955
+ const findSegmentByOffset = (at, size) => {
17956
+ let lo = 0;
17957
+ let hi = segmentsByOffset.length - 1;
17958
+ while (lo <= hi) {
17959
+ const mid = lo + hi >> 1;
17960
+ const entry = segmentsByOffset[mid];
17961
+ if (at < entry.offset) hi = mid - 1;
17962
+ else if (at >= entry.offset + entry.length) lo = mid + 1;
17963
+ else return at + size <= entry.offset + entry.length ? entry : void 0;
17964
+ }
17965
+ return void 0;
17966
+ };
17101
17967
  const tdata = segmentNames.indexOf(".tdata");
17102
17968
  const tlsTemplate = tdata < 0 ? void 0 : passiveSegments(bytes)[tdata];
17103
17969
  const tlsStart = tlsTemplate && tlsTemplate.byteOffset - bytes.byteOffset;
@@ -17162,7 +18028,7 @@ function resolveSdkReferences(source, sdk, forwarders) {
17162
18028
  const encoding = width.width;
17163
18029
  if (kind === "address" && target.id === 11 && encoding === "u64" && addend === 0n) {
17164
18030
  const section2 = OBJC_SECTION_BOUNDARY.exec(name3)?.[1];
17165
- if (section2 && !segmentNames.includes(section2)) {
18031
+ if (section2 && !segmentNameSet.has(section2)) {
17166
18032
  bytes.fill(0, at, at + 8);
17167
18033
  continue;
17168
18034
  }
@@ -17174,9 +18040,7 @@ function resolveSdkReferences(source, sdk, forwarders) {
17174
18040
  if (tlsStart !== void 0 && at >= tlsStart && at < tlsStart + tlsTemplate.length)
17175
18041
  linkage.tls.push(at - tlsStart, size, value);
17176
18042
  else {
17177
- const segment = segments.find(
17178
- (entry) => at >= entry.offset && at + size <= entry.offset + entry.length
17179
- );
18043
+ const segment = findSegmentByOffset(at, size);
17180
18044
  if (!segment)
17181
18045
  throw new Error(`Swift SDK relocation has no load address for ${name3}`);
17182
18046
  linkage.data.push(segment.address + at - segment.offset, size, value);
@@ -17220,15 +18084,29 @@ function resolveSdkReferences(source, sdk, forwarders) {
17220
18084
  }
17221
18085
  }
17222
18086
  }
17223
- const entries2 = imports.map((entry) => {
18087
+ const encodedNameBuf = (name3) => {
18088
+ const raw2 = Buffer.from(name3, "utf8");
18089
+ const len = uleb4(raw2.length);
18090
+ const out = Buffer.allocUnsafe(len.length + raw2.length);
18091
+ for (let i = 0; i < len.length; i++) out[i] = len[i];
18092
+ raw2.copy(out, len.length);
18093
+ return out;
18094
+ };
18095
+ const importParts = [];
18096
+ let importEntryCount = imports.length + 1;
18097
+ for (const entry of imports) {
17224
18098
  const slot = entry.kind === 0 && entry.module === "env" ? functionSlots.get(entry.name) : void 0;
17225
- return [
17226
- ...encodedName2(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
17227
- ...encodedName2(slot === void 0 ? entry.name : String(slot)),
17228
- ...bytes.subarray(entry.start, entry.end)
17229
- ];
17230
- });
17231
- entries2.push([...encodedName2("env"), ...encodedName2("__stack_pointer"), 3, 126, 1]);
18099
+ importParts.push(
18100
+ encodedNameBuf(slot === void 0 ? entry.module : NATIVE_SDK_IMPORT_MODULE),
18101
+ encodedNameBuf(slot === void 0 ? entry.name : String(slot)),
18102
+ bytes.subarray(entry.start, entry.end)
18103
+ );
18104
+ }
18105
+ importParts.push(
18106
+ encodedNameBuf("env"),
18107
+ encodedNameBuf("__stack_pointer"),
18108
+ Buffer.from([3, 126, 1])
18109
+ );
17232
18110
  const tags = sections.find((section2) => section2.id === 13);
17233
18111
  if (tags) {
17234
18112
  const r = wasmReader(bytes, tags.start);
@@ -17243,15 +18121,18 @@ function resolveSdkReferences(source, sdk, forwarders) {
17243
18121
  throw new Error(
17244
18122
  `Swift app defines an exception tag the sdk does not own: ${name3}`
17245
18123
  );
17246
- entries2.push([
17247
- ...encodedName2("env"),
17248
- ...encodedName2(name3),
17249
- 4,
17250
- ...bytes.subarray(start, r.at)
17251
- ]);
18124
+ importParts.push(
18125
+ encodedNameBuf("env"),
18126
+ encodedNameBuf(name3),
18127
+ Buffer.from([4]),
18128
+ bytes.subarray(start, r.at)
18129
+ );
18130
+ importEntryCount++;
17252
18131
  }
17253
18132
  }
17254
- const globals = [];
18133
+ const globalParts = [
18134
+ Buffer.from(uleb4(globalCount - 1 + syntheticGlobals.length))
18135
+ ];
17255
18136
  for (let index = 0; index < globalCount; index++) {
17256
18137
  const start = gr.at;
17257
18138
  const type = gr.byte();
@@ -17263,12 +18144,12 @@ function resolveSdkReferences(source, sdk, forwarders) {
17263
18144
  if (gr.byte() !== 11) throw new Error("app global initializer has no end");
17264
18145
  if (index === 0) continue;
17265
18146
  const value = got.get(index);
17266
- if (value === void 0) globals.push(...bytes.subarray(start, gr.at));
17267
- else globals.push(type, 1, type === 126 ? 66 : 65, 0, 11);
18147
+ if (value === void 0) globalParts.push(bytes.subarray(start, gr.at));
18148
+ else globalParts.push(Buffer.from([type, 1, type === 126 ? 66 : 65, 0, 11]));
17268
18149
  }
17269
18150
  for (const type of syntheticGlobals) {
17270
18151
  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];
17271
- globals.push(type, 1, ...zero, 11);
18152
+ globalParts.push(Buffer.from([type, 1, ...zero, 11]));
17272
18153
  }
17273
18154
  const exportSection = sections.find((s) => s.id === 7);
17274
18155
  if (!exportSection) throw new Error("app link has no exports");
@@ -17291,24 +18172,21 @@ function resolveSdkReferences(source, sdk, forwarders) {
17291
18172
  throw new Error("Swift app exceeds its reserved static memory range");
17292
18173
  }
17293
18174
  }
18175
+ const exportParts = [
18176
+ Buffer.from(uleb4(exportCount + 1 + got.size)),
18177
+ bytes.subarray(originalExportsStart, exportSection.end)
18178
+ ];
18179
+ for (const [index, value] of got) {
18180
+ exportParts.push(
18181
+ encodedNameBuf(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
18182
+ Buffer.from([3, ...uleb4(index)])
18183
+ );
18184
+ }
18185
+ exportParts.push(encodedNameBuf("__indirect_function_table"), Buffer.from([1, 0]));
17294
18186
  const replaced = /* @__PURE__ */ new Map([
17295
- [2, [...uleb4(entries2.length), ...entries2.flat()]],
17296
- [6, [...uleb4(globalCount - 1 + syntheticGlobals.length), ...globals]],
17297
- [
17298
- 7,
17299
- [
17300
- ...uleb4(exportCount + 1 + got.size),
17301
- ...bytes.subarray(originalExportsStart, exportSection.end),
17302
- ...[...got].flatMap(([index, value]) => [
17303
- ...encodedName2(`${NATIVE_SDK_GLOBAL_PREFIX}${value}.${index}`),
17304
- 3,
17305
- ...uleb4(index)
17306
- ]),
17307
- ...encodedName2("__indirect_function_table"),
17308
- 1,
17309
- 0
17310
- ]
17311
- ]
18187
+ [2, Buffer.concat([Buffer.from(uleb4(importEntryCount)), ...importParts])],
18188
+ [6, Buffer.concat(globalParts)],
18189
+ [7, Buffer.concat(exportParts)]
17312
18190
  ]);
17313
18191
  const rebuiltCode = expanded.length ? expandSdkRelocations(
17314
18192
  bytes,
@@ -17320,9 +18198,13 @@ function resolveSdkReferences(source, sdk, forwarders) {
17320
18198
  if (s === tags || s.name === "linking" || s.name?.startsWith("reloc.") || s.name === ".swift1_autolink_entries")
17321
18199
  continue;
17322
18200
  const payload = replaced.get(s.id);
17323
- parts.push(
17324
- s.id === 10 && rebuiltCode ? rebuiltCode : payload ? Uint8Array.from([s.id, ...uleb4(payload.length), ...payload]) : bytes.subarray(s.offset, s.end)
17325
- );
18201
+ if (s.id === 10 && rebuiltCode) {
18202
+ parts.push(rebuiltCode);
18203
+ } else if (payload) {
18204
+ parts.push(Buffer.from([s.id, ...uleb4(payload.length)]), payload);
18205
+ } else {
18206
+ parts.push(bytes.subarray(s.offset, s.end));
18207
+ }
17326
18208
  }
17327
18209
  return { bytes: Buffer.concat(parts), linkage };
17328
18210
  }
@@ -17420,6 +18302,49 @@ function readSwiftSdkUsage(mapFile, linkedFile, sdkObjects) {
17420
18302
  constructors: [...new Set(constructorKeys(map, (0, import_node_fs36.readFileSync)(linkedFile)))]
17421
18303
  };
17422
18304
  }
18305
+ function swiftSdkProjectionSpans(sdk, imageFor) {
18306
+ const { manifest, block } = readSwiftSdkManifest(sdk);
18307
+ const guestObjects = manifest.guestObjects;
18308
+ if (!guestObjects) return [];
18309
+ const { strings } = manifest;
18310
+ const fields = block("pieces");
18311
+ const ordered = [];
18312
+ for (let i = 0; i < fields.length; i += SWIFT_SDK_PIECE_FIELDS) {
18313
+ const size = fields[i + 1];
18314
+ if (!size) continue;
18315
+ ordered.push({
18316
+ address: fields[i],
18317
+ size,
18318
+ object: strings[fields[i + 3]]
18319
+ });
18320
+ }
18321
+ ordered.sort((a, b) => a.address - b.address);
18322
+ const imageOf = (object3) => {
18323
+ const product = guestObjects[object3]?.product;
18324
+ return product === void 0 ? void 0 : imageFor(object3, product);
18325
+ };
18326
+ const spans = [];
18327
+ for (let index = 0; index < ordered.length; index++) {
18328
+ const { object: object3, address, size } = ordered[index];
18329
+ const image = imageOf(object3);
18330
+ if (image === void 0) continue;
18331
+ let next = index + 1;
18332
+ while (next < ordered.length && ordered[next].address < address + size) next++;
18333
+ const end = ordered[next]?.address ?? address + size;
18334
+ spans.push({ image, space: "linear-memory", address, length: end - address });
18335
+ }
18336
+ const functionKeys = block("functions");
18337
+ const slots = block("functionSlots");
18338
+ for (let index = 0; index < functionKeys.length; index++) {
18339
+ const slot = slots[index];
18340
+ if (!slot) continue;
18341
+ const key = strings[functionKeys[index]];
18342
+ const image = imageOf(key.slice(0, key.indexOf(":")));
18343
+ if (image !== void 0)
18344
+ spans.push({ image, space: "function-table", address: slot, length: 1 });
18345
+ }
18346
+ return spans;
18347
+ }
17423
18348
  function selectSwiftSdkData(sdk, usage, linkage, projection) {
17424
18349
  const { manifest, block, segments } = readSwiftSdkManifest(sdk);
17425
18350
  const { strings } = manifest;
@@ -17442,15 +18367,24 @@ function selectSwiftSdkData(sdk, usage, linkage, projection) {
17442
18367
  });
17443
18368
  }
17444
18369
  const memory = new Map(segments.map((segment) => [segment.name, segment]));
17445
- const read = (address2, size) => {
18370
+ let lastSegment = segments[0];
18371
+ const segmentAt = (address2, size) => {
18372
+ if (lastSegment && address2 >= lastSegment.address && address2 + size <= lastSegment.address + lastSegment.data.length)
18373
+ return lastSegment;
17446
18374
  for (const segment of segments)
17447
- if (address2 >= segment.address && address2 + size <= segment.address + segment.data.length)
17448
- return segment.data.subarray(
17449
- address2 - segment.address,
17450
- address2 - segment.address + size
17451
- );
18375
+ if (address2 >= segment.address && address2 + size <= segment.address + segment.data.length) {
18376
+ lastSegment = segment;
18377
+ return segment;
18378
+ }
17452
18379
  return void 0;
17453
18380
  };
18381
+ const read = (address2, size) => {
18382
+ const segment = segmentAt(address2, size);
18383
+ return segment?.data.subarray(
18384
+ address2 - segment.address,
18385
+ address2 - segment.address + size
18386
+ );
18387
+ };
17454
18388
  const appSectionsByObject = /* @__PURE__ */ new Map();
17455
18389
  const appSections = /* @__PURE__ */ new Set();
17456
18390
  const appSymbols = /* @__PURE__ */ new Set();
@@ -17556,9 +18490,7 @@ function selectSwiftSdkData(sdk, usage, linkage, projection) {
17556
18490
  const classAddress = Number(
17557
18491
  new DataView(field.buffer, field.byteOffset, 8).getBigUint64(0, true)
17558
18492
  );
17559
- const segment = segments.find(
17560
- ({ address: address3, data }) => classAddress >= address3 && classAddress < address3 + data.length
17561
- );
18493
+ const segment = segmentAt(classAddress, 1);
17562
18494
  if (!segment) continue;
17563
18495
  const start = classAddress - segment.address;
17564
18496
  const end = segment.data.indexOf(0, start);
@@ -17766,7 +18698,7 @@ function selectSwiftSdkData(sdk, usage, linkage, projection) {
17766
18698
  if (current)
17767
18699
  runs.push({
17768
18700
  address: current.address,
17769
- bytes: Uint8Array.from(Buffer.concat(current.parts))
18701
+ bytes: Buffer.concat(current.parts)
17770
18702
  });
17771
18703
  };
17772
18704
  for (const piece of loaded) {
@@ -18184,13 +19116,19 @@ async function compileGuestLink(options) {
18184
19116
  const selectedSource = source.artifacts.filter(
18185
19117
  (artifact) => selected.has(import_node_path37.default.resolve(rewritten.get(artifact.path) ?? artifact.path))
18186
19118
  );
19119
+ const admittedCores = Number(process.env.TM_EXEC_CPU_CORES);
19120
+ const linuxMemory = process.env.TM_EXEC_ADMITTED === "1" && process.env.LINUX_BUILD_SCOPE ? Number(process.env.TM_EXEC_LINUX_MEMORY_MAX) : NaN;
19121
+ const clangReplayJobs = Number.isInteger(admittedCores) && admittedCores > 0 ? Math.min(
19122
+ admittedCores,
19123
+ Number.isSafeInteger(linuxMemory) && linuxMemory > 0 ? Math.max(options.jobs, Math.floor(linuxMemory / (512 * 1024 ** 2))) : Math.max(options.jobs, admittedCores)
19124
+ ) : options.jobs;
18187
19125
  const clangOptions2 = sourceGuestClangLinkOptions({
18188
19126
  buildDirectory: options.buildDirectory,
18189
19127
  directory,
18190
19128
  toolchainBin: options.toolchainBin,
18191
19129
  swiftCompiler: options.swiftCompiler,
18192
19130
  objects: selectedSource.map((artifact) => artifact.path),
18193
- jobs: options.jobs
19131
+ jobs: clangReplayJobs
18194
19132
  });
18195
19133
  const links = sourceGuestRuntimeLinks({
18196
19134
  toolchainBin: options.toolchainBin,
@@ -18292,9 +19230,9 @@ async function compileGuestLink(options) {
18292
19230
  }
18293
19231
  };
18294
19232
  },
18295
- resolvePlan: (selected, plan) => {
19233
+ resolvePlan: (selected, plan, readSelected) => {
18296
19234
  if (!prepared) throw new Error("guest runtime selection is unavailable");
18297
- const scope = selectedGuestSymbolInputs(plan, selected);
19235
+ const scope = selectedGuestSymbolInputs(plan, selected, readSelected);
18298
19236
  const owners = new Map(scope.owners);
18299
19237
  owners.set(import_node_path37.default.join(directory, "projection-discovery.o"), 0);
18300
19238
  const providersByImage = Map.groupBy(scope.owners, ([, image]) => image);
@@ -18372,7 +19310,8 @@ async function compileGuestLink(options) {
18372
19310
  createSwiftSdkBinding: createSwiftSdkBinding2,
18373
19311
  finishSwiftAppModule: finishSwiftAppModule2,
18374
19312
  linkSwiftAppModule: linkSwiftAppModule2,
18375
- readSwiftSdkUsage: readSwiftSdkUsage2
19313
+ readSwiftSdkUsage: readSwiftSdkUsage2,
19314
+ swiftSdkProjectionSpans: swiftSdkProjectionSpans2
18376
19315
  } = await Promise.resolve().then(() => (init_swift_sdk_app_module(), swift_sdk_app_module_exports));
18377
19316
  const project = options.project;
18378
19317
  const work = project ? (0, import_node_fs37.mkdtempSync)(import_node_path37.default.join(directory, "app-module-")) : import_node_path37.default.join(directory, "app-module");
@@ -18394,7 +19333,28 @@ async function compileGuestLink(options) {
18394
19333
  }
18395
19334
  const usage = readSwiftSdkUsage2(result.mapPath, options.output, sdkObjectKeys);
18396
19335
  const linkedModule = import_node_path37.default.join(work, "app.wasm");
19336
+ const sdkSpans = swiftSdkProjectionSpans2(
19337
+ sdk,
19338
+ (object3, product) => sdkObjectImages.get(object3) ?? sdkProductImages.get(product)
19339
+ );
18397
19340
  let storage = reserved;
19341
+ if (sdkSpans.length > 0) {
19342
+ const sdkCounts = guestProjectionRegionCounts(storage.images.length, sdkSpans);
19343
+ storage = reserveGuestProjectionStorage(
19344
+ storage.images,
19345
+ storage.capacities.map((capacity, index) => ({
19346
+ ...capacity,
19347
+ regions: capacity.regions + sdkCounts[index] + 16
19348
+ }))
19349
+ );
19350
+ const projectionSource = import_node_path37.default.join(work, "projection.c");
19351
+ (0, import_node_fs37.writeFileSync)(projectionSource, storage.source);
19352
+ (0, import_node_child_process23.execFileSync)(
19353
+ import_node_path37.default.join(options.toolchainBin, "clang"),
19354
+ [...clangOptions, "-c", projectionSource, "-o", projectionObject],
19355
+ { stdio: "pipe" }
19356
+ );
19357
+ }
18398
19358
  for (; ; ) {
18399
19359
  const link = await linkSwiftAppModule2({
18400
19360
  objects: [...owners.keys()],
@@ -18432,11 +19392,7 @@ async function compileGuestLink(options) {
18432
19392
  bindingRows.set((address - values.address) / 8, value);
18433
19393
  } else data.push(address, size, value);
18434
19394
  }
18435
- const sdkSpans = [];
18436
- const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk, usage, {
18437
- imageFor: (object3, product) => sdkObjectImages.get(object3) ?? sdkProductImages.get(product),
18438
- spans: sdkSpans
18439
- });
19395
+ const binding = createSwiftSdkBinding2({ ...link.linkage, data }, sdk, usage);
18440
19396
  const linked = (0, import_node_fs37.readFileSync)(
18441
19397
  project ? projectOutputFile(work, linkedModule, project) : linkedModule
18442
19398
  );
@@ -26170,7 +27126,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
26170
27126
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
26171
27127
  MULTI_MANIFEST_VERSION = 76;
26172
27128
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
26173
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
27129
+ compilerSourceDigest = true ? "d4cf22b53d08266bf9bd0238bffe899805f62daeb3d628664ee351830e496cda" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
26174
27130
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
26175
27131
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
26176
27132
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));