kernel/
process_standard.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Tock default Process implementation.
6//!
7//! `ProcessStandard` is an implementation for a userspace process running on
8//! the Tock kernel.
9
10use core::cell::Cell;
11use core::cmp;
12use core::fmt::Write;
13use core::num::NonZeroU32;
14use core::ptr::NonNull;
15use core::{mem, ptr, slice, str};
16
17use crate::collections::queue::Queue;
18use crate::collections::ring_buffer::RingBuffer;
19use crate::config;
20use crate::debug;
21use crate::errorcode::ErrorCode;
22use crate::kernel::Kernel;
23use crate::platform::chip::Chip;
24use crate::platform::mpu::{self, MPU};
25use crate::process::BinaryVersion;
26use crate::process::ProcessBinary;
27use crate::process::{Error, FunctionCall, FunctionCallSource, Process, Task};
28use crate::process::{FaultAction, ProcessCustomGrantIdentifier, ProcessId};
29use crate::process::{ProcessAddresses, ProcessSizes, ShortId};
30use crate::process::{State, StoppedState};
31use crate::process_checker::AcceptedCredential;
32use crate::process_loading::ProcessLoadError;
33use crate::process_policies::ProcessFaultPolicy;
34use crate::process_policies::ProcessStandardStoragePermissionsPolicy;
35use crate::processbuffer::{ReadOnlyProcessBuffer, ReadWriteProcessBuffer};
36use crate::storage_permissions::StoragePermissions;
37use crate::syscall::{self, Syscall, SyscallReturn, UserspaceKernelBoundary};
38use crate::upcall::UpcallId;
39use crate::utilities::capability_ptr::{CapabilityPtr, CapabilityPtrPermissions};
40use crate::utilities::cells::{MapCell, NumericCellExt, OptionalCell};
41
42use tock_tbf::types::CommandPermissions;
43
44/// Interface supported by [`ProcessStandard`] for recording debug information.
45///
46/// This trait provides flexibility to users of [`ProcessStandard`] to determine
47/// how debugging information should be recorded, or if debugging information
48/// should be recorded at all.
49///
50/// Platforms that want to only maintain certain debugging information can
51/// implement only part of this trait.
52///
53/// Tock provides a default implementation of this trait on the `()` type.
54/// Kernels that wish to use [`ProcessStandard`] but do not need process-level
55/// debugging information can use `()` as the `ProcessStandardDebug` type.
56pub trait ProcessStandardDebug: Default {
57    /// Record the address in flash the process expects to start at.
58    fn set_fixed_address_flash(&self, address: u32);
59    /// Get the address in flash the process expects to start at, if it was
60    /// recorded.
61    fn get_fixed_address_flash(&self) -> Option<u32>;
62    /// Record the address in RAM the process expects to start at.
63    fn set_fixed_address_ram(&self, address: u32);
64    /// Get the address in RAM the process expects to start at, if it was
65    /// recorded.
66    fn get_fixed_address_ram(&self) -> Option<u32>;
67    /// Record the address where the process placed its heap.
68    fn set_app_heap_start_pointer(&self, ptr: *const u8);
69    /// Get the address where the process placed its heap, if it was recorded.
70    fn get_app_heap_start_pointer(&self) -> Option<*const u8>;
71    /// Record the address where the process placed its stack.
72    fn set_app_stack_start_pointer(&self, ptr: *const u8);
73    /// Get the address where the process placed its stack, if it was recorded.
74    fn get_app_stack_start_pointer(&self) -> Option<*const u8>;
75    /// Update the lowest address that the process's stack has reached.
76    fn set_app_stack_min_pointer(&self, ptr: *const u8);
77    /// Get the lowest address of the process's stack , if it was recorded.
78    fn get_app_stack_min_pointer(&self) -> Option<*const u8>;
79    /// Provide the current address of the bottom of the stack and record the
80    /// address if it is the lowest address that the process's stack has
81    /// reached.
82    fn set_new_app_stack_min_pointer(&self, ptr: *const u8);
83
84    /// Record the most recent system call the process called.
85    fn set_last_syscall(&self, syscall: Syscall);
86    /// Get the most recent system call the process called, if it was recorded.
87    fn get_last_syscall(&self) -> Option<Syscall>;
88    /// Clear any record of the most recent system call the process called.
89    fn reset_last_syscall(&self);
90
91    /// Increase the recorded count of the number of system calls the process
92    /// has called.
93    fn increment_syscall_count(&self);
94    /// Get the recorded count of the number of system calls the process has
95    /// called.
96    ///
97    /// This should return 0 if
98    /// [`ProcessStandardDebug::increment_syscall_count()`] is never called.
99    fn get_syscall_count(&self) -> usize;
100    /// Reset the recorded count of the number of system calls called by the app
101    /// to 0.
102    fn reset_syscall_count(&self);
103
104    /// Increase the recorded count of the number of upcalls that have been
105    /// dropped for the process.
106    fn increment_dropped_upcall_count(&self);
107    /// Get the recorded count of the number of upcalls that have been dropped
108    /// for the process.
109    ///
110    /// This should return 0 if
111    /// [`ProcessStandardDebug::increment_dropped_upcall_count()`] is never
112    /// called.
113    fn get_dropped_upcall_count(&self) -> usize;
114    /// Reset the recorded count of the number of upcalls that have been dropped
115    /// for the process to 0.
116    fn reset_dropped_upcall_count(&self);
117
118    /// Increase the recorded count of the number of times the process has
119    /// exceeded its timeslice.
120    fn increment_timeslice_expiration_count(&self);
121    /// Get the recorded count of the number times the process has exceeded its
122    /// timeslice.
123    ///
124    /// This should return 0 if
125    /// [`ProcessStandardDebug::increment_timeslice_expiration_count()`] is
126    /// never called.
127    fn get_timeslice_expiration_count(&self) -> usize;
128    /// Reset the recorded count of the number of the process has exceeded its
129    /// timeslice to 0.
130    fn reset_timeslice_expiration_count(&self);
131}
132
133/// A debugging implementation for [`ProcessStandard`] that records the full
134/// debugging state.
135pub struct ProcessStandardDebugFull {
136    /// Inner field for the debug state that is in a [`MapCell`] to provide
137    /// mutable access.
138    debug: MapCell<ProcessStandardDebugFullInner>,
139}
140
141/// Struct for debugging [`ProcessStandard`] processes that records the full set
142/// of debugging information.
143///
144/// These pointers and counters are not strictly required for kernel operation,
145/// but provide helpful information when an app crashes.
146#[derive(Default)]
147struct ProcessStandardDebugFullInner {
148    /// If this process was compiled for fixed addresses, save the address
149    /// it must be at in flash. This is useful for debugging and saves having
150    /// to re-parse the entire TBF header.
151    fixed_address_flash: Option<u32>,
152
153    /// If this process was compiled for fixed addresses, save the address
154    /// it must be at in RAM. This is useful for debugging and saves having
155    /// to re-parse the entire TBF header.
156    fixed_address_ram: Option<u32>,
157
158    /// Where the process has started its heap in RAM.
159    app_heap_start_pointer: Option<*const u8>,
160
161    /// Where the start of the stack is for the process. If the kernel does the
162    /// PIC setup for this app then we know this, otherwise we need the app to
163    /// tell us where it put its stack.
164    app_stack_start_pointer: Option<*const u8>,
165
166    /// How low have we ever seen the stack pointer.
167    app_stack_min_pointer: Option<*const u8>,
168
169    /// How many syscalls have occurred since the process started.
170    syscall_count: usize,
171
172    /// What was the most recent syscall.
173    last_syscall: Option<Syscall>,
174
175    /// How many upcalls were dropped because the queue was insufficiently
176    /// long.
177    dropped_upcall_count: usize,
178
179    /// How many times this process has been paused because it exceeded its
180    /// timeslice.
181    timeslice_expiration_count: usize,
182}
183
184impl ProcessStandardDebug for ProcessStandardDebugFull {
185    fn set_fixed_address_flash(&self, address: u32) {
186        self.debug.map(|d| d.fixed_address_flash = Some(address));
187    }
188    fn get_fixed_address_flash(&self) -> Option<u32> {
189        self.debug.map_or(None, |d| d.fixed_address_flash)
190    }
191    fn set_fixed_address_ram(&self, address: u32) {
192        self.debug.map(|d| d.fixed_address_ram = Some(address));
193    }
194    fn get_fixed_address_ram(&self) -> Option<u32> {
195        self.debug.map_or(None, |d| d.fixed_address_ram)
196    }
197    fn set_app_heap_start_pointer(&self, ptr: *const u8) {
198        self.debug.map(|d| d.app_heap_start_pointer = Some(ptr));
199    }
200    fn get_app_heap_start_pointer(&self) -> Option<*const u8> {
201        self.debug.map_or(None, |d| d.app_heap_start_pointer)
202    }
203    fn set_app_stack_start_pointer(&self, ptr: *const u8) {
204        self.debug.map(|d| d.app_stack_start_pointer = Some(ptr));
205    }
206    fn get_app_stack_start_pointer(&self) -> Option<*const u8> {
207        self.debug.map_or(None, |d| d.app_stack_start_pointer)
208    }
209    fn set_app_stack_min_pointer(&self, ptr: *const u8) {
210        self.debug.map(|d| d.app_stack_min_pointer = Some(ptr));
211    }
212    fn get_app_stack_min_pointer(&self) -> Option<*const u8> {
213        self.debug.map_or(None, |d| d.app_stack_min_pointer)
214    }
215    fn set_new_app_stack_min_pointer(&self, ptr: *const u8) {
216        self.debug.map(|d| {
217            match d.app_stack_min_pointer {
218                None => d.app_stack_min_pointer = Some(ptr),
219                Some(asmp) => {
220                    // Update max stack depth if needed.
221                    if ptr < asmp {
222                        d.app_stack_min_pointer = Some(ptr);
223                    }
224                }
225            }
226        });
227    }
228
229    fn set_last_syscall(&self, syscall: Syscall) {
230        self.debug.map(|d| d.last_syscall = Some(syscall));
231    }
232    fn get_last_syscall(&self) -> Option<Syscall> {
233        self.debug.map_or(None, |d| d.last_syscall)
234    }
235    fn reset_last_syscall(&self) {
236        self.debug.map(|d| d.last_syscall = None);
237    }
238
239    fn increment_syscall_count(&self) {
240        self.debug.map(|d| d.syscall_count += 1);
241    }
242    fn get_syscall_count(&self) -> usize {
243        self.debug.map_or(0, |d| d.syscall_count)
244    }
245    fn reset_syscall_count(&self) {
246        self.debug.map(|d| d.syscall_count = 0);
247    }
248
249    fn increment_dropped_upcall_count(&self) {
250        self.debug.map(|d| d.dropped_upcall_count += 1);
251    }
252    fn get_dropped_upcall_count(&self) -> usize {
253        self.debug.map_or(0, |d| d.dropped_upcall_count)
254    }
255    fn reset_dropped_upcall_count(&self) {
256        self.debug.map(|d| d.dropped_upcall_count = 0);
257    }
258
259    fn increment_timeslice_expiration_count(&self) {
260        self.debug.map(|d| d.timeslice_expiration_count += 1);
261    }
262    fn get_timeslice_expiration_count(&self) -> usize {
263        self.debug.map_or(0, |d| d.timeslice_expiration_count)
264    }
265    fn reset_timeslice_expiration_count(&self) {
266        self.debug.map(|d| d.timeslice_expiration_count = 0);
267    }
268}
269
270impl Default for ProcessStandardDebugFull {
271    fn default() -> Self {
272        Self {
273            debug: MapCell::new(ProcessStandardDebugFullInner::default()),
274        }
275    }
276}
277
278impl ProcessStandardDebug for () {
279    fn set_fixed_address_flash(&self, _address: u32) {}
280    fn get_fixed_address_flash(&self) -> Option<u32> {
281        None
282    }
283    fn set_fixed_address_ram(&self, _address: u32) {}
284    fn get_fixed_address_ram(&self) -> Option<u32> {
285        None
286    }
287    fn set_app_heap_start_pointer(&self, _ptr: *const u8) {}
288    fn get_app_heap_start_pointer(&self) -> Option<*const u8> {
289        None
290    }
291    fn set_app_stack_start_pointer(&self, _ptr: *const u8) {}
292    fn get_app_stack_start_pointer(&self) -> Option<*const u8> {
293        None
294    }
295    fn set_app_stack_min_pointer(&self, _ptr: *const u8) {}
296    fn get_app_stack_min_pointer(&self) -> Option<*const u8> {
297        None
298    }
299    fn set_new_app_stack_min_pointer(&self, _ptr: *const u8) {}
300
301    fn set_last_syscall(&self, _syscall: Syscall) {}
302    fn get_last_syscall(&self) -> Option<Syscall> {
303        None
304    }
305    fn reset_last_syscall(&self) {}
306
307    fn increment_syscall_count(&self) {}
308    fn get_syscall_count(&self) -> usize {
309        0
310    }
311    fn reset_syscall_count(&self) {}
312    fn increment_dropped_upcall_count(&self) {}
313    fn get_dropped_upcall_count(&self) -> usize {
314        0
315    }
316    fn reset_dropped_upcall_count(&self) {}
317    fn increment_timeslice_expiration_count(&self) {}
318    fn get_timeslice_expiration_count(&self) -> usize {
319        0
320    }
321    fn reset_timeslice_expiration_count(&self) {}
322}
323
324/// Entry that is stored in the grant pointer table at the top of process
325/// memory.
326///
327/// One copy of this entry struct is stored per grant region defined in the
328/// kernel. This type allows the core kernel to lookup a grant based on the
329/// driver_num associated with the grant, and also holds the pointer to the
330/// memory allocated for the particular grant.
331#[repr(C)]
332struct GrantPointerEntry {
333    /// The syscall driver number associated with the allocated grant.
334    ///
335    /// This defaults to 0 if the grant has not been allocated. Note, however,
336    /// that 0 is a valid driver_num, and therefore cannot be used to check if a
337    /// grant is allocated or not.
338    driver_num: usize,
339
340    /// The start of the memory location where the grant has been allocated, or
341    /// null if the grant has not been allocated.
342    grant_ptr: *mut u8,
343}
344
345/// A type for userspace processes in Tock.
346///
347/// As its name implies, this is the standard implementation for Tock processes
348/// that exposes the full support for processes running on embedded hardware.
349///
350/// [`ProcessStandard`] is templated on two parameters:
351///
352/// - `C`: [`Chip`]: The implementation must know the [`Chip`] the kernel is
353///   running on to properly store architecture-specific and MPU state for the
354///   process.
355/// - `D`: [`ProcessStandardDebug`]: This configures the debugging mechanism the
356///   process uses for storing optional debugging data. Kernels that do not wish
357///   to store per-process debugging state can use the `()` type for this
358///   parameter.
359pub struct ProcessStandard<'a, C: 'static + Chip, D: 'static + ProcessStandardDebug + Default> {
360    /// Identifier of this process and the index of the process in the process
361    /// table.
362    process_id: Cell<ProcessId>,
363
364    /// An application ShortId, generated from process loading and
365    /// checking, which denotes the security identity of this process.
366    app_id: ShortId,
367
368    /// Pointer to the main Kernel struct.
369    kernel: &'static Kernel,
370
371    /// Pointer to the struct that defines the actual chip the kernel is running
372    /// on. This is used because processes have subtle hardware-based
373    /// differences. Specifically, the actual syscall interface and how
374    /// processes are switched to is architecture-specific, and how memory must
375    /// be allocated for memory protection units is also hardware-specific.
376    chip: &'static C,
377
378    /// Application memory layout:
379    ///
380    /// ```text
381    ///     ╒════════ ← memory_start + memory_len
382    ///  ╔═ │ Grant Pointers
383    ///  ║  │ ──────
384    ///     │ Process Control Block
385    ///  D  │ ──────
386    ///  Y  │ Grant Regions
387    ///  N  │
388    ///  A  │   ↓
389    ///  M  │ ──────  ← kernel_memory_break
390    ///  I  │
391    ///  C  │ ──────  ← app_break               ═╗
392    ///     │                                    ║
393    ///  ║  │   ↑                                  A
394    ///  ║  │  Heap                              P C
395    ///  ╠═ │ ──────  ← app_heap_start           R C
396    ///     │  Data                              O E
397    ///  F  │ ──────  ← data_start_pointer       C S
398    ///  I  │ Stack                              E S
399    ///  X  │   ↓                                S I
400    ///  E  │                                    S B
401    ///  D  │ ──────  ← current_stack_pointer      L
402    ///     │                                    ║ E
403    ///  ╚═ ╘════════ ← memory_start            ═╝
404    /// ```
405    ///
406    /// The start of process memory. We store this as a pointer and length and
407    /// not a slice due to Rust aliasing rules. If we were to store a slice,
408    /// then any time another slice to the same memory or an ProcessBuffer is
409    /// used in the kernel would be undefined behavior.
410    memory_start: *const u8,
411    /// Number of bytes of memory allocated to this process.
412    memory_len: usize,
413
414    /// Reference to the slice of `GrantPointerEntry`s stored in the process's
415    /// memory reserved for the kernel. These driver numbers are zero and
416    /// pointers are null if the grant region has not been allocated. When the
417    /// grant region is allocated these pointers are updated to point to the
418    /// allocated memory and the driver number is set to match the driver that
419    /// owns the grant. No other reference to these pointers exists in the Tock
420    /// kernel.
421    grant_pointers: MapCell<&'static mut [GrantPointerEntry]>,
422
423    /// Pointer to the end of the allocated (and MPU protected) grant region.
424    kernel_memory_break: Cell<*const u8>,
425
426    /// Pointer to the end of process RAM that has been sbrk'd to the process.
427    app_break: Cell<*const u8>,
428
429    /// Pointer to high water mark for process buffers shared through `allow`
430    allow_high_water_mark: Cell<*const u8>,
431
432    /// Process flash segment. This is the region of nonvolatile flash that
433    /// the process occupies.
434    flash: &'static [u8],
435
436    /// The footers of the process binary (may be zero-sized), which are metadata
437    /// about the process not covered by integrity. Used, among other things, to
438    /// store signatures.
439    footers: &'static [u8],
440
441    /// Collection of pointers to the TBF header in flash.
442    header: tock_tbf::types::TbfHeader<'static>,
443
444    /// Credential that was approved for this process, or `None` if the
445    /// credential was permitted to run without an accepted credential.
446    credential: Option<AcceptedCredential>,
447
448    /// State saved on behalf of the process each time the app switches to the
449    /// kernel.
450    stored_state:
451        MapCell<<<C as Chip>::UserspaceKernelBoundary as UserspaceKernelBoundary>::StoredState>,
452
453    /// The current state of the app. The scheduler uses this to determine
454    /// whether it can schedule this app to execute.
455    ///
456    /// The `state` is used both for bookkeeping for the scheduler as well as
457    /// for enabling control by other parts of the system. The scheduler keeps
458    /// track of if a process is ready to run or not by switching between the
459    /// `Running` and `Yielded` states. The system can control the process by
460    /// switching it to a "stopped" state to prevent the scheduler from
461    /// scheduling it.
462    state: Cell<State>,
463
464    /// How to respond if this process faults.
465    fault_policy: &'a dyn ProcessFaultPolicy,
466
467    /// Storage permissions for this process.
468    storage_permissions: StoragePermissions,
469
470    /// Configuration data for the MPU
471    mpu_config: MapCell<<<C as Chip>::MPU as MPU>::MpuConfig>,
472
473    /// MPU regions are saved as a pointer-size pair.
474    mpu_regions: [Cell<Option<mpu::Region>>; 6],
475
476    /// Essentially a list of upcalls that want to call functions in the
477    /// process.
478    tasks: MapCell<RingBuffer<'a, Task>>,
479
480    /// Count of how many times this process has entered the fault condition and
481    /// been restarted. This is used by some `ProcessRestartPolicy`s to
482    /// determine if the process should be restarted or not.
483    restart_count: Cell<usize>,
484
485    /// The completion code set by the process when it last exited, restarted,
486    /// or was terminated. If the process is has never terminated, then the
487    /// `OptionalCell` will be empty (i.e. `None`). If the process has exited,
488    /// restarted, or terminated, the `OptionalCell` will contain an optional 32
489    /// bit value. The option will be `None` if the process crashed or was
490    /// stopped by the kernel and there is no provided completion code. If the
491    /// process called the exit syscall then the provided completion code will
492    /// be stored as `Some(completion code)`.
493    completion_code: OptionalCell<Option<u32>>,
494
495    /// Values kept so that we can print useful debug messages when apps fault.
496    debug: D,
497}
498
499impl<C: Chip, D: 'static + ProcessStandardDebug> Process for ProcessStandard<'_, C, D> {
500    fn processid(&self) -> ProcessId {
501        self.process_id.get()
502    }
503
504    fn short_app_id(&self) -> ShortId {
505        self.app_id
506    }
507
508    fn binary_version(&self) -> Option<BinaryVersion> {
509        let version = self.header.get_binary_version();
510        match NonZeroU32::new(version) {
511            Some(version_nonzero) => Some(BinaryVersion::new(version_nonzero)),
512            None => None,
513        }
514    }
515
516    fn get_credential(&self) -> Option<AcceptedCredential> {
517        self.credential
518    }
519
520    fn enqueue_task(&self, task: Task) -> Result<(), ErrorCode> {
521        // If this app is in a `Fault` state then we shouldn't schedule
522        // any work for it.
523        if !self.is_running() {
524            return Err(ErrorCode::NODEVICE);
525        }
526
527        let ret = self.tasks.map_or(Err(ErrorCode::FAIL), |tasks| {
528            match tasks.enqueue(task) {
529                true => {
530                    // The task has been successfully enqueued.
531                    Ok(())
532                }
533                false => {
534                    // The task could not be enqueued as there is
535                    // insufficient space in the ring buffer.
536                    Err(ErrorCode::NOMEM)
537                }
538            }
539        });
540
541        if ret.is_err() {
542            // On any error we were unable to enqueue the task. Record the
543            // error, but importantly do _not_ increment kernel work.
544            self.debug.increment_dropped_upcall_count();
545        }
546
547        ret
548    }
549
550    fn ready(&self) -> bool {
551        self.tasks.map_or(false, |ring_buf| ring_buf.has_elements())
552            || self.state.get() == State::Running
553    }
554
555    fn remove_pending_upcalls(&self, upcall_id: UpcallId) -> usize {
556        self.tasks.map_or(0, |tasks| {
557            let count_before = tasks.len();
558            tasks.retain(|task| match task {
559                // Remove only tasks that are function calls with an id equal
560                // to `upcall_id`.
561                Task::FunctionCall(function_call) => match function_call.source {
562                    FunctionCallSource::Kernel => true,
563                    FunctionCallSource::Driver(id) => id != upcall_id,
564                },
565                _ => true,
566            });
567            let count_after = tasks.len();
568            if config::CONFIG.trace_syscalls {
569                debug!(
570                    "[{:?}] remove_pending_upcalls[{:#x}:{}] = {} upcall(s) removed",
571                    self.processid(),
572                    upcall_id.driver_num,
573                    upcall_id.subscribe_num,
574                    count_before - count_after,
575                );
576            }
577            count_before - count_after
578        })
579    }
580
581    fn is_running(&self) -> bool {
582        match self.state.get() {
583            State::Running | State::Yielded | State::YieldedFor(_) | State::Stopped(_) => true,
584            _ => false,
585        }
586    }
587
588    fn get_state(&self) -> State {
589        self.state.get()
590    }
591
592    fn set_yielded_state(&self) {
593        if self.state.get() == State::Running {
594            self.state.set(State::Yielded);
595        }
596    }
597
598    fn set_yielded_for_state(&self, upcall_id: UpcallId) {
599        if self.state.get() == State::Running {
600            self.state.set(State::YieldedFor(upcall_id));
601        }
602    }
603
604    fn stop(&self) {
605        match self.state.get() {
606            State::Running => self.state.set(State::Stopped(StoppedState::Running)),
607            State::Yielded => self.state.set(State::Stopped(StoppedState::Yielded)),
608            State::YieldedFor(upcall_id) => self
609                .state
610                .set(State::Stopped(StoppedState::YieldedFor(upcall_id))),
611            State::Stopped(_stopped_state) => {
612                // Already stopped, nothing to do.
613            }
614            State::Faulted | State::Terminated => {
615                // Stop has no meaning on a inactive process.
616            }
617        }
618    }
619
620    fn resume(&self) {
621        if let State::Stopped(stopped_state) = self.state.get() {
622            match stopped_state {
623                StoppedState::Running => self.state.set(State::Running),
624                StoppedState::Yielded => self.state.set(State::Yielded),
625                StoppedState::YieldedFor(upcall_id) => self.state.set(State::YieldedFor(upcall_id)),
626            }
627        }
628    }
629
630    fn set_fault_state(&self) {
631        // Use the per-process fault policy to determine what action the kernel
632        // should take since the process faulted.
633        let action = self.fault_policy.action(self);
634        match action {
635            FaultAction::Panic => {
636                // process faulted. Panic and print status
637                self.state.set(State::Faulted);
638                panic!("Process {} had a fault", self.get_process_name());
639            }
640            FaultAction::Restart => {
641                self.try_restart(None);
642            }
643            FaultAction::Stop => {
644                // This looks a lot like restart, except we just leave the app
645                // how it faulted and mark it as `Faulted`. By clearing
646                // all of the app's todo work it will not be scheduled, and
647                // clearing all of the grant regions will cause capsules to drop
648                // this app as well.
649                self.terminate(None);
650                self.state.set(State::Faulted);
651            }
652        }
653    }
654
655    fn start(&self, _cap: &dyn crate::capabilities::ProcessStartCapability) {
656        // `start()` can only be called on a terminated process.
657        if self.get_state() != State::Terminated {
658            return;
659        }
660
661        // Reset to start the process.
662        if let Ok(()) = self.reset() {
663            self.state.set(State::Yielded);
664        }
665    }
666
667    fn try_restart(&self, completion_code: Option<u32>) {
668        // `try_restart()` cannot be called if the process is terminated. Only
669        // `start()` can start a terminated process.
670        if self.get_state() == State::Terminated {
671            return;
672        }
673
674        // Terminate the process, freeing its state and removing any
675        // pending tasks from the scheduler's queue.
676        self.terminate(completion_code);
677
678        // If there is a kernel policy that controls restarts, it should be
679        // implemented here. For now, always restart.
680        if let Ok(()) = self.reset() {
681            self.state.set(State::Yielded);
682        }
683
684        // Decide what to do with res later. E.g., if we can't restart
685        // want to reclaim the process resources.
686    }
687
688    fn terminate(&self, completion_code: Option<u32>) {
689        // A process can be terminated if it is running or in the `Faulted`
690        // state. Otherwise, you cannot terminate it and this method return
691        // early.
692        //
693        // The kernel can terminate in the `Faulted` state to return the process
694        // to a state in which it can run again (e.g., reset it).
695        if !self.is_running() && self.get_state() != State::Faulted {
696            return;
697        }
698
699        // And remove those tasks
700        self.tasks.map(|tasks| {
701            tasks.empty();
702        });
703
704        // Clear any grant regions this app has setup with any capsules.
705        unsafe {
706            self.grant_ptrs_reset();
707        }
708
709        // Save the completion code.
710        self.completion_code.set(completion_code);
711
712        // Mark the app as stopped so the scheduler won't try to run it.
713        self.state.set(State::Terminated);
714    }
715
716    fn get_restart_count(&self) -> usize {
717        self.restart_count.get()
718    }
719
720    fn has_tasks(&self) -> bool {
721        self.tasks.map_or(false, |tasks| tasks.has_elements())
722    }
723
724    fn dequeue_task(&self) -> Option<Task> {
725        self.tasks.map_or(None, |tasks| tasks.dequeue())
726    }
727
728    fn remove_upcall(&self, upcall_id: UpcallId) -> Option<Task> {
729        self.tasks.map_or(None, |tasks| {
730            tasks.remove_first_matching(|task| match task {
731                Task::FunctionCall(fc) => match fc.source {
732                    FunctionCallSource::Driver(upid) => upid == upcall_id,
733                    _ => false,
734                },
735                Task::ReturnValue(rv) => rv.upcall_id == upcall_id,
736                Task::IPC(_) => false,
737            })
738        })
739    }
740
741    fn pending_tasks(&self) -> usize {
742        self.tasks.map_or(0, |tasks| tasks.len())
743    }
744
745    fn get_command_permissions(&self, driver_num: usize, offset: usize) -> CommandPermissions {
746        self.header.get_command_permissions(driver_num, offset)
747    }
748
749    fn get_storage_permissions(&self) -> StoragePermissions {
750        self.storage_permissions
751    }
752
753    fn number_writeable_flash_regions(&self) -> usize {
754        self.header.number_writeable_flash_regions()
755    }
756
757    fn get_writeable_flash_region(&self, region_index: usize) -> (usize, usize) {
758        self.header.get_writeable_flash_region(region_index)
759    }
760
761    fn update_stack_start_pointer(&self, stack_pointer: *const u8) {
762        if stack_pointer >= self.mem_start() && stack_pointer < self.mem_end() {
763            self.debug.set_app_stack_start_pointer(stack_pointer);
764            // We also reset the minimum stack pointer because whatever
765            // value we had could be entirely wrong by now.
766            self.debug.set_app_stack_min_pointer(stack_pointer);
767        }
768    }
769
770    fn update_heap_start_pointer(&self, heap_pointer: *const u8) {
771        if heap_pointer >= self.mem_start() && heap_pointer < self.mem_end() {
772            self.debug.set_app_heap_start_pointer(heap_pointer);
773        }
774    }
775
776    fn setup_mpu(&self) {
777        self.mpu_config.map(|config| {
778            self.chip.mpu().configure_mpu(config);
779        });
780    }
781
782    fn add_mpu_region(
783        &self,
784        unallocated_memory_start: *const u8,
785        unallocated_memory_size: usize,
786        min_region_size: usize,
787    ) -> Option<mpu::Region> {
788        self.mpu_config.and_then(|config| {
789            let new_region = self.chip.mpu().allocate_region(
790                unallocated_memory_start,
791                unallocated_memory_size,
792                min_region_size,
793                mpu::Permissions::ReadWriteOnly,
794                config,
795            )?;
796
797            for region in self.mpu_regions.iter() {
798                if region.get().is_none() {
799                    region.set(Some(new_region));
800                    return Some(new_region);
801                }
802            }
803
804            // Not enough room in Process struct to store the MPU region.
805            None
806        })
807    }
808
809    fn remove_mpu_region(&self, region: mpu::Region) -> Result<(), ErrorCode> {
810        self.mpu_config.map_or(Err(ErrorCode::INVAL), |config| {
811            // Find the existing mpu region that we are removing; it needs to match exactly.
812            if let Some(internal_region) = self.mpu_regions.iter().find(|r| r.get() == Some(region))
813            {
814                self.chip
815                    .mpu()
816                    .remove_memory_region(region, config)
817                    .or(Err(ErrorCode::FAIL))?;
818
819                // Remove this region from the tracking cache of mpu_regions
820                internal_region.set(None);
821                Ok(())
822            } else {
823                Err(ErrorCode::INVAL)
824            }
825        })
826    }
827
828    fn sbrk(&self, increment: isize) -> Result<CapabilityPtr, Error> {
829        // Do not modify an inactive process.
830        if !self.is_running() {
831            return Err(Error::InactiveApp);
832        }
833
834        let new_break = self.app_break.get().wrapping_offset(increment);
835        self.brk(new_break)
836    }
837
838    fn brk(&self, new_break: *const u8) -> Result<CapabilityPtr, Error> {
839        // Do not modify an inactive process.
840        if !self.is_running() {
841            return Err(Error::InactiveApp);
842        }
843
844        self.mpu_config.map_or(Err(Error::KernelError), |config| {
845            if new_break < self.allow_high_water_mark.get() || new_break >= self.mem_end() {
846                Err(Error::AddressOutOfBounds)
847            } else if new_break > self.kernel_memory_break.get() {
848                Err(Error::OutOfMemory)
849            } else if let Err(()) = self.chip.mpu().update_app_memory_region(
850                new_break,
851                self.kernel_memory_break.get(),
852                mpu::Permissions::ReadWriteOnly,
853                config,
854            ) {
855                Err(Error::OutOfMemory)
856            } else {
857                let old_break = self.app_break.get();
858                self.app_break.set(new_break);
859                self.chip.mpu().configure_mpu(config);
860
861                let base = self.mem_start() as usize;
862                let break_result = unsafe {
863                    CapabilityPtr::new_with_authority(
864                        old_break as *const (),
865                        base,
866                        (new_break as usize) - base,
867                        CapabilityPtrPermissions::ReadWrite,
868                    )
869                };
870
871                Ok(break_result)
872            }
873        })
874    }
875
876    #[allow(clippy::not_unsafe_ptr_arg_deref)]
877    fn build_readwrite_process_buffer(
878        &self,
879        buf_start_addr: *mut u8,
880        size: usize,
881    ) -> Result<ReadWriteProcessBuffer, ErrorCode> {
882        if !self.is_running() {
883            // Do not operate on an inactive process
884            return Err(ErrorCode::FAIL);
885        }
886
887        // A process is allowed to pass any pointer if the buffer length is 0,
888        // as to revoke kernel access to a memory region without granting access
889        // to another one
890        if size == 0 {
891            // Clippy complains that we're dereferencing a pointer in a public
892            // and safe function here. While we are not dereferencing the
893            // pointer here, we pass it along to an unsafe function, which is as
894            // dangerous (as it is likely to be dereferenced down the line).
895            //
896            // Relevant discussion:
897            // https://github.com/rust-lang/rust-clippy/issues/3045
898            //
899            // It should be fine to ignore the lint here, as a buffer of length
900            // 0 will never allow dereferencing any memory in a safe manner.
901            //
902            // ### Safety
903            //
904            // We specify a zero-length buffer, so the implementation of
905            // `ReadWriteProcessBuffer` will handle any safety issues.
906            // Therefore, we can encapsulate the unsafe.
907            Ok(unsafe { ReadWriteProcessBuffer::new(buf_start_addr, 0, self.processid()) })
908        } else if self.in_app_owned_memory(buf_start_addr, size) {
909            // TODO: Check for buffer aliasing here
910
911            // Valid buffer, we need to adjust the app's watermark
912            // note: `in_app_owned_memory` ensures this offset does not wrap
913            let buf_end_addr = buf_start_addr.wrapping_add(size);
914            let new_water_mark = cmp::max(self.allow_high_water_mark.get(), buf_end_addr);
915            self.allow_high_water_mark.set(new_water_mark);
916
917            // Clippy complains that we're dereferencing a pointer in a public
918            // and safe function here. While we are not dereferencing the
919            // pointer here, we pass it along to an unsafe function, which is as
920            // dangerous (as it is likely to be dereferenced down the line).
921            //
922            // Relevant discussion:
923            // https://github.com/rust-lang/rust-clippy/issues/3045
924            //
925            // It should be fine to ignore the lint here, as long as we make
926            // sure that we're pointing towards userspace memory (verified using
927            // `in_app_owned_memory`) and respect alignment and other
928            // constraints of the Rust references created by
929            // `ReadWriteProcessBuffer`.
930            //
931            // ### Safety
932            //
933            // We encapsulate the unsafe here on the condition in the TODO
934            // above, as we must ensure that this `ReadWriteProcessBuffer` will
935            // be the only reference to this memory.
936            Ok(unsafe { ReadWriteProcessBuffer::new(buf_start_addr, size, self.processid()) })
937        } else {
938            Err(ErrorCode::INVAL)
939        }
940    }
941
942    #[allow(clippy::not_unsafe_ptr_arg_deref)]
943    fn build_readonly_process_buffer(
944        &self,
945        buf_start_addr: *const u8,
946        size: usize,
947    ) -> Result<ReadOnlyProcessBuffer, ErrorCode> {
948        if !self.is_running() {
949            // Do not operate on an inactive process
950            return Err(ErrorCode::FAIL);
951        }
952
953        // A process is allowed to pass any pointer if the buffer length is 0,
954        // as to revoke kernel access to a memory region without granting access
955        // to another one
956        if size == 0 {
957            // Clippy complains that we're dereferencing a pointer in a public
958            // and safe function here. While we are not dereferencing the
959            // pointer here, we pass it along to an unsafe function, which is as
960            // dangerous (as it is likely to be dereferenced down the line).
961            //
962            // Relevant discussion:
963            // https://github.com/rust-lang/rust-clippy/issues/3045
964            //
965            // It should be fine to ignore the lint here, as a buffer of length
966            // 0 will never allow dereferencing any memory in a safe manner.
967            //
968            // ### Safety
969            //
970            // We specify a zero-length buffer, so the implementation of
971            // `ReadOnlyProcessBuffer` will handle any safety issues. Therefore,
972            // we can encapsulate the unsafe.
973            Ok(unsafe { ReadOnlyProcessBuffer::new(buf_start_addr, 0, self.processid()) })
974        } else if self.in_app_owned_memory(buf_start_addr, size)
975            || self.in_app_flash_memory(buf_start_addr, size)
976        {
977            // TODO: Check for buffer aliasing here
978
979            if self.in_app_owned_memory(buf_start_addr, size) {
980                // Valid buffer, and since this is in read-write memory (i.e.
981                // not flash), we need to adjust the process's watermark. Note:
982                // `in_app_owned_memory()` ensures this offset does not wrap.
983                let buf_end_addr = buf_start_addr.wrapping_add(size);
984                let new_water_mark = cmp::max(self.allow_high_water_mark.get(), buf_end_addr);
985                self.allow_high_water_mark.set(new_water_mark);
986            }
987
988            // Clippy complains that we're dereferencing a pointer in a public
989            // and safe function here. While we are not dereferencing the
990            // pointer here, we pass it along to an unsafe function, which is as
991            // dangerous (as it is likely to be dereferenced down the line).
992            //
993            // Relevant discussion:
994            // https://github.com/rust-lang/rust-clippy/issues/3045
995            //
996            // It should be fine to ignore the lint here, as long as we make
997            // sure that we're pointing towards userspace memory (verified using
998            // `in_app_owned_memory` or `in_app_flash_memory`) and respect
999            // alignment and other constraints of the Rust references created by
1000            // `ReadWriteProcessBuffer`.
1001            //
1002            // ### Safety
1003            //
1004            // We encapsulate the unsafe here on the condition in the TODO
1005            // above, as we must ensure that this `ReadOnlyProcessBuffer` will
1006            // be the only reference to this memory.
1007            Ok(unsafe { ReadOnlyProcessBuffer::new(buf_start_addr, size, self.processid()) })
1008        } else {
1009            Err(ErrorCode::INVAL)
1010        }
1011    }
1012
1013    unsafe fn set_byte(&self, addr: *mut u8, value: u8) -> bool {
1014        if self.in_app_owned_memory(addr, 1) {
1015            // We verify that this will only write process-accessible memory,
1016            // but this can still be undefined behavior if something else holds
1017            // a reference to this memory.
1018            *addr = value;
1019            true
1020        } else {
1021            false
1022        }
1023    }
1024
1025    fn grant_is_allocated(&self, grant_num: usize) -> Option<bool> {
1026        // Do not modify an inactive process.
1027        if !self.is_running() {
1028            return None;
1029        }
1030
1031        // Update the grant pointer to the address of the new allocation.
1032        self.grant_pointers.map_or(None, |grant_pointers| {
1033            // Implement `grant_pointers[grant_num]` without a chance of a
1034            // panic.
1035            grant_pointers
1036                .get(grant_num)
1037                .map(|grant_entry| !grant_entry.grant_ptr.is_null())
1038        })
1039    }
1040
1041    fn allocate_grant(
1042        &self,
1043        grant_num: usize,
1044        driver_num: usize,
1045        size: usize,
1046        align: usize,
1047    ) -> Result<(), ()> {
1048        // Do not modify an inactive process.
1049        if !self.is_running() {
1050            return Err(());
1051        }
1052
1053        // Verify the grant_num is valid.
1054        if grant_num >= self.kernel.get_grant_count_and_finalize() {
1055            return Err(());
1056        }
1057
1058        // Verify that the grant is not already allocated. If the pointer is not
1059        // null then the grant is already allocated.
1060        if let Some(is_allocated) = self.grant_is_allocated(grant_num) {
1061            if is_allocated {
1062                return Err(());
1063            }
1064        }
1065
1066        // Verify that there is not already a grant allocated with the same
1067        // `driver_num`.
1068        let exists = self.grant_pointers.map_or(false, |grant_pointers| {
1069            // Check our list of grant pointers if the driver number is used.
1070            grant_pointers.iter().any(|grant_entry| {
1071                // Check if the grant is both allocated (its grant pointer is
1072                // non null) and the driver number matches.
1073                (!grant_entry.grant_ptr.is_null()) && grant_entry.driver_num == driver_num
1074            })
1075        });
1076        // If we find a match, then the `driver_num` must already be used and
1077        // the grant allocation fails.
1078        if exists {
1079            return Err(());
1080        }
1081
1082        // Use the shared grant allocator function to actually allocate memory.
1083        // Returns `None` if the allocation cannot be created.
1084        if let Some(grant_ptr) = self.allocate_in_grant_region_internal(size, align) {
1085            // Update the grant pointer to the address of the new allocation.
1086            self.grant_pointers.map_or(Err(()), |grant_pointers| {
1087                // Implement `grant_pointers[grant_num] = grant_ptr` without a
1088                // chance of a panic.
1089                grant_pointers
1090                    .get_mut(grant_num)
1091                    .map_or(Err(()), |grant_entry| {
1092                        // Actually set the driver num and grant pointer.
1093                        grant_entry.driver_num = driver_num;
1094                        grant_entry.grant_ptr = grant_ptr.as_ptr();
1095
1096                        // If all of this worked, return true.
1097                        Ok(())
1098                    })
1099            })
1100        } else {
1101            // Could not allocate the memory for the grant region.
1102            Err(())
1103        }
1104    }
1105
1106    fn allocate_custom_grant(
1107        &self,
1108        size: usize,
1109        align: usize,
1110    ) -> Result<(ProcessCustomGrantIdentifier, NonNull<u8>), ()> {
1111        // Do not modify an inactive process.
1112        if !self.is_running() {
1113            return Err(());
1114        }
1115
1116        // Use the shared grant allocator function to actually allocate memory.
1117        // Returns `None` if the allocation cannot be created.
1118        if let Some(ptr) = self.allocate_in_grant_region_internal(size, align) {
1119            // Create the identifier that the caller will use to get access to
1120            // this custom grant in the future.
1121            let identifier = self.create_custom_grant_identifier(ptr);
1122
1123            Ok((identifier, ptr))
1124        } else {
1125            // Could not allocate memory for the custom grant.
1126            Err(())
1127        }
1128    }
1129
1130    fn enter_grant(&self, grant_num: usize) -> Result<NonNull<u8>, Error> {
1131        // Do not try to access the grant region of an inactive process.
1132        if !self.is_running() {
1133            return Err(Error::InactiveApp);
1134        }
1135
1136        // Retrieve the grant pointer from the `grant_pointers` slice. We use
1137        // `[slice].get()` so that if the grant number is invalid this will
1138        // return `Err` and not panic.
1139        self.grant_pointers
1140            .map_or(Err(Error::KernelError), |grant_pointers| {
1141                // Implement `grant_pointers[grant_num]` without a chance of a
1142                // panic.
1143                match grant_pointers.get_mut(grant_num) {
1144                    Some(grant_entry) => {
1145                        // Get a copy of the actual grant pointer.
1146                        let grant_ptr = grant_entry.grant_ptr;
1147
1148                        // Check if the grant pointer is marked that the grant
1149                        // has already been entered. If so, return an error.
1150                        if (grant_ptr as usize) & 0x1 == 0x1 {
1151                            // Lowest bit is one, meaning this grant has been
1152                            // entered.
1153                            Err(Error::AlreadyInUse)
1154                        } else {
1155                            // Now, to mark that the grant has been entered, we
1156                            // set the lowest bit to one and save this as the
1157                            // grant pointer.
1158                            grant_entry.grant_ptr = (grant_ptr as usize | 0x1) as *mut u8;
1159
1160                            // And we return the grant pointer to the entered
1161                            // grant.
1162                            Ok(unsafe { NonNull::new_unchecked(grant_ptr) })
1163                        }
1164                    }
1165                    None => Err(Error::AddressOutOfBounds),
1166                }
1167            })
1168    }
1169
1170    fn enter_custom_grant(
1171        &self,
1172        identifier: ProcessCustomGrantIdentifier,
1173    ) -> Result<*mut u8, Error> {
1174        // Do not try to access the grant region of an inactive process.
1175        if !self.is_running() {
1176            return Err(Error::InactiveApp);
1177        }
1178
1179        // Get the address of the custom grant based on the identifier.
1180        let custom_grant_address = self.get_custom_grant_address(identifier);
1181
1182        // We never deallocate custom grants and only we can change the
1183        // `identifier` so we know this is a valid address for the custom grant.
1184        Ok(custom_grant_address as *mut u8)
1185    }
1186
1187    unsafe fn leave_grant(&self, grant_num: usize) {
1188        // Do not modify an inactive process.
1189        if !self.is_running() {
1190            return;
1191        }
1192
1193        self.grant_pointers.map(|grant_pointers| {
1194            // Implement `grant_pointers[grant_num]` without a chance of a
1195            // panic.
1196            if let Some(grant_entry) = grant_pointers.get_mut(grant_num) {
1197                // Get a copy of the actual grant pointer.
1198                let grant_ptr = grant_entry.grant_ptr;
1199
1200                // Now, to mark that the grant has been released, we set the
1201                // lowest bit back to zero and save this as the grant
1202                // pointer.
1203                grant_entry.grant_ptr = (grant_ptr as usize & !0x1) as *mut u8;
1204            }
1205        });
1206    }
1207
1208    fn grant_allocated_count(&self) -> Option<usize> {
1209        // Do not modify an inactive process.
1210        if !self.is_running() {
1211            return None;
1212        }
1213
1214        self.grant_pointers.map(|grant_pointers| {
1215            // Filter our list of grant pointers into just the non-null ones,
1216            // and count those. A grant is allocated if its grant pointer is
1217            // non-null.
1218            grant_pointers
1219                .iter()
1220                .filter(|grant_entry| !grant_entry.grant_ptr.is_null())
1221                .count()
1222        })
1223    }
1224
1225    fn lookup_grant_from_driver_num(&self, driver_num: usize) -> Result<usize, Error> {
1226        self.grant_pointers
1227            .map_or(Err(Error::KernelError), |grant_pointers| {
1228                // Filter our list of grant pointers into just the non null
1229                // ones, and count those. A grant is allocated if its grant
1230                // pointer is non-null.
1231                match grant_pointers.iter().position(|grant_entry| {
1232                    // Only consider allocated grants.
1233                    (!grant_entry.grant_ptr.is_null()) && grant_entry.driver_num == driver_num
1234                }) {
1235                    Some(idx) => Ok(idx),
1236                    None => Err(Error::OutOfMemory),
1237                }
1238            })
1239    }
1240
1241    fn is_valid_upcall_function_pointer(&self, upcall_fn: *const ()) -> bool {
1242        let ptr = upcall_fn as *const u8;
1243        let size = mem::size_of::<*const u8>();
1244
1245        // It is okay if this function is in memory or flash.
1246        self.in_app_flash_memory(ptr, size) || self.in_app_owned_memory(ptr, size)
1247    }
1248
1249    fn get_process_name(&self) -> &'static str {
1250        self.header.get_package_name().unwrap_or("")
1251    }
1252
1253    fn get_completion_code(&self) -> Option<Option<u32>> {
1254        self.completion_code.get()
1255    }
1256
1257    fn set_syscall_return_value(&self, return_value: SyscallReturn) {
1258        match self.stored_state.map(|stored_state| unsafe {
1259            // Actually set the return value for a particular process.
1260            //
1261            // The UKB implementation uses the bounds of process-accessible
1262            // memory to verify that any memory changes are valid. Here, the
1263            // unsafe promise we are making is that the bounds passed to the UKB
1264            // are correct.
1265            self.chip
1266                .userspace_kernel_boundary()
1267                .set_syscall_return_value(
1268                    self.mem_start(),
1269                    self.app_break.get(),
1270                    stored_state,
1271                    return_value,
1272                )
1273        }) {
1274            Some(Ok(())) => {
1275                // If we get an `Ok` we are all set.
1276
1277                // The process is either already in the running state (having
1278                // just called a nonblocking syscall like command) or needs to
1279                // be moved to the running state having called Yield-WaitFor and
1280                // now needing to be resumed. Either way we can set the state to
1281                // running.
1282                self.state.set(State::Running);
1283            }
1284
1285            Some(Err(())) => {
1286                // If we get an `Err`, then the UKB implementation could not set
1287                // the return value, likely because the process's stack is no
1288                // longer accessible to it. All we can do is fault.
1289                self.set_fault_state();
1290            }
1291
1292            None => {
1293                // We should never be here since `stored_state` should always be
1294                // occupied.
1295                self.set_fault_state();
1296            }
1297        }
1298    }
1299
1300    fn set_process_function(&self, callback: FunctionCall) {
1301        // See if we can actually enqueue this function for this process.
1302        // Architecture-specific code handles actually doing this since the
1303        // exact method is both architecture- and implementation-specific.
1304        //
1305        // This can fail, for example if the process does not have enough memory
1306        // remaining.
1307        match self.stored_state.map(|stored_state| {
1308            // Let the UKB implementation handle setting the process's PC so
1309            // that the process executes the upcall function. We encapsulate
1310            // unsafe here because we are guaranteeing that the memory bounds
1311            // passed to `set_process_function` are correct.
1312            unsafe {
1313                self.chip.userspace_kernel_boundary().set_process_function(
1314                    self.mem_start(),
1315                    self.app_break.get(),
1316                    stored_state,
1317                    callback,
1318                )
1319            }
1320        }) {
1321            Some(Ok(())) => {
1322                // If we got an `Ok` we are all set and should mark that this
1323                // process is ready to be scheduled.
1324
1325                // Move this process to the "running" state so the scheduler
1326                // will schedule it.
1327                self.state.set(State::Running);
1328            }
1329
1330            Some(Err(())) => {
1331                // If we got an Error, then there was likely not enough room on
1332                // the stack to allow the process to execute this function given
1333                // the details of the particular architecture this is running
1334                // on. This process has essentially faulted, so we mark it as
1335                // such.
1336                self.set_fault_state();
1337            }
1338
1339            None => {
1340                // We should never be here since `stored_state` should always be
1341                // occupied.
1342                self.set_fault_state();
1343            }
1344        }
1345    }
1346
1347    fn switch_to(&self) -> Option<syscall::ContextSwitchReason> {
1348        // Cannot switch to an invalid process
1349        if !self.is_running() {
1350            return None;
1351        }
1352
1353        let (switch_reason, stack_pointer) =
1354            self.stored_state.map_or((None, None), |stored_state| {
1355                // Switch to the process. We guarantee that the memory pointers
1356                // we pass are valid, ensuring this context switch is safe.
1357                // Therefore we encapsulate the `unsafe`.
1358                unsafe {
1359                    let (switch_reason, optional_stack_pointer) = self
1360                        .chip
1361                        .userspace_kernel_boundary()
1362                        .switch_to_process(self.mem_start(), self.app_break.get(), stored_state);
1363                    (Some(switch_reason), optional_stack_pointer)
1364                }
1365            });
1366
1367        // If the UKB implementation passed us a stack pointer, update our
1368        // debugging state. This is completely optional.
1369        if let Some(sp) = stack_pointer {
1370            self.debug.set_new_app_stack_min_pointer(sp);
1371        }
1372
1373        switch_reason
1374    }
1375
1376    fn debug_syscall_count(&self) -> usize {
1377        self.debug.get_syscall_count()
1378    }
1379
1380    fn debug_dropped_upcall_count(&self) -> usize {
1381        self.debug.get_dropped_upcall_count()
1382    }
1383
1384    fn debug_timeslice_expiration_count(&self) -> usize {
1385        self.debug.get_timeslice_expiration_count()
1386    }
1387
1388    fn debug_timeslice_expired(&self) {
1389        self.debug.increment_timeslice_expiration_count();
1390    }
1391
1392    fn debug_syscall_called(&self, last_syscall: Syscall) {
1393        self.debug.increment_syscall_count();
1394        self.debug.set_last_syscall(last_syscall);
1395    }
1396
1397    fn debug_syscall_last(&self) -> Option<Syscall> {
1398        self.debug.get_last_syscall()
1399    }
1400
1401    fn get_addresses(&self) -> ProcessAddresses {
1402        ProcessAddresses {
1403            flash_start: self.flash_start() as usize,
1404            flash_non_protected_start: self.flash_non_protected_start() as usize,
1405            flash_integrity_end: ((self.flash.as_ptr() as usize)
1406                + (self.header.get_binary_end() as usize))
1407                as *const u8,
1408            flash_end: self.flash_end() as usize,
1409            sram_start: self.mem_start() as usize,
1410            sram_app_brk: self.app_memory_break() as usize,
1411            sram_grant_start: self.kernel_memory_break() as usize,
1412            sram_end: self.mem_end() as usize,
1413            sram_heap_start: self.debug.get_app_heap_start_pointer().map(|p| p as usize),
1414            sram_stack_top: self.debug.get_app_stack_start_pointer().map(|p| p as usize),
1415            sram_stack_bottom: self.debug.get_app_stack_min_pointer().map(|p| p as usize),
1416        }
1417    }
1418
1419    fn get_sizes(&self) -> ProcessSizes {
1420        ProcessSizes {
1421            grant_pointers: mem::size_of::<GrantPointerEntry>()
1422                * self.kernel.get_grant_count_and_finalize(),
1423            upcall_list: Self::CALLBACKS_OFFSET,
1424            process_control_block: Self::PROCESS_STRUCT_OFFSET,
1425        }
1426    }
1427
1428    fn print_full_process(&self, writer: &mut dyn Write) {
1429        if !config::CONFIG.debug_panics {
1430            return;
1431        }
1432
1433        self.stored_state.map(|stored_state| {
1434            // We guarantee the memory bounds pointers provided to the UKB are
1435            // correct.
1436            unsafe {
1437                self.chip.userspace_kernel_boundary().print_context(
1438                    self.mem_start(),
1439                    self.app_break.get(),
1440                    stored_state,
1441                    writer,
1442                );
1443            }
1444        });
1445
1446        // Display grant information.
1447        let number_grants = self.kernel.get_grant_count_and_finalize();
1448        let _ = writer.write_fmt(format_args!(
1449            "\
1450            \r\n Total number of grant regions defined: {}\r\n",
1451            self.kernel.get_grant_count_and_finalize()
1452        ));
1453        let rows = number_grants.div_ceil(3);
1454
1455        // Access our array of grant pointers.
1456        self.grant_pointers.map(|grant_pointers| {
1457            // Iterate each grant and show its address.
1458            for i in 0..rows {
1459                for j in 0..3 {
1460                    let index = i + (rows * j);
1461                    if index >= number_grants {
1462                        break;
1463                    }
1464
1465                    // Implement `grant_pointers[grant_num]` without a chance of
1466                    // a panic.
1467                    grant_pointers.get(index).map(|grant_entry| {
1468                        if grant_entry.grant_ptr.is_null() {
1469                            let _ =
1470                                writer.write_fmt(format_args!("  Grant {:>2} : --        ", index));
1471                        } else {
1472                            let _ = writer.write_fmt(format_args!(
1473                                "  Grant {:>2} {:#x}: {:p}",
1474                                index, grant_entry.driver_num, grant_entry.grant_ptr
1475                            ));
1476                        }
1477                    });
1478                }
1479                let _ = writer.write_fmt(format_args!("\r\n"));
1480            }
1481        });
1482
1483        // Display the current state of the MPU for this process.
1484        self.mpu_config.map(|config| {
1485            let _ = writer.write_fmt(format_args!("{}", config));
1486        });
1487
1488        // Print a helpful message on how to re-compile a process to view the
1489        // listing file. If a process is PIC, then we also need to print the
1490        // actual addresses the process executed at so that the .lst file can be
1491        // generated for those addresses. If the process was already compiled
1492        // for a fixed address, then just generating a .lst file is fine.
1493
1494        if self.debug.get_fixed_address_flash().is_some() {
1495            // Fixed addresses, can just run `make lst`.
1496            let _ = writer.write_fmt(format_args!(
1497                "\
1498                    \r\nTo debug libtock-c apps, run `make lst` in the app's\
1499                    \r\nfolder and open the arch.{:#x}.{:#x}.lst file.\r\n\r\n",
1500                self.debug.get_fixed_address_flash().unwrap_or(0),
1501                self.debug.get_fixed_address_ram().unwrap_or(0)
1502            ));
1503        } else {
1504            // PIC, need to specify the addresses.
1505            let sram_start = self.mem_start() as usize;
1506            let flash_start = self.flash.as_ptr() as usize;
1507            let flash_init_fn = flash_start + self.header.get_init_function_offset() as usize;
1508
1509            let _ = writer.write_fmt(format_args!(
1510                "\
1511                    \r\nTo debug libtock-c apps, run\
1512                    \r\n`make debug RAM_START={:#x} FLASH_INIT={:#x}`\
1513                    \r\nin the app's folder and open the .lst file.\r\n\r\n",
1514                sram_start, flash_init_fn
1515            ));
1516        }
1517    }
1518
1519    fn get_stored_state(&self, out: &mut [u8]) -> Result<usize, ErrorCode> {
1520        self.stored_state
1521            .map(|stored_state| {
1522                self.chip
1523                    .userspace_kernel_boundary()
1524                    .store_context(stored_state, out)
1525            })
1526            .unwrap_or(Err(ErrorCode::FAIL))
1527    }
1528}
1529
1530impl<C: 'static + Chip, D: 'static + ProcessStandardDebug> ProcessStandard<'_, C, D> {
1531    // Memory offset for upcall ring buffer (10 element length).
1532    const CALLBACK_LEN: usize = 10;
1533    const CALLBACKS_OFFSET: usize = mem::size_of::<Task>() * Self::CALLBACK_LEN;
1534
1535    // Memory offset to make room for this process's metadata.
1536    const PROCESS_STRUCT_OFFSET: usize = mem::size_of::<ProcessStandard<C, D>>();
1537
1538    /// Create a `ProcessStandard` object based on the found `ProcessBinary`.
1539    pub(crate) unsafe fn create<'a>(
1540        kernel: &'static Kernel,
1541        chip: &'static C,
1542        pb: ProcessBinary,
1543        remaining_memory: &'a mut [u8],
1544        fault_policy: &'static dyn ProcessFaultPolicy,
1545        storage_permissions_policy: &'static dyn ProcessStandardStoragePermissionsPolicy<C, D>,
1546        app_id: ShortId,
1547        index: usize,
1548    ) -> Result<(Option<&'static dyn Process>, &'a mut [u8]), (ProcessLoadError, &'a mut [u8])>
1549    {
1550        let process_name = pb.header.get_package_name();
1551        let process_ram_requested_size = pb.header.get_minimum_app_ram_size() as usize;
1552
1553        // Initialize MPU region configuration.
1554        let mut mpu_config = match chip.mpu().new_config() {
1555            Some(mpu_config) => mpu_config,
1556            None => return Err((ProcessLoadError::MpuConfigurationError, remaining_memory)),
1557        };
1558
1559        // Allocate MPU region for flash.
1560        if chip
1561            .mpu()
1562            .allocate_region(
1563                pb.flash.as_ptr(),
1564                pb.flash.len(),
1565                pb.flash.len(),
1566                mpu::Permissions::ReadExecuteOnly,
1567                &mut mpu_config,
1568            )
1569            .is_none()
1570        {
1571            if config::CONFIG.debug_load_processes {
1572                debug!(
1573                        "[!] flash={:#010X}-{:#010X} process={:?} - couldn't allocate MPU region for flash",
1574                        pb.flash.as_ptr() as usize,
1575                        pb.flash.as_ptr() as usize + pb.flash.len() - 1,
1576                        process_name
1577                    );
1578            }
1579            return Err((ProcessLoadError::MpuInvalidFlashLength, remaining_memory));
1580        }
1581
1582        // Determine how much space we need in the application's memory space
1583        // just for kernel and grant state. We need to make sure we allocate
1584        // enough memory just for that.
1585
1586        // Make room for grant pointers.
1587        let grant_ptr_size = mem::size_of::<GrantPointerEntry>();
1588        let grant_ptrs_num = kernel.get_grant_count_and_finalize();
1589        let grant_ptrs_offset = grant_ptrs_num * grant_ptr_size;
1590
1591        // Initial size of the kernel-owned part of process memory can be
1592        // calculated directly based on the initial size of all kernel-owned
1593        // data structures.
1594        //
1595        // We require our kernel memory break (located at the end of the
1596        // MPU-returned allocated memory region) to be word-aligned. However, we
1597        // don't have any explicit alignment constraints from the MPU. To ensure
1598        // that the below kernel-owned data structures still fit into the
1599        // kernel-owned memory even with padding for alignment, add an extra
1600        // `sizeof(usize)` bytes.
1601        let initial_kernel_memory_size = grant_ptrs_offset
1602            + Self::CALLBACKS_OFFSET
1603            + Self::PROCESS_STRUCT_OFFSET
1604            + core::mem::size_of::<usize>();
1605
1606        // By default we start with the initial size of process-accessible
1607        // memory set to 0. This maximizes the flexibility that processes have
1608        // to allocate their memory as they see fit. If a process needs more
1609        // accessible memory it must use the `brk` memop syscalls to request
1610        // more memory.
1611        //
1612        // We must take into account any process-accessible memory required by
1613        // the context switching implementation and allocate at least that much
1614        // memory so that we can successfully switch to the process. This is
1615        // architecture and implementation specific, so we query that now.
1616        let min_process_memory_size = chip
1617            .userspace_kernel_boundary()
1618            .initial_process_app_brk_size();
1619
1620        // We have to ensure that we at least ask the MPU for
1621        // `min_process_memory_size` so that we can be sure that `app_brk` is
1622        // not set inside the kernel-owned memory region. Now, in practice,
1623        // processes should not request 0 (or very few) bytes of memory in their
1624        // TBF header (i.e. `process_ram_requested_size` will almost always be
1625        // much larger than `min_process_memory_size`), as they are unlikely to
1626        // work with essentially no available memory. But, we still must protect
1627        // for that case.
1628        let min_process_ram_size = cmp::max(process_ram_requested_size, min_process_memory_size);
1629
1630        // Minimum memory size for the process.
1631        let min_total_memory_size = min_process_ram_size + initial_kernel_memory_size;
1632
1633        // Check if this process requires a fixed memory start address. If so,
1634        // try to adjust the memory region to work for this process.
1635        //
1636        // Right now, we only support skipping some RAM and leaving a chunk
1637        // unused so that the memory region starts where the process needs it
1638        // to.
1639        let remaining_memory = if let Some(fixed_memory_start) = pb.header.get_fixed_address_ram() {
1640            // The process does have a fixed address.
1641            if fixed_memory_start == remaining_memory.as_ptr() as u32 {
1642                // Address already matches.
1643                remaining_memory
1644            } else if fixed_memory_start > remaining_memory.as_ptr() as u32 {
1645                // Process wants a memory address farther in memory. Try to
1646                // advance the memory region to make the address match.
1647                let diff = (fixed_memory_start - remaining_memory.as_ptr() as u32) as usize;
1648                if diff > remaining_memory.len() {
1649                    // We ran out of memory.
1650                    let actual_address =
1651                        remaining_memory.as_ptr() as u32 + remaining_memory.len() as u32 - 1;
1652                    let expected_address = fixed_memory_start;
1653                    return Err((
1654                        ProcessLoadError::MemoryAddressMismatch {
1655                            actual_address,
1656                            expected_address,
1657                        },
1658                        remaining_memory,
1659                    ));
1660                } else {
1661                    // Change the memory range to start where the process
1662                    // requested it. Because of the if statement above we know this should
1663                    // work. Doing it more cleanly would be good but was a bit beyond my borrow
1664                    // ken; calling get_mut has a mutable borrow.-pal
1665                    &mut remaining_memory[diff..]
1666                }
1667            } else {
1668                // Address is earlier in memory, nothing we can do.
1669                let actual_address = remaining_memory.as_ptr() as u32;
1670                let expected_address = fixed_memory_start;
1671                return Err((
1672                    ProcessLoadError::MemoryAddressMismatch {
1673                        actual_address,
1674                        expected_address,
1675                    },
1676                    remaining_memory,
1677                ));
1678            }
1679        } else {
1680            remaining_memory
1681        };
1682
1683        // Determine where process memory will go and allocate an MPU region.
1684        //
1685        // `[allocation_start, allocation_size)` will cover both
1686        //
1687        // - the app-owned `min_process_memory_size`-long part of memory (at
1688        //   some offset within `remaining_memory`), as well as
1689        //
1690        // - the kernel-owned allocation growing downward starting at the end
1691        //   of this allocation, `initial_kernel_memory_size` bytes long.
1692        //
1693        let (allocation_start, allocation_size) = match chip.mpu().allocate_app_memory_region(
1694            remaining_memory.as_ptr(),
1695            remaining_memory.len(),
1696            min_total_memory_size,
1697            min_process_memory_size,
1698            initial_kernel_memory_size,
1699            mpu::Permissions::ReadWriteOnly,
1700            &mut mpu_config,
1701        ) {
1702            Some((memory_start, memory_size)) => (memory_start, memory_size),
1703            None => {
1704                // Failed to load process. Insufficient memory.
1705                if config::CONFIG.debug_load_processes {
1706                    debug!(
1707                            "[!] flash={:#010X}-{:#010X} process={:?} - couldn't allocate memory region of size >= {:#X}",
1708                            pb.flash.as_ptr() as usize,
1709                            pb.flash.as_ptr() as usize + pb.flash.len() - 1,
1710                            process_name,
1711                            min_total_memory_size
1712                        );
1713                }
1714                return Err((ProcessLoadError::NotEnoughMemory, remaining_memory));
1715            }
1716        };
1717
1718        // Determine the offset of the app-owned part of the above memory
1719        // allocation. An MPU may not place it at the very start of
1720        // `remaining_memory` for internal alignment constraints. This can only
1721        // overflow if the MPU implementation is incorrect; a compliant
1722        // implementation must return a memory allocation within the
1723        // `remaining_memory` slice.
1724        let app_memory_start_offset =
1725            allocation_start as usize - remaining_memory.as_ptr() as usize;
1726
1727        // Check if the memory region is valid for the process. If a process
1728        // included a fixed address for the start of RAM in its TBF header (this
1729        // field is optional, processes that are position independent do not
1730        // need a fixed address) then we check that we used the same address
1731        // when we allocated it in RAM.
1732        if let Some(fixed_memory_start) = pb.header.get_fixed_address_ram() {
1733            let actual_address = remaining_memory.as_ptr() as u32 + app_memory_start_offset as u32;
1734            let expected_address = fixed_memory_start;
1735            if actual_address != expected_address {
1736                return Err((
1737                    ProcessLoadError::MemoryAddressMismatch {
1738                        actual_address,
1739                        expected_address,
1740                    },
1741                    remaining_memory,
1742                ));
1743            }
1744        }
1745
1746        // With our MPU allocation, we can begin to divide up the
1747        // `remaining_memory` slice into individual regions for the process and
1748        // kernel, as follows:
1749        //
1750        //
1751        //  +-----------------------------------------------------------------
1752        //  | remaining_memory
1753        //  +----------------------------------------------------+------------
1754        //  v                                                    v
1755        //  +----------------------------------------------------+
1756        //  | allocated_padded_memory                            |
1757        //  +--+-------------------------------------------------+
1758        //     v                                                 v
1759        //     +-------------------------------------------------+
1760        //     | allocated_memory                                |
1761        //     +-------------------------------------------------+
1762        //     v                                                 v
1763        //     +-----------------------+-------------------------+
1764        //     | app_accessible_memory | allocated_kernel_memory |
1765        //     +-----------------------+-------------------+-----+
1766        //                                                 v
1767        //                               kernel memory break
1768        //                                                  \---+/
1769        //                                                      v
1770        //                                        optional padding
1771        //
1772        //
1773        // First split the `remaining_memory` into two slices:
1774        //
1775        // - `allocated_padded_memory`: the allocated memory region, containing
1776        //
1777        //   1. optional padding at the start of the memory region of
1778        //      `app_memory_start_offset` bytes,
1779        //
1780        //   2. the app accessible memory region of `min_process_memory_size`,
1781        //
1782        //   3. optional unallocated memory, and
1783        //
1784        //   4. kernel-reserved memory, growing downward starting at
1785        //      `app_memory_padding`.
1786        //
1787        // - `unused_memory`: the rest of the `remaining_memory`, not assigned
1788        //   to this app.
1789        //
1790        let (allocated_padded_memory, unused_memory) =
1791            remaining_memory.split_at_mut(app_memory_start_offset + allocation_size);
1792
1793        // Now, slice off the (optional) padding at the start:
1794        let (_padding, allocated_memory) =
1795            allocated_padded_memory.split_at_mut(app_memory_start_offset);
1796
1797        // We continue to sub-slice the `allocated_memory` into
1798        // process-accessible and kernel-owned memory. Prior to that, store the
1799        // start and length ofthe overall allocation:
1800        let allocated_memory_start = allocated_memory.as_ptr();
1801        let allocated_memory_len = allocated_memory.len();
1802
1803        // Slice off the process-accessible memory:
1804        let (app_accessible_memory, allocated_kernel_memory) =
1805            allocated_memory.split_at_mut(min_process_memory_size);
1806
1807        // Set the initial process-accessible memory:
1808        let initial_app_brk = app_accessible_memory
1809            .as_ptr()
1810            .add(app_accessible_memory.len());
1811
1812        // Set the initial allow high water mark to the start of process memory
1813        // since no `allow` calls have been made yet.
1814        let initial_allow_high_water_mark = app_accessible_memory.as_ptr();
1815
1816        // Set up initial grant region.
1817        //
1818        // `kernel_memory_break` is set to the end of kernel-accessible memory
1819        // and grows downward.
1820        //
1821        // We require the `kernel_memory_break` to be aligned to a
1822        // word-boundary, as we rely on this during offset calculations to
1823        // kernel-accessed structs (e.g. the grant pointer table) below. As it
1824        // moves downward in the address space, we can't use the `align_offset`
1825        // convenience functions.
1826        //
1827        // Calling `wrapping_sub` is safe here, as we've factored in an optional
1828        // padding of at most `sizeof(usize)` bytes in the calculation of
1829        // `initial_kernel_memory_size` above.
1830        let mut kernel_memory_break = allocated_kernel_memory
1831            .as_ptr()
1832            .add(allocated_kernel_memory.len());
1833
1834        kernel_memory_break = kernel_memory_break
1835            .wrapping_sub(kernel_memory_break as usize % core::mem::size_of::<usize>());
1836
1837        // Now that we know we have the space we can setup the grant pointers.
1838        kernel_memory_break = kernel_memory_break.offset(-(grant_ptrs_offset as isize));
1839
1840        // This is safe, `kernel_memory_break` is aligned to a word-boundary,
1841        // and `grant_ptrs_offset` is a multiple of the word size.
1842        #[allow(clippy::cast_ptr_alignment)]
1843        // Set all grant pointers to null.
1844        let grant_pointers = slice::from_raw_parts_mut(
1845            kernel_memory_break as *mut GrantPointerEntry,
1846            grant_ptrs_num,
1847        );
1848        for grant_entry in grant_pointers.iter_mut() {
1849            grant_entry.driver_num = 0;
1850            grant_entry.grant_ptr = ptr::null_mut();
1851        }
1852
1853        // Now that we know we have the space we can setup the memory for the
1854        // upcalls.
1855        kernel_memory_break = kernel_memory_break.offset(-(Self::CALLBACKS_OFFSET as isize));
1856
1857        // This is safe today, as MPU constraints ensure that `memory_start`
1858        // will always be aligned on at least a word boundary, and that
1859        // memory_size will be aligned on at least a word boundary, and
1860        // `grant_ptrs_offset` is a multiple of the word size. Thus,
1861        // `kernel_memory_break` must be word aligned. While this is unlikely to
1862        // change, it should be more proactively enforced.
1863        //
1864        // TODO: https://github.com/tock/tock/issues/1739
1865        #[allow(clippy::cast_ptr_alignment)]
1866        // Set up ring buffer for upcalls to the process.
1867        let upcall_buf =
1868            slice::from_raw_parts_mut(kernel_memory_break as *mut Task, Self::CALLBACK_LEN);
1869        let tasks = RingBuffer::new(upcall_buf);
1870
1871        // Last thing in the kernel region of process RAM is the process struct.
1872        kernel_memory_break = kernel_memory_break.offset(-(Self::PROCESS_STRUCT_OFFSET as isize));
1873        let process_struct_memory_location = kernel_memory_break;
1874
1875        // Create the Process struct in the app grant region.
1876        // Note that this requires every field be explicitly initialized, as
1877        // we are just transforming a pointer into a structure.
1878        let process: &mut ProcessStandard<C, D> =
1879            &mut *(process_struct_memory_location as *mut ProcessStandard<'static, C, D>);
1880
1881        // Ask the kernel for a unique identifier for this process that is being
1882        // created.
1883        let unique_identifier = kernel.create_process_identifier();
1884
1885        // Save copies of these in case the app was compiled for fixed addresses
1886        // for later debugging.
1887        let fixed_address_flash = pb.header.get_fixed_address_flash();
1888        let fixed_address_ram = pb.header.get_fixed_address_ram();
1889
1890        process
1891            .process_id
1892            .set(ProcessId::new(kernel, unique_identifier, index));
1893        process.app_id = app_id;
1894        process.kernel = kernel;
1895        process.chip = chip;
1896        process.allow_high_water_mark = Cell::new(initial_allow_high_water_mark);
1897        process.memory_start = allocated_memory_start;
1898        process.memory_len = allocated_memory_len;
1899        process.header = pb.header;
1900        process.kernel_memory_break = Cell::new(kernel_memory_break);
1901        process.app_break = Cell::new(initial_app_brk);
1902        process.grant_pointers = MapCell::new(grant_pointers);
1903
1904        process.credential = pb.credential.get();
1905        process.footers = pb.footers;
1906        process.flash = pb.flash;
1907
1908        process.stored_state = MapCell::new(Default::default());
1909        // Mark this process as approved and leave it to the kernel to start it.
1910        process.state = Cell::new(State::Yielded);
1911        process.fault_policy = fault_policy;
1912        process.restart_count = Cell::new(0);
1913        process.completion_code = OptionalCell::empty();
1914
1915        process.mpu_config = MapCell::new(mpu_config);
1916        process.mpu_regions = [
1917            Cell::new(None),
1918            Cell::new(None),
1919            Cell::new(None),
1920            Cell::new(None),
1921            Cell::new(None),
1922            Cell::new(None),
1923        ];
1924        process.tasks = MapCell::new(tasks);
1925
1926        process.debug = D::default();
1927        if let Some(fix_addr_flash) = fixed_address_flash {
1928            process.debug.set_fixed_address_flash(fix_addr_flash);
1929        }
1930        if let Some(fix_addr_ram) = fixed_address_ram {
1931            process.debug.set_fixed_address_ram(fix_addr_ram);
1932        }
1933
1934        // Handle any architecture-specific requirements for a new process.
1935        //
1936        // NOTE! We have to ensure that the start of process-accessible memory
1937        // (`app_memory_start`) is word-aligned. Since we currently start
1938        // process-accessible memory at the beginning of the allocated memory
1939        // region, we trust the MPU to give us a word-aligned starting address.
1940        //
1941        // TODO: https://github.com/tock/tock/issues/1739
1942        match process.stored_state.map(|stored_state| {
1943            chip.userspace_kernel_boundary().initialize_process(
1944                app_accessible_memory.as_ptr(),
1945                initial_app_brk,
1946                stored_state,
1947            )
1948        }) {
1949            Some(Ok(())) => {}
1950            _ => {
1951                if config::CONFIG.debug_load_processes {
1952                    debug!(
1953                        "[!] flash={:#010X}-{:#010X} process={:?} - couldn't initialize process",
1954                        pb.flash.as_ptr() as usize,
1955                        pb.flash.as_ptr() as usize + pb.flash.len() - 1,
1956                        process_name
1957                    );
1958                }
1959                // Note that since remaining_memory was split by split_at_mut into
1960                // application memory and unused_memory, a failure here will leak
1961                // the application memory. Not leaking it requires being able to
1962                // reconstitute the original memory slice.
1963                return Err((ProcessLoadError::InternalError, unused_memory));
1964            }
1965        }
1966
1967        let flash_start = process.flash.as_ptr();
1968        let app_start =
1969            flash_start.wrapping_add(process.header.get_app_start_offset() as usize) as usize;
1970        let init_addr =
1971            flash_start.wrapping_add(process.header.get_init_function_offset() as usize) as usize;
1972        let fn_base = flash_start as usize;
1973        let fn_len = process.flash.len();
1974
1975        // We need to construct a capability with sufficient authority to cover all of a user's
1976        // code, with permissions to execute it. The entirety of flash is sufficient.
1977
1978        let init_fn = CapabilityPtr::new_with_authority(
1979            init_addr as *const (),
1980            fn_base,
1981            fn_len,
1982            CapabilityPtrPermissions::Execute,
1983        );
1984
1985        process.tasks.map(|tasks| {
1986            tasks.enqueue(Task::FunctionCall(FunctionCall {
1987                source: FunctionCallSource::Kernel,
1988                pc: init_fn,
1989                argument0: app_start,
1990                argument1: process.memory_start as usize,
1991                argument2: process.memory_len,
1992                argument3: (process.app_break.get() as usize).into(),
1993            }));
1994        });
1995
1996        // Set storage permissions. Put this at the end so that `process` is
1997        // completely formed before using it to determine the storage
1998        // permissions.
1999        process.storage_permissions = storage_permissions_policy.get_permissions(process);
2000
2001        // Return the process object and a remaining memory for processes slice.
2002        Ok((Some(process), unused_memory))
2003    }
2004
2005    /// Reset the process, resetting all of its state and re-initializing it so
2006    /// it can start running. Assumes the process is not running but is still in
2007    /// flash and still has its memory region allocated to it.
2008    fn reset(&self) -> Result<(), ErrorCode> {
2009        // We need a new process identifier for this process since the restarted
2010        // version is in effect a new process. This is also necessary to
2011        // invalidate any stored `ProcessId`s that point to the old version of
2012        // the process. However, the process has not moved locations in the
2013        // processes array, so we copy the existing index.
2014        let old_index = self.process_id.get().index;
2015        let new_identifier = self.kernel.create_process_identifier();
2016        self.process_id
2017            .set(ProcessId::new(self.kernel, new_identifier, old_index));
2018
2019        // Reset debug information that is per-execution and not per-process.
2020        self.debug.reset_last_syscall();
2021        self.debug.reset_syscall_count();
2022        self.debug.reset_dropped_upcall_count();
2023        self.debug.reset_timeslice_expiration_count();
2024
2025        // Reset MPU region configuration.
2026        //
2027        // TODO: ideally, this would be moved into a helper function used by
2028        // both create() and reset(), but process load debugging complicates
2029        // this. We just want to create new config with only flash and memory
2030        // regions.
2031        //
2032        // We must have a previous MPU configuration stored, fault the
2033        // process if this invariant is violated. We avoid allocating
2034        // a new MPU configuration, as this may eventually exhaust the
2035        // number of available MPU configurations.
2036        let mut mpu_config = self.mpu_config.take().ok_or(ErrorCode::FAIL)?;
2037        self.chip.mpu().reset_config(&mut mpu_config);
2038
2039        // Allocate MPU region for flash.
2040        let app_mpu_flash = self.chip.mpu().allocate_region(
2041            self.flash.as_ptr(),
2042            self.flash.len(),
2043            self.flash.len(),
2044            mpu::Permissions::ReadExecuteOnly,
2045            &mut mpu_config,
2046        );
2047        if app_mpu_flash.is_none() {
2048            // We were unable to allocate an MPU region for flash. This is very
2049            // unexpected since we previously ran this process. However, we
2050            // return now and leave the process faulted and it will not be
2051            // scheduled.
2052            return Err(ErrorCode::FAIL);
2053        }
2054
2055        // RAM
2056
2057        // Re-determine the minimum amount of RAM the kernel must allocate to
2058        // the process based on the specific requirements of the syscall
2059        // implementation.
2060        let min_process_memory_size = self
2061            .chip
2062            .userspace_kernel_boundary()
2063            .initial_process_app_brk_size();
2064
2065        // Recalculate initial_kernel_memory_size as was done in create()
2066        let grant_ptr_size = mem::size_of::<(usize, *mut u8)>();
2067        let grant_ptrs_num = self.kernel.get_grant_count_and_finalize();
2068        let grant_ptrs_offset = grant_ptrs_num * grant_ptr_size;
2069
2070        let initial_kernel_memory_size =
2071            grant_ptrs_offset + Self::CALLBACKS_OFFSET + Self::PROCESS_STRUCT_OFFSET;
2072
2073        let app_mpu_mem = self.chip.mpu().allocate_app_memory_region(
2074            self.mem_start(),
2075            self.memory_len,
2076            self.memory_len, //we want exactly as much as we had before restart
2077            min_process_memory_size,
2078            initial_kernel_memory_size,
2079            mpu::Permissions::ReadWriteOnly,
2080            &mut mpu_config,
2081        );
2082        let (app_mpu_mem_start, app_mpu_mem_len) = match app_mpu_mem {
2083            Some((start, len)) => (start, len),
2084            None => {
2085                // We couldn't configure the MPU for the process. This shouldn't
2086                // happen since we were able to start the process before, but at
2087                // this point it is better to leave the app faulted and not
2088                // schedule it.
2089                return Err(ErrorCode::NOMEM);
2090            }
2091        };
2092
2093        // Reset memory pointers now that we know the layout of the process
2094        // memory and know that we can configure the MPU.
2095
2096        // app_brk is set based on minimum syscall size above the start of
2097        // memory.
2098        let app_brk = app_mpu_mem_start.wrapping_add(min_process_memory_size);
2099        self.app_break.set(app_brk);
2100        // kernel_brk is calculated backwards from the end of memory the size of
2101        // the initial kernel data structures.
2102        let kernel_brk = app_mpu_mem_start
2103            .wrapping_add(app_mpu_mem_len)
2104            .wrapping_sub(initial_kernel_memory_size);
2105        self.kernel_memory_break.set(kernel_brk);
2106        // High water mark for `allow`ed memory is reset to the start of the
2107        // process's memory region.
2108        self.allow_high_water_mark.set(app_mpu_mem_start);
2109
2110        // Store the adjusted MPU configuration:
2111        self.mpu_config.replace(mpu_config);
2112
2113        // Handle any architecture-specific requirements for a process when it
2114        // first starts (as it would when it is new).
2115        let ukb_init_process = self.stored_state.map_or(Err(()), |stored_state| unsafe {
2116            self.chip.userspace_kernel_boundary().initialize_process(
2117                app_mpu_mem_start,
2118                app_brk,
2119                stored_state,
2120            )
2121        });
2122        match ukb_init_process {
2123            Ok(()) => {}
2124            Err(()) => {
2125                // We couldn't initialize the architecture-specific state for
2126                // this process. This shouldn't happen since the app was able to
2127                // be started before, but at this point the app is no longer
2128                // valid. The best thing we can do now is leave the app as still
2129                // faulted and not schedule it.
2130                return Err(ErrorCode::RESERVE);
2131            }
2132        }
2133
2134        self.restart_count.increment();
2135
2136        // Mark the state as `Yielded` for the scheduler.
2137        self.state.set(State::Yielded);
2138
2139        // And queue up this app to be restarted.
2140        let flash_start = self.flash_start();
2141        let app_start =
2142            flash_start.wrapping_add(self.header.get_app_start_offset() as usize) as usize;
2143        let init_addr =
2144            flash_start.wrapping_add(self.header.get_init_function_offset() as usize) as usize;
2145
2146        // We need to construct a capability with sufficient authority to cover all of a user's
2147        // code, with permissions to execute it. The entirety of flash is sufficient.
2148
2149        let init_fn = unsafe {
2150            CapabilityPtr::new_with_authority(
2151                init_addr as *const (),
2152                flash_start as usize,
2153                (self.flash_end() as usize) - (flash_start as usize),
2154                CapabilityPtrPermissions::Execute,
2155            )
2156        };
2157
2158        self.enqueue_task(Task::FunctionCall(FunctionCall {
2159            source: FunctionCallSource::Kernel,
2160            pc: init_fn,
2161            argument0: app_start,
2162            argument1: self.memory_start as usize,
2163            argument2: self.memory_len,
2164            argument3: (self.app_break.get() as usize).into(),
2165        }))
2166    }
2167
2168    /// Checks if the buffer represented by the passed in base pointer and size
2169    /// is within the RAM bounds currently exposed to the processes (i.e. ending
2170    /// at `app_break`). If this method returns `true`, the buffer is guaranteed
2171    /// to be accessible to the process and to not overlap with the grant
2172    /// region.
2173    fn in_app_owned_memory(&self, buf_start_addr: *const u8, size: usize) -> bool {
2174        // TODO: On some platforms, CapabilityPtr has sufficient authority that we
2175        // could skip this check.
2176        // CapabilityPtr needs to make it slightly further, and we need to add
2177        // interfaces that tell us how much assurance it gives on the current
2178        // platform.
2179        let buf_end_addr = buf_start_addr.wrapping_add(size);
2180
2181        buf_end_addr >= buf_start_addr
2182            && buf_start_addr >= self.mem_start()
2183            && buf_end_addr <= self.app_break.get()
2184    }
2185
2186    /// Checks if the buffer represented by the passed in base pointer and size
2187    /// are within the readable region of an application's flash memory.  If
2188    /// this method returns true, the buffer is guaranteed to be readable to the
2189    /// process.
2190    fn in_app_flash_memory(&self, buf_start_addr: *const u8, size: usize) -> bool {
2191        // TODO: On some platforms, CapabilityPtr has sufficient authority that we
2192        // could skip this check.
2193        // CapabilityPtr needs to make it slightly further, and we need to add
2194        // interfaces that tell us how much assurance it gives on the current
2195        // platform.
2196        let buf_end_addr = buf_start_addr.wrapping_add(size);
2197
2198        buf_end_addr >= buf_start_addr
2199            && buf_start_addr >= self.flash_non_protected_start()
2200            && buf_end_addr <= self.flash_end()
2201    }
2202
2203    /// Reset all `grant_ptr`s to NULL.
2204    unsafe fn grant_ptrs_reset(&self) {
2205        self.grant_pointers.map(|grant_pointers| {
2206            for grant_entry in grant_pointers.iter_mut() {
2207                grant_entry.driver_num = 0;
2208                grant_entry.grant_ptr = ptr::null_mut();
2209            }
2210        });
2211    }
2212
2213    /// Allocate memory in a process's grant region.
2214    ///
2215    /// Ensures that the allocation is of `size` bytes and aligned to `align`
2216    /// bytes.
2217    ///
2218    /// If there is not enough memory, or the MPU cannot isolate the process
2219    /// accessible region from the new kernel memory break after doing the
2220    /// allocation, then this will return `None`.
2221    fn allocate_in_grant_region_internal(&self, size: usize, align: usize) -> Option<NonNull<u8>> {
2222        self.mpu_config.and_then(|config| {
2223            // First, compute the candidate new pointer. Note that at this point
2224            // we have not yet checked whether there is space for this
2225            // allocation or that it meets alignment requirements.
2226            let new_break_unaligned = self.kernel_memory_break.get().wrapping_sub(size);
2227
2228            // Our minimum alignment requirement is two bytes, so that the
2229            // lowest bit of the address will always be zero and we can use it
2230            // as a flag. It doesn't hurt to increase the alignment (except for
2231            // potentially a wasted byte) so we make sure `align` is at least
2232            // two.
2233            let align = cmp::max(align, 2);
2234
2235            // The alignment must be a power of two, 2^a. The expression
2236            // `!(align - 1)` then returns a mask with leading ones, followed by
2237            // `a` trailing zeros.
2238            let alignment_mask = !(align - 1);
2239            let new_break = (new_break_unaligned as usize & alignment_mask) as *const u8;
2240
2241            // Verify there is space for this allocation
2242            if new_break < self.app_break.get() {
2243                None
2244                // Verify it didn't wrap around
2245            } else if new_break > self.kernel_memory_break.get() {
2246                None
2247                // Verify this is compatible with the MPU.
2248            } else if let Err(()) = self.chip.mpu().update_app_memory_region(
2249                self.app_break.get(),
2250                new_break,
2251                mpu::Permissions::ReadWriteOnly,
2252                config,
2253            ) {
2254                None
2255            } else {
2256                // Allocation is valid.
2257
2258                // We always allocate down, so we must lower the
2259                // kernel_memory_break.
2260                self.kernel_memory_break.set(new_break);
2261
2262                // We need `grant_ptr` as a mutable pointer.
2263                let grant_ptr = new_break as *mut u8;
2264
2265                // ### Safety
2266                //
2267                // Here we are guaranteeing that `grant_ptr` is not null. We can
2268                // ensure this because we just created `grant_ptr` based on the
2269                // process's allocated memory, and we know it cannot be null.
2270                unsafe { Some(NonNull::new_unchecked(grant_ptr)) }
2271            }
2272        })
2273    }
2274
2275    /// Create the identifier for a custom grant that grant.rs uses to access
2276    /// the custom grant.
2277    ///
2278    /// We create this identifier by calculating the number of bytes between
2279    /// where the custom grant starts and the end of the process memory.
2280    fn create_custom_grant_identifier(&self, ptr: NonNull<u8>) -> ProcessCustomGrantIdentifier {
2281        let custom_grant_address = ptr.as_ptr() as usize;
2282        let process_memory_end = self.mem_end() as usize;
2283
2284        ProcessCustomGrantIdentifier {
2285            offset: process_memory_end - custom_grant_address,
2286        }
2287    }
2288
2289    /// Use a `ProcessCustomGrantIdentifier` to find the address of the
2290    /// custom grant.
2291    ///
2292    /// This reverses `create_custom_grant_identifier()`.
2293    fn get_custom_grant_address(&self, identifier: ProcessCustomGrantIdentifier) -> usize {
2294        let process_memory_end = self.mem_end() as usize;
2295
2296        // Subtract the offset in the identifier from the end of the process
2297        // memory to get the address of the custom grant.
2298        process_memory_end - identifier.offset
2299    }
2300
2301    /// Return the app's read and modify storage permissions from the TBF header
2302    /// if it exists.
2303    ///
2304    /// If the header does not exist then return `None`. If the header does
2305    /// exist, this returns a 5-tuple with:
2306    ///
2307    /// - `write_allowed`: bool. If this process should have write permissions.
2308    /// - `read_count`: usize. How many read IDs are valid.
2309    /// - `read_ids`: [u32]. The read IDs.
2310    /// - `modify_count`: usze. How many modify IDs are valid.
2311    /// - `modify_ids`: [u32]. The modify IDs.
2312    pub fn get_tbf_storage_permissions(&self) -> Option<(bool, usize, [u32; 8], usize, [u32; 8])> {
2313        let read_perms = self.header.get_storage_read_ids();
2314        let modify_perms = self.header.get_storage_modify_ids();
2315
2316        match (read_perms, modify_perms) {
2317            (Some((read_count, read_ids)), Some((modify_count, modify_ids))) => Some((
2318                self.header.get_storage_write_id().is_some(),
2319                read_count,
2320                read_ids,
2321                modify_count,
2322                modify_ids,
2323            )),
2324            _ => None,
2325        }
2326    }
2327
2328    /// The start address of allocated RAM for this process.
2329    fn mem_start(&self) -> *const u8 {
2330        self.memory_start
2331    }
2332
2333    /// The first address after the end of the allocated RAM for this process.
2334    fn mem_end(&self) -> *const u8 {
2335        self.memory_start.wrapping_add(self.memory_len)
2336    }
2337
2338    /// The start address of the flash region allocated for this process.
2339    fn flash_start(&self) -> *const u8 {
2340        self.flash.as_ptr()
2341    }
2342
2343    /// Get the first address of process's flash that isn't protected by the
2344    /// kernel. The protected range of flash contains the TBF header and
2345    /// potentially other state the kernel is storing on behalf of the process,
2346    /// and cannot be edited by the process.
2347    fn flash_non_protected_start(&self) -> *const u8 {
2348        ((self.flash.as_ptr() as usize) + self.header.get_protected_size() as usize) as *const u8
2349    }
2350
2351    /// The first address after the end of the flash region allocated for this
2352    /// process.
2353    fn flash_end(&self) -> *const u8 {
2354        self.flash.as_ptr().wrapping_add(self.flash.len())
2355    }
2356
2357    /// The lowest address of the grant region for the process.
2358    fn kernel_memory_break(&self) -> *const u8 {
2359        self.kernel_memory_break.get()
2360    }
2361
2362    /// Return the highest address the process has access to, or the current
2363    /// process memory brk.
2364    fn app_memory_break(&self) -> *const u8 {
2365        self.app_break.get()
2366    }
2367}