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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Mechanisms for handling and defining system calls.
//!
//! This includes:
//! - syscall class
//! - error types
//! - interface trait for context switches

use core::fmt::Write;

use crate::errorcode::ErrorCode;
use crate::process;

pub use crate::syscall_driver::{CommandReturn, SyscallDriver};

/// Helper function to split a u64 into a higher and lower u32.
///
/// Used in encoding 64-bit wide system call return values on 32-bit
/// platforms.
#[inline]
fn u64_to_be_u32s(src: u64) -> (u32, u32) {
    let src_bytes = src.to_be_bytes();
    let src_msb = u32::from_be_bytes([src_bytes[0], src_bytes[1], src_bytes[2], src_bytes[3]]);
    let src_lsb = u32::from_be_bytes([src_bytes[4], src_bytes[5], src_bytes[6], src_bytes[7]]);

    (src_msb, src_lsb)
}

// ---------- SYSTEMCALL ARGUMENT DECODING ----------

/// Enumeration of the system call classes based on the identifiers
/// specified in the Tock ABI.
///
/// These are encoded as 8 bit values as on some architectures the value can
/// be encoded in the instruction itself.
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum SyscallClass {
    Yield = 0,
    Subscribe = 1,
    Command = 2,
    ReadWriteAllow = 3,
    ReadOnlyAllow = 4,
    Memop = 5,
    Exit = 6,
    UserspaceReadableAllow = 7,
}

/// Enumeration of the yield system calls based on the Yield identifier
/// values specified in the Tock ABI.
#[derive(Copy, Clone, Debug)]
pub enum YieldCall {
    NoWait = 0,
    Wait = 1,
}

// Required as long as no solution to
// https://github.com/rust-lang/rfcs/issues/2783 is integrated into
// the standard library
impl TryFrom<u8> for SyscallClass {
    type Error = u8;

    fn try_from(syscall_class_id: u8) -> Result<SyscallClass, u8> {
        match syscall_class_id {
            0 => Ok(SyscallClass::Yield),
            1 => Ok(SyscallClass::Subscribe),
            2 => Ok(SyscallClass::Command),
            3 => Ok(SyscallClass::ReadWriteAllow),
            4 => Ok(SyscallClass::ReadOnlyAllow),
            5 => Ok(SyscallClass::Memop),
            6 => Ok(SyscallClass::Exit),
            7 => Ok(SyscallClass::UserspaceReadableAllow),
            i => Err(i),
        }
    }
}

/// Decoded system calls as defined in TRD 104.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Syscall {
    /// Structure representing an invocation of the Yield system call class.
    ///
    /// - `which`: the Yield identifier value
    /// - `address`: the no wait field
    Yield { which: usize, address: *mut u8 },

    /// Structure representing an invocation of the Subscribe system call class.
    ///
    /// - `driver_number`: the driver identifier
    /// - `subdriver_number`: the subscribe identifier
    /// - `upcall_ptr`: upcall pointer to the upcall function
    /// - `appdata`: userspace application data
    Subscribe {
        driver_number: usize,
        subdriver_number: usize,
        upcall_ptr: *mut (),
        appdata: usize,
    },

    /// Structure representing an invocation of the Command system call class.
    ///
    /// - `driver_number`: the driver identifier
    /// - `subdriver_number`: the command identifier
    /// - `arg0`: value passed to the `Command` implementation
    /// - `arg1`: value passed to the `Command` implementation
    Command {
        driver_number: usize,
        subdriver_number: usize,
        arg0: usize,
        arg1: usize,
    },

    /// Structure representing an invocation of the ReadWriteAllow system call
    /// class.
    ///
    /// - `driver_number`: the driver identifier
    /// - `subdriver_number`: the buffer identifier
    /// - `allow_address`: the address where the buffer starts
    /// - `allow_size`: the size of the buffer in bytes
    ReadWriteAllow {
        driver_number: usize,
        subdriver_number: usize,
        allow_address: *mut u8,
        allow_size: usize,
    },

    /// Structure representing an invocation of the ReadWriteAllow system call
    /// class, but with shared kernel and app access.
    ///
    /// - `driver_number`: the driver identifier
    /// - `subdriver_number`: the buffer identifier
    /// - `allow_address`: the address where the buffer starts
    /// - `allow_size`: the size of the buffer in bytes
    UserspaceReadableAllow {
        driver_number: usize,
        subdriver_number: usize,
        allow_address: *mut u8,
        allow_size: usize,
    },

    /// Structure representing an invocation of the ReadOnlyAllow system call
    /// class.
    ///
    /// - `driver_number`: the driver identifier
    /// - `subdriver_number`: the buffer identifier
    /// - `allow_address`: the address where the buffer starts
    /// - `allow_size`: the size of the buffer in bytes
    ReadOnlyAllow {
        driver_number: usize,
        subdriver_number: usize,
        allow_address: *const u8,
        allow_size: usize,
    },

    /// Structure representing an invocation of the Memop system call class.
    ///
    /// - `operand`: the operation
    /// - `arg0`: the operation argument
    Memop { operand: usize, arg0: usize },

    /// Structure representing an invocation of the Exit system call class.
    ///
    /// - `which`: the exit identifier
    /// - `completion_code`: the completion code passed into the kernel
    Exit {
        which: usize,
        completion_code: usize,
    },
}

impl Syscall {
    /// Helper function for converting raw values passed back from an application
    /// into a `Syscall` type in Tock, representing an typed version of a system
    /// call invocation. The method returns None if the values do not specify
    /// a valid system call.
    ///
    /// Different architectures have different ABIs for a process and the kernel
    /// to exchange data. The 32-bit ABI for CortexM and RISCV microcontrollers is
    /// specified in TRD104.
    pub fn from_register_arguments(
        syscall_number: u8,
        r0: usize,
        r1: usize,
        r2: usize,
        r3: usize,
    ) -> Option<Syscall> {
        match SyscallClass::try_from(syscall_number) {
            Ok(SyscallClass::Yield) => Some(Syscall::Yield {
                which: r0,
                address: r1 as *mut u8,
            }),
            Ok(SyscallClass::Subscribe) => Some(Syscall::Subscribe {
                driver_number: r0,
                subdriver_number: r1,
                upcall_ptr: r2 as *mut (),
                appdata: r3,
            }),
            Ok(SyscallClass::Command) => Some(Syscall::Command {
                driver_number: r0,
                subdriver_number: r1,
                arg0: r2,
                arg1: r3,
            }),
            Ok(SyscallClass::ReadWriteAllow) => Some(Syscall::ReadWriteAllow {
                driver_number: r0,
                subdriver_number: r1,
                allow_address: r2 as *mut u8,
                allow_size: r3,
            }),
            Ok(SyscallClass::UserspaceReadableAllow) => Some(Syscall::UserspaceReadableAllow {
                driver_number: r0,
                subdriver_number: r1,
                allow_address: r2 as *mut u8,
                allow_size: r3,
            }),
            Ok(SyscallClass::ReadOnlyAllow) => Some(Syscall::ReadOnlyAllow {
                driver_number: r0,
                subdriver_number: r1,
                allow_address: r2 as *const u8,
                allow_size: r3,
            }),
            Ok(SyscallClass::Memop) => Some(Syscall::Memop {
                operand: r0,
                arg0: r1,
            }),
            Ok(SyscallClass::Exit) => Some(Syscall::Exit {
                which: r0,
                completion_code: r1,
            }),
            Err(_) => None,
        }
    }

    /// Get the `driver_number` for the syscall classes that use driver numbers.
    pub fn driver_number(&self) -> Option<usize> {
        match *self {
            Syscall::Subscribe {
                driver_number,
                subdriver_number: _,
                upcall_ptr: _,
                appdata: _,
            } => Some(driver_number),
            Syscall::Command {
                driver_number,
                subdriver_number: _,
                arg0: _,
                arg1: _,
            } => Some(driver_number),
            Syscall::ReadWriteAllow {
                driver_number,
                subdriver_number: _,
                allow_address: _,
                allow_size: _,
            } => Some(driver_number),
            Syscall::UserspaceReadableAllow {
                driver_number,
                subdriver_number: _,
                allow_address: _,
                allow_size: _,
            } => Some(driver_number),
            Syscall::ReadOnlyAllow {
                driver_number,
                subdriver_number: _,
                allow_address: _,
                allow_size: _,
            } => Some(driver_number),
            _ => None,
        }
    }

    /// Get the `subdriver_number` for the syscall classes that use sub driver
    /// numbers.
    pub fn subdriver_number(&self) -> Option<usize> {
        match *self {
            Syscall::Subscribe {
                driver_number: _,
                subdriver_number,
                upcall_ptr: _,
                appdata: _,
            } => Some(subdriver_number),
            Syscall::Command {
                driver_number: _,
                subdriver_number,
                arg0: _,
                arg1: _,
            } => Some(subdriver_number),
            Syscall::ReadWriteAllow {
                driver_number: _,
                subdriver_number,
                allow_address: _,
                allow_size: _,
            } => Some(subdriver_number),
            Syscall::UserspaceReadableAllow {
                driver_number: _,
                subdriver_number,
                allow_address: _,
                allow_size: _,
            } => Some(subdriver_number),
            Syscall::ReadOnlyAllow {
                driver_number: _,
                subdriver_number,
                allow_address: _,
                allow_size: _,
            } => Some(subdriver_number),
            _ => None,
        }
    }
}

// ---------- SYSCALL RETURN VALUE ENCODING ----------

/// Enumeration of the system call return type variant identifiers described
/// in TRD104.
///
/// Each variant is associated with the respective variant identifier
/// that would be passed along with the return value to userspace.
#[repr(u32)]
#[derive(Copy, Clone, Debug)]
pub enum SyscallReturnVariant {
    Failure = 0,
    FailureU32 = 1,
    FailureU32U32 = 2,
    FailureU64 = 3,
    Success = 128,
    SuccessU32 = 129,
    SuccessU32U32 = 130,
    SuccessU64 = 131,
    SuccessU32U32U32 = 132,
    SuccessU32U64 = 133,
}

/// Enumeration of the possible system call return variants specified
/// in TRD104.
///
/// This struct operates over primitive types such as integers of
/// fixed length and pointers. It is constructed by the scheduler and
/// passed down to the architecture to be encoded into registers,
/// using the provided
/// [`encode_syscall_return`](SyscallReturn::encode_syscall_return)
/// method.
///
/// Capsules do not use this struct. Capsules use higher level Rust
/// types
/// (e.g. [`ReadWriteProcessBuffer`](crate::processbuffer::ReadWriteProcessBuffer)
/// and `GrantKernelData`) or wrappers around this struct
/// ([`CommandReturn`]) which limit the
/// available constructors to safely constructable variants.
#[derive(Copy, Clone, Debug)]
pub enum SyscallReturn {
    /// Generic error case
    Failure(ErrorCode),
    /// Generic error case, with an additional 32-bit data field
    FailureU32(ErrorCode, u32),
    /// Generic error case, with two additional 32-bit data fields
    FailureU32U32(ErrorCode, u32, u32),
    /// Generic error case, with an additional 64-bit data field
    FailureU64(ErrorCode, u64),
    /// Generic success case
    Success,
    /// Generic success case, with an additional 32-bit data field
    SuccessU32(u32),
    /// Generic success case, with two additional 32-bit data fields
    SuccessU32U32(u32, u32),
    /// Generic success case, with three additional 32-bit data fields
    SuccessU32U32U32(u32, u32, u32),
    /// Generic success case, with an additional 64-bit data field
    SuccessU64(u64),
    /// Generic success case, with an additional 32-bit and 64-bit
    /// data field
    SuccessU32U64(u32, u64),

    // These following types are used by the scheduler so that it can
    // return values to userspace in an architecture (pointer-width)
    // independent way. The kernel passes these types (rather than
    // ProcessBuffer or Upcall) for two reasons. First, since the
    // kernel/scheduler makes promises about the lifetime and safety
    // of these types, it does not want to leak them to other
    // code. Second, if subscribe or allow calls pass invalid values
    // (pointers out of valid memory), the kernel cannot construct an
    // ProcessBuffer or Upcall type but needs to be able to return a
    // failure. -pal 11/24/20
    /// Read/Write allow success case, returns the previous allowed
    /// buffer and size to the process.
    AllowReadWriteSuccess(*mut u8, usize),
    /// Read/Write allow failure case, returns the passed allowed
    /// buffer and size to the process.
    AllowReadWriteFailure(ErrorCode, *mut u8, usize),

    /// Shared Read/Write allow success case, returns the previous allowed
    /// buffer and size to the process.
    UserspaceReadableAllowSuccess(*mut u8, usize),
    /// Shared Read/Write allow failure case, returns the passed allowed
    /// buffer and size to the process.
    UserspaceReadableAllowFailure(ErrorCode, *mut u8, usize),

    /// Read only allow success case, returns the previous allowed
    /// buffer and size to the process.
    AllowReadOnlySuccess(*const u8, usize),
    /// Read only allow failure case, returns the passed allowed
    /// buffer and size to the process.
    AllowReadOnlyFailure(ErrorCode, *const u8, usize),

    /// Subscribe success case, returns the previous upcall function
    /// pointer and application data.
    SubscribeSuccess(*const (), usize),
    /// Subscribe failure case, returns the passed upcall function
    /// pointer and application data.
    SubscribeFailure(ErrorCode, *const (), usize),
}

impl SyscallReturn {
    /// Transforms a CommandReturn, which is wrapper around a subset of
    /// SyscallReturn, into a SyscallReturn.
    ///
    /// This allows CommandReturn to include only the variants of SyscallReturn
    /// that can be returned from a Command, while having an inexpensive way to
    /// handle it as a SyscallReturn for more generic code paths.
    pub(crate) fn from_command_return(res: CommandReturn) -> Self {
        res.into_inner()
    }

    /// Returns true if the `SyscallReturn` is any success type.
    pub(crate) fn is_success(&self) -> bool {
        match self {
            SyscallReturn::Success => true,
            SyscallReturn::SuccessU32(_) => true,
            SyscallReturn::SuccessU32U32(_, _) => true,
            SyscallReturn::SuccessU32U32U32(_, _, _) => true,
            SyscallReturn::SuccessU64(_) => true,
            SyscallReturn::SuccessU32U64(_, _) => true,
            SyscallReturn::AllowReadWriteSuccess(_, _) => true,
            SyscallReturn::UserspaceReadableAllowSuccess(_, _) => true,
            SyscallReturn::AllowReadOnlySuccess(_, _) => true,
            SyscallReturn::SubscribeSuccess(_, _) => true,
            SyscallReturn::Failure(_) => false,
            SyscallReturn::FailureU32(_, _) => false,
            SyscallReturn::FailureU32U32(_, _, _) => false,
            SyscallReturn::FailureU64(_, _) => false,
            SyscallReturn::AllowReadWriteFailure(_, _, _) => false,
            SyscallReturn::UserspaceReadableAllowFailure(_, _, _) => false,
            SyscallReturn::AllowReadOnlyFailure(_, _, _) => false,
            SyscallReturn::SubscribeFailure(_, _, _) => false,
        }
    }

    /// Encode the system call return value into 4 registers, following
    /// the encoding specified in TRD104. Architectures which do not follow
    /// TRD104 are free to define their own encoding.
    pub fn encode_syscall_return(&self, a0: &mut u32, a1: &mut u32, a2: &mut u32, a3: &mut u32) {
        match *self {
            SyscallReturn::Failure(e) => {
                *a0 = SyscallReturnVariant::Failure as u32;
                *a1 = usize::from(e) as u32;
            }
            SyscallReturn::FailureU32(e, data0) => {
                *a0 = SyscallReturnVariant::FailureU32 as u32;
                *a1 = usize::from(e) as u32;
                *a2 = data0;
            }
            SyscallReturn::FailureU32U32(e, data0, data1) => {
                *a0 = SyscallReturnVariant::FailureU32U32 as u32;
                *a1 = usize::from(e) as u32;
                *a2 = data0;
                *a3 = data1;
            }
            SyscallReturn::FailureU64(e, data0) => {
                let (data0_msb, data0_lsb) = u64_to_be_u32s(data0);
                *a0 = SyscallReturnVariant::FailureU64 as u32;
                *a1 = usize::from(e) as u32;
                *a2 = data0_lsb;
                *a3 = data0_msb;
            }
            SyscallReturn::Success => {
                *a0 = SyscallReturnVariant::Success as u32;
            }
            SyscallReturn::SuccessU32(data0) => {
                *a0 = SyscallReturnVariant::SuccessU32 as u32;
                *a1 = data0;
            }
            SyscallReturn::SuccessU32U32(data0, data1) => {
                *a0 = SyscallReturnVariant::SuccessU32U32 as u32;
                *a1 = data0;
                *a2 = data1;
            }
            SyscallReturn::SuccessU32U32U32(data0, data1, data2) => {
                *a0 = SyscallReturnVariant::SuccessU32U32U32 as u32;
                *a1 = data0;
                *a2 = data1;
                *a3 = data2;
            }
            SyscallReturn::SuccessU64(data0) => {
                let (data0_msb, data0_lsb) = u64_to_be_u32s(data0);

                *a0 = SyscallReturnVariant::SuccessU64 as u32;
                *a1 = data0_lsb;
                *a2 = data0_msb;
            }
            SyscallReturn::SuccessU32U64(data0, data1) => {
                let (data1_msb, data1_lsb) = u64_to_be_u32s(data1);

                *a0 = SyscallReturnVariant::SuccessU32U64 as u32;
                *a1 = data0;
                *a2 = data1_lsb;
                *a3 = data1_msb;
            }
            SyscallReturn::AllowReadWriteSuccess(ptr, len) => {
                *a0 = SyscallReturnVariant::SuccessU32U32 as u32;
                *a1 = ptr as u32;
                *a2 = len as u32;
            }
            SyscallReturn::UserspaceReadableAllowSuccess(ptr, len) => {
                *a0 = SyscallReturnVariant::SuccessU32U32 as u32;
                *a1 = ptr as u32;
                *a2 = len as u32;
            }
            SyscallReturn::AllowReadWriteFailure(err, ptr, len) => {
                *a0 = SyscallReturnVariant::FailureU32U32 as u32;
                *a1 = usize::from(err) as u32;
                *a2 = ptr as u32;
                *a3 = len as u32;
            }
            SyscallReturn::UserspaceReadableAllowFailure(err, ptr, len) => {
                *a0 = SyscallReturnVariant::FailureU32U32 as u32;
                *a1 = usize::from(err) as u32;
                *a2 = ptr as u32;
                *a3 = len as u32;
            }
            SyscallReturn::AllowReadOnlySuccess(ptr, len) => {
                *a0 = SyscallReturnVariant::SuccessU32U32 as u32;
                *a1 = ptr as u32;
                *a2 = len as u32;
            }
            SyscallReturn::AllowReadOnlyFailure(err, ptr, len) => {
                *a0 = SyscallReturnVariant::FailureU32U32 as u32;
                *a1 = usize::from(err) as u32;
                *a2 = ptr as u32;
                *a3 = len as u32;
            }
            SyscallReturn::SubscribeSuccess(ptr, data) => {
                *a0 = SyscallReturnVariant::SuccessU32U32 as u32;
                *a1 = ptr as u32;
                *a2 = data as u32;
            }
            SyscallReturn::SubscribeFailure(err, ptr, data) => {
                *a0 = SyscallReturnVariant::FailureU32U32 as u32;
                *a1 = usize::from(err) as u32;
                *a2 = ptr as u32;
                *a3 = data as u32;
            }
        }
    }
}

// ---------- USERSPACE KERNEL BOUNDARY ----------

/// `ContentSwitchReason` specifies why the process stopped executing and
/// execution returned to the kernel.
#[derive(PartialEq, Copy, Clone)]
pub enum ContextSwitchReason {
    /// Process called a syscall. Also returns the syscall and relevant values.
    SyscallFired { syscall: Syscall },
    /// Process triggered the hardfault handler.
    /// The implementation should still save registers in the event that the
    /// `Platform` can handle the fault and allow the app to continue running.
    /// For more details on this see `Platform::process_fault_hook()`.
    Fault,
    /// Process interrupted (e.g. by a hardware event)
    Interrupted,
}

/// The `UserspaceKernelBoundary` trait is implemented by the
/// architectural component of the chip implementation of Tock. This
/// trait allows the kernel to switch to and from processes
/// in an architecture-independent manner.
///
/// Exactly how upcalls and return values are passed between
/// kernelspace and userspace is architecture specific. The
/// architecture may use process memory to store state when
/// switching. Therefore, functions in this trait are passed the
/// bounds of process-accessible memory so that the architecture
/// implementation can verify it is reading and writing memory that
/// the process has valid access to. These bounds are passed through
/// `accessible_memory_start` and `app_brk` pointers.
pub trait UserspaceKernelBoundary {
    /// Some architecture-specific struct containing per-process state that must
    /// be kept while the process is not running. For example, for keeping CPU
    /// registers that aren't stored on the stack.
    ///
    /// Implementations should **not** rely on the `Default` constructor (custom
    /// or derived) for any initialization of a process's stored state. The
    /// initialization must happen in the `initialize_process()` function.
    type StoredState: Default;

    /// Called by the kernel during process creation to inform the kernel of the
    /// minimum amount of process-accessible RAM needed by a new process. This
    /// allows for architecture-specific process layout decisions, such as stack
    /// pointer initialization.
    ///
    /// This returns the minimum number of bytes of process-accessible memory
    /// the kernel must allocate to a process so that a successful context
    /// switch is possible.
    ///
    /// Some architectures may not need any allocated memory, and this should
    /// return 0. In general, implementations should try to pre-allocate the
    /// minimal amount of process-accessible memory (i.e. return as close to 0
    /// as possible) to provide the most flexibility to the process. However,
    /// the return value will be nonzero for architectures where values are
    /// passed in memory between kernelspace and userspace during syscalls or a
    /// stack needs to be setup.
    fn initial_process_app_brk_size(&self) -> usize;

    /// Called by the kernel after it has memory allocated to it but before it
    /// is allowed to begin executing. Allows for architecture-specific process
    /// setup, e.g. allocating a syscall stack frame.
    ///
    /// This function must also initialize the stored state (if needed).
    ///
    /// The kernel calls this function with the start of memory allocated to the
    /// process by providing `accessible_memory_start`. It also provides the
    /// `app_brk` pointer which marks the end of process-accessible memory. The
    /// kernel guarantees that `accessible_memory_start` will be word-aligned.
    ///
    /// If successful, this function returns `Ok()`. If the process syscall
    /// state cannot be initialized with the available amount of memory, or for
    /// any other reason, it should return `Err()`.
    ///
    /// This function may be called multiple times on the same process. For
    /// example, if a process crashes and is to be restarted, this must be
    /// called. Or if the process is moved this may need to be called.
    ///
    /// ### Safety
    ///
    /// This function guarantees that it if needs to change process memory, it
    /// will only change memory starting at `accessible_memory_start` and before
    /// `app_brk`. The caller is responsible for guaranteeing that those
    /// pointers are valid for the process.
    unsafe fn initialize_process(
        &self,
        accessible_memory_start: *const u8,
        app_brk: *const u8,
        state: &mut Self::StoredState,
    ) -> Result<(), ()>;

    /// Set the return value the process should see when it begins executing
    /// again after the syscall. This will only be called after a process has
    /// called a syscall.
    ///
    /// The process to set the return value for is specified by the `state`
    /// value. The `return_value` is the value that should be passed to the
    /// process so that when it resumes executing it knows the return value of
    /// the syscall it called.
    ///
    /// ### Safety
    ///
    /// This function guarantees that it if needs to change process memory, it
    /// will only change memory starting at `accessible_memory_start` and before
    /// `app_brk`. The caller is responsible for guaranteeing that those
    /// pointers are valid for the process.
    unsafe fn set_syscall_return_value(
        &self,
        accessible_memory_start: *const u8,
        app_brk: *const u8,
        state: &mut Self::StoredState,
        return_value: SyscallReturn,
    ) -> Result<(), ()>;

    /// Set the function that the process should execute when it is resumed.
    /// This has two major uses: 1) sets up the initial function call to
    /// `_start` when the process is started for the very first time; 2) tells
    /// the process to execute a upcall function after calling `yield()`.
    ///
    /// **Note:** This method cannot be called in conjunction with
    /// `set_syscall_return_value`, as the injected function will clobber the
    /// return value.
    ///
    /// ### Arguments
    ///
    /// - `accessible_memory_start` is the address of the start of the
    ///   process-accessible memory region for this process.
    /// - `app_brk` is the address of the current process break. This marks the
    ///   end of the memory region the process has access to. Note, this is not
    ///   the end of the entire memory region allocated to the process. Some
    ///   memory above this address is still allocated for the process, but if
    ///   the process tries to access it an MPU fault will occur.
    /// - `state` is the stored state for this process.
    /// - `upcall` is the function that should be executed when the process
    ///   resumes.
    ///
    /// ### Return
    ///
    /// Returns `Ok(())` if the function was successfully enqueued for the
    /// process. Returns `Err(())` if the function was not, likely because there
    /// is insufficient memory available to do so.
    ///
    /// ### Safety
    ///
    /// This function guarantees that it if needs to change process memory, it
    /// will only change memory starting at `accessible_memory_start` and before
    /// `app_brk`. The caller is responsible for guaranteeing that those
    /// pointers are valid for the process.
    unsafe fn set_process_function(
        &self,
        accessible_memory_start: *const u8,
        app_brk: *const u8,
        state: &mut Self::StoredState,
        upcall: process::FunctionCall,
    ) -> Result<(), ()>;

    /// Context switch to a specific process.
    ///
    /// This returns two values in a tuple.
    ///
    /// 1. A `ContextSwitchReason` indicating why the process stopped executing
    ///    and switched back to the kernel.
    /// 2. Optionally, the current stack pointer used by the process. This is
    ///    optional because it is only for debugging in process.rs. By sharing
    ///    the process's stack pointer with process.rs users can inspect the
    ///    state and see the stack depth, which might be useful for debugging.
    ///
    /// ### Safety
    ///
    /// This function guarantees that it if needs to change process memory, it
    /// will only change memory starting at `accessible_memory_start` and before
    /// `app_brk`. The caller is responsible for guaranteeing that those
    /// pointers are valid for the process.
    unsafe fn switch_to_process(
        &self,
        accessible_memory_start: *const u8,
        app_brk: *const u8,
        state: &mut Self::StoredState,
    ) -> (ContextSwitchReason, Option<*const u8>);

    /// Display architecture specific (e.g. CPU registers or status flags) data
    /// for a process identified by the stored state for that process.
    ///
    /// ### Safety
    ///
    /// This function guarantees that it if needs to change process memory, it
    /// will only change memory starting at `accessible_memory_start` and before
    /// `app_brk`. The caller is responsible for guaranteeing that those
    /// pointers are valid for the process.
    unsafe fn print_context(
        &self,
        accessible_memory_start: *const u8,
        app_brk: *const u8,
        state: &Self::StoredState,
        writer: &mut dyn Write,
    );

    /// Store architecture specific (e.g. CPU registers or status flags) data
    /// for a process. On success returns the number of elements written to out.
    fn store_context(&self, state: &Self::StoredState, out: &mut [u8]) -> Result<usize, ErrorCode>;
}