peachsim 0.1.1881 → 0.1.1887

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 (160) hide show
  1. package/cli/commands/control.ts +11 -10
  2. package/cli/commands/reset.ts +1 -1
  3. package/cli/native-input.ts +1 -1
  4. package/cli/outbound-endpoints.ts +1 -1
  5. package/detox/index.ts +62 -1
  6. package/dist-lib/agent-daemon-client.cjs +1 -1
  7. package/dist-lib/agent-events.cjs +1 -1
  8. package/dist-lib/attached-projects.cjs +1 -1
  9. package/dist-lib/auth/shared-session.cjs +1 -1
  10. package/dist-lib/backend-origin.cjs +1 -1
  11. package/dist-lib/beta.cjs +1 -1
  12. package/dist-lib/beta.mjs +1 -1
  13. package/dist-lib/bridge-constants.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.cjs +1 -1
  15. package/dist-lib/bridge-contract-input.mjs +1 -1
  16. package/dist-lib/bridge-contract.cjs +1 -1
  17. package/dist-lib/bridge-contract.mjs +1 -1
  18. package/dist-lib/bundle-channel.cjs +9079 -4305
  19. package/dist-lib/capture-contract.cjs +1 -1
  20. package/dist-lib/capture-contract.mjs +1 -1
  21. package/dist-lib/cloud-contract.cjs +1 -1
  22. package/dist-lib/cloud-contract.mjs +1 -1
  23. package/dist-lib/cloud-test-args.cjs +1 -1
  24. package/dist-lib/cloud-test-args.mjs +1 -1
  25. package/dist-lib/cloud.cjs +1 -1
  26. package/dist-lib/cloud.mjs +1 -1
  27. package/dist-lib/config.cjs +1 -1
  28. package/dist-lib/config.mjs +1 -1
  29. package/dist-lib/detox/index.cjs +35 -2
  30. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  31. package/dist-lib/expo-swift-bundle.cjs +8609 -3976
  32. package/dist-lib/expo-swift-metadata.cjs +5 -1
  33. package/dist-lib/expo-swift-metadata.mjs +5 -1
  34. package/dist-lib/home-paths.cjs +1 -1
  35. package/dist-lib/host/bridge-host.cjs +9894 -5149
  36. package/dist-lib/host/fetch-proxy-handler.cjs +93 -13
  37. package/dist-lib/host/fetch-proxy-overrides.cjs +10 -2
  38. package/dist-lib/host/fetch-proxy-overrides.mjs +8 -2
  39. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  40. package/dist-lib/host/websocket-proxy.cjs +1 -1
  41. package/dist-lib/index.cjs +538 -120
  42. package/dist-lib/jump-to-source-babel.cjs +1 -1
  43. package/dist-lib/jump-to-source-native.cjs +1 -1
  44. package/dist-lib/kotlin-host.cjs +1 -1
  45. package/dist-lib/menu.cjs +1 -1
  46. package/dist-lib/menu.mjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  48. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  49. package/dist-lib/metro-production-bundle.cjs +1 -1
  50. package/dist-lib/metro-production-bundle.mjs +1 -1
  51. package/dist-lib/metro.cjs +536 -118
  52. package/dist-lib/native-app-identity-project.cjs +408 -72
  53. package/dist-lib/native-app-identity-project.mjs +739 -375
  54. package/dist-lib/native-app-identity.cjs +37 -1
  55. package/dist-lib/native-app-identity.mjs +36 -1
  56. package/dist-lib/native-firebase-metadata.cjs +1 -1
  57. package/dist-lib/native-firebase-metadata.mjs +1 -1
  58. package/dist-lib/pdfium-raster.cjs +1 -1
  59. package/dist-lib/pdfium-raster.mjs +1 -1
  60. package/dist-lib/plist.cjs +1 -1
  61. package/dist-lib/plist.mjs +1 -1
  62. package/dist-lib/profiles.cjs +1 -1
  63. package/dist-lib/public-brand.cjs +1 -1
  64. package/dist-lib/public-origins-lib-esm.json +61 -28
  65. package/dist-lib/public-origins-lib.json +250 -92
  66. package/dist-lib/react-native-host-modules.cjs +1 -1
  67. package/dist-lib/react-native-host-modules.mjs +1 -1
  68. package/dist-lib/reap-browser.cjs +1 -1
  69. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  70. package/dist-lib/sdk.cjs +1 -1
  71. package/dist-lib/sdk.mjs +1 -1
  72. package/dist-lib/skills.cjs +16568 -11674
  73. package/dist-lib/swift-compile.cjs +6874 -2537
  74. package/dist-lib/swift-compile.mjs +6207 -1866
  75. package/dist-lib/swift-package.cjs +20 -3
  76. package/dist-lib/swift-package.mjs +20 -3
  77. package/dist-lib/swift-submit.cjs +2 -2
  78. package/dist-lib/swift-submit.mjs +2 -2
  79. package/dist-lib/swift-toolchain.cjs +19 -1
  80. package/dist-lib/swift.cjs +1 -1
  81. package/dist-lib/vite-swift.cjs +8753 -4124
  82. package/dist-lib/vite.cjs +93 -13
  83. package/dist-lib/worklet-executable.cjs +1 -1
  84. package/dist-lib/worklet-executable.mjs +1 -1
  85. package/dist-types/packages/peach-engine/src/engine/canvaskit-api.d.ts +1 -1
  86. package/dist-types/packages/peach-engine/src/engine/fontDataContract.d.ts +2 -0
  87. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  88. package/dist-types/packages/peach-engine/src/render-worker/native-ui-protocol.d.ts +1 -0
  89. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +11 -1
  90. package/dist-types/packages/peach-engine/src/render-worker/shell-tree-wire.d.ts +2 -1
  91. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  92. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +10 -1
  93. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  94. package/dist-types/packages/peach-kit/src/ui/popover-placement.d.ts +1 -1
  95. package/dist-types/packages/sootsim-swift/src/securityHostContract.d.ts +10 -0
  96. package/package.json +1 -1
  97. package/runtime-companion.json +1 -1
  98. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHost.h +555 -0
  99. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +1 -0
  100. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes +6 -0
  101. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSURLProtocol.h +0 -1
  102. package/sdk/ios/System/Library/Frameworks/QuartzCore.framework/Modules/module.modulemap +6 -0
  103. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarButtonItemBadge.h +1 -1
  104. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarMinimization.h +1 -1
  105. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIScrollView.h +1 -1
  106. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UISearchTab.h +1 -1
  107. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITab.h +1 -1
  108. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITabAccessory.h +2 -2
  109. package/sdk/ios/usr/include/os/activity.h +534 -0
  110. package/sdk/ios/usr/include/os.modulemap +15 -0
  111. package/sdk/ios/wasm/include/fcntl.h +16 -0
  112. package/sdk/ios/wasm/include/string.h +5 -0
  113. package/sdk/native-hashes.json +1 -1
  114. package/src/dns-over-https.ts +61 -9
  115. package/src/expo-swift-bundle.ts +2 -7
  116. package/src/expo-swift-host.ts +11 -3
  117. package/src/host/fetch-proxy-handler.ts +51 -2
  118. package/src/host/fetch-proxy-overrides.ts +4 -0
  119. package/src/host/hostname-resolver.ts +9 -5
  120. package/src/native-app-identity-project.ts +13 -2
  121. package/src/native-app-identity.ts +47 -0
  122. package/src/nitro-adapter.lock.json +260 -260
  123. package/src/nitro-bundle.ts +7 -10
  124. package/src/nitro-superset.lock.json +4 -4
  125. package/src/podspec-sources.ts +20 -0
  126. package/src/storageSnapshotContract.ts +20 -1
  127. package/src/swift-compile.ts +409 -77
  128. package/src/swift-compiler-digest.ts +15 -0
  129. package/src/swift-coverage/xcode-packages.ts +3 -2
  130. package/src/swift-distribution.lock.json +12 -12
  131. package/src/swift-guest-archive.ts +153 -0
  132. package/src/swift-guest-compile.ts +449 -0
  133. package/src/swift-guest-image-ledger.ts +656 -0
  134. package/src/swift-guest-link-plan.ts +52 -0
  135. package/src/swift-guest-link.ts +1414 -0
  136. package/src/swift-guest-linked-spans.ts +338 -0
  137. package/src/swift-guest-manifest.ts +141 -0
  138. package/src/swift-guest-projection-storage.ts +310 -0
  139. package/src/swift-guest-projection.ts +252 -0
  140. package/src/swift-guest-runtime-plan.ts +834 -0
  141. package/src/swift-guest-source-inputs.ts +427 -0
  142. package/src/swift-guest-source-plan.ts +279 -0
  143. package/src/swift-host.ts +157 -36
  144. package/src/swift-icu.ts +60 -18
  145. package/src/swift-link-roots.ts +27 -50
  146. package/src/swift-package-manifest.ts +34 -18
  147. package/src/swift-package.ts +32 -2
  148. package/src/swift-packages.ts +138 -17
  149. package/src/swift-runtime-products.ts +73 -0
  150. package/src/swift-shared-sdk.ts +1 -1
  151. package/src/swift-submit.ts +15 -3
  152. package/src/swift-toolchain.ts +18 -0
  153. package/src/swift-wasm-prune.ts +313 -14
  154. package/src/swiftContract.ts +83 -0
  155. package/src/swiftRuntimeProductContract.ts +85 -45
  156. package/src/turbo-bundle.ts +1 -1
  157. package/src/turbo-codegen-intake.ts +10 -3
  158. package/src/turbo-runtime.lock.json +23 -23
  159. package/src/wasm-optimize.ts +16 -4
  160. package/src/xcode-project.ts +142 -14
@@ -0,0 +1,310 @@
1
+ import {
2
+ guestLinkedSpans,
3
+ guestWasmDataSegments,
4
+ type GuestLinkedSpan,
5
+ } from './swift-guest-linked-spans'
6
+ import {
7
+ reserveGuestImageProjection,
8
+ type ReservedGuestImageProjection,
9
+ } from './swift-guest-projection'
10
+ import {
11
+ isSwiftGuestImageManifest,
12
+ type SwiftGuestImageManifest,
13
+ type SwiftGuestImageRegion,
14
+ } from './swiftGuestImageContract'
15
+
16
+ export interface GuestProjectionCapacity {
17
+ readonly regions: number
18
+ readonly memoryProtection: { readonly initial: number; readonly maximum: number }
19
+ readonly tableProtection: { readonly initial: number; readonly maximum: number }
20
+ }
21
+
22
+ export interface ReservedGuestProjectionStorage {
23
+ readonly source: string
24
+ readonly projection: ReservedGuestImageProjection
25
+ readonly images: readonly SwiftGuestImageManifest[]
26
+ readonly capacities: readonly GuestProjectionCapacity[]
27
+ readonly countMarkers: readonly number[]
28
+ }
29
+
30
+ // region counts are uint32 in the runtime tables; this only rejects absurd reservations.
31
+ const maxProjectionRegions = 1 << 20
32
+
33
+ /** Bound regions by selected object functions and data segments, plus generated inputs. */
34
+ export function guestProjectionRegionCapacity(
35
+ objects: readonly Uint8Array[],
36
+ generatedRanges: number,
37
+ ): number {
38
+ if (!Number.isInteger(generatedRanges) || generatedRanges < 0)
39
+ throw new Error('invalid generated guest range capacity')
40
+ let capacity = generatedRanges
41
+ for (const object of objects) {
42
+ if (Buffer.from(object.subarray(0, 8)).toString('hex') !== '0061736d01000000')
43
+ throw new Error('expected selected wasm object')
44
+ let offset = 8
45
+ const number = (limit: number) => {
46
+ let value = 0
47
+ let shift = 0
48
+ for (;;) {
49
+ if (offset >= limit || shift > 28) throw new Error('invalid wasm object integer')
50
+ const byte = object[offset++]!
51
+ value += (byte & 127) * 2 ** shift
52
+ if (!(byte & 128)) return value
53
+ shift += 7
54
+ }
55
+ }
56
+ while (offset < object.length) {
57
+ const section = object[offset++]!
58
+ const size = number(object.length)
59
+ const end = offset + size
60
+ if (end > object.length) throw new Error('invalid wasm object section')
61
+ if (section === 3 || section === 11) capacity += number(end)
62
+ offset = end
63
+ }
64
+ }
65
+ if (capacity < 1 || capacity > maxProjectionRegions)
66
+ throw new Error('guest projection capacity out of range')
67
+ return capacity
68
+ }
69
+
70
+ /** Reserve image records before final linking; the count is filled from actual linked spans. */
71
+ export function reserveGuestProjectionStorage(
72
+ images: readonly SwiftGuestImageManifest[],
73
+ capacities: readonly GuestProjectionCapacity[],
74
+ ): ReservedGuestProjectionStorage {
75
+ if (images.length !== capacities.length)
76
+ throw new Error('guest projection capacity mismatch')
77
+ const placeholders = images.map((image, index) => {
78
+ const capacity = capacities[index]!
79
+ if (
80
+ !Number.isInteger(capacity.regions) ||
81
+ capacity.regions < 1 ||
82
+ capacity.regions > maxProjectionRegions
83
+ )
84
+ throw new Error('invalid guest projection capacity')
85
+ if (image.regions.length)
86
+ throw new Error('automatic projection requires unshaped images')
87
+ const regions: SwiftGuestImageRegion[] = Array.from(
88
+ { length: capacity.regions },
89
+ () => ({
90
+ name: '__WASM',
91
+ space: 'function-table',
92
+ address: 0,
93
+ length: 0,
94
+ initialProtection: 7,
95
+ maximumProtection: 7,
96
+ sections: [],
97
+ }),
98
+ )
99
+ const value = { ...image, regions }
100
+ if (!isSwiftGuestImageManifest(value)) throw new Error('invalid guest image metadata')
101
+ return value
102
+ })
103
+ const projection = reserveGuestImageProjection(placeholders)
104
+ const lines = projection.source.split('\n')
105
+ const imageStart = lines.indexOf(
106
+ 'const struct peach_guest_image __peach_guest_images[] = {',
107
+ )
108
+ if (imageStart < 0) throw new Error('guest image records missing')
109
+ // Keep every patchable byte in the optimized data segments, including the
110
+ // high zero bytes of space and protection fields.
111
+ for (let index = 0; index < imageStart; index++) {
112
+ const line = lines[index]!
113
+ if (!line.startsWith(' {')) continue
114
+ const retained = line
115
+ .replace(', 1u, ', ', 4294967295u, ')
116
+ .replace(', 7u, 7u, 0u, 0},', ', 4294967295u, 4294967295u, 0u, 0},')
117
+ if (retained === line || !retained.endsWith(', 4294967295u, 4294967295u, 0u, 0},'))
118
+ throw new Error('guest region record shape changed')
119
+ lines[index] = retained
120
+ }
121
+ const countMarkers = images.map((_, index) => {
122
+ if (index >= 65535) throw new Error('too many guest images')
123
+ const marker = 0xfc010101 + ((index % 255) << 8) + (Math.floor(index / 255) << 16)
124
+ const line = lines[imageStart + 1 + index]!
125
+ const suffix = `, ${capacities[index]!.regions}u, regions_${index}},`
126
+ if (!line.endsWith(suffix)) throw new Error('guest image record shape changed')
127
+ lines[imageStart + 1 + index] =
128
+ line.slice(0, -suffix.length) + `, ${marker}u, regions_${index}},`
129
+ return marker
130
+ })
131
+ return { source: lines.join('\n'), projection, images, capacities, countMarkers }
132
+ }
133
+
134
+ /** Use only owned actual ranges, merging adjacent or overlapping ranges of one image. */
135
+ export function planGuestProjectionRegions(
136
+ images: readonly SwiftGuestImageManifest[],
137
+ capacities: readonly GuestProjectionCapacity[],
138
+ spans: readonly GuestLinkedSpan[],
139
+ ): SwiftGuestImageManifest[] {
140
+ if (images.length !== capacities.length)
141
+ throw new Error('guest projection capacity mismatch')
142
+ const sorted = [...spans].sort(
143
+ (a, b) =>
144
+ a.space.localeCompare(b.space) || a.address - b.address || a.image - b.image,
145
+ )
146
+ const merged: GuestLinkedSpan[] = []
147
+ for (const span of sorted) {
148
+ if (
149
+ !Number.isInteger(span.image) ||
150
+ span.image < 0 ||
151
+ span.image >= images.length ||
152
+ !Number.isInteger(span.address) ||
153
+ !Number.isInteger(span.length) ||
154
+ span.address < 0 ||
155
+ span.length <= 0 ||
156
+ span.address + span.length > 0x100000000
157
+ )
158
+ throw new Error('invalid linked guest span')
159
+ const previous = merged[merged.length - 1]
160
+ if (
161
+ previous &&
162
+ previous.space === span.space &&
163
+ span.address < previous.address + previous.length &&
164
+ previous.image !== span.image
165
+ )
166
+ throw new Error('linked guest span has ambiguous image ownership')
167
+ if (
168
+ previous &&
169
+ previous.space === span.space &&
170
+ previous.image === span.image &&
171
+ span.address <= previous.address + previous.length
172
+ ) {
173
+ merged[merged.length - 1] = {
174
+ ...previous,
175
+ length:
176
+ Math.max(previous.address + previous.length, span.address + span.length) -
177
+ previous.address,
178
+ }
179
+ } else merged.push(span)
180
+ }
181
+ return images.map((image, index) => {
182
+ const capacity = capacities[index]!
183
+ const regions = merged
184
+ .filter((span) => span.image === index)
185
+ .map((span): SwiftGuestImageRegion => {
186
+ const protection =
187
+ span.space === 'linear-memory'
188
+ ? capacity.memoryProtection
189
+ : capacity.tableProtection
190
+ return {
191
+ name: '__WASM',
192
+ space: span.space,
193
+ address: span.address,
194
+ length: span.length,
195
+ initialProtection: protection.initial,
196
+ maximumProtection: protection.maximum,
197
+ sections: [],
198
+ }
199
+ })
200
+ if (regions.length > capacity.regions)
201
+ throw new Error(`guest projection region capacity exceeded for ${image.id}`)
202
+ const result = { ...image, regions }
203
+ if (!isSwiftGuestImageManifest(result)) throw new Error('invalid planned guest image')
204
+ return result
205
+ })
206
+ }
207
+
208
+ /** Fill bounded records after optimization without advertising unused capacity. */
209
+ export function finalizeGuestProjectionStorage(options: {
210
+ readonly map: string
211
+ readonly linked: Uint8Array
212
+ readonly optimized: Uint8Array
213
+ readonly owners: ReadonlyMap<string, number>
214
+ readonly sectionOwners: ReadonlyMap<string, number>
215
+ readonly projectionObject: string
216
+ readonly reserved: ReservedGuestProjectionStorage
217
+ }): { readonly wasm: Uint8Array; readonly images: readonly SwiftGuestImageManifest[] } {
218
+ const owner = options.owners.get(options.projectionObject)
219
+ if (owner === undefined) throw new Error('guest projection object has no image owner')
220
+ const spans = guestLinkedSpans(
221
+ options.map,
222
+ options.linked,
223
+ options.optimized,
224
+ options.owners,
225
+ options.sectionOwners,
226
+ )
227
+ const images = planGuestProjectionRegions(
228
+ options.reserved.images,
229
+ options.reserved.capacities,
230
+ spans,
231
+ )
232
+ const ranges = guestLinkedSpans(
233
+ options.map,
234
+ options.linked,
235
+ options.optimized,
236
+ new Map([[options.projectionObject, owner]]),
237
+ ).filter((span) => span.space === 'linear-memory')
238
+ const result = Buffer.from(options.optimized)
239
+ const data = guestWasmDataSegments(options.optimized)
240
+ const locations = new Map<number, number>()
241
+ const counts = new Map<number, number>()
242
+ const markers = new Map(
243
+ options.reserved.countMarkers.map((marker, index) => [marker, index]),
244
+ )
245
+ for (const range of ranges)
246
+ for (const segment of data) {
247
+ const first = Math.max(range.address, segment.address)
248
+ const last = Math.min(
249
+ range.address + range.length,
250
+ segment.address + segment.length,
251
+ )
252
+ const start = segment.offset + first - segment.address
253
+ const end = segment.offset + last - segment.address
254
+ for (let offset = start; offset <= end - 4; offset++) {
255
+ const value = result.readUInt32LE(offset)
256
+ const count = markers.get(value)
257
+ if (count !== undefined) {
258
+ if (counts.has(count))
259
+ throw new Error('duplicate guest projection count marker')
260
+ counts.set(count, offset)
261
+ }
262
+ if (
263
+ offset > end - 8 ||
264
+ result[offset + 3] !== 0xfe ||
265
+ result[offset + 7] !== 0xfd
266
+ )
267
+ continue
268
+ const low = result[offset]!,
269
+ middle = result[offset + 1]!,
270
+ high = result[offset + 2]!
271
+ if (!low || !middle || !high) continue
272
+ const index = low - 1 + (middle - 1) * 255 + (high - 1) * 255 ** 2
273
+ const slot = options.reserved.projection.slots[index]
274
+ if (
275
+ !slot ||
276
+ value !== slot.address ||
277
+ result.readUInt32LE(offset + 4) !== slot.length
278
+ )
279
+ continue
280
+ if (locations.has(index))
281
+ throw new Error('duplicate guest projection range marker')
282
+ if (offset < start + 4 || offset + 16 > end)
283
+ throw new Error('guest projection record crosses data boundary')
284
+ if (
285
+ result.readUInt32LE(offset - 4) !== 0xffffffff ||
286
+ result.readUInt32LE(offset + 8) !== 0xffffffff ||
287
+ result.readUInt32LE(offset + 12) !== 0xffffffff
288
+ )
289
+ throw new Error('guest projection record changed during optimization')
290
+ locations.set(index, offset)
291
+ }
292
+ }
293
+ for (const [index, marker] of options.reserved.countMarkers.entries()) {
294
+ const offset = counts.get(index)
295
+ if (offset === undefined || result.readUInt32LE(offset) !== marker)
296
+ throw new Error('missing guest projection count marker')
297
+ result.writeUInt32LE(images[index]!.regions.length, offset)
298
+ }
299
+ for (const [index, slot] of options.reserved.projection.slots.entries()) {
300
+ const offset = locations.get(index)
301
+ if (offset === undefined) throw new Error('missing guest projection range marker')
302
+ const region = images[slot.image]!.regions[slot.region]
303
+ result.writeUInt32LE(region?.space === 'function-table' ? 1 : 0, offset - 4)
304
+ result.writeUInt32LE(region?.address ?? 0, offset)
305
+ result.writeUInt32LE(region?.length ?? 0, offset + 4)
306
+ result.writeUInt32LE(region?.initialProtection ?? 0, offset + 8)
307
+ result.writeUInt32LE(region?.maximumProtection ?? 0, offset + 12)
308
+ }
309
+ return { wasm: result, images }
310
+ }
@@ -0,0 +1,252 @@
1
+ import {
2
+ guestLinkedSpans,
3
+ guestWasmDataSegments,
4
+ type GuestLinkedSpan,
5
+ } from './swift-guest-linked-spans'
6
+ import {
7
+ isSwiftGuestImageManifest,
8
+ type SwiftGuestImageManifest,
9
+ } from './swiftGuestImageContract'
10
+
11
+ interface ProjectionSlot {
12
+ readonly image: number
13
+ readonly region: number
14
+ readonly section: number | null
15
+ readonly address: number
16
+ readonly length: number
17
+ }
18
+
19
+ export interface ReservedGuestImageProjection {
20
+ readonly source: string
21
+ readonly shape: readonly string[]
22
+ readonly slots: readonly ProjectionSlot[]
23
+ }
24
+
25
+ function projectionShape(image: SwiftGuestImageManifest): string {
26
+ return JSON.stringify([
27
+ image.version,
28
+ image.id,
29
+ image.installName,
30
+ image.fileType,
31
+ image.target.triple,
32
+ image.target.pointerWidth,
33
+ image.target.byteOrder,
34
+ image.target.cpuType,
35
+ image.target.cpuSubtype,
36
+ image.inputsSha256,
37
+ image.uuid,
38
+ image.buildVersion.platform,
39
+ [
40
+ image.buildVersion.minimum.major,
41
+ image.buildVersion.minimum.minor,
42
+ image.buildVersion.minimum.patch,
43
+ ],
44
+ [
45
+ image.buildVersion.sdk.major,
46
+ image.buildVersion.sdk.minor,
47
+ image.buildVersion.sdk.patch,
48
+ ],
49
+ image.regions.map((region) => [
50
+ region.name,
51
+ region.space,
52
+ region.initialProtection,
53
+ region.maximumProtection,
54
+ region.sections.map((section) => [section.name, section.alignment, section.flags]),
55
+ ]),
56
+ ])
57
+ }
58
+
59
+ /** Reserve fixed-width range fields before the last link and optimizer. */
60
+ export function reserveGuestImageProjection(
61
+ images: readonly SwiftGuestImageManifest[],
62
+ ): ReservedGuestImageProjection {
63
+ const slots: ProjectionSlot[] = []
64
+ const values = images.map((image, imageIndex) => ({
65
+ ...image,
66
+ regions: image.regions.map((region, regionIndex) => {
67
+ const reserve = (section: number | null) => {
68
+ const index = slots.length
69
+ if (index >= 255 ** 3) throw new Error('too many guest projection ranges')
70
+ // nonzero bytes prevent wasm-opt trimming the start of a marker when
71
+ // it splits zero-filled data segments.
72
+ const payload =
73
+ (index % 255) +
74
+ 1 +
75
+ (Math.floor(index / 255) % 255) * 256 +
76
+ 256 +
77
+ Math.floor(index / 255 ** 2) * 65536 +
78
+ 65536
79
+ const slot = {
80
+ image: imageIndex,
81
+ region: regionIndex,
82
+ section,
83
+ address: 0xfe000000 + payload,
84
+ length: 0xfd000000 + payload,
85
+ }
86
+ slots.push(slot)
87
+ return { address: slot.address, length: slot.length }
88
+ }
89
+ const range = reserve(null)
90
+ return {
91
+ ...region,
92
+ ...range,
93
+ sections: region.sections.map((section, index) => ({
94
+ ...section,
95
+ ...reserve(index),
96
+ })),
97
+ }
98
+ }),
99
+ }))
100
+ return {
101
+ source: emitGuestImageProjection(values),
102
+ shape: images.map(projectionShape),
103
+ slots,
104
+ }
105
+ }
106
+
107
+ /** Fill reserved fields in optimized data without changing any linked address. */
108
+ export function finalizeGuestImageProjection(
109
+ wasm: Uint8Array,
110
+ reserved: ReservedGuestImageProjection,
111
+ images: readonly SwiftGuestImageManifest[],
112
+ projectionData: readonly { readonly address: number; readonly length: number }[],
113
+ ): Uint8Array {
114
+ if (
115
+ images.length !== reserved.shape.length ||
116
+ images.some(
117
+ (image, index) =>
118
+ !isSwiftGuestImageManifest(image) ||
119
+ projectionShape(image) !== reserved.shape[index],
120
+ )
121
+ )
122
+ throw new Error('guest projection layout changed after linking')
123
+ const data = guestWasmDataSegments(wasm)
124
+ const result = Buffer.from(wasm)
125
+ const locations = new Map<number, number>()
126
+ for (const range of projectionData) {
127
+ for (const segment of data) {
128
+ const first = Math.max(range.address, segment.address)
129
+ const last = Math.min(
130
+ range.address + range.length,
131
+ segment.address + segment.length,
132
+ )
133
+ const start = segment.offset + first - segment.address
134
+ const end = segment.offset + last - segment.address
135
+ for (let offset = start; offset <= end - 8; offset++) {
136
+ if (result[offset + 3] !== 0xfe || result[offset + 7] !== 0xfd) continue
137
+ const low = result[offset]!
138
+ const middle = result[offset + 1]!
139
+ const high = result[offset + 2]!
140
+ if (!low || !middle || !high) continue
141
+ const index = low - 1 + (middle - 1) * 255 + (high - 1) * 255 ** 2
142
+ const slot = reserved.slots[index]
143
+ if (
144
+ !slot ||
145
+ result.readUInt32LE(offset) !== slot.address ||
146
+ result.readUInt32LE(offset + 4) !== slot.length
147
+ )
148
+ continue
149
+ if (locations.has(index))
150
+ throw new Error(`duplicate guest projection range marker ${index}`)
151
+ locations.set(index, offset)
152
+ }
153
+ }
154
+ }
155
+ for (const [index, slot] of reserved.slots.entries()) {
156
+ const offset = locations.get(index)
157
+ if (offset === undefined)
158
+ throw new Error(`missing guest projection range marker ${index}`)
159
+ const region = images[slot.image]!.regions[slot.region]!
160
+ const value = slot.section === null ? region : region.sections[slot.section]!
161
+ result.writeUInt32LE(value.address, offset)
162
+ result.writeUInt32LE(value.length, offset + 4)
163
+ }
164
+ return result
165
+ }
166
+
167
+ /** Bind manifests to the final map and optimized module, then fill their ranges. */
168
+ export function finalizeLinkedGuestImages(options: {
169
+ readonly map: string
170
+ readonly linked: Uint8Array
171
+ readonly optimized: Uint8Array
172
+ readonly owners: ReadonlyMap<string, number>
173
+ readonly sectionOwners: ReadonlyMap<string, number>
174
+ readonly projectionObject: string
175
+ readonly reserved: ReservedGuestImageProjection
176
+ readonly manifests: (
177
+ spans: readonly GuestLinkedSpan[],
178
+ ) => readonly SwiftGuestImageManifest[]
179
+ }): { readonly wasm: Uint8Array; readonly images: readonly SwiftGuestImageManifest[] } {
180
+ const image = options.owners.get(options.projectionObject)
181
+ if (image === undefined) throw new Error('guest projection object has no image owner')
182
+ const spans = guestLinkedSpans(
183
+ options.map,
184
+ options.linked,
185
+ options.optimized,
186
+ options.owners,
187
+ options.sectionOwners,
188
+ )
189
+ const projectionData = guestLinkedSpans(
190
+ options.map,
191
+ options.linked,
192
+ options.optimized,
193
+ new Map([[options.projectionObject, image]]),
194
+ ).filter((span) => span.space === 'linear-memory')
195
+ const images = options.manifests(spans)
196
+ return {
197
+ images,
198
+ wasm: finalizeGuestImageProjection(
199
+ options.optimized,
200
+ options.reserved,
201
+ images,
202
+ projectionData,
203
+ ),
204
+ }
205
+ }
206
+
207
+ // emit exact utf8 bytes; octal escapes have fixed width even before a digit.
208
+ function cString(value: string): string {
209
+ return `"${[...Buffer.from(value, 'utf8')]
210
+ .map((byte) => `\\${byte.toString(8).padStart(3, '0')}`)
211
+ .join('')}"`
212
+ }
213
+
214
+ /** Emit the runtime tables for the finalized image manifests. */
215
+ export function emitGuestImageProjection(
216
+ images: readonly SwiftGuestImageManifest[],
217
+ ): string {
218
+ const lines = ['#include "guest-image-projection.h"']
219
+ images.forEach((image, i) => {
220
+ image.regions.forEach((region, r) => {
221
+ if (!region.sections.length) return
222
+ lines.push(`static const struct peach_guest_section sections_${i}_${r}[] = {`)
223
+ for (const section of region.sections)
224
+ lines.push(
225
+ ` {${cString(section.name)}, ${section.address}u, ${section.length}u, ${section.alignment}u, ${section.flags}u},`,
226
+ )
227
+ lines.push('};')
228
+ })
229
+ if (!image.regions.length) return
230
+ lines.push(`static const struct peach_guest_region regions_${i}[] = {`)
231
+ image.regions.forEach((region, r) => {
232
+ lines.push(
233
+ ` {${cString(region.name)}, ${region.space === 'function-table' ? 1 : 0}u, ${region.address}u, ${region.length}u, ${region.initialProtection}u, ${region.maximumProtection}u, ${region.sections.length}u, ${region.sections.length ? `sections_${i}_${r}` : '0'}},`,
234
+ )
235
+ })
236
+ lines.push('};')
237
+ })
238
+ lines.push('const struct peach_guest_image __peach_guest_images[] = {')
239
+ for (const [i, image] of images.entries()) {
240
+ const uuid = image.uuid
241
+ .match(/../g)!
242
+ .map((byte) => `0x${byte}`)
243
+ .join(', ')
244
+ const version = (v: { major: number; minor: number; patch: number }) =>
245
+ (v.major * 65536 + v.minor * 256 + v.patch).toString()
246
+ lines.push(
247
+ ` {${cString(image.installName)}, ${image.fileType === 'executable' ? 2 : 6}u, {${uuid}}, ${image.buildVersion.platform}u, ${version(image.buildVersion.minimum)}u, ${version(image.buildVersion.sdk)}u, ${image.regions.length}u, ${image.regions.length ? `regions_${i}` : '0'}},`,
248
+ )
249
+ }
250
+ lines.push('};', `const uint32_t __peach_guest_image_count = ${images.length}u;`, '')
251
+ return lines.join('\n')
252
+ }