peachsim 0.1.2599 → 0.1.2601

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 (133) hide show
  1. package/cli/commands/detect.ts +16 -10
  2. package/dist-lib/agent-daemon-client.cjs +1 -1
  3. package/dist-lib/agent-events.cjs +1 -1
  4. package/dist-lib/attached-projects.cjs +1 -1
  5. package/dist-lib/auth/shared-session.cjs +1 -1
  6. package/dist-lib/backend-origin.cjs +1 -1
  7. package/dist-lib/beta.cjs +1 -1
  8. package/dist-lib/beta.mjs +2 -2
  9. package/dist-lib/bridge-constants.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.mjs +5 -5
  12. package/dist-lib/bridge-contract.cjs +1 -1
  13. package/dist-lib/bridge-contract.mjs +3 -3
  14. package/dist-lib/bundle-channel.cjs +11432 -11074
  15. package/dist-lib/capture-contract.cjs +1 -1
  16. package/dist-lib/capture-contract.mjs +3 -3
  17. package/dist-lib/cloud-contract.cjs +1 -1
  18. package/dist-lib/cloud-contract.mjs +3 -3
  19. package/dist-lib/cloud-test-args.cjs +1 -1
  20. package/dist-lib/cloud-test-args.mjs +2 -2
  21. package/dist-lib/cloud.cjs +1 -1
  22. package/dist-lib/cloud.mjs +7 -7
  23. package/dist-lib/config.cjs +1 -1
  24. package/dist-lib/config.mjs +5 -5
  25. package/dist-lib/detox/index.cjs +11 -2276
  26. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  27. package/dist-lib/esm-chunks/{acorn-KSGHEC5L.mjs → acorn-QZ2CUPHM.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-CK4NJNKN.mjs → chunk-36UH63MB.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-HDVUUMWS.mjs → chunk-3XOVNNLW.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-IFVAWDHV.mjs → chunk-4DSC65OJ.mjs} +5 -5
  31. package/dist-lib/esm-chunks/{chunk-KYAFF2Q6.mjs → chunk-5SWBLCBW.mjs} +5 -5
  32. package/dist-lib/esm-chunks/{chunk-JDBFQAWY.mjs → chunk-6YPM2YPR.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-CQ4RWCRW.mjs → chunk-7NCBX65P.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-BWGJ6NXY.mjs → chunk-AJARDL5C.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-7AHYPBWO.mjs → chunk-CK3Z4ICA.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-VQUR3L3X.mjs → chunk-E26HGQSD.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-WIT6VFZO.mjs → chunk-EWL5AKTY.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-F5HRYLB4.mjs → chunk-EZ4QHTFM.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-MPWL7GEG.mjs → chunk-K7OOJRZB.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-WTHOPBFM.mjs → chunk-N4YUQWGP.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-P4IK6BSJ.mjs → chunk-OSRDW3DT.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-E2OVC7ZZ.mjs → chunk-PE2YXAKR.mjs} +3 -3
  43. package/dist-lib/esm-chunks/{chunk-PC5C5JIJ.mjs → chunk-Q37TTP7V.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-7WHQG7AP.mjs → chunk-RL5UG2KA.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-V6QNDMVW.mjs → chunk-SGLGSFK7.mjs} +2 -2
  46. package/dist-lib/esm-chunks/{chunk-35Z53AZY.mjs → chunk-SYLKF7NM.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-4D3WJ4I7.mjs → chunk-VZZ4446Y.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-YJOP3ITO.mjs → chunk-Y4RGOFWV.mjs} +4 -4
  49. package/dist-lib/esm-chunks/{chunk-S6JNYU27.mjs → chunk-ZGZPGLDT.mjs} +1024 -653
  50. package/dist-lib/esm-chunks/{metro-layout-parser-PPZSA2LY.mjs → metro-layout-parser-GIQWWTMJ.mjs} +3 -3
  51. package/dist-lib/esm-chunks/{swift-package-prebuilt-L7A7TT6Q.mjs → swift-package-prebuilt-XEZH6YEY.mjs} +10 -10
  52. package/dist-lib/esm-chunks/{swift-sdk-app-module-B63EAEQ5.mjs → swift-sdk-app-module-COF7L4HK.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-QQQA3AAT.mjs → swift-sdk-image-AQCBWHPL.mjs} +14 -14
  54. package/dist-lib/esm-chunks/{swift-sdk-image-producer-QP6XD5O7.mjs → swift-sdk-image-producer-5L5LD4VP.mjs} +4 -4
  55. package/dist-lib/expo-swift-bundle.cjs +12833 -12475
  56. package/dist-lib/expo-swift-metadata.cjs +1 -1
  57. package/dist-lib/expo-swift-metadata.mjs +7 -7
  58. package/dist-lib/home-paths.cjs +1 -1
  59. package/dist-lib/host/bridge-host.cjs +12809 -12451
  60. package/dist-lib/host/fetch-proxy-handler.cjs +5434 -5422
  61. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  62. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  63. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  64. package/dist-lib/host/websocket-proxy.cjs +1 -1
  65. package/dist-lib/index.cjs +10 -2275
  66. package/dist-lib/kotlin-host.cjs +1 -1
  67. package/dist-lib/menu.cjs +1 -1
  68. package/dist-lib/menu.mjs +3 -3
  69. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  70. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  71. package/dist-lib/metro-production-bundle.cjs +1 -1
  72. package/dist-lib/metro-production-bundle.mjs +4 -4
  73. package/dist-lib/native-app-identity-project.cjs +23 -11
  74. package/dist-lib/native-app-identity-project.mjs +16 -16
  75. package/dist-lib/native-app-identity.cjs +1 -1
  76. package/dist-lib/native-app-identity.mjs +6 -6
  77. package/dist-lib/native-firebase-metadata.cjs +1 -1
  78. package/dist-lib/native-firebase-metadata.mjs +3 -3
  79. package/dist-lib/pdfium-raster.cjs +1 -1
  80. package/dist-lib/pdfium-raster.mjs +2 -2
  81. package/dist-lib/plist.cjs +1 -1
  82. package/dist-lib/plist.mjs +3 -3
  83. package/dist-lib/profiles.cjs +1 -1
  84. package/dist-lib/public-brand.cjs +1 -1
  85. package/dist-lib/public-origins-lib-esm.json +82 -81
  86. package/dist-lib/public-origins-lib.json +372 -435
  87. package/dist-lib/react-native-host-modules.cjs +1 -1
  88. package/dist-lib/react-native-host-modules.mjs +2 -2
  89. package/dist-lib/reap-browser.cjs +1 -1
  90. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  91. package/dist-lib/sdk.cjs +1 -1
  92. package/dist-lib/sdk.mjs +8 -8
  93. package/dist-lib/skills.cjs +1107 -745
  94. package/dist-lib/swift-compile.cjs +1029 -652
  95. package/dist-lib/swift-compile.mjs +10 -10
  96. package/dist-lib/swift-package.cjs +1 -1
  97. package/dist-lib/swift-package.mjs +3 -3
  98. package/dist-lib/swift-submit.cjs +1 -1
  99. package/dist-lib/swift-submit.mjs +6 -6
  100. package/dist-lib/swift-svg-raster.cjs +1 -1
  101. package/dist-lib/swift-svg-raster.mjs +2 -2
  102. package/dist-lib/swift-toolchain.cjs +1 -1
  103. package/dist-lib/swift.cjs +1 -1
  104. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  107. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  110. package/dist-lib/vendor/ignore.cjs +1 -1
  111. package/dist-lib/vendor/magic-string.cjs +1 -1
  112. package/dist-lib/vendor/plist.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/package.json +1 -3
  126. package/src/device-catalog.ts +4 -5
  127. package/src/ios-version.ts +8 -0
  128. package/src/kotlin-version-catalog.ts +6 -4
  129. package/src/swift-guest-compile.ts +5 -3
  130. package/src/swift-guest-image-ledger.ts +563 -264
  131. package/src/swift-guest-link.ts +628 -468
  132. package/src/wasm-binary-sections.ts +1 -1
  133. package/dist-lib/vendor/smol-toml.cjs +0 -768
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2599 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2601 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  import {
3
3
  SWIFT_AUTOLINK_LINKER,
4
4
  SWIFT_CACHE_HOLD_MARKER,
@@ -21,7 +21,7 @@ import {
21
21
  windowAdmission,
22
22
  withSwiftRootLock,
23
23
  writeSwiftAutolinkLinker
24
- } from "./chunk-CK4NJNKN.mjs";
24
+ } from "./chunk-36UH63MB.mjs";
25
25
  import {
26
26
  SWIFT_BINARY_TREES_DIR,
27
27
  SWIFT_NATIVE_INPUT_ROOT,
@@ -36,7 +36,7 @@ import {
36
36
  isSwiftResourcePath,
37
37
  isSwiftSourceLinkGraph,
38
38
  swiftProjectFilesProblems
39
- } from "./chunk-WIT6VFZO.mjs";
39
+ } from "./chunk-EWL5AKTY.mjs";
40
40
  import {
41
41
  OBJC_RESOURCE_ACCESSOR_BODY,
42
42
  OBJC_RESOURCE_ACCESSOR_HEADER,
@@ -60,16 +60,16 @@ import {
60
60
  swiftPackagePartition,
61
61
  swiftTargetModuleName,
62
62
  withoutGlogModuleMap
63
- } from "./chunk-BWGJ6NXY.mjs";
63
+ } from "./chunk-AJARDL5C.mjs";
64
64
  import {
65
65
  rnxPublicBrand
66
- } from "./chunk-HDVUUMWS.mjs";
66
+ } from "./chunk-3XOVNNLW.mjs";
67
67
  import {
68
68
  isRecord
69
- } from "./chunk-P4IK6BSJ.mjs";
69
+ } from "./chunk-OSRDW3DT.mjs";
70
70
  import {
71
71
  __publicField
72
- } from "./chunk-7WHQG7AP.mjs";
72
+ } from "./chunk-RL5UG2KA.mjs";
73
73
 
74
74
  // src/swift-compile.ts
75
75
  import {
@@ -9307,13 +9307,25 @@ function llvmType(value) {
9307
9307
  }
9308
9308
  var OBJC_INIT_RECORD = ".objc_init";
9309
9309
  var TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
9310
+ function concatParts(parts) {
9311
+ let total = 0;
9312
+ for (let i = 0; i < parts.length; i++) total += parts[i].byteLength;
9313
+ const out = Buffer.allocUnsafe(total);
9314
+ let offset = 0;
9315
+ for (let i = 0; i < parts.length; i++) {
9316
+ const part = parts[i];
9317
+ out.set(part, offset);
9318
+ offset += part.byteLength;
9319
+ }
9320
+ return out;
9321
+ }
9322
+ var sha256PairHex = typeof Bun !== "undefined" ? (first, second) => new Bun.CryptoHasher("sha256").update(first).update("\0").update(second).digest("hex") : (first, second) => createHash7("sha256").update(first).update("\0").update(second).digest("hex");
9310
9323
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options = {}) {
9311
9324
  if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
9312
9325
  const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9313
- const { sdkLookupOnly, sdkProduct, collectRewrittenSymbols } = options;
9326
+ const { sdkLookupOnly, sdkProduct, collectRewrittenSymbols, scan: scan2 } = options;
9314
9327
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
9315
9328
  const rewrite = binding !== void 0;
9316
- const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
9317
9329
  const types = [];
9318
9330
  const functionTypes = [];
9319
9331
  const definitions = [];
@@ -9324,10 +9336,344 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
9324
9336
  const eventImportNames = [];
9325
9337
  const functionSymbols = [];
9326
9338
  const addressTaken = /* @__PURE__ */ new Set();
9327
- let usesDlsym = false;
9328
- let usesDlerror = false;
9339
+ let usesDlsym = scan2?.usesDlsym ?? false;
9340
+ let usesDlerror = scan2?.usesDlerror ?? false;
9329
9341
  const dlerrorAlias = sdkLookupOnly ? "__peach_sdk_dlerror" : "__peach_dlerror";
9330
9342
  const usedSymbols = /* @__PURE__ */ new Set();
9343
+ const rewriteImportSection = (start, end) => {
9344
+ let offset = start;
9345
+ const number3 = () => {
9346
+ if (offset < end) {
9347
+ const first = bytes[offset];
9348
+ if (first < 128) {
9349
+ offset++;
9350
+ return first;
9351
+ }
9352
+ }
9353
+ let value = 0;
9354
+ let shift = 0;
9355
+ for (; ; ) {
9356
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
9357
+ const byte = bytes[offset++];
9358
+ value += (byte & 127) * 2 ** shift;
9359
+ if (!(byte & 128)) return value;
9360
+ shift += 7;
9361
+ }
9362
+ };
9363
+ const string2 = () => {
9364
+ const length = number3();
9365
+ const strEnd = offset + length;
9366
+ if (strEnd > end) throw new Error("invalid wasm string");
9367
+ const value = rawBuf.toString("utf8", offset, strEnd);
9368
+ offset = strEnd;
9369
+ return value;
9370
+ };
9371
+ const count = number3();
9372
+ const importWriter = new ByteWriter(end - start + 64);
9373
+ importWriter.uleb(count);
9374
+ for (let i = 0; i < count; i++) {
9375
+ const entryStart = offset;
9376
+ const module = string2();
9377
+ const nameStart = offset;
9378
+ const name = string2();
9379
+ const nameEnd = offset;
9380
+ const kind = bytes[offset++];
9381
+ if (kind === 0) {
9382
+ number3();
9383
+ if (collectRewrittenSymbols) functionImportNames.push(name);
9384
+ } else if (kind === 1) {
9385
+ const referenceType = bytes[offset++];
9386
+ if (referenceType !== 112 && referenceType !== 111)
9387
+ throw new Error("unsupported table type");
9388
+ const flags = number3();
9389
+ if (flags & ~7) throw new Error("unsupported table limits");
9390
+ number3();
9391
+ if (flags & 1) number3();
9392
+ } else if (kind === 2) {
9393
+ const flags = number3();
9394
+ if (flags & ~7) throw new Error("unsupported memory limits");
9395
+ number3();
9396
+ if (flags & 1) number3();
9397
+ } else if (kind === 3) offset += 2;
9398
+ else if (kind === 4) {
9399
+ number3();
9400
+ number3();
9401
+ } else throw new Error("unsupported wasm import");
9402
+ const isDlsym = instrumentDynamicLookups && module === "env" && name === "dlsym" && kind === 0;
9403
+ const isDlerror = instrumentDynamicLookups && module === "env" && name === "dlerror" && kind === 0;
9404
+ const rewrittenName = isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module === "env" && name !== "dlsym" && name !== "dlerror" ? binding(name) ?? name : name;
9405
+ if (rewrittenName === name) {
9406
+ importWriter.bytes(bytes, entryStart, offset);
9407
+ } else {
9408
+ importWriter.bytes(bytes, entryStart, nameStart);
9409
+ importWriter.string(rewrittenName);
9410
+ importWriter.bytes(bytes, nameEnd, offset);
9411
+ }
9412
+ if (collectRewrittenSymbols) {
9413
+ if (kind === 0)
9414
+ functionImportNames[functionImportNames.length - 1] = rewrittenName;
9415
+ else if (kind === 1) tableImportNames.push(rewrittenName);
9416
+ else if (kind === 3) globalImportNames.push(rewrittenName);
9417
+ else if (kind === 4) eventImportNames.push(rewrittenName);
9418
+ }
9419
+ }
9420
+ if (offset !== end) throw new Error("invalid wasm import section");
9421
+ return importWriter.finish();
9422
+ };
9423
+ const rewriteLinkingSection = (start, end) => {
9424
+ let offset = start;
9425
+ const number3 = () => {
9426
+ if (offset < end) {
9427
+ const first = bytes[offset];
9428
+ if (first < 128) {
9429
+ offset++;
9430
+ return first;
9431
+ }
9432
+ }
9433
+ let value = 0;
9434
+ let shift = 0;
9435
+ for (; ; ) {
9436
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
9437
+ const byte = bytes[offset++];
9438
+ value += (byte & 127) * 2 ** shift;
9439
+ if (!(byte & 128)) return value;
9440
+ shift += 7;
9441
+ }
9442
+ };
9443
+ const string2 = () => {
9444
+ const length = number3();
9445
+ const strEnd = offset + length;
9446
+ if (strEnd > end) throw new Error("invalid wasm string");
9447
+ const value = rawBuf.toString("utf8", offset, strEnd);
9448
+ offset = strEnd;
9449
+ return value;
9450
+ };
9451
+ const sectionName = string2();
9452
+ const version2 = number3();
9453
+ if (version2 !== 2) throw new Error("unsupported wasm linking version");
9454
+ const subsections = [];
9455
+ let objcLoader;
9456
+ while (offset < end) {
9457
+ const kind = bytes[offset++];
9458
+ const length = number3();
9459
+ const stop = offset + length;
9460
+ if (stop > end) throw new Error("invalid linking subsection");
9461
+ const contentStart = offset;
9462
+ if (kind === 7 && !sdkLookupOnly) {
9463
+ const comdatWriter = new ByteWriter(length + 64);
9464
+ const count = number3();
9465
+ comdatWriter.uleb(count);
9466
+ for (let i = 0; i < count; i++) {
9467
+ const group = string2();
9468
+ const begin = offset;
9469
+ number3();
9470
+ const members = number3();
9471
+ for (let member = 0; member < members * 2; member++) number3();
9472
+ comdatWriter.string(
9473
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
9474
+ );
9475
+ comdatWriter.bytes(bytes, begin, offset);
9476
+ }
9477
+ if (offset !== stop) throw new Error("invalid comdat subsection");
9478
+ const buf = comdatWriter.finish();
9479
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
9480
+ } else if (kind === 8) {
9481
+ const entryWriter = new ByteWriter(length + 128);
9482
+ let extraWriter;
9483
+ const count = number3();
9484
+ let added = 0;
9485
+ for (let i = 0; i < count; i++) {
9486
+ const begin = offset;
9487
+ const symbolKind = bytes[offset++];
9488
+ const flags = number3();
9489
+ const flagsEnd = offset;
9490
+ let index = -1;
9491
+ let name = "";
9492
+ let nameStart = -1;
9493
+ let nameEnd = -1;
9494
+ const isLocalDefined = !(flags & 16) && (flags & 3) === 2;
9495
+ if (symbolKind === 0 || symbolKind === 2 || symbolKind === 4 || symbolKind === 5) {
9496
+ index = number3();
9497
+ if (!(flags & 16) || flags & 64) {
9498
+ nameStart = offset;
9499
+ const nameLen = number3();
9500
+ nameEnd = offset + nameLen;
9501
+ if (nameEnd > end) throw new Error("invalid wasm string");
9502
+ if (!isLocalDefined || !sdkLookupOnly && symbolKind === 0 && nameLen === OBJC_LOAD_FUNCTION.length) {
9503
+ name = rawBuf.toString("utf8", offset, nameEnd);
9504
+ }
9505
+ offset = nameEnd;
9506
+ }
9507
+ } else if (symbolKind === 1) {
9508
+ nameStart = offset;
9509
+ const nameLen = number3();
9510
+ nameEnd = offset + nameLen;
9511
+ if (nameEnd > end) throw new Error("invalid wasm string");
9512
+ if (!isLocalDefined) name = rawBuf.toString("utf8", offset, nameEnd);
9513
+ offset = nameEnd;
9514
+ if (!(flags & 16)) {
9515
+ if ((flags & 3) !== 3) {
9516
+ number3();
9517
+ number3();
9518
+ }
9519
+ number3();
9520
+ if ((flags & 3) === 3) offset++;
9521
+ }
9522
+ } else if (symbolKind === 3) number3();
9523
+ else throw new Error("unsupported wasm symbol kind");
9524
+ if (!sdkLookupOnly && symbolKind === 0 && !(flags & 16) && name === OBJC_LOAD_FUNCTION) {
9525
+ objcLoader = i;
9526
+ }
9527
+ if (isLocalDefined) {
9528
+ entryWriter.bytes(bytes, begin, offset);
9529
+ continue;
9530
+ }
9531
+ let rewrittenSym = name;
9532
+ let addedCanonical;
9533
+ let bound;
9534
+ let alias;
9535
+ if ((name === "dlsym" && usesDlsym || name === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
9536
+ rewrittenSym = name === "dlsym" ? callerAlias : dlerrorAlias;
9537
+ entryWriter.bytes(bytes, begin, nameStart);
9538
+ entryWriter.string(rewrittenSym);
9539
+ entryWriter.bytes(bytes, nameEnd, offset);
9540
+ } else if (flags & 16 && name !== "dlsym" && name !== "dlerror" && (bound = binding(name)) !== void 0) {
9541
+ rewrittenSym = bound;
9542
+ entryWriter.bytes(bytes, begin, nameStart);
9543
+ entryWriter.string(rewrittenSym);
9544
+ entryWriter.bytes(bytes, nameEnd, offset);
9545
+ } else if (!(flags & 16) && (alias = names.get(name)) !== void 0) {
9546
+ if (symbolKind !== 0 && symbolKind !== 1)
9547
+ throw new Error(`unsupported symbol ${name}`);
9548
+ if (preserveCanonical.has(name)) {
9549
+ entryWriter.bytes(bytes, begin, offset);
9550
+ extraWriter ?? (extraWriter = new ByteWriter(256));
9551
+ extraWriter.byte(bytes[begin]);
9552
+ extraWriter.uleb(flags & ~32);
9553
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
9554
+ extraWriter.string(alias);
9555
+ extraWriter.bytes(bytes, nameEnd, offset);
9556
+ added++;
9557
+ addedCanonical = alias;
9558
+ } else {
9559
+ rewrittenSym = alias;
9560
+ entryWriter.bytes(bytes, begin, nameStart);
9561
+ entryWriter.string(alias);
9562
+ entryWriter.bytes(bytes, nameEnd, offset);
9563
+ }
9564
+ } else {
9565
+ entryWriter.bytes(bytes, begin, offset);
9566
+ }
9567
+ if (collectRewrittenSymbols) {
9568
+ if (flags & 16) {
9569
+ const resolved = flags & 64 || symbolKind === 1 ? rewrittenSym : symbolKind === 0 ? functionImportNames[index] ?? "" : symbolKind === 2 ? globalImportNames[index] ?? "" : symbolKind === 4 ? eventImportNames[index] ?? "" : symbolKind === 5 ? tableImportNames[index] ?? "" : "";
9570
+ if (resolved) collectRewrittenSymbols.referenced.add(resolved);
9571
+ } else {
9572
+ if (rewrittenSym) collectRewrittenSymbols.defined.add(rewrittenSym);
9573
+ if (addedCanonical) collectRewrittenSymbols.defined.add(addedCanonical);
9574
+ }
9575
+ }
9576
+ }
9577
+ if (offset !== stop) throw new Error("invalid symbol subsection");
9578
+ const countBytes = encodeNumber(count + added);
9579
+ const entryBuf = entryWriter.finish();
9580
+ if (extraWriter) {
9581
+ const extraBuf = extraWriter.finish();
9582
+ subsections.push({
9583
+ kind,
9584
+ parts: [countBytes, entryBuf, extraBuf],
9585
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
9586
+ });
9587
+ } else {
9588
+ subsections.push({
9589
+ kind,
9590
+ parts: [countBytes, entryBuf],
9591
+ byteLength: countBytes.length + entryBuf.length
9592
+ });
9593
+ }
9594
+ } else {
9595
+ subsections.push({
9596
+ kind,
9597
+ parts: [bytes.subarray(contentStart, stop)],
9598
+ byteLength: length
9599
+ });
9600
+ }
9601
+ offset = stop;
9602
+ }
9603
+ const linkingWriter = new ByteWriter(end - start + 128);
9604
+ linkingWriter.string(sectionName);
9605
+ linkingWriter.uleb(version2);
9606
+ for (const subsection of subsections) {
9607
+ if (subsection.kind === 6 && objcLoader !== void 0) {
9608
+ const content = subsection.parts[0];
9609
+ const [count, entriesStart] = readNumber(content, 0);
9610
+ const initWriter = new ByteWriter(content.length + 16);
9611
+ initWriter.bytes(content, 0, entriesStart);
9612
+ let entryStart = entriesStart;
9613
+ for (let i = 0; i < count; i++) {
9614
+ const [, symbolStart] = readNumber(content, entryStart);
9615
+ const [symbol, entryEnd] = readNumber(content, symbolStart);
9616
+ if (symbol === objcLoader) {
9617
+ initWriter.uleb(1);
9618
+ initWriter.bytes(content, symbolStart, entryEnd);
9619
+ } else {
9620
+ initWriter.bytes(content, entryStart, entryEnd);
9621
+ }
9622
+ entryStart = entryEnd;
9623
+ }
9624
+ if (entryStart !== content.length)
9625
+ throw new Error("invalid init functions subsection");
9626
+ const initBuf = initWriter.finish();
9627
+ linkingWriter.byte(subsection.kind);
9628
+ linkingWriter.uleb(initBuf.length);
9629
+ linkingWriter.bytes(initBuf);
9630
+ } else {
9631
+ linkingWriter.byte(subsection.kind);
9632
+ linkingWriter.uleb(subsection.byteLength);
9633
+ for (const part of subsection.parts) linkingWriter.bytes(part);
9634
+ }
9635
+ }
9636
+ return linkingWriter.finish();
9637
+ };
9638
+ if (rewrite && scan2 && (scan2.importHeaderStart < 0 || scan2.linkingHeaderStart < 0 || scan2.importHeaderStart < scan2.linkingHeaderStart)) {
9639
+ const parts = [];
9640
+ let cursor = 0;
9641
+ if (scan2.importHeaderStart >= 0) {
9642
+ if (scan2.importHeaderStart > cursor)
9643
+ parts.push(bytes.subarray(cursor, scan2.importHeaderStart));
9644
+ const rewrittenImport = rewriteImportSection(scan2.importStart, scan2.importEnd);
9645
+ parts.push(Buffer.from([2]), encodeNumber(rewrittenImport.length), rewrittenImport);
9646
+ cursor = scan2.importEnd;
9647
+ }
9648
+ if (scan2.linkingHeaderStart >= 0) {
9649
+ if (scan2.linkingHeaderStart > cursor)
9650
+ parts.push(bytes.subarray(cursor, scan2.linkingHeaderStart));
9651
+ const rewrittenLinking = rewriteLinkingSection(scan2.linkingStart, scan2.linkingEnd);
9652
+ parts.push(
9653
+ Buffer.from([0]),
9654
+ encodeNumber(rewrittenLinking.length),
9655
+ rewrittenLinking
9656
+ );
9657
+ cursor = scan2.linkingEnd;
9658
+ }
9659
+ if (cursor < bytes.length) parts.push(bytes.subarray(cursor));
9660
+ return {
9661
+ bytes: concatParts(parts),
9662
+ definitions,
9663
+ functionImports,
9664
+ usesDlsym,
9665
+ usesDlerror,
9666
+ usedSymbols,
9667
+ addressTaken: []
9668
+ };
9669
+ }
9670
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
9671
+ let importHeaderStart = -1;
9672
+ let importStart = -1;
9673
+ let importEnd = -1;
9674
+ let linkingHeaderStart = -1;
9675
+ let linkingStart = -1;
9676
+ let linkingEnd = -1;
9331
9677
  let position = 8;
9332
9678
  while (position < bytes.length) {
9333
9679
  const headerStart = position;
@@ -9391,6 +9737,9 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
9391
9737
  types.push({ parameters, results });
9392
9738
  }
9393
9739
  } else if (id === 2) {
9740
+ importHeaderStart = headerStart;
9741
+ importStart = start;
9742
+ importEnd = end;
9394
9743
  const count = number3();
9395
9744
  const importWriter = rewrite ? new ByteWriter(size + 64) : void 0;
9396
9745
  importWriter?.uleb(count);
@@ -9465,210 +9814,88 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
9465
9814
  } else if (id === 0) {
9466
9815
  const sectionName = string2();
9467
9816
  if (sectionName === "linking") {
9468
- const version2 = number3();
9469
- if (version2 !== 2) throw new Error("unsupported wasm linking version");
9470
- const subsections = rewrite ? [] : void 0;
9471
- let objcLoader;
9472
- while (offset < end) {
9473
- const kind = bytes[offset++];
9474
- const length = number3();
9475
- const stop = offset + length;
9476
- if (stop > end) throw new Error("invalid linking subsection");
9477
- const contentStart = offset;
9478
- if (kind === 7 && rewrite && !sdkLookupOnly) {
9479
- const comdatWriter = new ByteWriter(length + 64);
9480
- const count = number3();
9481
- comdatWriter.uleb(count);
9482
- for (let i = 0; i < count; i++) {
9483
- const group = string2();
9484
- const begin = offset;
9485
- number3();
9486
- const members = number3();
9487
- for (let member = 0; member < members * 2; member++) number3();
9488
- comdatWriter.string(
9489
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
9490
- );
9491
- comdatWriter.bytes(bytes, begin, offset);
9492
- }
9493
- if (offset !== stop) throw new Error("invalid comdat subsection");
9494
- const buf = comdatWriter.finish();
9495
- subsections.push({ kind, parts: [buf], byteLength: buf.length });
9496
- } else if (kind === 8) {
9497
- const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
9498
- let extraWriter;
9499
- const count = number3();
9500
- let added = 0;
9501
- for (let i = 0; i < count; i++) {
9502
- const begin = offset;
9503
- const symbolKind = bytes[offset++];
9504
- const flags = number3();
9505
- const flagsEnd = offset;
9506
- let index = -1;
9507
- let name = "";
9508
- let nameStart = -1;
9509
- let nameEnd = -1;
9510
- if (symbolKind === 0 || symbolKind === 2 || symbolKind === 4 || symbolKind === 5) {
9511
- index = number3();
9512
- if (!(flags & 16) || flags & 64) {
9513
- nameStart = offset;
9514
- name = string2();
9515
- nameEnd = offset;
9516
- }
9517
- } else if (symbolKind === 1) {
9518
- nameStart = offset;
9519
- name = string2();
9520
- nameEnd = offset;
9521
- if (!(flags & 16)) {
9522
- if ((flags & 3) !== 3) {
9523
- number3();
9817
+ linkingHeaderStart = headerStart;
9818
+ linkingStart = start;
9819
+ linkingEnd = end;
9820
+ if (rewrite) {
9821
+ rewrittenSection = rewriteLinkingSection(start, end);
9822
+ } else {
9823
+ const version2 = number3();
9824
+ if (version2 !== 2) throw new Error("unsupported wasm linking version");
9825
+ while (offset < end) {
9826
+ const kind = bytes[offset++];
9827
+ const length = number3();
9828
+ const stop = offset + length;
9829
+ if (stop > end) throw new Error("invalid linking subsection");
9830
+ if (kind === 8) {
9831
+ const count = number3();
9832
+ for (let i = 0; i < count; i++) {
9833
+ const symbolKind = bytes[offset++];
9834
+ const flags = number3();
9835
+ let index = -1;
9836
+ let name = "";
9837
+ if (symbolKind === 0 || symbolKind === 2 || symbolKind === 4 || symbolKind === 5) {
9838
+ index = number3();
9839
+ if (!(flags & 16) || flags & 64) name = string2();
9840
+ } else if (symbolKind === 1) {
9841
+ const nameLen = number3();
9842
+ const nameEnd = offset + nameLen;
9843
+ if (nameEnd > end) throw new Error("invalid wasm string");
9844
+ if (flags & 16 || (flags & 3) !== 2)
9845
+ name = rawBuf.toString("utf8", offset, nameEnd);
9846
+ offset = nameEnd;
9847
+ if (!(flags & 16)) {
9848
+ if ((flags & 3) !== 3) {
9849
+ number3();
9850
+ number3();
9851
+ }
9524
9852
  number3();
9853
+ if ((flags & 3) === 3) offset++;
9525
9854
  }
9526
- number3();
9527
- if ((flags & 3) === 3) offset++;
9528
- }
9529
- } else if (symbolKind === 3) number3();
9530
- else throw new Error("unsupported wasm symbol kind");
9531
- if (!rewrite && symbolKind === 0)
9532
- functionSymbols[i] = name || functionImportNames[index];
9533
- if (rewrite && !sdkLookupOnly && name === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
9534
- objcLoader = i;
9535
- }
9536
- const alias = names.get(name);
9537
- if (!rewrite && flags & 16 && symbolKind === 1 && alias)
9538
- usedSymbols.add(name);
9539
- if (entryWriter && binding) {
9540
- let rewrittenSym = name;
9541
- let addedCanonical;
9542
- if ((name === "dlsym" && usesDlsym || name === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
9543
- rewrittenSym = name === "dlsym" ? callerAlias : dlerrorAlias;
9544
- entryWriter.bytes(bytes, begin, nameStart);
9545
- entryWriter.string(rewrittenSym);
9546
- entryWriter.bytes(bytes, nameEnd, offset);
9547
- } else if (flags & 16 && name !== "dlsym" && name !== "dlerror" && binding(name) !== void 0) {
9548
- rewrittenSym = binding(name);
9549
- entryWriter.bytes(bytes, begin, nameStart);
9550
- entryWriter.string(rewrittenSym);
9551
- entryWriter.bytes(bytes, nameEnd, offset);
9552
- } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
9855
+ } else if (symbolKind === 3) number3();
9856
+ else throw new Error("unsupported wasm symbol kind");
9857
+ if (symbolKind === 0)
9858
+ functionSymbols[i] = name || functionImportNames[index];
9859
+ if (flags & 16) {
9860
+ if (symbolKind === 1 && names.has(name)) usedSymbols.add(name);
9861
+ } else if ((flags & 3) !== 2 && names.has(name)) {
9553
9862
  if (symbolKind !== 0 && symbolKind !== 1)
9554
9863
  throw new Error(`unsupported symbol ${name}`);
9555
- if (preserveCanonical.has(name)) {
9556
- entryWriter.bytes(bytes, begin, offset);
9557
- extraWriter ?? (extraWriter = new ByteWriter(256));
9558
- extraWriter.byte(bytes[begin]);
9559
- extraWriter.uleb(flags & ~32);
9560
- extraWriter.bytes(bytes, flagsEnd, nameStart);
9561
- extraWriter.string(alias);
9562
- extraWriter.bytes(bytes, nameEnd, offset);
9563
- added++;
9564
- addedCanonical = alias;
9565
- } else {
9566
- rewrittenSym = alias;
9567
- entryWriter.bytes(bytes, begin, nameStart);
9568
- entryWriter.string(alias);
9569
- entryWriter.bytes(bytes, nameEnd, offset);
9570
- }
9571
- } else {
9572
- entryWriter.bytes(bytes, begin, offset);
9573
- }
9574
- if (collectRewrittenSymbols) {
9575
- if (flags & 16) {
9576
- const resolved = flags & 64 || symbolKind === 1 ? rewrittenSym : symbolKind === 0 ? functionImportNames[index] ?? "" : symbolKind === 2 ? globalImportNames[index] ?? "" : symbolKind === 4 ? eventImportNames[index] ?? "" : symbolKind === 5 ? tableImportNames[index] ?? "" : "";
9577
- if (resolved) collectRewrittenSymbols.referenced.add(resolved);
9578
- } else if ((flags & 3) !== 2) {
9579
- if (rewrittenSym) collectRewrittenSymbols.defined.add(rewrittenSym);
9580
- if (addedCanonical)
9581
- collectRewrittenSymbols.defined.add(addedCanonical);
9582
- }
9583
- }
9584
- } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
9585
- if (symbolKind !== 0 && symbolKind !== 1)
9586
- throw new Error(`unsupported symbol ${name}`);
9587
- const type = symbolKind === 0 ? types[functionTypes[index]] : void 0;
9588
- if (symbolKind === 0 && !type) throw new Error(`missing type for ${name}`);
9589
- definitions.push({
9590
- name,
9591
- kind: symbolKind === 0 ? "function" : "data",
9592
- weak: (flags & 3) === 1,
9593
- exportName: (flags & 32) !== 0,
9594
- hidden: (flags & 4) !== 0,
9595
- type
9596
- });
9597
- }
9598
- }
9599
- if (offset !== stop) throw new Error("invalid symbol subsection");
9600
- if (entryWriter) {
9601
- const countBytes = encodeNumber(count + added);
9602
- const entryBuf = entryWriter.finish();
9603
- if (extraWriter) {
9604
- const extraBuf = extraWriter.finish();
9605
- subsections.push({
9606
- kind,
9607
- parts: [countBytes, entryBuf, extraBuf],
9608
- byteLength: countBytes.length + entryBuf.length + extraBuf.length
9609
- });
9610
- } else {
9611
- subsections.push({
9612
- kind,
9613
- parts: [countBytes, entryBuf],
9614
- byteLength: countBytes.length + entryBuf.length
9615
- });
9616
- }
9617
- }
9618
- } else if (subsections) {
9619
- subsections.push({
9620
- kind,
9621
- parts: [bytes.subarray(contentStart, stop)],
9622
- byteLength: length
9623
- });
9624
- }
9625
- offset = stop;
9626
- }
9627
- if (subsections) {
9628
- const linkingWriter = new ByteWriter(size + 128);
9629
- linkingWriter.string(sectionName);
9630
- linkingWriter.uleb(version2);
9631
- for (const subsection of subsections) {
9632
- if (subsection.kind === 6 && objcLoader !== void 0) {
9633
- const content = subsection.parts[0];
9634
- const [count, entriesStart] = readNumber(content, 0);
9635
- const initWriter = new ByteWriter(content.length + 16);
9636
- initWriter.bytes(content, 0, entriesStart);
9637
- let entryStart = entriesStart;
9638
- for (let i = 0; i < count; i++) {
9639
- const [, symbolStart] = readNumber(content, entryStart);
9640
- const [symbol, entryEnd] = readNumber(content, symbolStart);
9641
- if (symbol === objcLoader) {
9642
- initWriter.uleb(1);
9643
- initWriter.bytes(content, symbolStart, entryEnd);
9644
- } else {
9645
- initWriter.bytes(content, entryStart, entryEnd);
9864
+ const type = symbolKind === 0 ? types[functionTypes[index]] : void 0;
9865
+ if (symbolKind === 0 && !type)
9866
+ throw new Error(`missing type for ${name}`);
9867
+ definitions.push({
9868
+ name,
9869
+ kind: symbolKind === 0 ? "function" : "data",
9870
+ weak: (flags & 3) === 1,
9871
+ exportName: (flags & 32) !== 0,
9872
+ hidden: (flags & 4) !== 0,
9873
+ type
9874
+ });
9646
9875
  }
9647
- entryStart = entryEnd;
9648
9876
  }
9649
- if (entryStart !== content.length)
9650
- throw new Error("invalid init functions subsection");
9651
- const initBuf = initWriter.finish();
9652
- linkingWriter.byte(subsection.kind);
9653
- linkingWriter.uleb(initBuf.length);
9654
- linkingWriter.bytes(initBuf);
9655
- } else {
9656
- linkingWriter.byte(subsection.kind);
9657
- linkingWriter.uleb(subsection.byteLength);
9658
- for (const part of subsection.parts) linkingWriter.bytes(part);
9877
+ if (offset !== stop) throw new Error("invalid symbol subsection");
9659
9878
  }
9879
+ offset = stop;
9660
9880
  }
9661
- rewrittenSection = linkingWriter.finish();
9662
9881
  }
9663
9882
  } else if (!rewrite && sectionName.startsWith("reloc.")) {
9664
9883
  number3();
9665
9884
  for (let count = number3(); count > 0; count--) {
9666
- const type = number3();
9667
- number3();
9668
- const name = functionSymbols[number3()];
9669
- if (ADDEND_RELOCATIONS.has(type)) number3();
9670
- if (name !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
9671
- addressTaken.add(name);
9885
+ const b0 = bytes[offset];
9886
+ const type = b0 < 128 ? (offset++, b0) : number3();
9887
+ if (offset < end && bytes[offset] < 128) offset++;
9888
+ else number3();
9889
+ const b2 = bytes[offset];
9890
+ const symIdx = b2 < 128 ? (offset++, b2) : number3();
9891
+ if (ADDEND_RELOCATIONS.has(type)) {
9892
+ if (offset < end && bytes[offset] < 128) offset++;
9893
+ else number3();
9894
+ }
9895
+ if (TABLE_INDEX_RELOCATIONS.has(type)) {
9896
+ const name = functionSymbols[symIdx];
9897
+ if (name !== void 0) addressTaken.add(name);
9898
+ }
9672
9899
  }
9673
9900
  if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
9674
9901
  }
@@ -9687,9 +9914,21 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
9687
9914
  }
9688
9915
  return {
9689
9916
  bytes: sections ? Buffer.concat(sections) : bytes,
9917
+ parts: sections,
9918
+ scan: !rewrite ? {
9919
+ importHeaderStart,
9920
+ importStart,
9921
+ importEnd,
9922
+ linkingHeaderStart,
9923
+ linkingStart,
9924
+ linkingEnd,
9925
+ usesDlsym,
9926
+ usesDlerror
9927
+ } : void 0,
9690
9928
  definitions,
9691
9929
  functionImports,
9692
9930
  usesDlsym,
9931
+ usesDlerror,
9693
9932
  usedSymbols,
9694
9933
  addressTaken: [...addressTaken]
9695
9934
  };
@@ -9759,7 +9998,8 @@ function createGuestImageLedger(input) {
9759
9998
  object: object2,
9760
9999
  aliases,
9761
10000
  usedSymbols: rewritten.usedSymbols,
9762
- functionImports: rewritten.functionImports
10001
+ functionImports: rewritten.functionImports,
10002
+ scan: rewritten.scan
9763
10003
  });
9764
10004
  for (const symbol of rewritten.definitions) {
9765
10005
  if (symbol.type && symbol.type.results.length > 1)
@@ -9804,10 +10044,24 @@ function createGuestImageLedger(input) {
9804
10044
  );
9805
10045
  }
9806
10046
  const preserveCanonical = /* @__PURE__ */ new Set();
9807
- const definitionsByName = Map.groupBy(definitions, (definition) => definition.name);
10047
+ let definitionsByName;
10048
+ const neededNames = /* @__PURE__ */ new Set();
10049
+ if (symbolIndices.has("__cxa_throw")) neededNames.add("__cxa_throw");
10050
+ for (const binding of input.directBindings ?? []) neededNames.add(binding.symbol);
10051
+ if (input.sdkWeakReferences) {
10052
+ definitionsByName = Map.groupBy(definitions, (definition) => definition.name);
10053
+ } else if (neededNames.size > 0) {
10054
+ definitionsByName = /* @__PURE__ */ new Map();
10055
+ for (const definition of definitions) {
10056
+ if (!neededNames.has(definition.name)) continue;
10057
+ let list = definitionsByName.get(definition.name);
10058
+ if (!list) definitionsByName.set(definition.name, list = []);
10059
+ list.push(definition);
10060
+ }
10061
+ }
9808
10062
  if (symbolIndices.has("__cxa_throw")) {
9809
10063
  const name = "__cxa_throw";
9810
- const matching = definitionsByName.get(name) ?? [];
10064
+ const matching = definitionsByName?.get(name) ?? [];
9811
10065
  if (new Set(matching.map((definition) => definition.image)).size >= 2 && matching.some((definition) => definition.weak)) {
9812
10066
  const weak = matching.filter((definition) => definition.weak);
9813
10067
  const strong = matching.filter((definition) => !definition.weak);
@@ -9901,7 +10155,7 @@ function createGuestImageLedger(input) {
9901
10155
  const unitsByPath = new Map(units.map((unit) => [unit.object.path, unit]));
9902
10156
  for (const binding of input.directBindings ?? []) {
9903
10157
  const unit = unitsByPath.get(binding.object);
9904
- const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
10158
+ const matches = (definitionsByName?.get(binding.symbol) ?? []).filter(
9905
10159
  (definition) => definition.object === binding.providerObject && definition.image === binding.providerImage
9906
10160
  );
9907
10161
  if (!unit || !unit.usedSymbols.has(binding.symbol) || matches.length !== 1)
@@ -9945,7 +10199,7 @@ function createGuestImageLedger(input) {
9945
10199
  }
9946
10200
  }
9947
10201
  const appSymbols = input.registerAppTables ? { referenced: /* @__PURE__ */ new Set(), defined: /* @__PURE__ */ new Set() } : void 0;
9948
- const objects = units.map(({ image, object: object2, aliases, functionImports }) => {
10202
+ const objects = units.map(({ image, object: object2, aliases, functionImports, scan: scan2 }) => {
9949
10203
  const shared = sharedLookupByImage.get(image);
9950
10204
  const own = startup.get(object2.path);
9951
10205
  const bindings = new Map(own);
@@ -9968,22 +10222,24 @@ function createGuestImageLedger(input) {
9968
10222
  }
9969
10223
  bindings.set(name, wrapper.symbol);
9970
10224
  }
10225
+ const rewritten = rewriteObject(
10226
+ object2.bytes,
10227
+ aliases,
10228
+ `__peach_dlsym_caller_${image}`,
10229
+ binding,
10230
+ object2.instrumentDynamicLookups,
10231
+ preserveCanonical,
10232
+ {
10233
+ sdkProduct: object2.sdkProduct,
10234
+ collectRewrittenSymbols: object2.sdkProduct === void 0 ? appSymbols : void 0,
10235
+ scan: scan2
10236
+ }
10237
+ );
9971
10238
  return {
9972
10239
  path: object2.path,
9973
10240
  instrumentDynamicLookups: object2.instrumentDynamicLookups,
9974
10241
  sdkProduct: object2.sdkProduct,
9975
- bytes: rewriteObject(
9976
- object2.bytes,
9977
- aliases,
9978
- `__peach_dlsym_caller_${image}`,
9979
- binding,
9980
- object2.instrumentDynamicLookups,
9981
- preserveCanonical,
9982
- {
9983
- sdkProduct: object2.sdkProduct,
9984
- collectRewrittenSymbols: object2.sdkProduct === void 0 ? appSymbols : void 0
9985
- }
9986
- ).bytes
10242
+ bytes: rewritten.bytes
9987
10243
  };
9988
10244
  });
9989
10245
  const exported = /* @__PURE__ */ new Map();
@@ -10148,8 +10404,7 @@ function sdkGuestCallerId(product) {
10148
10404
  return (hash | 2147483648) >>> 0;
10149
10405
  }
10150
10406
  function sdkGuestSymbolName(product, name) {
10151
- const digest = createHash7("sha256").update(product).update("\0").update(name).digest("hex");
10152
- return `__peach_sdk_symbol_${digest.slice(0, 32)}`;
10407
+ return `__peach_sdk_symbol_${sha256PairHex(product, name).slice(0, 32)}`;
10153
10408
  }
10154
10409
  function rewriteSdkGuestLookup(bytes, callerId) {
10155
10410
  return rewriteObject(
@@ -10235,7 +10490,7 @@ function encodeWasmNumber(value) {
10235
10490
  }
10236
10491
  }
10237
10492
  function encodeWasmName(name) {
10238
- const bytes = [...Buffer.from(name)];
10493
+ const bytes = new TextEncoder().encode(name);
10239
10494
  return [...encodeWasmNumber(bytes.length), ...bytes];
10240
10495
  }
10241
10496
  function readWasmSection(bytes, start, end) {
@@ -10649,9 +10904,31 @@ function guestDyldValueRange(map) {
10649
10904
  }
10650
10905
 
10651
10906
  // src/swift-guest-link.ts
10652
- import { execFileSync as execFileSync7 } from "node:child_process";
10907
+ import { execFile as execFile2, execFileSync as execFileSync7 } from "node:child_process";
10653
10908
  import fs9 from "node:fs";
10654
10909
  import path20 from "node:path";
10910
+ import { promisify as promisify2 } from "node:util";
10911
+
10912
+ // ../../src/helpers/mapLimit.ts
10913
+ async function mapLimit(items, limit, worker) {
10914
+ const results = new Array(items.length);
10915
+ let next = 0;
10916
+ let failure;
10917
+ await Promise.all(
10918
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
10919
+ while (!failure && next < items.length) {
10920
+ const index = next++;
10921
+ try {
10922
+ results[index] = await worker(items[index], index);
10923
+ } catch (error) {
10924
+ failure ?? (failure = { error });
10925
+ }
10926
+ }
10927
+ })
10928
+ );
10929
+ if (failure) throw failure.error;
10930
+ return results;
10931
+ }
10655
10932
 
10656
10933
  // src/swift-guest-link-plan.ts
10657
10934
  function selectedGuestInputImage(artifact, member) {
@@ -12361,6 +12638,7 @@ async function lowerWasm(file, output, options) {
12361
12638
  }
12362
12639
 
12363
12640
  // src/swift-guest-link.ts
12641
+ var execFileAsync = promisify2(execFile2);
12364
12642
  function remapGuestLinkPlan(plan, rewritten) {
12365
12643
  return {
12366
12644
  ...plan,
@@ -12370,7 +12648,9 @@ function remapGuestLinkPlan(plan, rewritten) {
12370
12648
  }))
12371
12649
  };
12372
12650
  }
12373
- function guestLinkInputFiles(args) {
12651
+ var WASM_MAGIC = Buffer.from([0, 97, 115, 109]);
12652
+ var BITCODE_MAGIC = Buffer.from([66, 67, 192, 222]);
12653
+ function guestLinkInputFilesWithKind(args) {
12374
12654
  const dirs = [];
12375
12655
  for (let i = 0; i < args.length; i++) {
12376
12656
  const arg = args[i];
@@ -12378,7 +12658,8 @@ function guestLinkInputFiles(args) {
12378
12658
  else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
12379
12659
  else if (arg.startsWith("--library-path=")) dirs.push(arg.slice(15));
12380
12660
  }
12381
- const inputs = /* @__PURE__ */ new Set();
12661
+ const magic = Buffer.allocUnsafe(8);
12662
+ const inputs = /* @__PURE__ */ new Map();
12382
12663
  for (let i = 0; i < args.length; i++) {
12383
12664
  const arg = args[i];
12384
12665
  if (arg === "-L" || arg === "--library-path" || arg === "-o" || arg === "--output") {
@@ -12387,29 +12668,52 @@ function guestLinkInputFiles(args) {
12387
12668
  }
12388
12669
  if (arg.startsWith("@")) throw new Error(`nested linker response file ${arg}`);
12389
12670
  let file;
12671
+ let kind;
12390
12672
  if (arg === "-l" || arg === "--library" || arg.startsWith("--library=") || arg.startsWith("-l") && arg.length > 2) {
12391
12673
  const name = arg === "-l" || arg === "--library" ? args[++i] : arg.startsWith("--library=") ? arg.slice(10) : arg.slice(2);
12392
12674
  const archive = name.startsWith(":") ? name.slice(1) : `lib${name}.a`;
12393
12675
  file = dirs.map((dir) => path20.join(dir, archive)).find((item) => fs9.existsSync(item));
12394
12676
  if (!file) throw new Error(`unresolved guest link library ${name}`);
12395
- } else if (!arg.startsWith("-") && fs9.existsSync(arg) && fs9.statSync(arg).isFile()) {
12396
- const fd = fs9.openSync(arg, "r");
12397
- const magic = Buffer.alloc(8);
12398
- try {
12399
- fs9.readSync(fd, magic, 0, magic.length, 0);
12400
- } finally {
12401
- fs9.closeSync(fd);
12677
+ } else if (!arg.startsWith("-")) {
12678
+ const resolved = path20.resolve(arg);
12679
+ if (inputs.has(resolved)) continue;
12680
+ const stat = fs9.statSync(arg, { throwIfNoEntry: false });
12681
+ if (stat?.isFile()) {
12682
+ const fd = fs9.openSync(arg, "r");
12683
+ let read = 0;
12684
+ try {
12685
+ read = fs9.readSync(fd, magic, 0, 8, 0);
12686
+ } finally {
12687
+ fs9.closeSync(fd);
12688
+ }
12689
+ if (read >= 4) {
12690
+ if (read >= 8 && (magic.toString("ascii") === "!<arch>\n" || magic.toString("ascii") === "!<thin>\n")) {
12691
+ file = arg;
12692
+ kind = "archive";
12693
+ } else if (magic.subarray(0, 4).equals(WASM_MAGIC) || magic.subarray(0, 4).equals(BITCODE_MAGIC)) {
12694
+ file = arg;
12695
+ kind = "object";
12696
+ }
12697
+ }
12698
+ }
12699
+ }
12700
+ if (file) {
12701
+ const resolved = path20.resolve(file);
12702
+ if (!inputs.has(resolved)) {
12703
+ if (!kind) {
12704
+ const fd = fs9.openSync(resolved, "r");
12705
+ try {
12706
+ fs9.readSync(fd, magic, 0, 8, 0);
12707
+ } finally {
12708
+ fs9.closeSync(fd);
12709
+ }
12710
+ kind = magic.toString("ascii") === "!<arch>\n" ? "archive" : "object";
12711
+ }
12712
+ inputs.set(resolved, kind);
12402
12713
  }
12403
- if (magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) || magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) || magic.toString("ascii") === "!<arch>\n" || magic.toString("ascii") === "!<thin>\n")
12404
- file = arg;
12405
12714
  }
12406
- if (file) inputs.add(path20.resolve(file));
12407
12715
  }
12408
- return [...inputs];
12409
- }
12410
- function unownedGuestLinkInputs(plan, args) {
12411
- const owned = new Set(plan.artifacts.map((artifact) => path20.resolve(artifact.path)));
12412
- return guestLinkInputFiles(args).filter((file) => !owned.has(file));
12716
+ return [...inputs].map(([filePath, kind]) => ({ path: filePath, kind }));
12413
12717
  }
12414
12718
  function occurrences(plan, args) {
12415
12719
  const dirs = [];
@@ -12575,15 +12879,15 @@ function withOutput(args, output, discovery) {
12575
12879
  result.push("-o", output);
12576
12880
  return result;
12577
12881
  }
12578
- function linkGuestImages(options) {
12882
+ async function linkGuestImages(options) {
12579
12883
  const { args, directory, wasmLd, clang, llvmAr } = options;
12580
12884
  let plan = options.plan;
12581
12885
  if (!plan.images.some((image) => image.id === options.ledgerDataImage))
12582
12886
  throw new Error(`unknown ledger data image ${options.ledgerDataImage}`);
12583
12887
  fs9.mkdirSync(directory, { recursive: true });
12584
- const discovery = path20.join(directory, "discovery.wasm");
12888
+ let discovery = path20.join(directory, "discovery.wasm");
12585
12889
  const whyPath = path20.join(directory, "why-extract.txt");
12586
- const mapPath = path20.join(directory, "discovery.map");
12890
+ let mapPath = path20.join(directory, "discovery.map");
12587
12891
  const runLink = (name, arguments_) => {
12588
12892
  const response = path20.join(directory, `${name}.rsp`);
12589
12893
  const trace = path20.join(directory, `${name}-inputs.txt`);
@@ -12602,19 +12906,24 @@ function linkGuestImages(options) {
12602
12906
  }
12603
12907
  return fs9.readFileSync(trace, "utf8");
12604
12908
  };
12909
+ const preselection = options.projection && options.preselectionDiscovery ? options.preselectionDiscovery : void 0;
12605
12910
  let discoveryProjection;
12606
12911
  if (options.projection) {
12607
- const source = path20.join(directory, "projection-discovery.c");
12608
- discoveryProjection = path20.join(directory, "projection-discovery.o");
12609
- fs9.writeFileSync(
12610
- source,
12611
- '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
12612
- );
12613
- execFileSync7(
12614
- clang,
12615
- [...options.projection.clangOptions, "-c", source, "-o", discoveryProjection],
12616
- { stdio: "pipe" }
12617
- );
12912
+ if (preselection) {
12913
+ discoveryProjection = preselection.projectionObject;
12914
+ } else {
12915
+ const source = path20.join(directory, "projection-discovery.c");
12916
+ discoveryProjection = path20.join(directory, "projection-discovery.o");
12917
+ fs9.writeFileSync(
12918
+ source,
12919
+ '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
12920
+ );
12921
+ execFileSync7(
12922
+ clang,
12923
+ [...options.projection.clangOptions, "-c", source, "-o", discoveryProjection],
12924
+ { stdio: "pipe" }
12925
+ );
12926
+ }
12618
12927
  }
12619
12928
  const archives = /* @__PURE__ */ new Map();
12620
12929
  const memberBytes = /* @__PURE__ */ new Map();
@@ -12652,6 +12961,17 @@ function linkGuestImages(options) {
12652
12961
  }
12653
12962
  return byName.get(item.member);
12654
12963
  };
12964
+ const reusePreselection = () => {
12965
+ discovery = preselection.wasm;
12966
+ mapPath = preselection.map;
12967
+ return selectedGuestLinkInputs(
12968
+ plan,
12969
+ args,
12970
+ fs9.readFileSync(preselection.why, "utf8"),
12971
+ fs9.readFileSync(preselection.trace, "utf8"),
12972
+ archives
12973
+ );
12974
+ };
12655
12975
  const discover = (provider2) => {
12656
12976
  const trace = runLink("discovery", [
12657
12977
  ...withOutput(args, discovery, true),
@@ -12681,9 +13001,10 @@ function linkGuestImages(options) {
12681
13001
  const eagerProvider = [...eagerObjects].some(
12682
13002
  (artifact) => needsProvider({ artifact, member: null })
12683
13003
  );
12684
- let selected = discover(eagerProvider);
13004
+ let selected = eagerProvider && preselection ? reusePreselection() : discover(eagerProvider);
12685
13005
  const provider = eagerProvider || selected.some((item) => !eagerObjects.has(item.artifact) && needsProvider(item));
12686
- if (provider && !eagerProvider) selected = discover(true);
13006
+ if (provider && !eagerProvider)
13007
+ selected = preselection ? reusePreselection() : discover(true);
12687
13008
  if (options.resolvePlan) {
12688
13009
  const identity = (value) => JSON.stringify([
12689
13010
  value.images.map(({ id, name }) => [id, name]),
@@ -12724,11 +13045,11 @@ function linkGuestImages(options) {
12724
13045
  const product = (item.member === null ? void 0 : artifact.memberSdkProducts?.get(item.member)) ?? artifact.sdkProduct;
12725
13046
  let sdkProduct;
12726
13047
  if (sharedSdk && product !== void 0) {
12727
- const original2 = options.projection?.identities.get(artifact.path);
12728
- if (original2 === void 0)
13048
+ const original = options.projection?.identities.get(artifact.path);
13049
+ if (original === void 0)
12729
13050
  throw new Error(`SDK input has no projection identity ${artifact.path}`);
12730
13051
  const origin = item.member === null ? void 0 : artifact.memberOrigins?.get(item.member);
12731
- const identity = item.member === null ? original2 : guestRuntimeMemberIdentity(original2, {
13052
+ const identity = item.member === null ? original : guestRuntimeMemberIdentity(original, {
12732
13053
  member: origin?.name ?? item.member,
12733
13054
  ordinal: origin?.ordinal ?? 1
12734
13055
  });
@@ -12795,76 +13116,11 @@ function linkGuestImages(options) {
12795
13116
  ),
12796
13117
  sdkCallerImages
12797
13118
  });
12798
- const replacements = /* @__PURE__ */ new Map();
12799
- const linkedOwners = /* @__PURE__ */ new Map();
12800
- const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]));
12801
- const appObjects = /* @__PURE__ */ new Map();
12802
- const sdkObjects = /* @__PURE__ */ new Map();
12803
- const finalArchives = /* @__PURE__ */ new Map();
12804
- for (const [index, artifact] of plan.artifacts.entries()) {
12805
- const prefix = `${artifact.path}(`;
12806
- if (artifact.kind === "object") {
12807
- const object2 = ledgerObjects.get(artifact.path);
12808
- if (!object2) continue;
12809
- const output2 = path20.join(directory, `object-${index}.o`);
12810
- fs9.writeFileSync(output2, object2.bytes);
12811
- replacements.set(artifact.path, output2);
12812
- linkedOwners.set(output2, selectedGuestInputImage(artifact, null));
12813
- const image = selectedGuestInputImage(artifact, null);
12814
- if (object2.sdkProduct === void 0) appObjects.set(output2, image);
12815
- else
12816
- sdkObjects.set(output2, {
12817
- image,
12818
- product: object2.sdkProduct,
12819
- identity: sdkIdentities.get(object2.path)
12820
- });
12821
- continue;
12822
- }
12823
- const members = archives.get(artifact.path);
12824
- if (!members) continue;
12825
- const listing = execFileSync7(llvmAr, ["t", artifact.path], {
12826
- encoding: "utf8"
12827
- }).trimEnd();
12828
- const listed = listing ? listing.split("\n") : [];
12829
- if (listed.length !== members.length || new Set(listed).size !== listed.length || members.some(
12830
- (member, i) => listed[i] !== member.name || path20.basename(member.name) !== member.name
12831
- ))
12832
- throw new Error(`unsupported archive layout ${artifact.path}`);
12833
- const memberDir = path20.join(directory, `archive-${index}`);
12834
- fs9.mkdirSync(memberDir, { recursive: true });
12835
- const output = path20.join(directory, `archive-${index}.a`);
12836
- const inputs = members.map((member) => {
12837
- const memberOutput = path20.join(memberDir, member.name);
12838
- const rewritten = ledgerObjects.get(`${prefix}${member.name})`);
12839
- fs9.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes);
12840
- if (rewritten) {
12841
- const image = selectedGuestInputImage(artifact, member.name);
12842
- linkedOwners.set(`${output}(${member.name})`, image);
12843
- if (rewritten.sdkProduct === void 0) appObjects.set(memberOutput, image);
12844
- else
12845
- sdkObjects.set(`${output}(${member.name})`, {
12846
- image,
12847
- product: rewritten.sdkProduct,
12848
- identity: sdkIdentities.get(rewritten.path)
12849
- });
12850
- }
12851
- return memberOutput;
12852
- });
12853
- fs9.rmSync(output, { force: true });
12854
- const response = path20.join(memberDir, "members.rsp");
12855
- fs9.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(" "));
12856
- execFileSync7(llvmAr, ["rcs", output, `@${response}`], { stdio: "pipe" });
12857
- finalArchives.set(
12858
- output,
12859
- members.map((member) => ({ name: member.name, bytes: new Uint8Array(0) }))
12860
- );
12861
- replacements.set(artifact.path, output);
12862
- }
12863
- const compileLedger = (name, source) => {
13119
+ const compileLedgerAsync = (name, source) => {
12864
13120
  const irPath = path20.join(directory, `${name}.ll`);
12865
13121
  const object2 = path20.join(directory, `${name}.o`);
12866
13122
  fs9.writeFileSync(irPath, source);
12867
- execFileSync7(
13123
+ return execFileAsync(
12868
13124
  clang,
12869
13125
  [
12870
13126
  "--target=wasm64-unknown-wasip1-threads",
@@ -12874,177 +13130,264 @@ function linkGuestImages(options) {
12874
13130
  "-o",
12875
13131
  object2
12876
13132
  ],
12877
- { stdio: "pipe" }
12878
- );
12879
- return object2;
13133
+ { maxBuffer: 64 * 1024 * 1024 }
13134
+ ).then(() => object2);
12880
13135
  };
12881
- const ledgerObject = compileLedger("ledger", ledger.llvmIR);
12882
- const lazyExports = path20.join(directory, "lazy-exports.rsp");
12883
- fs9.writeFileSync(lazyExports, guestLazyExports(ledger.lazyFunctions));
12884
- linkedOwners.set(ledgerObject, options.ledgerDataImage);
12885
- const sectionOwners = new Map(
12886
- ledger.callerWrappers.map(({ symbol, image }) => [
12887
- `${ledgerObject}:(${symbol})`,
12888
- image
12889
- ])
12890
- );
12891
- const byToken = new Map(
12892
- occurrences(plan, args).map(({ artifact, token }) => [
12893
- token,
12894
- replacements.get(artifact.path)
12895
- ])
12896
- );
12897
- const placed = /* @__PURE__ */ new Set();
12898
- const finalArgs = args.map((arg) => byToken.get(arg) ?? arg).filter((arg) => {
12899
- if (!arg.endsWith(".o") && !arg.endsWith(".a")) return true;
12900
- if (placed.has(arg)) return false;
12901
- placed.add(arg);
12902
- return true;
12903
- });
12904
- const finalOutput = path20.join(directory, "final.wasm");
12905
- const finalWhy = path20.join(directory, "final-why-extract.txt");
12906
- const linkFinal = (projectionObject2, layoutMap) => runLink("final", [
12907
- ...withOutput(finalArgs, finalOutput, false),
12908
- ledgerObject,
12909
- `@${lazyExports}`,
12910
- ...projectionObject2 ? [projectionObject2] : [],
12911
- ...provider ? [`--undefined=${providerSymbol}`] : [],
12912
- ...layoutMap ? [`--Map=${layoutMap}`] : [],
12913
- `--why-extract=${finalWhy}`
12914
- ]);
12915
- let projectionObject;
12916
- let projectionStorage;
12917
- let finalTrace;
12918
- if (options.projection) {
12919
- const projection = options.projection;
12920
- if (!plan.images.some((image) => image.id === projection.image))
12921
- throw new Error("guest projection has no source image");
12922
- if (projection.images.length !== plan.images.length || projection.images.some(
12923
- (image, index) => image.image !== index || plan.images[index]?.id !== index
12924
- ))
12925
- throw new Error("guest projection image order differs from link plan");
12926
- const selectedInputs = selectedGuestManifestInputs(
12927
- plan,
12928
- selected,
12929
- projection.identities,
12930
- readSelected
12931
- );
12932
- const images = projection.images.map(
12933
- (image) => createGuestImageManifest({
12934
- ...image,
12935
- inputs: selectedInputs.get(image.image) ?? [],
12936
- linkOptions: projection.linkOptions,
12937
- regions: []
12938
- })
12939
- );
12940
- objectBytes.clear();
12941
- memberBytes.clear();
12942
- archives.clear();
12943
- if (!discoveryRegions) throw new Error("guest projection layout object missing");
12944
- const regionsBefore = discoveryRegions;
12945
- const ledgerPieces = guestProjectionRegionCapacity([fs9.readFileSync(ledgerObject)], 0);
12946
- const bundleCount = images.filter(
12947
- (image) => image.resourceBundlePath !== void 0
12948
- ).length;
12949
- const projectionPieces = images.length + 2 + (bundleCount ? bundleCount + 1 : 0);
12950
- let capacities = ledger.images.map((image) => ({
12951
- regions: regionsBefore[image.id] + 1 + ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length + (image.id === options.ledgerDataImage ? ledgerPieces : 0) + (image.id === projection.image ? projectionPieces : 0),
12952
- memoryProtection: projection.memoryProtection,
12953
- tableProtection: projection.tableProtection
12954
- }));
12955
- const projectionSource = path20.join(directory, "projection.c");
12956
- projectionObject = path20.join(directory, "projection.o");
12957
- const callerMap = args.find((arg) => arg.startsWith("--Map="))?.slice("--Map=".length);
12958
- const layoutMap = callerMap ?? path20.join(directory, "projection-layout.map");
12959
- for (; ; ) {
12960
- projectionStorage = reserveGuestProjectionStorage(images, capacities);
12961
- fs9.writeFileSync(projectionSource, projectionStorage.source);
12962
- execFileSync7(
12963
- clang,
12964
- [...projection.clangOptions, "-c", projectionSource, "-o", projectionObject],
12965
- { stdio: "pipe" }
12966
- );
12967
- finalTrace = linkFinal(projectionObject, callerMap ? void 0 : layoutMap);
12968
- if (sharedSdk) break;
12969
- const wasm = fs9.readFileSync(finalOutput);
12970
- const actual = guestProjectionRegionCounts(
12971
- images.length,
12972
- guestLinkedSpans(
12973
- guestLinkLines(layoutMap),
12974
- wasm,
12975
- wasm,
12976
- new Map(linkedOwners).set(projectionObject, projection.image),
12977
- sectionOwners
12978
- )
13136
+ const ledgerObjectPromise = compileLedgerAsync("ledger", ledger.llvmIR);
13137
+ const appLedgerObjectPromise = options.onSplitInputs && ledger.appLLVMIR ? compileLedgerAsync("app-ledger", ledger.appLLVMIR) : void 0;
13138
+ try {
13139
+ const replacements = /* @__PURE__ */ new Map();
13140
+ const linkedOwners = /* @__PURE__ */ new Map();
13141
+ const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]));
13142
+ const appObjects = /* @__PURE__ */ new Map();
13143
+ const sdkObjects = /* @__PURE__ */ new Map();
13144
+ const finalArchives = /* @__PURE__ */ new Map();
13145
+ const archiveJobs = [];
13146
+ for (const [index, artifact] of plan.artifacts.entries()) {
13147
+ const prefix = `${artifact.path}(`;
13148
+ if (artifact.kind === "object") {
13149
+ const object2 = ledgerObjects.get(artifact.path);
13150
+ if (!object2) continue;
13151
+ const output2 = path20.join(directory, `object-${index}.o`);
13152
+ fs9.writeFileSync(output2, object2.bytes);
13153
+ replacements.set(artifact.path, output2);
13154
+ linkedOwners.set(output2, selectedGuestInputImage(artifact, null));
13155
+ const image = selectedGuestInputImage(artifact, null);
13156
+ if (object2.sdkProduct === void 0) appObjects.set(output2, image);
13157
+ else
13158
+ sdkObjects.set(output2, {
13159
+ image,
13160
+ product: object2.sdkProduct,
13161
+ identity: sdkIdentities.get(object2.path)
13162
+ });
13163
+ continue;
13164
+ }
13165
+ const members = archives.get(artifact.path);
13166
+ if (!members) continue;
13167
+ const memberDir = path20.join(directory, `archive-${index}`);
13168
+ fs9.mkdirSync(memberDir, { recursive: true });
13169
+ const output = path20.join(directory, `archive-${index}.a`);
13170
+ const inputs = members.map((member) => {
13171
+ const memberOutput = path20.join(memberDir, member.name);
13172
+ const rewritten = ledgerObjects.get(`${prefix}${member.name})`);
13173
+ fs9.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes);
13174
+ if (rewritten) {
13175
+ const image = selectedGuestInputImage(artifact, member.name);
13176
+ linkedOwners.set(`${output}(${member.name})`, image);
13177
+ if (rewritten.sdkProduct === void 0) appObjects.set(memberOutput, image);
13178
+ else
13179
+ sdkObjects.set(`${output}(${member.name})`, {
13180
+ image,
13181
+ product: rewritten.sdkProduct,
13182
+ identity: sdkIdentities.get(rewritten.path)
13183
+ });
13184
+ }
13185
+ return memberOutput;
13186
+ });
13187
+ fs9.rmSync(output, { force: true });
13188
+ const response = path20.join(memberDir, "members.rsp");
13189
+ fs9.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(" "));
13190
+ finalArchives.set(
13191
+ output,
13192
+ members.map((member) => ({ name: member.name, bytes: new Uint8Array(0) }))
12979
13193
  );
12980
- if (actual.every((count, index) => count <= capacities[index].regions)) break;
12981
- capacities = capacities.map((capacity, index) => ({
12982
- ...capacity,
12983
- regions: Math.max(actual[index], capacity.regions)
12984
- }));
12985
- }
12986
- linkedOwners.set(projectionObject, projection.image);
12987
- } else finalTrace = linkFinal();
12988
- const finalSelection = selectedGuestLinkInputs(
12989
- remapGuestLinkPlan(plan, replacements),
12990
- finalArgs,
12991
- fs9.readFileSync(finalWhy, "utf8"),
12992
- finalTrace,
12993
- finalArchives
12994
- );
12995
- const original = new Map([...replacements].map(([before2, after2]) => [after2, before2]));
12996
- const key = (item) => JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member]);
12997
- const before = new Set(selected.map(key));
12998
- const after = new Set(finalSelection.map(key));
12999
- const changed = [...before].filter((item) => !after.has(item));
13000
- changed.push(...[...after].filter((item) => !before.has(item)));
13001
- if (changed.length)
13002
- throw new Error(
13003
- `guest link selected different inputs after rewriting:
13004
- ${changed.join("\n")}`
13005
- );
13006
- fs9.renameSync(finalOutput, outputPath(args));
13007
- if (KEEP_WASM_NAMES)
13008
- fs9.writeFileSync(
13009
- outputPath(args),
13010
- nameGuestImageAliases(fs9.readFileSync(outputPath(args)), plan.symbols)
13011
- );
13012
- if (projectionStorage && projectionObject)
13013
- options.projection.onReserved(projectionStorage, projectionObject);
13014
- options.onLinkedOwners?.(linkedOwners);
13015
- options.onLinkedSections?.(sectionOwners);
13016
- options.onDyldRows?.(ledger);
13017
- if (options.onSplitInputs && ledger.appLLVMIR) {
13018
- const appLedgerObject = compileLedger("app-ledger", ledger.appLLVMIR);
13019
- const appSections = new Map(
13194
+ replacements.set(artifact.path, output);
13195
+ archiveJobs.push({ artifact, index, members, memberDir, output, response });
13196
+ }
13197
+ const [ledgerObject] = await Promise.all([
13198
+ ledgerObjectPromise,
13199
+ mapLimit(archiveJobs, 8, async ({ artifact, members, output, response }) => {
13200
+ const { stdout } = await execFileAsync(llvmAr, ["t", artifact.path], {
13201
+ encoding: "utf8",
13202
+ maxBuffer: 64 * 1024 * 1024
13203
+ });
13204
+ const listing = stdout.trimEnd();
13205
+ const listed = listing ? listing.split("\n") : [];
13206
+ if (listed.length !== members.length || new Set(listed).size !== listed.length || members.some(
13207
+ (member, i) => listed[i] !== member.name || path20.basename(member.name) !== member.name
13208
+ ))
13209
+ throw new Error(`unsupported archive layout ${artifact.path}`);
13210
+ await execFileAsync(llvmAr, ["rcs", output, `@${response}`], {
13211
+ maxBuffer: 64 * 1024 * 1024
13212
+ });
13213
+ })
13214
+ ]);
13215
+ const lazyExports = path20.join(directory, "lazy-exports.rsp");
13216
+ fs9.writeFileSync(lazyExports, guestLazyExports(ledger.lazyFunctions));
13217
+ linkedOwners.set(ledgerObject, options.ledgerDataImage);
13218
+ const sectionOwners = new Map(
13020
13219
  ledger.callerWrappers.map(({ symbol, image }) => [
13021
- `${appLedgerObject}:(${symbol})`,
13220
+ `${ledgerObject}:(${symbol})`,
13022
13221
  image
13023
13222
  ])
13024
13223
  );
13025
- appObjects.set(appLedgerObject, options.ledgerDataImage);
13026
- let appReferencedSymbols;
13027
- let appDefinedSymbols;
13028
- if (ledger.appReferencedSymbols && ledger.appDefinedSymbols) {
13029
- const referenced = new Set(ledger.appReferencedSymbols);
13030
- const defined = new Set(ledger.appDefinedSymbols);
13031
- const ledgerSyms = guestWasmSymbols(fs9.readFileSync(appLedgerObject));
13032
- for (const name of ledgerSyms.undefined) referenced.add(name);
13033
- for (const name of ledgerSyms.defined) defined.add(name);
13034
- appReferencedSymbols = referenced;
13035
- appDefinedSymbols = defined;
13036
- }
13037
- options.onSplitInputs({
13038
- appObjects,
13039
- appSections,
13040
- sdkObjects,
13041
- lazyFunctions: ledger.appLazyFunctions ?? [],
13042
- dyldSymbols: ledger.dyldSymbols,
13043
- appReferencedSymbols,
13044
- appDefinedSymbols
13224
+ const byToken = new Map(
13225
+ occurrences(plan, args).map(({ artifact, token }) => [
13226
+ token,
13227
+ replacements.get(artifact.path)
13228
+ ])
13229
+ );
13230
+ const placed = /* @__PURE__ */ new Set();
13231
+ const finalArgs = args.map((arg) => byToken.get(arg) ?? arg).filter((arg) => {
13232
+ if (!arg.endsWith(".o") && !arg.endsWith(".a")) return true;
13233
+ if (placed.has(arg)) return false;
13234
+ placed.add(arg);
13235
+ return true;
13045
13236
  });
13237
+ const finalOutput = path20.join(directory, "final.wasm");
13238
+ const finalWhy = path20.join(directory, "final-why-extract.txt");
13239
+ const linkFinal = (projectionObject2, layoutMap) => runLink("final", [
13240
+ ...withOutput(finalArgs, finalOutput, false),
13241
+ ledgerObject,
13242
+ `@${lazyExports}`,
13243
+ ...projectionObject2 ? [projectionObject2] : [],
13244
+ ...provider ? [`--undefined=${providerSymbol}`] : [],
13245
+ ...layoutMap ? [`--Map=${layoutMap}`] : [],
13246
+ `--why-extract=${finalWhy}`
13247
+ ]);
13248
+ let projectionObject;
13249
+ let projectionStorage;
13250
+ let finalTrace;
13251
+ if (options.projection) {
13252
+ const projection = options.projection;
13253
+ if (!plan.images.some((image) => image.id === projection.image))
13254
+ throw new Error("guest projection has no source image");
13255
+ if (projection.images.length !== plan.images.length || projection.images.some(
13256
+ (image, index) => image.image !== index || plan.images[index]?.id !== index
13257
+ ))
13258
+ throw new Error("guest projection image order differs from link plan");
13259
+ const selectedInputs = selectedGuestManifestInputs(
13260
+ plan,
13261
+ selected,
13262
+ projection.identities,
13263
+ readSelected
13264
+ );
13265
+ const images = projection.images.map(
13266
+ (image) => createGuestImageManifest({
13267
+ ...image,
13268
+ inputs: selectedInputs.get(image.image) ?? [],
13269
+ linkOptions: projection.linkOptions,
13270
+ regions: []
13271
+ })
13272
+ );
13273
+ objectBytes.clear();
13274
+ memberBytes.clear();
13275
+ archives.clear();
13276
+ if (!discoveryRegions) throw new Error("guest projection layout object missing");
13277
+ const regionsBefore = discoveryRegions;
13278
+ const ledgerPieces = guestProjectionRegionCapacity(
13279
+ [fs9.readFileSync(ledgerObject)],
13280
+ 0
13281
+ );
13282
+ const bundleCount = images.filter(
13283
+ (image) => image.resourceBundlePath !== void 0
13284
+ ).length;
13285
+ const projectionPieces = images.length + 2 + (bundleCount ? bundleCount + 1 : 0);
13286
+ let capacities = ledger.images.map((image) => ({
13287
+ regions: regionsBefore[image.id] + 1 + ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length + (image.id === options.ledgerDataImage ? ledgerPieces : 0) + (image.id === projection.image ? projectionPieces : 0),
13288
+ memoryProtection: projection.memoryProtection,
13289
+ tableProtection: projection.tableProtection
13290
+ }));
13291
+ const projectionSource = path20.join(directory, "projection.c");
13292
+ projectionObject = path20.join(directory, "projection.o");
13293
+ const callerMap = args.find((arg) => arg.startsWith("--Map="))?.slice("--Map=".length);
13294
+ const layoutMap = callerMap ?? path20.join(directory, "projection-layout.map");
13295
+ for (; ; ) {
13296
+ projectionStorage = reserveGuestProjectionStorage(images, capacities);
13297
+ fs9.writeFileSync(projectionSource, projectionStorage.source);
13298
+ execFileSync7(
13299
+ clang,
13300
+ [...projection.clangOptions, "-c", projectionSource, "-o", projectionObject],
13301
+ { stdio: "pipe" }
13302
+ );
13303
+ finalTrace = linkFinal(projectionObject, callerMap ? void 0 : layoutMap);
13304
+ if (sharedSdk) break;
13305
+ const wasm = fs9.readFileSync(finalOutput);
13306
+ const actual = guestProjectionRegionCounts(
13307
+ images.length,
13308
+ guestLinkedSpans(
13309
+ guestLinkLines(layoutMap),
13310
+ wasm,
13311
+ wasm,
13312
+ new Map(linkedOwners).set(projectionObject, projection.image),
13313
+ sectionOwners
13314
+ )
13315
+ );
13316
+ if (actual.every((count, index) => count <= capacities[index].regions)) break;
13317
+ capacities = capacities.map((capacity, index) => ({
13318
+ ...capacity,
13319
+ regions: Math.max(actual[index], capacity.regions)
13320
+ }));
13321
+ }
13322
+ linkedOwners.set(projectionObject, projection.image);
13323
+ } else finalTrace = linkFinal();
13324
+ const finalSelection = selectedGuestLinkInputs(
13325
+ remapGuestLinkPlan(plan, replacements),
13326
+ finalArgs,
13327
+ fs9.readFileSync(finalWhy, "utf8"),
13328
+ finalTrace,
13329
+ finalArchives
13330
+ );
13331
+ const original = new Map([...replacements].map(([before2, after2]) => [after2, before2]));
13332
+ const key = (item) => JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member]);
13333
+ const before = new Set(selected.map(key));
13334
+ const after = new Set(finalSelection.map(key));
13335
+ const changed = [...before].filter((item) => !after.has(item));
13336
+ changed.push(...[...after].filter((item) => !before.has(item)));
13337
+ if (changed.length)
13338
+ throw new Error(
13339
+ `guest link selected different inputs after rewriting:
13340
+ ${changed.join("\n")}`
13341
+ );
13342
+ fs9.renameSync(finalOutput, outputPath(args));
13343
+ if (KEEP_WASM_NAMES)
13344
+ fs9.writeFileSync(
13345
+ outputPath(args),
13346
+ nameGuestImageAliases(fs9.readFileSync(outputPath(args)), plan.symbols)
13347
+ );
13348
+ if (projectionStorage && projectionObject)
13349
+ options.projection.onReserved(projectionStorage, projectionObject);
13350
+ options.onLinkedOwners?.(linkedOwners);
13351
+ options.onLinkedSections?.(sectionOwners);
13352
+ options.onDyldRows?.(ledger);
13353
+ if (options.onSplitInputs && appLedgerObjectPromise) {
13354
+ const appLedgerObject = await appLedgerObjectPromise;
13355
+ const appSections = new Map(
13356
+ ledger.callerWrappers.map(({ symbol, image }) => [
13357
+ `${appLedgerObject}:(${symbol})`,
13358
+ image
13359
+ ])
13360
+ );
13361
+ appObjects.set(appLedgerObject, options.ledgerDataImage);
13362
+ let appReferencedSymbols;
13363
+ let appDefinedSymbols;
13364
+ if (ledger.appReferencedSymbols && ledger.appDefinedSymbols) {
13365
+ const referenced = new Set(ledger.appReferencedSymbols);
13366
+ const defined = new Set(ledger.appDefinedSymbols);
13367
+ const ledgerSyms = guestWasmSymbols(fs9.readFileSync(appLedgerObject));
13368
+ for (const name of ledgerSyms.undefined) referenced.add(name);
13369
+ for (const name of ledgerSyms.defined) defined.add(name);
13370
+ appReferencedSymbols = referenced;
13371
+ appDefinedSymbols = defined;
13372
+ }
13373
+ options.onSplitInputs({
13374
+ appObjects,
13375
+ appSections,
13376
+ sdkObjects,
13377
+ lazyFunctions: ledger.appLazyFunctions ?? [],
13378
+ dyldSymbols: ledger.dyldSymbols,
13379
+ appReferencedSymbols,
13380
+ appDefinedSymbols
13381
+ });
13382
+ }
13383
+ return selected;
13384
+ } catch (error) {
13385
+ await Promise.allSettled([
13386
+ ledgerObjectPromise,
13387
+ ...appLedgerObjectPromise ? [appLedgerObjectPromise] : []
13388
+ ]);
13389
+ throw error;
13046
13390
  }
13047
- return selected;
13048
13391
  }
13049
13392
  function linkedMapSymbols(lines) {
13050
13393
  const names = /* @__PURE__ */ new Set();
@@ -13146,24 +13489,19 @@ function aliasGuestLinkArguments(input, archives) {
13146
13489
  throw new Error("aliased guest archive is not a link input");
13147
13490
  return result;
13148
13491
  }
13149
- function linkCompleteGuestImages(options) {
13492
+ async function linkCompleteGuestImages(options) {
13150
13493
  const args = normalizedGuestLinkArgs(options.args);
13151
- const unowned = unownedGuestLinkInputs(options.plan, args);
13152
- const candidates = unowned.map((file) => {
13153
- const descriptor = fs9.openSync(file, "r");
13154
- const magic = Buffer.alloc(8);
13155
- try {
13156
- fs9.readSync(descriptor, magic, 0, magic.length, 0);
13157
- } finally {
13158
- fs9.closeSync(descriptor);
13159
- }
13160
- return {
13494
+ const owned = new Set(
13495
+ options.plan.artifacts.map((artifact) => path20.resolve(artifact.path))
13496
+ );
13497
+ const candidates = guestLinkInputFilesWithKind(args).filter((item) => !owned.has(item.path)).map(
13498
+ ({ path: file, kind }) => ({
13161
13499
  path: file,
13162
- kind: magic.toString("ascii") === "!<arch>\n" ? "archive" : "object",
13500
+ kind,
13163
13501
  image: null,
13164
13502
  instrumentDynamicLookups: false
13165
- };
13166
- });
13503
+ })
13504
+ );
13167
13505
  return linkGuestImages({
13168
13506
  ...options,
13169
13507
  args,
@@ -13172,22 +13510,19 @@ function linkCompleteGuestImages(options) {
13172
13510
  }
13173
13511
  function discoverGuestLinkInputs(options) {
13174
13512
  const args = normalizedGuestLinkArgs(options.args);
13175
- const artifacts = guestLinkInputFiles(args).map((file) => {
13176
- const descriptor = fs9.openSync(file, "r");
13177
- const magic = Buffer.alloc(8);
13178
- try {
13179
- fs9.readSync(descriptor, magic, 0, magic.length, 0);
13180
- } finally {
13181
- fs9.closeSync(descriptor);
13182
- }
13183
- const kind = magic.toString("ascii") === "!<arch>\n" ? "archive" : "object";
13184
- return { path: file, kind, image: 0, instrumentDynamicLookups: false };
13185
- });
13513
+ const artifacts = guestLinkInputFilesWithKind(args).map(
13514
+ ({ path: file, kind }) => ({
13515
+ path: file,
13516
+ kind,
13517
+ image: 0,
13518
+ instrumentDynamicLookups: false
13519
+ })
13520
+ );
13186
13521
  const plan = { images: [], callers: [], artifacts, symbols: [] };
13187
13522
  fs9.mkdirSync(options.directory, { recursive: true });
13188
13523
  const why = path20.join(options.directory, "preselection-why.txt");
13189
13524
  const response = path20.join(options.directory, "preselection.rsp");
13190
- const output = process.platform !== "win32" ? "/dev/null" : path20.join(options.directory, "preselection.wasm");
13525
+ const output = options.output ?? (process.platform !== "win32" ? "/dev/null" : path20.join(options.directory, "preselection.wasm"));
13191
13526
  const flags = [
13192
13527
  ...withOutput(args, output, true),
13193
13528
  ...options.objects,
@@ -13195,6 +13530,7 @@ function discoverGuestLinkInputs(options) {
13195
13530
  // the selection that assigns member owners.
13196
13531
  "--undefined=__peach_dlsym_from_image",
13197
13532
  `--why-extract=${why}`,
13533
+ ...options.mapPath ? [`--Map=${options.mapPath}`] : [],
13198
13534
  "--trace"
13199
13535
  ];
13200
13536
  fs9.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(" "));
@@ -13208,6 +13544,7 @@ function discoverGuestLinkInputs(options) {
13208
13544
  } finally {
13209
13545
  fs9.closeSync(traceOutput);
13210
13546
  }
13547
+ options.onOutput?.({ why, trace, output, mapPath: options.mapPath });
13211
13548
  return selectedGuestLinkInputs(
13212
13549
  plan,
13213
13550
  args,
@@ -13232,7 +13569,10 @@ function prepareGuestRuntimeInputs(options) {
13232
13569
  )
13233
13570
  );
13234
13571
  const archives = [];
13235
- for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
13572
+ for (const { path: file, kind } of guestLinkInputFilesWithKind(
13573
+ normalizedGuestLinkArgs(options.args)
13574
+ )) {
13575
+ if (kind !== "archive") continue;
13236
13576
  const original = originals.get(file) ?? file;
13237
13577
  if (!recordedArchives.has(original) && libraryArchiveTarget(original) === null)
13238
13578
  continue;
@@ -13247,11 +13587,23 @@ function prepareGuestRuntimeInputs(options) {
13247
13587
  );
13248
13588
  }
13249
13589
  const args = aliasGuestLinkArguments(options.args, archives);
13590
+ let discovery;
13250
13591
  const selected = discoverGuestLinkInputs({
13251
13592
  args,
13252
13593
  directory: options.directory,
13253
13594
  wasmLd: options.wasmLd,
13254
- objects: options.discoveryObjects
13595
+ objects: options.discoveryObjects,
13596
+ output: options.discoveryOutput,
13597
+ mapPath: options.discoveryMap,
13598
+ onOutput: options.discoveryOutput && options.discoveryMap && options.discoveryObjects.length === 1 ? ({ why, trace, output, mapPath }) => {
13599
+ discovery = {
13600
+ wasm: output,
13601
+ map: mapPath,
13602
+ why,
13603
+ trace,
13604
+ projectionObject: options.discoveryObjects[0]
13605
+ };
13606
+ } : void 0
13255
13607
  });
13256
13608
  const originalSelection = originalGuestArchiveSelections(selected, archives);
13257
13609
  const closure = guestRuntimeProductsForInputs({
@@ -13283,7 +13635,15 @@ function prepareGuestRuntimeInputs(options) {
13283
13635
  rewritten: options.rewritten,
13284
13636
  images: new Map([...closure.images, ...closure.containingImages])
13285
13637
  });
13286
- return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
13638
+ return {
13639
+ args,
13640
+ selected,
13641
+ originalSelection,
13642
+ archives,
13643
+ sdkProducts,
13644
+ archiveArtifacts,
13645
+ discovery
13646
+ };
13287
13647
  }
13288
13648
  function selectedGuestSymbolInputs(plan, selected, readSelected) {
13289
13649
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
@@ -13377,10 +13737,21 @@ function verifyGuestSymbolScopes(options) {
13377
13737
  const records = /* @__PURE__ */ new Map();
13378
13738
  for (const line of guestLinkLines(tracePath)) {
13379
13739
  const refSep = line.lastIndexOf(": reference to ");
13380
- const defSep = line.lastIndexOf(": definition of ");
13381
- if (refSep < 0 && defSep < 0) continue;
13382
- const isRef = refSep > defSep;
13383
- const sep = isRef ? refSep : defSep;
13740
+ let isRef = false;
13741
+ let sep = -1;
13742
+ if (refSep >= 0) {
13743
+ const defAfter = line.indexOf(": definition of ", refSep + 15);
13744
+ if (defAfter >= 0) {
13745
+ sep = line.lastIndexOf(": definition of ");
13746
+ isRef = false;
13747
+ } else {
13748
+ sep = refSep;
13749
+ isRef = true;
13750
+ }
13751
+ } else {
13752
+ sep = line.lastIndexOf(": definition of ");
13753
+ if (sep < 0) continue;
13754
+ }
13384
13755
  const symbol = line.slice(sep + (isRef ? 15 : 16));
13385
13756
  if (!requested.has(symbol) || options.hostImports.has(symbol)) continue;
13386
13757
  let record = records.get(symbol);
@@ -13550,131 +13921,129 @@ function verifyGuestSymbolScopes(options) {
13550
13921
  }
13551
13922
  return { bindings: result, directBindings };
13552
13923
  }
13553
- function linkPrunedGuestImages(options) {
13554
- let result;
13924
+ async function linkPrunedGuestImages(options) {
13925
+ let pruned;
13555
13926
  pruneSwiftWasmLink(
13556
13927
  options.buildDirectory,
13557
13928
  options.toolchainBin,
13558
13929
  options.moduleRoot,
13559
13930
  options.staticClangTargets,
13560
13931
  void 0,
13561
- (args, rewritten, sdk) => {
13562
- if (args.some((arg) => arg === "--Map" || arg.startsWith("--Map=")))
13563
- throw new Error("guest link already has a linker map");
13564
- const framework = options.framework;
13565
- const prepared = options.prepareRuntime?.(args, rewritten, sdk);
13566
- if (prepared && options.sdkProducts !== null)
13567
- throw new Error("guest runtime products supplied twice");
13568
- const linkedArgs = prepared?.args ?? args;
13569
- const sdkProducts = prepared?.sdkProducts ?? (typeof options.sdkProducts === "function" ? options.sdkProducts(args, rewritten, sdk) : options.sdkProducts);
13570
- const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts);
13571
- let frameworkArtifacts = [];
13572
- const selectedObjects = prepared && new Set(
13573
- prepared.selected.filter((item) => item.member === null).map((item) => path20.resolve(item.artifact))
13574
- );
13575
- const selectedFramework = framework && (!prepared || framework.product.objects.some((object2) => {
13576
- const original = path20.resolve(framework.root, object2.path);
13577
- const linked = path20.resolve(rewritten.get(original) ?? original);
13578
- return selectedObjects?.has(linked) ?? false;
13579
- }));
13580
- if (framework && selectedFramework) {
13581
- const image = sdkProducts?.images.get(
13582
- frameworkRuntimeProductId(framework.product)
13583
- );
13584
- if (image === void 0)
13585
- throw new Error(
13586
- "framework objects require their declared compiler runtime image"
13587
- );
13588
- frameworkArtifacts = guestFrameworkLinkArtifacts(
13589
- framework.product,
13590
- framework.root,
13932
+ (args2, rewritten2, sdk2) => {
13933
+ pruned = { args: args2, rewritten: rewritten2, sdk: sdk2 };
13934
+ },
13935
+ options.resourceReferences
13936
+ );
13937
+ if (!pruned) throw new Error("guest link did not receive pruned inputs");
13938
+ const { args, rewritten, sdk } = pruned;
13939
+ if (args.some((arg) => arg === "--Map" || arg.startsWith("--Map=")))
13940
+ throw new Error("guest link already has a linker map");
13941
+ const framework = options.framework;
13942
+ const prepared = options.prepareRuntime?.(args, rewritten, sdk);
13943
+ if (prepared && options.sdkProducts !== null)
13944
+ throw new Error("guest runtime products supplied twice");
13945
+ const linkedArgs = prepared?.args ?? args;
13946
+ const sdkProducts = prepared?.sdkProducts ?? (typeof options.sdkProducts === "function" ? options.sdkProducts(args, rewritten, sdk) : options.sdkProducts);
13947
+ const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts);
13948
+ let frameworkArtifacts = [];
13949
+ const selectedObjects = prepared && new Set(
13950
+ prepared.selected.filter((item) => item.member === null).map((item) => path20.resolve(item.artifact))
13951
+ );
13952
+ const selectedFramework = framework && (!prepared || framework.product.objects.some((object2) => {
13953
+ const original = path20.resolve(framework.root, object2.path);
13954
+ const linked = path20.resolve(rewritten.get(original) ?? original);
13955
+ return selectedObjects?.has(linked) ?? false;
13956
+ }));
13957
+ if (framework && selectedFramework) {
13958
+ const image = sdkProducts?.images.get(frameworkRuntimeProductId(framework.product));
13959
+ if (image === void 0)
13960
+ throw new Error("framework objects require their declared compiler runtime image");
13961
+ frameworkArtifacts = guestFrameworkLinkArtifacts(
13962
+ framework.product,
13963
+ framework.root,
13964
+ linkedArgs,
13965
+ rewritten,
13966
+ image
13967
+ );
13968
+ }
13969
+ if (sdkProducts) {
13970
+ for (const image of guestSdkProductImages(
13971
+ sdkProducts.products.map((entry) => entry.product),
13972
+ sdkProducts.images
13973
+ )) {
13974
+ const planned = sourcePlan.images.find((entry) => entry.id === image.id);
13975
+ if (!planned || planned.name !== image.name || planned.dependencies.length !== image.dependencies.length || planned.dependencies.some(
13976
+ (dependency, index) => dependency !== image.dependencies[index]
13977
+ ))
13978
+ throw new Error(`SDK image scope differs from source product ${image.name}`);
13979
+ }
13980
+ }
13981
+ const remappedPlan = remapGuestLinkPlan(
13982
+ {
13983
+ ...sourcePlan,
13984
+ artifacts: [
13985
+ ...sourcePlan.artifacts,
13986
+ ...frameworkArtifacts,
13987
+ ...sdkProducts ? guestSdkProductLinkArtifacts(
13988
+ sdkProducts.products,
13989
+ sdk,
13591
13990
  linkedArgs,
13991
+ sdkProducts.linkedArchives,
13592
13992
  rewritten,
13593
- image
13594
- );
13595
- }
13596
- if (sdkProducts) {
13597
- for (const image of guestSdkProductImages(
13598
- sdkProducts.products.map((entry) => entry.product),
13599
- sdkProducts.images
13600
- )) {
13601
- const planned = sourcePlan.images.find((entry) => entry.id === image.id);
13602
- if (!planned || planned.name !== image.name || planned.dependencies.length !== image.dependencies.length || planned.dependencies.some(
13603
- (dependency, index) => dependency !== image.dependencies[index]
13604
- ))
13605
- throw new Error(`SDK image scope differs from source product ${image.name}`);
13606
- }
13607
- }
13608
- const remappedPlan = remapGuestLinkPlan(
13609
- {
13610
- ...sourcePlan,
13611
- artifacts: [
13612
- ...sourcePlan.artifacts,
13613
- ...frameworkArtifacts,
13614
- ...sdkProducts ? guestSdkProductLinkArtifacts(
13615
- sdkProducts.products,
13616
- sdk,
13617
- linkedArgs,
13618
- sdkProducts.linkedArchives,
13619
- rewritten,
13620
- new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
13621
- prepared?.selected
13622
- ) : [],
13623
- ...prepared?.archiveArtifacts ?? []
13624
- ]
13625
- },
13626
- rewritten
13627
- );
13628
- const plan = aliasGuestLinkPlan(remappedPlan, prepared?.archives ?? []);
13629
- let owners = /* @__PURE__ */ new Map();
13630
- let generatedSectionOwners = /* @__PURE__ */ new Map();
13631
- let projection = typeof options.projection === "function" ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan) : options.projection;
13632
- if (projection && prepared) {
13633
- const identities = new Map(projection.identities);
13634
- for (const [before, after] of rewritten) {
13635
- const identity = identities.get(before);
13636
- const existing = identities.get(after);
13637
- if (identity !== void 0 && existing !== void 0 && existing !== identity)
13638
- throw new Error(`rewritten guest input has conflicting identity ${after}`);
13639
- if (identity !== void 0) identities.set(after, identity);
13640
- }
13641
- projection = {
13642
- ...projection,
13643
- identities: aliasGuestLinkIdentities(identities, prepared.archives)
13644
- };
13645
- }
13646
- const selected = linkCompleteGuestImages({
13647
- plan,
13648
- args: [...linkedArgs, `--Map=${options.mapPath}`],
13649
- directory: options.linkDirectory,
13650
- wasmLd: path20.join(options.toolchainBin, "wasm-ld"),
13651
- clang: path20.join(options.toolchainBin, "clang"),
13652
- llvmAr: path20.join(options.toolchainBin, "llvm-ar"),
13653
- ledgerDataImage: options.ledgerDataImage,
13654
- projection,
13655
- resolvePlan: options.resolvePlan,
13656
- sharedSdk: options.sharedSdk,
13657
- onSplitInputs: options.onSplitInputs,
13658
- onDyldRows: options.onDyldRows,
13659
- onLinkedOwners: (value) => {
13660
- owners = value;
13661
- },
13662
- onLinkedSections: (value) => {
13663
- generatedSectionOwners = value;
13664
- }
13665
- });
13666
- result = {
13667
- selected,
13668
- owners,
13669
- generatedSectionOwners,
13670
- sdk,
13671
- mapPath: options.mapPath
13672
- };
13993
+ new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
13994
+ prepared?.selected
13995
+ ) : [],
13996
+ ...prepared?.archiveArtifacts ?? []
13997
+ ]
13673
13998
  },
13674
- options.resourceReferences
13999
+ rewritten
13675
14000
  );
13676
- if (!result) throw new Error("guest link did not receive pruned inputs");
13677
- return result;
14001
+ const plan = aliasGuestLinkPlan(remappedPlan, prepared?.archives ?? []);
14002
+ let owners = /* @__PURE__ */ new Map();
14003
+ let generatedSectionOwners = /* @__PURE__ */ new Map();
14004
+ let projection = typeof options.projection === "function" ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan) : options.projection;
14005
+ if (projection && prepared) {
14006
+ const identities = new Map(projection.identities);
14007
+ for (const [before, after] of rewritten) {
14008
+ const identity = identities.get(before);
14009
+ const existing = identities.get(after);
14010
+ if (identity !== void 0 && existing !== void 0 && existing !== identity)
14011
+ throw new Error(`rewritten guest input has conflicting identity ${after}`);
14012
+ if (identity !== void 0) identities.set(after, identity);
14013
+ }
14014
+ projection = {
14015
+ ...projection,
14016
+ identities: aliasGuestLinkIdentities(identities, prepared.archives)
14017
+ };
14018
+ }
14019
+ const selected = await linkCompleteGuestImages({
14020
+ plan,
14021
+ args: [...linkedArgs, `--Map=${options.mapPath}`],
14022
+ directory: options.linkDirectory,
14023
+ wasmLd: path20.join(options.toolchainBin, "wasm-ld"),
14024
+ clang: path20.join(options.toolchainBin, "clang"),
14025
+ llvmAr: path20.join(options.toolchainBin, "llvm-ar"),
14026
+ ledgerDataImage: options.ledgerDataImage,
14027
+ projection,
14028
+ preselectionDiscovery: prepared?.discovery,
14029
+ resolvePlan: options.resolvePlan,
14030
+ sharedSdk: options.sharedSdk,
14031
+ onSplitInputs: options.onSplitInputs,
14032
+ onDyldRows: options.onDyldRows,
14033
+ onLinkedOwners: (value) => {
14034
+ owners = value;
14035
+ },
14036
+ onLinkedSections: (value) => {
14037
+ generatedSectionOwners = value;
14038
+ }
14039
+ });
14040
+ return {
14041
+ selected,
14042
+ owners,
14043
+ generatedSectionOwners,
14044
+ sdk,
14045
+ mapPath: options.mapPath
14046
+ };
13678
14047
  }
13679
14048
 
13680
14049
  // src/swift-guest-source-inputs.ts
@@ -14602,8 +14971,8 @@ async function compileGuestLink(options) {
14602
14971
  `--sysroot=${options.sysroot}`,
14603
14972
  `-I${path24.join(options.moduleRoot, "include")}`
14604
14973
  ];
14605
- const stubSource = path24.join(directory, "preselection-projection.c");
14606
- const stub = path24.join(directory, "preselection-projection.o");
14974
+ const stubSource = path24.join(directory, "projection-discovery.c");
14975
+ const stub = path24.join(directory, "projection-discovery.o");
14607
14976
  writeFileSync6(
14608
14977
  stubSource,
14609
14978
  '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
@@ -14663,10 +15032,10 @@ async function compileGuestLink(options) {
14663
15032
  };
14664
15033
  const sdk = options.sdkImage;
14665
15034
  const sdkCallers = sdk?.sdkInterface.guestCallers;
14666
- const sdkObjects = sdk ? (await import("./swift-sdk-image-QQQA3AAT.mjs")).readSwiftSdkManifestIndex(sdk).guestObjects : void 0;
15035
+ const sdkObjects = sdk ? (await import("./swift-sdk-image-AQCBWHPL.mjs")).readSwiftSdkManifestIndex(sdk).guestObjects : void 0;
14667
15036
  if (sdk && (!sdkCallers || !sdkObjects))
14668
15037
  throw new Error("the SDK image has no guest link manifest");
14669
- const result = linkPrunedGuestImages({
15038
+ const result = await linkPrunedGuestImages({
14670
15039
  buildDirectory: options.buildDirectory,
14671
15040
  toolchainBin: options.toolchainBin,
14672
15041
  moduleRoot: options.moduleRoot,
@@ -14695,6 +15064,8 @@ async function compileGuestLink(options) {
14695
15064
  wasmLd: path24.join(options.toolchainBin, "wasm-ld"),
14696
15065
  llvmAr: path24.join(options.toolchainBin, "llvm-ar"),
14697
15066
  discoveryObjects: [stub],
15067
+ discoveryOutput: path24.join(directory, "discovery.wasm"),
15068
+ discoveryMap: path24.join(directory, "discovery.map"),
14698
15069
  products: catalogs.products,
14699
15070
  rewritten,
14700
15071
  sdk: sdk2,
@@ -14957,7 +15328,7 @@ async function compileGuestLink(options) {
14957
15328
  linkSwiftAppModule,
14958
15329
  readSwiftSdkUsage,
14959
15330
  swiftSdkProjectionSpans
14960
- } = await import("./swift-sdk-app-module-B63EAEQ5.mjs");
15331
+ } = await import("./swift-sdk-app-module-COF7L4HK.mjs");
14961
15332
  const project = options.project;
14962
15333
  const work = project ? mkdtempSync2(path24.join(directory, "app-module-")) : path24.join(directory, "app-module");
14963
15334
  if (project) chownSync(work, project.uid, project.gid);
@@ -15433,13 +15804,13 @@ function swiftHeaderDependencies(root, files, targets, nativeTargets, producers,
15433
15804
  }
15434
15805
 
15435
15806
  // src/swift-icu.ts
15436
- import { execFile as execFile2 } from "node:child_process";
15807
+ import { execFile as execFile3 } from "node:child_process";
15437
15808
  import { createHash as createHash15, randomUUID as randomUUID4 } from "node:crypto";
15438
15809
  import { existsSync as existsSync6, readFileSync as readFileSync15 } from "node:fs";
15439
15810
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
15440
15811
  import os2 from "node:os";
15441
15812
  import path27 from "node:path";
15442
- import { promisify as promisify2 } from "node:util";
15813
+ import { promisify as promisify3 } from "node:util";
15443
15814
  import {
15444
15815
  brotliCompress,
15445
15816
  constants as zlibConstants,
@@ -15503,10 +15874,10 @@ function swiftIcuPack(blob, deflate2) {
15503
15874
  }
15504
15875
 
15505
15876
  // src/swift-icu.ts
15506
- var run = promisify2(execFile2);
15507
- var deflate = promisify2(gzip);
15508
- var compressBrotli = promisify2(brotliCompress);
15509
- var inflateGzip = promisify2(gunzip);
15877
+ var run = promisify3(execFile3);
15878
+ var deflate = promisify3(gzip);
15879
+ var compressBrotli = promisify3(brotliCompress);
15880
+ var inflateGzip = promisify3(gunzip);
15510
15881
  var ARCHIVE = "wasi/lib_FoundationICU.a";
15511
15882
  var MEMBER = "icu_packaged_data.cpp.obj";
15512
15883
  var raw = /* @__PURE__ */ new Map();
@@ -17687,7 +18058,7 @@ var darwinRecordsRegion = (quoted2) => quoted2.length ? ["-Wl,--start-lib", ...q
17687
18058
  var REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
17688
18059
  var MULTI_MANIFEST_VERSION = 76;
17689
18060
  var SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
17690
- var compilerSourceDigest = true ? "4d55fa7cbb29586c08e4e51867226f96047bae2103c89f4fa59d9cf3ed3862fb" : swiftCompilerSourceDigest(import.meta.dirname);
18061
+ var compilerSourceDigest = true ? "6fbcbab3535da2f464a19f4d3c1db8a7e4b393927e5158477332f4cc978cc22f" : swiftCompilerSourceDigest(import.meta.dirname);
17691
18062
  function swiftArtifactHash(input, release, moduleRoot) {
17692
18063
  return swiftCompileInputHash(input, release).update(swiftModuleDigest(moduleRoot)).digest("hex");
17693
18064
  }
@@ -22545,7 +22916,7 @@ async function compileSwiftProjectOnce(sources, options) {
22545
22916
  const distribution = swiftDistributionAt(moduleRoot);
22546
22917
  const mirrorDistribution = options.linkOnly || options.project ? null : distribution;
22547
22918
  if (distribution) refreshSwiftCacheHold(moduleRoot);
22548
- const input = distribution && !options.intermediates ? (await import("./swift-package-prebuilt-L7A7TT6Q.mjs")).useSwiftPackagePrebuilts(
22919
+ const input = distribution && !options.intermediates ? (await import("./swift-package-prebuilt-XEZH6YEY.mjs")).useSwiftPackagePrebuilts(
22549
22920
  sources,
22550
22921
  moduleRoot,
22551
22922
  options.toolchainBin
@@ -22559,7 +22930,7 @@ async function compileSwiftProjectOnce(sources, options) {
22559
22930
  multi: compileTargets(input).length > 0
22560
22931
  };
22561
22932
  const sdkModule = options.sdkModule && !options.linkOnly;
22562
- const sdkImage = sdkModule ? await (await import("./swift-sdk-image-QQQA3AAT.mjs")).buildSwiftSdkImage(
22933
+ const sdkImage = sdkModule ? await (await import("./swift-sdk-image-AQCBWHPL.mjs")).buildSwiftSdkImage(
22563
22934
  moduleRoot,
22564
22935
  !!guestGraph,
22565
22936
  distribution ? [] : linkedFrameworkTargets(moduleRoot, input).imports,
@@ -23264,7 +23635,7 @@ ${cap}` : "";
23264
23635
  if (sdkImage && binding)
23265
23636
  sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding };
23266
23637
  } else if (sdkImage) {
23267
- const { buildSwiftAppModule } = await import("./swift-sdk-app-module-B63EAEQ5.mjs");
23638
+ const { buildSwiftAppModule } = await import("./swift-sdk-app-module-COF7L4HK.mjs");
23268
23639
  const binding = await buildSwiftAppModule({
23269
23640
  buildRoot: root,
23270
23641
  toolchainBin: options.toolchainBin,