systemless 0.42.2

High-Level Emulation for classic Macintosh applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use super::ids::{AddressSpaceId, ArtifactId, CaptureId, ContextId, OperationId, ProviderId};
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ByteOrder {
    Big,
    Little,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AddressMappingKind {
    Ram,
    Rom,
    Mmio,
    Unmapped,
    Unknown,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct AddressAccess {
    pub read: bool,
    pub write: bool,
    pub execute: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AddressSpaceDescriptor {
    pub id: AddressSpaceId,
    pub name: String,
    pub address_bits: u16,
    pub byte_order: ByteOrder,
    pub mapping: AddressMappingKind,
    pub access: AddressAccess,
    pub supports_translation: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextLifecycle {
    Active,
    Suspended,
    Unavailable,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ExecutionContextDescriptor {
    pub id: ContextId,
    pub architecture: String,
    pub task: Option<String>,
    pub lifecycle: ContextLifecycle,
    pub address_spaces: Vec<AddressSpaceId>,
    pub capabilities: ContextCapabilities,
}

/// `{"kind":"active"}` resolves at request time; `{"kind":"id","id":1}` names
/// an installed context. IDs remain stable within a session generation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ContextSelector {
    Active,
    Id { id: ContextId },
}

impl ContextSelector {
    pub fn active() -> Self {
        Self::Active
    }

    pub fn explicit(id: ContextId) -> Self {
        Self::Id { id }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct ContextCapabilities {
    pub pause: bool,
    pub resume: bool,
    pub step: bool,
    pub exact_step: bool,
    pub set_breakpoint: bool,
    pub read_registers: bool,
    pub disassembly: bool,
    pub exact_disassembly: bool,
    pub stack_preview: bool,
    pub write_registers: bool,
    pub read_memory: bool,
    pub write_memory: bool,
    pub precise_breakpoints: bool,
    pub watchpoints: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct AddressSpaceCapabilities {
    pub read: bool,
    pub write: bool,
    pub observational_reads: bool,
    pub code_cache_invalidation: bool,
    pub max_transfer_bytes: u64,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
pub enum StopReason {
    UserPause,
    StepCompleted,
    PcBreakpoint { id: super::ids::BreakpointId },
    CaptureBoundary { id: CaptureId },
    UnsupportedTransition,
    Watchpoint { id: super::ids::WatchpointId },
    TerminalHalt,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct StopInfo {
    pub id: u64,
    pub revision: u64,
    pub context: Option<ContextId>,
    pub location: Option<ExecutionLocation>,
    pub reason: StopReason,
    pub guest_tick: Option<u32>,
    pub execution_units: Option<u64>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum DebugExecutionState {
    Running,
    Paused { stop: StopInfo },
    Stepping { operation_id: OperationId },
}

impl DebugExecutionState {
    pub fn is_paused(&self) -> bool {
        matches!(self, DebugExecutionState::Paused { .. })
    }

    pub fn is_running(&self) -> bool {
        matches!(self, DebugExecutionState::Running)
    }

    pub fn is_stepping(&self) -> bool {
        matches!(self, DebugExecutionState::Stepping { .. })
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct DebugAddress {
    /// Address-space ID discovered through `ListAddressSpaces`.
    pub space: AddressSpaceId,
    /// Byte offset, serialized as a JSON number (not a hexadecimal string).
    pub offset: u64,
}

impl DebugAddress {
    pub fn new(space: AddressSpaceId, offset: u64) -> Self {
        Self { space, offset }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct ExecutionLocation {
    pub context: ContextId,
    pub address: DebugAddress,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RegisterWidth {
    Bits8,
    Bits16,
    Bits32,
    Bits64,
    Bits128,
    Other(u16),
}

impl RegisterWidth {
    pub fn bits(self) -> u16 {
        match self {
            RegisterWidth::Bits8 => 8,
            RegisterWidth::Bits16 => 16,
            RegisterWidth::Bits32 => 32,
            RegisterWidth::Bits64 => 64,
            RegisterWidth::Bits128 => 128,
            RegisterWidth::Other(bits) => bits,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RegisterCategory {
    General,
    Address,
    ProgramCounter,
    StackPointer,
    Status,
    FloatingPoint,
    Vector,
    Control,
    Other,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RegisterRole {
    ProgramCounter,
    StackPointer,
    FramePointer,
    LinkRegister,
    ConditionCodes,
    Other,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RegisterDescriptor {
    pub id: u32,
    pub name: String,
    pub width: RegisterWidth,
    pub category: RegisterCategory,
    pub role: Option<RegisterRole>,
    pub readable: bool,
    pub writable: bool,
    pub flags: Vec<RegisterFlag>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RegisterFlag {
    pub bit: u16,
    pub name: String,
    pub description: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "encoding", rename_all = "snake_case")]
pub enum RegisterValue {
    Unsigned { value: u64, width_bits: u16 },
    // Big-endian register bytes.
    Bytes { bytes: Vec<u8>, width_bits: u16 },
}

impl RegisterValue {
    pub fn unsigned(value: u64, width_bits: u16) -> Self {
        if width_bits > 32 {
            Self::Bytes {
                bytes: value.to_be_bytes().to_vec(),
                width_bits,
            }
        } else {
            Self::Unsigned { value, width_bits }
        }
    }

    pub fn bytes(bytes: Vec<u8>, width_bits: u16) -> Self {
        Self::Bytes { bytes, width_bits }
    }

    pub fn as_u64(&self) -> Option<u64> {
        match self {
            RegisterValue::Unsigned { value, .. } => Some(*value),
            RegisterValue::Bytes { bytes, width_bits } if *width_bits <= 64 && bytes.len() <= 8 => {
                Some(
                    bytes
                        .iter()
                        .fold(0, |value, byte| (value << 8) | u64::from(*byte)),
                )
            }
            RegisterValue::Bytes { .. } => None,
        }
    }

    pub fn width_bits(&self) -> u16 {
        match self {
            RegisterValue::Unsigned { width_bits, .. }
            | RegisterValue::Bytes { width_bits, .. } => *width_bits,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct RegisterSnapshot {
    pub descriptor: RegisterDescriptor,
    pub value: RegisterValue,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DisassemblyLine {
    pub address: DebugAddress,
    pub text: String,
    pub size: u8,
    pub approximate: bool,
    pub bytes: Vec<u8>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct StackPreview {
    pub context: ContextId,
    /// Lowest address covered by `bytes`, in the context's stack space.
    pub address: DebugAddress,
    pub bytes: Vec<u8>,
    pub stride: u8,
    pub truncated: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct MemoryReadResult {
    pub address: DebugAddress,
    pub bytes: Vec<u8>,
    pub truncated: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SurfaceKind {
    GuestFramebuffer,
    HostPresentationMirror,
    Texture,
    BackingBuffer,
    Other,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PixelFormat {
    Mono1,
    Indexed2,
    Indexed4,
    Indexed8,
    Rgb555,
    Xrgb1555,
    Rgb888,
    Xrgb8888,
    Argb8888,
    Unknown,
}

impl PixelFormat {
    pub fn bits(self) -> Option<u16> {
        match self {
            PixelFormat::Mono1 => Some(1),
            PixelFormat::Indexed2 => Some(2),
            PixelFormat::Indexed4 => Some(4),
            PixelFormat::Indexed8 => Some(8),
            PixelFormat::Rgb555 | PixelFormat::Xrgb1555 => Some(16),
            PixelFormat::Rgb888 => Some(24),
            PixelFormat::Xrgb8888 | PixelFormat::Argb8888 => Some(32),
            PixelFormat::Unknown => None,
        }
    }

    pub fn is_indexed(self) -> bool {
        matches!(
            self,
            PixelFormat::Mono1
                | PixelFormat::Indexed2
                | PixelFormat::Indexed4
                | PixelFormat::Indexed8
        )
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DisplayOutputDescriptor {
    pub id: u64,
    pub name: String,
    pub width: u32,
    pub height: u32,
    pub depth: u16,
    pub surfaces: Vec<u64>,
    pub palette_entries: u32,
    pub source: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct GraphicsSurfaceDescriptor {
    pub id: u64,
    pub name: String,
    pub kind: SurfaceKind,
    pub width: u32,
    pub height: u32,
    pub stride_bytes: u32,
    pub pixel_format: PixelFormat,
    pub byte_order: ByteOrder,
    pub base: Option<DebugAddress>,
    pub scale: u32,
    pub has_palette: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct GraphicsSnapshot {
    pub schema_version: u32,
    pub outputs: Vec<DisplayOutputDescriptor>,
    pub surfaces: Vec<GraphicsSurfaceDescriptor>,
    pub palette_argb: Option<Vec<u32>>,
    pub truncated: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderObjectDescriptor {
    pub id: u64,
    pub kind: String,
    pub label: String,
    pub related: Vec<u64>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderSnapshotKind {
    State,
    Collection,
    Timeline,
    Image,
    Buffer,
    Record,
    Diagnostic,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct InspectionProviderDescriptor {
    pub id: ProviderId,
    pub name: String,
    pub schema_version: u32,
    pub observational: bool,
    pub snapshots: Vec<ProviderSnapshotKind>,
    pub collection_limit: usize,
    pub required_boundary: Option<CaptureBoundaryKind>,
    pub limitations: Vec<String>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureBoundaryKind {
    /// Between runner calls; no presentation synchronization is implied.
    CommandSafePoint,
    /// After outer-frame chrome redraw and guest audio finalization.
    LogicalFrameComplete,
    /// Reserved; currently returns `BoundaryUnavailable` when requested.
    GuestPresentationRequest,
    /// Reserved; currently returns `BoundaryUnavailable` when requested.
    BackendReadbackReady,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CaptureBoundaryCapabilities {
    pub kind: CaptureBoundaryKind,
    pub providers: Vec<ProviderId>,
    pub atomic_across_providers: bool,
    pub limitations: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ArtifactDescriptor {
    pub id: ArtifactId,
    pub provider: Option<ProviderId>,
    pub format: Option<String>,
    pub byte_len: u64,
    pub provenance: String,
    pub related: Vec<u64>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DecodedArtifact {
    pub artifact: ArtifactId,
    pub format: Option<String>,
    pub metadata: Vec<(String, String)>,
    pub warnings: Vec<String>,
    pub preview_dimensions: Option<(u32, u32)>,
    pub preview_rgba8: Option<Vec<u8>>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CaptureManifest {
    pub id: CaptureId,
    pub session: super::ids::SessionId,
    pub boundary: CaptureBoundaryKind,
    pub providers: Vec<ProviderId>,
    pub revision: u64,
    pub stop: Option<u64>,
    pub guest_tick: Option<u32>,
    pub execution_units: Option<u64>,
    pub artifacts: Vec<ArtifactDescriptor>,
    pub omitted: Vec<String>,
    pub truncated: bool,
    pub atomic: bool,
    pub synchronization: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DebugNotification {
    pub sequence: u64,
    pub payload: NotificationPayload,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum NotificationPayload {
    ExecutionStateChanged {
        state: DebugExecutionState,
    },
    OperationCompleted {
        operation_id: OperationId,
        result: Box<OperationOutcome>,
    },
    CaptureAvailable {
        id: CaptureId,
    },
    ContextChanged {
        active: Option<ContextId>,
    },
    Invalidated {
        session: super::ids::SessionId,
    },
    TerminalState {
        halted: bool,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum OperationOutcome {
    /// `stop` carries the stop this operation produced, so a stepping client
    /// does not need a follow-up `ExecutionStatus` to learn the new location.
    /// It is null for operations that complete without stopping execution.
    Completed { stop: Option<StopInfo> },
    Captured { capture_id: CaptureId },
    Failed { message: String },
    Cancelled,
    Unavailable { reason: String },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationStatus {
    pub id: OperationId,
    pub state: OperationState,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum OperationState {
    Pending,
    Completed { result: OperationOutcome },
    Expired,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn register_value_preserves_exact_bits() {
        let value = RegisterValue::unsigned(u64::MAX, 64);
        assert_eq!(value.as_u64(), Some(u64::MAX));

        let wide = RegisterValue::bytes(vec![0xAB; 16], 128);
        assert_eq!(wide.width_bits(), 128);
        assert_eq!(wide.as_u64(), None);
    }

    #[test]
    fn execution_state_classification() {
        let stop = StopInfo {
            id: 1,
            revision: 0,
            context: None,
            location: None,
            reason: StopReason::UserPause,
            guest_tick: None,
            execution_units: None,
        };
        assert!(DebugExecutionState::Paused { stop }.is_paused());
        assert!(DebugExecutionState::Running.is_running());
        assert!(DebugExecutionState::Stepping {
            operation_id: OperationId(1)
        }
        .is_stepping());
    }
}