kernel/
process_loading.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//! Helper functions and machines for loading process binaries into in-memory
6//! Tock processes.
7//!
8//! Process loaders are responsible for parsing the binary formats of Tock
9//! processes, checking whether they are allowed to be loaded, and if so
10//! initializing a process structure to run it.
11//!
12//! This module provides multiple process loader options depending on which
13//! features a particular board requires.
14
15use core::cell::Cell;
16use core::fmt;
17
18use crate::capabilities::ProcessManagementCapability;
19use crate::config;
20use crate::debug;
21use crate::deferred_call::{DeferredCall, DeferredCallClient};
22use crate::kernel::Kernel;
23use crate::platform::chip::Chip;
24use crate::process::{Process, ShortId};
25use crate::process_binary::{ProcessBinary, ProcessBinaryError};
26use crate::process_checker::AcceptedCredential;
27use crate::process_checker::{AppIdPolicy, ProcessCheckError, ProcessCheckerMachine};
28use crate::process_policies::ProcessFaultPolicy;
29use crate::process_policies::ProcessStandardStoragePermissionsPolicy;
30use crate::process_standard::ProcessStandard;
31use crate::process_standard::{ProcessStandardDebug, ProcessStandardDebugFull};
32use crate::utilities::cells::{MapCell, OptionalCell};
33
34/// Errors that can occur when trying to load and create processes.
35pub enum ProcessLoadError {
36    /// Not enough memory to meet the amount requested by a process. Modify the
37    /// process to request less memory, flash fewer processes, or increase the
38    /// size of the region your board reserves for process memory.
39    NotEnoughMemory,
40
41    /// A process was loaded with a length in flash that the MPU does not
42    /// support. The fix is probably to correct the process size, but this could
43    /// also be caused by a bad MPU implementation.
44    MpuInvalidFlashLength,
45
46    /// The MPU configuration failed for some other, unspecified reason. This
47    /// could be of an internal resource exhaustion, or a mismatch between the
48    /// (current) MPU constraints and process requirements.
49    MpuConfigurationError,
50
51    /// A process specified a fixed memory address that it needs its memory
52    /// range to start at, and the kernel did not or could not give the process
53    /// a memory region starting at that address.
54    MemoryAddressMismatch {
55        actual_address: u32,
56        expected_address: u32,
57    },
58
59    /// There is nowhere in the `PROCESSES` array to store this process.
60    NoProcessSlot,
61
62    /// Process loading failed because parsing the binary failed.
63    BinaryError(ProcessBinaryError),
64
65    /// Process loading failed because checking the process failed.
66    CheckError(ProcessCheckError),
67
68    /// Process loading error due (likely) to a bug in the kernel. If you get
69    /// this error please open a bug report.
70    InternalError,
71}
72
73impl fmt::Debug for ProcessLoadError {
74    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75        match self {
76            ProcessLoadError::NotEnoughMemory => {
77                write!(f, "Not able to provide RAM requested by app")
78            }
79
80            ProcessLoadError::MpuInvalidFlashLength => {
81                write!(f, "App flash length not supported by MPU")
82            }
83
84            ProcessLoadError::MpuConfigurationError => {
85                write!(f, "Configuring the MPU failed")
86            }
87
88            ProcessLoadError::MemoryAddressMismatch {
89                actual_address,
90                expected_address,
91            } => write!(
92                f,
93                "App memory does not match requested address Actual:{:#x}, Expected:{:#x}",
94                actual_address, expected_address
95            ),
96
97            ProcessLoadError::NoProcessSlot => {
98                write!(f, "Nowhere to store the loaded process")
99            }
100
101            ProcessLoadError::BinaryError(binary_error) => {
102                writeln!(f, "Error parsing process binary")?;
103                write!(f, "{:?}", binary_error)
104            }
105
106            ProcessLoadError::CheckError(check_error) => {
107                writeln!(f, "Error checking process")?;
108                write!(f, "{:?}", check_error)
109            }
110
111            ProcessLoadError::InternalError => write!(f, "Error in kernel. Likely a bug."),
112        }
113    }
114}
115
116////////////////////////////////////////////////////////////////////////////////
117// SYNCHRONOUS PROCESS LOADING
118////////////////////////////////////////////////////////////////////////////////
119
120/// Load processes into runnable process structures.
121///
122/// Load processes (stored as TBF objects in flash) into runnable process
123/// structures stored in the `procs` array and mark all successfully loaded
124/// processes as runnable. This method does not check the cryptographic
125/// credentials of TBF objects. Platforms for which code size is tight and do
126/// not need to check TBF credentials can call this method because it results in
127/// a smaller kernel, as it does not invoke the credential checking state
128/// machine.
129///
130/// This function is made `pub` so that board files can use it, but loading
131/// processes from slices of flash an memory is fundamentally unsafe. Therefore,
132/// we require the `ProcessManagementCapability` to call this function.
133// Mark inline always to reduce code size. Since this is only called in one
134// place (a board's main.rs), by inlining the load_*processes() functions, the
135// compiler can elide many checks which reduces code size appreciably. Note,
136// however, these functions require a rather large stack frame, which may be an
137// issue for boards small kernel stacks.
138#[inline(always)]
139pub fn load_processes<C: Chip>(
140    kernel: &'static Kernel,
141    chip: &'static C,
142    app_flash: &'static [u8],
143    app_memory: &'static mut [u8],
144    fault_policy: &'static dyn ProcessFaultPolicy,
145    _capability_management: &dyn ProcessManagementCapability,
146) -> Result<(), ProcessLoadError> {
147    load_processes_from_flash::<C, ProcessStandardDebugFull>(
148        kernel,
149        chip,
150        app_flash,
151        app_memory,
152        fault_policy,
153    )?;
154
155    if config::CONFIG.debug_process_credentials {
156        debug!("Checking: no checking, load and run all processes");
157        for proc in kernel.get_process_iter() {
158            debug!("Running {}", proc.get_process_name());
159        }
160    }
161    Ok(())
162}
163
164/// Helper function to load processes from flash into an array of active
165/// processes. This is the default template for loading processes, but a board
166/// is able to create its own `load_processes()` function and use that instead.
167///
168/// Processes are found in flash starting from the given address and iterating
169/// through Tock Binary Format (TBF) headers. Processes are given memory out of
170/// the `app_memory` buffer until either the memory is exhausted or the
171/// allocated number of processes are created. This buffer is a non-static slice,
172/// ensuring that this code cannot hold onto the slice past the end of this function
173/// (instead, processes store a pointer and length), which necessary for later
174/// creation of `ProcessBuffer`s in this memory region to be sound.
175/// A reference to each process is stored in the provided `procs` array.
176/// How process faults are handled by the
177/// kernel must be provided and is assigned to every created process.
178///
179/// Returns `Ok(())` if process discovery went as expected. Returns a
180/// `ProcessLoadError` if something goes wrong during TBF parsing or process
181/// creation.
182#[inline(always)]
183fn load_processes_from_flash<C: Chip, D: ProcessStandardDebug + 'static>(
184    kernel: &'static Kernel,
185    chip: &'static C,
186    app_flash: &'static [u8],
187    app_memory: &'static mut [u8],
188    fault_policy: &'static dyn ProcessFaultPolicy,
189) -> Result<(), ProcessLoadError> {
190    if config::CONFIG.debug_load_processes {
191        debug!(
192            "Loading processes from flash={:#010X}-{:#010X} into sram={:#010X}-{:#010X}",
193            app_flash.as_ptr() as usize,
194            app_flash.as_ptr() as usize + app_flash.len() - 1,
195            app_memory.as_ptr() as usize,
196            app_memory.as_ptr() as usize + app_memory.len() - 1
197        );
198    }
199
200    let mut remaining_flash = app_flash;
201    let mut remaining_memory = app_memory;
202
203    loop {
204        match kernel.next_available_process_slot() {
205            Ok((index, slot)) => {
206                let load_binary_result = discover_process_binary(remaining_flash);
207
208                match load_binary_result {
209                    Ok((new_flash, process_binary)) => {
210                        remaining_flash = new_flash;
211
212                        let load_result = load_process::<C, D>(
213                            kernel,
214                            chip,
215                            process_binary,
216                            remaining_memory,
217                            ShortId::LocallyUnique,
218                            index,
219                            fault_policy,
220                            &(),
221                        );
222                        match load_result {
223                            Ok((new_mem, proc)) => {
224                                remaining_memory = new_mem;
225                                match proc {
226                                    Some(p) => {
227                                        if config::CONFIG.debug_load_processes {
228                                            debug!("Loaded process {}", p.get_process_name())
229                                        }
230                                        slot.set(p);
231                                    }
232                                    None => {
233                                        if config::CONFIG.debug_load_processes {
234                                            debug!("No process loaded.");
235                                        }
236                                    }
237                                }
238                            }
239                            Err((new_mem, err)) => {
240                                remaining_memory = new_mem;
241                                if config::CONFIG.debug_load_processes {
242                                    debug!("Processes load error: {:?}.", err);
243                                }
244                            }
245                        }
246                    }
247                    Err((new_flash, err)) => {
248                        remaining_flash = new_flash;
249                        match err {
250                            ProcessBinaryError::NotEnoughFlash
251                            | ProcessBinaryError::TbfHeaderNotFound => {
252                                if config::CONFIG.debug_load_processes {
253                                    debug!("No more processes to load: {:?}.", err);
254                                }
255                                // No more processes to load.
256                                break;
257                            }
258
259                            ProcessBinaryError::TbfHeaderParseFailure(_)
260                            | ProcessBinaryError::IncompatibleKernelVersion { .. }
261                            | ProcessBinaryError::IncorrectFlashAddress { .. }
262                            | ProcessBinaryError::NotEnabledProcess
263                            | ProcessBinaryError::Padding => {
264                                if config::CONFIG.debug_load_processes {
265                                    debug!("Unable to use process binary: {:?}.", err);
266                                }
267
268                                // Skip this binary and move to the next one.
269                                continue;
270                            }
271                        }
272                    }
273                }
274            }
275            Err(()) => {
276                // No slot available.
277                if config::CONFIG.debug_load_processes {
278                    debug!("No more process slots to load processes into.");
279                }
280            }
281        }
282    }
283    Ok(())
284}
285
286////////////////////////////////////////////////////////////////////////////////
287// HELPER FUNCTIONS
288////////////////////////////////////////////////////////////////////////////////
289
290/// Find a process binary stored at the beginning of `flash` and create a
291/// `ProcessBinary` object if the process is viable to run on this kernel.
292fn discover_process_binary(
293    flash: &'static [u8],
294) -> Result<(&'static [u8], ProcessBinary), (&'static [u8], ProcessBinaryError)> {
295    if config::CONFIG.debug_load_processes {
296        debug!(
297            "Looking for process binary in flash={:#010X}-{:#010X}",
298            flash.as_ptr() as usize,
299            flash.as_ptr() as usize + flash.len() - 1
300        );
301    }
302
303    // If this fails, not enough remaining flash to check for an app.
304    let test_header_slice = flash
305        .get(0..8)
306        .ok_or((flash, ProcessBinaryError::NotEnoughFlash))?;
307
308    // Pass the first eight bytes to tbfheader to parse out the length of
309    // the tbf header and app. We then use those values to see if we have
310    // enough flash remaining to parse the remainder of the header.
311    //
312    // Start by converting [u8] to [u8; 8].
313    let header = test_header_slice
314        .try_into()
315        .or(Err((flash, ProcessBinaryError::NotEnoughFlash)))?;
316
317    let (version, header_length, app_length) =
318        match tock_tbf::parse::parse_tbf_header_lengths(header) {
319            Ok((v, hl, el)) => (v, hl, el),
320            Err(tock_tbf::types::InitialTbfParseError::InvalidHeader(app_length)) => {
321                // If we could not parse the header, then we want to skip over
322                // this app and look for the next one.
323                (0, 0, app_length)
324            }
325            Err(tock_tbf::types::InitialTbfParseError::UnableToParse) => {
326                // Since Tock apps use a linked list, it is very possible the
327                // header we started to parse is intentionally invalid to signal
328                // the end of apps. This is ok and just means we have finished
329                // loading apps.
330                return Err((flash, ProcessBinaryError::TbfHeaderNotFound));
331            }
332        };
333
334    // Now we can get a slice which only encompasses the length of flash
335    // described by this tbf header.  We will either parse this as an actual
336    // app, or skip over this region.
337    let app_flash = flash
338        .get(0..app_length as usize)
339        .ok_or((flash, ProcessBinaryError::NotEnoughFlash))?;
340
341    // Advance the flash slice for process discovery beyond this last entry.
342    // This will be the start of where we look for a new process since Tock
343    // processes are allocated back-to-back in flash.
344    let remaining_flash = flash
345        .get(app_flash.len()..)
346        .ok_or((flash, ProcessBinaryError::NotEnoughFlash))?;
347
348    let pb = ProcessBinary::create(app_flash, header_length as usize, version, true)
349        .map_err(|e| (remaining_flash, e))?;
350
351    Ok((remaining_flash, pb))
352}
353
354/// Load a process stored as a TBF process binary with `app_memory` as the RAM
355/// pool that its RAM should be allocated from. Returns `Ok` if the process
356/// object was created, `Err` with a relevant error if the process object could
357/// not be created.
358fn load_process<C: Chip, D: ProcessStandardDebug>(
359    kernel: &'static Kernel,
360    chip: &'static C,
361    process_binary: ProcessBinary,
362    app_memory: &'static mut [u8],
363    app_id: ShortId,
364    index: usize,
365    fault_policy: &'static dyn ProcessFaultPolicy,
366    storage_policy: &'static dyn ProcessStandardStoragePermissionsPolicy<C, D>,
367) -> Result<(&'static mut [u8], Option<&'static dyn Process>), (&'static mut [u8], ProcessLoadError)>
368{
369    if config::CONFIG.debug_load_processes {
370        debug!(
371            "Loading: process flash={:#010X}-{:#010X} ram={:#010X}-{:#010X}",
372            process_binary.flash.as_ptr() as usize,
373            process_binary.flash.as_ptr() as usize + process_binary.flash.len() - 1,
374            app_memory.as_ptr() as usize,
375            app_memory.as_ptr() as usize + app_memory.len() - 1
376        );
377    }
378
379    // Need to reassign remaining_memory in every iteration so the compiler
380    // knows it will not be re-borrowed.
381    // If we found an actual app header, try to create a `Process`
382    // object. We also need to shrink the amount of remaining memory
383    // based on whatever is assigned to the new process if one is
384    // created.
385
386    // Try to create a process object from that app slice. If we don't
387    // get a process and we didn't get a loading error (aka we got to
388    // this point), then the app is a disabled process or just padding.
389    let (process_option, unused_memory) = unsafe {
390        ProcessStandard::<C, D>::create(
391            kernel,
392            chip,
393            process_binary,
394            app_memory,
395            fault_policy,
396            storage_policy,
397            app_id,
398            index,
399        )
400        .map_err(|(e, memory)| (memory, e))?
401    };
402
403    process_option.map(|process| {
404        if config::CONFIG.debug_load_processes {
405            debug!(
406                "Loading: {} [{}] flash={:#010X}-{:#010X} ram={:#010X}-{:#010X}",
407                process.get_process_name(),
408                index,
409                process.get_addresses().flash_start,
410                process.get_addresses().flash_end,
411                process.get_addresses().sram_start,
412                process.get_addresses().sram_end - 1,
413            );
414        }
415    });
416
417    Ok((unused_memory, process_option))
418}
419
420////////////////////////////////////////////////////////////////////////////////
421// ASYNCHRONOUS PROCESS LOADING
422////////////////////////////////////////////////////////////////////////////////
423
424/// Client for asynchronous process loading.
425///
426/// This supports a client that is notified after trying to load each process in
427/// flash. Also there is a callback for after all processes have been
428/// discovered.
429pub trait ProcessLoadingAsyncClient {
430    /// A process was successfully found in flash, checked, and loaded into a
431    /// `ProcessStandard` object.
432    fn process_loaded(&self, result: Result<(), ProcessLoadError>);
433
434    /// There are no more processes in flash to be loaded.
435    fn process_loading_finished(&self);
436}
437
438/// Asynchronous process loading.
439///
440/// Machines which implement this trait perform asynchronous process loading and
441/// signal completion through `ProcessLoadingAsyncClient`.
442///
443/// Various process loaders may exist. This includes a loader from a MCU's
444/// integrated flash, or a loader from an external flash chip.
445pub trait ProcessLoadingAsync<'a> {
446    /// Set the client to receive callbacks about process loading and when
447    /// process loading has finished.
448    fn set_client(&self, client: &'a dyn ProcessLoadingAsyncClient);
449
450    /// Set the credential checking policy for the loader.
451    fn set_policy(&self, policy: &'a dyn AppIdPolicy);
452
453    /// Start the process loading operation.
454    fn start(&self);
455}
456
457/// Operating mode of the loader.
458#[derive(Clone, Copy)]
459enum SequentialProcessLoaderMachineState {
460    /// Phase of discovering `ProcessBinary` objects in flash.
461    DiscoverProcessBinaries,
462    /// Phase of loading `ProcessBinary`s into `Process`es.
463    LoadProcesses,
464}
465
466/// Operating mode of the sequential process loader.
467///
468/// The loader supports loading processes from flash at boot, and loading processes
469/// that were written to flash dynamically at runtime. Most of the internal logic is the
470/// same (and therefore reused), but we need to track which mode of operation the
471/// loader is in.
472#[derive(Clone, Copy)]
473enum SequentialProcessLoaderMachineRunMode {
474    /// The loader was called by a board's main function at boot.
475    BootMode,
476    /// The loader was called by a dynamic process loader at runtime.
477    RuntimeMode,
478}
479
480/// Enum to hold the padding requirements for a new application.
481#[derive(Clone, Copy, PartialEq, Default)]
482pub enum PaddingRequirement {
483    #[default]
484    None,
485    PrePad,
486    PostPad,
487    PreAndPostPad,
488}
489
490/// A machine for loading processes stored sequentially in a region of flash.
491///
492/// Load processes (stored as TBF objects in flash) into runnable process
493/// structures stored in the `procs` array. This machine scans the footers in
494/// the TBF for cryptographic credentials for binary integrity, passing them to
495/// the checker to decide whether the process has sufficient credentials to run.
496pub struct SequentialProcessLoaderMachine<'a, C: Chip + 'static, D: ProcessStandardDebug + 'static>
497{
498    /// Client to notify as processes are loaded and process loading finishes after boot.
499    boot_client: OptionalCell<&'a dyn ProcessLoadingAsyncClient>,
500    /// Client to notify as processes are loaded and process loading finishes during runtime.
501    runtime_client: OptionalCell<&'a dyn ProcessLoadingAsyncClient>,
502    /// Machine to use to check process credentials.
503    checker: &'static ProcessCheckerMachine,
504    /// Array to store `ProcessBinary`s after checking credentials.
505    proc_binaries: MapCell<&'static mut [Option<ProcessBinary>]>,
506    /// Total available flash for process binaries on this board.
507    flash_bank: Cell<&'static [u8]>,
508    /// Flash memory region to load processes from.
509    flash: Cell<&'static [u8]>,
510    /// Memory available to assign to applications.
511    app_memory: Cell<&'static mut [u8]>,
512    /// Mechanism for generating async callbacks.
513    deferred_call: DeferredCall,
514    /// Reference to the kernel object for creating Processes.
515    kernel: &'static Kernel,
516    /// Reference to the Chip object for creating Processes.
517    chip: &'static C,
518    /// The policy to use when determining ShortIds and process uniqueness.
519    policy: OptionalCell<&'a dyn AppIdPolicy>,
520    /// The fault policy to assign to each created Process.
521    fault_policy: &'static dyn ProcessFaultPolicy,
522    /// The storage permissions policy to assign to each created Process.
523    storage_policy: &'static dyn ProcessStandardStoragePermissionsPolicy<C, D>,
524    /// Current mode of the loading machine.
525    state: OptionalCell<SequentialProcessLoaderMachineState>,
526    /// Current operating mode of the loading machine.
527    run_mode: OptionalCell<SequentialProcessLoaderMachineRunMode>,
528}
529
530impl<'a, C: Chip, D: ProcessStandardDebug> SequentialProcessLoaderMachine<'a, C, D> {
531    /// This function is made `pub` so that board files can use it, but loading
532    /// processes from slices of flash an memory is fundamentally unsafe.
533    /// Therefore, we require the `ProcessManagementCapability` to call this
534    /// function.
535    pub fn new(
536        checker: &'static ProcessCheckerMachine,
537        proc_binaries: &'static mut [Option<ProcessBinary>],
538        kernel: &'static Kernel,
539        chip: &'static C,
540        flash: &'static [u8],
541        app_memory: &'static mut [u8],
542        fault_policy: &'static dyn ProcessFaultPolicy,
543        storage_policy: &'static dyn ProcessStandardStoragePermissionsPolicy<C, D>,
544        policy: &'static dyn AppIdPolicy,
545        _capability_management: &dyn ProcessManagementCapability,
546    ) -> Self {
547        Self {
548            deferred_call: DeferredCall::new(),
549            checker,
550            boot_client: OptionalCell::empty(),
551            runtime_client: OptionalCell::empty(),
552            run_mode: OptionalCell::empty(),
553            proc_binaries: MapCell::new(proc_binaries),
554            kernel,
555            chip,
556            flash_bank: Cell::new(flash),
557            flash: Cell::new(flash),
558            app_memory: Cell::new(app_memory),
559            policy: OptionalCell::new(policy),
560            fault_policy,
561            storage_policy,
562            state: OptionalCell::empty(),
563        }
564    }
565
566    /// Set the runtime client to receive callbacks about process loading and when
567    /// process loading has finished.
568    pub fn set_runtime_client(&self, client: &'a dyn ProcessLoadingAsyncClient) {
569        self.runtime_client.set(client);
570    }
571
572    /// Find the current active client based on the operation mode.
573    fn get_current_client(&self) -> Option<&dyn ProcessLoadingAsyncClient> {
574        match self.run_mode.get()? {
575            SequentialProcessLoaderMachineRunMode::BootMode => self.boot_client.get(),
576            SequentialProcessLoaderMachineRunMode::RuntimeMode => self.runtime_client.get(),
577        }
578    }
579
580    /// Find a slot in the `PROCESS_BINARIES` array to store this process.
581    fn find_open_process_binary_slot(&self) -> Option<usize> {
582        self.proc_binaries.map_or(None, |proc_bins| {
583            for (i, p) in proc_bins.iter().enumerate() {
584                if p.is_none() {
585                    return Some(i);
586                }
587            }
588            None
589        })
590    }
591
592    fn load_and_check(&self) {
593        let ret = self.discover_process_binary();
594        match ret {
595            Ok(pb) => match self.checker.check(pb) {
596                Ok(()) => {}
597                Err(e) => {
598                    self.get_current_client().map(|client| {
599                        client.process_loaded(Err(ProcessLoadError::CheckError(e)));
600                    });
601                }
602            },
603            Err(ProcessBinaryError::NotEnoughFlash)
604            | Err(ProcessBinaryError::TbfHeaderNotFound) => {
605                // These two errors occur when there are no more app binaries in
606                // flash. Now we can move to actually loading process binaries
607                // into full processes.
608
609                self.state
610                    .set(SequentialProcessLoaderMachineState::LoadProcesses);
611                self.deferred_call.set();
612            }
613            Err(e) => {
614                if config::CONFIG.debug_load_processes {
615                    debug!("Loading: unable to create ProcessBinary: {:?}", e);
616                }
617
618                // Other process binary errors indicate the process is not
619                // compatible. Signal error and try the next item in flash.
620                self.get_current_client().map(|client| {
621                    client.process_loaded(Err(ProcessLoadError::BinaryError(e)));
622                });
623
624                self.deferred_call.set();
625            }
626        }
627    }
628
629    /// Try to parse a process binary from flash.
630    ///
631    /// Returns the process binary object or an error if a valid process
632    /// binary could not be extracted.
633    fn discover_process_binary(&self) -> Result<ProcessBinary, ProcessBinaryError> {
634        let flash = self.flash.get();
635
636        match discover_process_binary(flash) {
637            Ok((remaining_flash, pb)) => {
638                self.flash.set(remaining_flash);
639                Ok(pb)
640            }
641
642            Err((remaining_flash, err)) => {
643                self.flash.set(remaining_flash);
644                Err(err)
645            }
646        }
647    }
648
649    /// Create process objects from the discovered process binaries.
650    ///
651    /// This verifies that the discovered processes are valid to run.
652    fn load_process_objects(&self) -> Result<(), ()> {
653        let proc_binaries = self.proc_binaries.take().ok_or(())?;
654        let proc_binaries_len = proc_binaries.len();
655
656        // Iterate all process binary entries.
657        for i in 0..proc_binaries_len {
658            // We are either going to load this process binary or discard it, so
659            // we can use `take()` here.
660            if let Some(process_binary) = proc_binaries[i].take() {
661                // We assume the process can be loaded. This is not the case
662                // if there is a conflicting process.
663                let mut ok_to_load = true;
664
665                // Start by iterating all other process binaries and seeing
666                // if any are in conflict (same AppID with newer version).
667                for proc_bin in proc_binaries.iter() {
668                    if let Some(other_process_binary) = proc_bin {
669                        let blocked =
670                            self.is_blocked_from_loading_by(&process_binary, other_process_binary);
671
672                        if blocked {
673                            ok_to_load = false;
674                            break;
675                        }
676                    }
677                }
678
679                // Go to next ProcessBinary if we cannot load this process.
680                if !ok_to_load {
681                    continue;
682                }
683
684                // Now scan the already loaded processes and make sure this
685                // doesn't conflict with any of those. Since those processes
686                // are already loaded, we just need to check if this process
687                // binary has the same AppID as an already loaded process.
688                for proc in self.kernel.get_process_iter() {
689                    let blocked = self.is_blocked_from_loading_by_process(&process_binary, proc);
690                    if blocked {
691                        ok_to_load = false;
692                        break;
693                    }
694                }
695
696                if !ok_to_load {
697                    continue;
698                }
699
700                // If we get here it is ok to load the process.
701                match self.kernel.next_available_process_slot() {
702                    Ok((index, slot)) => {
703                        // Calculate the ShortId for this new process.
704                        let short_app_id = self.policy.map_or(ShortId::LocallyUnique, |policy| {
705                            policy.to_short_id(&process_binary)
706                        });
707
708                        // Try to create a `Process` object.
709                        let load_result = load_process(
710                            self.kernel,
711                            self.chip,
712                            process_binary,
713                            self.app_memory.take(),
714                            short_app_id,
715                            index,
716                            self.fault_policy,
717                            self.storage_policy,
718                        );
719                        match load_result {
720                            Ok((new_mem, proc)) => {
721                                self.app_memory.set(new_mem);
722                                match proc {
723                                    Some(p) => {
724                                        if config::CONFIG.debug_load_processes {
725                                            debug!(
726                                                "Loading: Loaded process {}",
727                                                p.get_process_name()
728                                            )
729                                        }
730
731                                        // Store the `ProcessStandard` object in the `PROCESSES`
732                                        // array.
733                                        slot.set(p);
734                                        // Notify the client the process was loaded
735                                        // successfully.
736                                        self.get_current_client().map(|client| {
737                                            client.process_loaded(Ok(()));
738                                        });
739                                    }
740                                    None => {
741                                        if config::CONFIG.debug_load_processes {
742                                            debug!("No process loaded.");
743                                        }
744                                    }
745                                }
746                            }
747                            Err((new_mem, err)) => {
748                                self.app_memory.set(new_mem);
749                                if config::CONFIG.debug_load_processes {
750                                    debug!("Could not load process: {:?}.", err);
751                                }
752                                self.get_current_client().map(|client| {
753                                    client.process_loaded(Err(err));
754                                });
755                            }
756                        }
757                    }
758                    Err(()) => {
759                        // Nowhere to store the process.
760                        self.get_current_client().map(|client| {
761                            client.process_loaded(Err(ProcessLoadError::NoProcessSlot));
762                        });
763                    }
764                }
765            }
766        }
767        self.proc_binaries.put(proc_binaries);
768
769        // We have iterated all discovered `ProcessBinary`s and loaded what we
770        // could so now we can signal that process loading is finished.
771        self.get_current_client().map(|client| {
772            client.process_loading_finished();
773        });
774
775        self.state.clear();
776        Ok(())
777    }
778
779    /// Check if `pb1` is blocked from running by `pb2`.
780    ///
781    /// `pb2` blocks `pb1` if:
782    ///
783    /// - They both have the same AppID or they both have the same ShortId, and
784    /// - `pb2` has a higher version number.
785    fn is_blocked_from_loading_by(&self, pb1: &ProcessBinary, pb2: &ProcessBinary) -> bool {
786        let same_app_id = self
787            .policy
788            .map_or(false, |policy| !policy.different_identifier(pb1, pb2));
789        let same_short_app_id = self.policy.map_or(false, |policy| {
790            policy.to_short_id(pb1) == policy.to_short_id(pb2)
791        });
792        let other_newer = pb2.header.get_binary_version() > pb1.header.get_binary_version();
793
794        let blocks = (same_app_id || same_short_app_id) && other_newer;
795
796        if config::CONFIG.debug_process_credentials {
797            debug!(
798                "Loading: ProcessBinary {}({:#02x}) does{} block {}({:#02x})",
799                pb2.header.get_package_name().unwrap_or(""),
800                pb2.flash.as_ptr() as usize,
801                if blocks { "" } else { " not" },
802                pb1.header.get_package_name().unwrap_or(""),
803                pb1.flash.as_ptr() as usize,
804            );
805        }
806
807        blocks
808    }
809
810    /// Check if `pb` is blocked from running by `process`.
811    ///
812    /// `process` blocks `pb` if:
813    ///
814    /// - They both have the same AppID, or
815    /// - They both have the same ShortId
816    ///
817    /// Since `process` is already loaded, we only have to enforce the AppID and
818    /// ShortId uniqueness guarantees.
819    fn is_blocked_from_loading_by_process(
820        &self,
821        pb: &ProcessBinary,
822        process: &dyn Process,
823    ) -> bool {
824        let same_app_id = self.policy.map_or(false, |policy| {
825            !policy.different_identifier_process(pb, process)
826        });
827        let same_short_app_id = self.policy.map_or(false, |policy| {
828            policy.to_short_id(pb) == process.short_app_id()
829        });
830
831        let blocks = same_app_id || same_short_app_id;
832
833        if config::CONFIG.debug_process_credentials {
834            debug!(
835                "Loading: Process {}({:#02x}) does{} block {}({:#02x})",
836                process.get_process_name(),
837                process.get_addresses().flash_start,
838                if blocks { "" } else { " not" },
839                pb.header.get_package_name().unwrap_or(""),
840                pb.flash.as_ptr() as usize,
841            );
842        }
843
844        blocks
845    }
846
847    ////////////////////////////////////////////////////////////////////////////////
848    // DYNAMIC PROCESS LOADING HELPERS
849    ////////////////////////////////////////////////////////////////////////////////
850
851    /// Scan the entire flash to populate lists of existing binaries addresses.
852    fn scan_flash_for_process_binaries(
853        &self,
854        flash: &'static [u8],
855        process_binaries_start_addresses: &mut [usize],
856        process_binaries_end_addresses: &mut [usize],
857    ) -> Result<(), ()> {
858        fn inner_function(
859            flash: &'static [u8],
860            process_binaries_start_addresses: &mut [usize],
861            process_binaries_end_addresses: &mut [usize],
862        ) -> Result<(), ProcessBinaryError> {
863            let flash_end = flash.as_ptr() as usize + flash.len() - 1;
864            let mut addresses = flash.as_ptr() as usize;
865            let mut index: usize = 0;
866
867            while addresses < flash_end {
868                let flash_offset = addresses - flash.as_ptr() as usize;
869
870                let test_header_slice = flash
871                    .get(flash_offset..flash_offset + 8)
872                    .ok_or(ProcessBinaryError::NotEnoughFlash)?;
873
874                let header = test_header_slice
875                    .try_into()
876                    .or(Err(ProcessBinaryError::NotEnoughFlash))?;
877
878                let (_version, header_length, app_length) =
879                    match tock_tbf::parse::parse_tbf_header_lengths(header) {
880                        Ok((v, hl, el)) => (v, hl, el),
881                        Err(tock_tbf::types::InitialTbfParseError::InvalidHeader(app_length)) => {
882                            (0, 0, app_length)
883                        }
884                        Err(tock_tbf::types::InitialTbfParseError::UnableToParse) => {
885                            return Ok(());
886                        }
887                    };
888
889                let app_flash = flash
890                    .get(flash_offset..flash_offset + app_length as usize)
891                    .ok_or(ProcessBinaryError::NotEnoughFlash)?;
892
893                let app_header = flash
894                    .get(flash_offset..flash_offset + header_length as usize)
895                    .ok_or(ProcessBinaryError::NotEnoughFlash)?;
896
897                let remaining_flash = flash
898                    .get(flash_offset + app_flash.len()..)
899                    .ok_or(ProcessBinaryError::NotEnoughFlash)?;
900
901                // Get the rest of the header. The `remaining_header` variable
902                // will continue to hold the remainder of the header we have
903                // not processed.
904                let remaining_header = app_header
905                    .get(16..)
906                    .ok_or(ProcessBinaryError::NotEnoughFlash)?;
907
908                if remaining_header.len() == 0 {
909                    // This is a padding app.
910                    if config::CONFIG.debug_load_processes {
911                        debug!("Is padding!");
912                    }
913                } else {
914                    // This is an app binary, add it to the pb arrays.
915                    process_binaries_start_addresses[index] = app_flash.as_ptr() as usize;
916                    process_binaries_end_addresses[index] =
917                        app_flash.as_ptr() as usize + app_length as usize;
918
919                    if config::CONFIG.debug_load_processes {
920                        debug!(
921                            "[Metadata] Process binary start address at index {}: {:#010x}, with end_address {:#010x}",
922                            index,
923                            process_binaries_start_addresses[index],
924                            process_binaries_end_addresses[index]
925                        );
926                    }
927                    index += 1;
928                    if index > process_binaries_start_addresses.len() - 1 {
929                        return Err(ProcessBinaryError::NotEnoughFlash);
930                    }
931                }
932                addresses = remaining_flash.as_ptr() as usize;
933            }
934
935            Ok(())
936        }
937
938        inner_function(
939            flash,
940            process_binaries_start_addresses,
941            process_binaries_end_addresses,
942        )
943        .or(Err(()))
944    }
945
946    /// Helper function to find the next potential aligned address for the
947    /// new app with size `app_length` assuming Cortex-M alignment rules.
948    fn find_next_cortex_m_aligned_address(&self, address: usize, app_length: usize) -> usize {
949        let remaining = address % app_length;
950        if remaining == 0 {
951            address
952        } else {
953            address + (app_length - remaining)
954        }
955    }
956
957    /// Function to compute the address for a new app with size `app_size`.
958    fn compute_new_process_binary_address(
959        &self,
960        app_size: usize,
961        process_binaries_start_addresses: &mut [usize],
962        process_binaries_end_addresses: &mut [usize],
963    ) -> usize {
964        let mut start_count = 0;
965        let mut end_count = 0;
966
967        // Remove zeros from addresses in place.
968        for i in 0..process_binaries_start_addresses.len() {
969            if process_binaries_start_addresses[i] != 0 {
970                process_binaries_start_addresses[start_count] = process_binaries_start_addresses[i];
971                start_count += 1;
972            }
973        }
974
975        for i in 0..process_binaries_end_addresses.len() {
976            if process_binaries_end_addresses[i] != 0 {
977                process_binaries_end_addresses[end_count] = process_binaries_end_addresses[i];
978                end_count += 1;
979            }
980        }
981
982        // If there is only one application in flash:
983        if start_count == 1 {
984            let potential_address = self
985                .find_next_cortex_m_aligned_address(process_binaries_end_addresses[0], app_size);
986            return potential_address;
987        }
988
989        // Otherwise, iterate through the sorted start and end addresses to find gaps for the new app.
990        for i in 0..start_count - 1 {
991            let gap_start = process_binaries_end_addresses[i];
992            let gap_end = process_binaries_start_addresses[i + 1];
993
994            // Ensure gap_end is valid (skip zeros - these indicate there are no process binaries).
995            if gap_end == 0 {
996                continue;
997            }
998
999            // If there is a valid gap, i.e., (gap_end > gap_start), check alignment.
1000            if gap_end > gap_start {
1001                let potential_address =
1002                    self.find_next_cortex_m_aligned_address(gap_start, app_size);
1003                if potential_address + app_size < gap_end {
1004                    return potential_address;
1005                }
1006            }
1007        }
1008        // If no gaps found, check after the last app.
1009        let last_app_end_address = process_binaries_end_addresses[end_count - 1];
1010        self.find_next_cortex_m_aligned_address(last_app_end_address, app_size)
1011    }
1012
1013    /// This function checks if there is a need to pad either before or after
1014    /// the new app to preserve the linked list.
1015    ///
1016    /// When do we pad?
1017    ///
1018    /// 1. When there is a binary  located in flash after the new app but
1019    ///    not immediately after, we need to add padding between the new
1020    ///    app and the existing app.
1021    /// 2. Due to MPU alignment, the new app may be similarly placed not
1022    ///    immediately after an existing process, in that case, we need to add
1023    ///    padding between the previous app and the new app.
1024    /// 3. If both the above conditions are met, we add both a prepadding and a
1025    ///    postpadding.
1026    /// 4. If either of these conditions are not met, we don't pad.
1027    ///
1028    /// Change checks against process binaries instead of processes?
1029    fn compute_padding_requirement_and_neighbors(
1030        &self,
1031        new_app_start_address: usize,
1032        app_length: usize,
1033        process_binaries_start_addresses: &[usize],
1034        process_binaries_end_addresses: &[usize],
1035    ) -> (PaddingRequirement, usize, usize) {
1036        // The end address of our newly loaded application.
1037        let new_app_end_address = new_app_start_address + app_length;
1038        // To store the address until which we need to write the padding app.
1039        let mut next_app_start_addr = 0;
1040        // To store the address from which we need to write the padding app.
1041        let mut previous_app_end_addr = 0;
1042        let mut padding_requirement: PaddingRequirement = PaddingRequirement::None;
1043
1044        // We compute the closest neighbor to our app such that:
1045        //
1046        // 1. If the new app is placed in between two existing binaries, we
1047        //    compute the closest located binaries.
1048        // 2. Once we compute these values, we determine if we need to write a
1049        //    pre pad header, or a post pad header, or both.
1050        // 3. If there are no apps after ours in the process binary array, we don't
1051        //    do anything.
1052
1053        // Postpad requirement.
1054        if let Some(next_closest_neighbor) = process_binaries_start_addresses
1055            .iter()
1056            .filter(|&&x| x > new_app_end_address - 1)
1057            .min()
1058        {
1059            // We found the next closest app in flash.
1060            next_app_start_addr = *next_closest_neighbor;
1061            if next_app_start_addr != 0 {
1062                padding_requirement = PaddingRequirement::PostPad;
1063            }
1064        } else {
1065            if config::CONFIG.debug_load_processes {
1066                debug!("No App Found after the new app so not adding post padding.");
1067            }
1068        }
1069
1070        // Prepad requirement.
1071        if let Some(previous_closest_neighbor) = process_binaries_end_addresses
1072            .iter()
1073            .filter(|&&x| x < new_app_start_address + 1)
1074            .max()
1075        {
1076            // We found the previous closest app in flash.
1077            previous_app_end_addr = *previous_closest_neighbor;
1078            if new_app_start_address - previous_app_end_addr != 0 {
1079                if padding_requirement == PaddingRequirement::PostPad {
1080                    padding_requirement = PaddingRequirement::PreAndPostPad;
1081                } else {
1082                    padding_requirement = PaddingRequirement::PrePad;
1083                }
1084            }
1085        } else {
1086            if config::CONFIG.debug_load_processes {
1087                debug!("No Previous App Found, so not padding before the new app.");
1088            }
1089        }
1090        (
1091            padding_requirement,
1092            previous_app_end_addr,
1093            next_app_start_addr,
1094        )
1095    }
1096
1097    /// This function scans flash, checks for, and returns an address that follows alignment rules given
1098    /// an app size of `new_app_size`.
1099    fn check_flash_for_valid_address(
1100        &self,
1101        new_app_size: usize,
1102        pb_start_address: &mut [usize],
1103        pb_end_address: &mut [usize],
1104    ) -> Result<usize, ProcessBinaryError> {
1105        let total_flash = self.flash_bank.get();
1106        let total_flash_start = total_flash.as_ptr() as usize;
1107        let total_flash_end = total_flash_start + total_flash.len() - 1;
1108
1109        match self.scan_flash_for_process_binaries(total_flash, pb_start_address, pb_end_address) {
1110            Ok(()) => {
1111                if config::CONFIG.debug_load_processes {
1112                    debug!("Successfully scanned flash");
1113                }
1114                let new_app_address = self.compute_new_process_binary_address(
1115                    new_app_size,
1116                    pb_start_address,
1117                    pb_end_address,
1118                );
1119                if new_app_address + new_app_size - 1 > total_flash_end {
1120                    Err(ProcessBinaryError::NotEnoughFlash)
1121                } else {
1122                    Ok(new_app_address)
1123                }
1124            }
1125            Err(()) => Err(ProcessBinaryError::NotEnoughFlash),
1126        }
1127    }
1128
1129    /// Function to check if the object with address `offset` of size `length` lies
1130    /// within flash bounds.
1131    pub fn check_if_within_flash_bounds(&self, offset: usize, length: usize) -> bool {
1132        let flash = self.flash_bank.get();
1133        let flash_end = flash.as_ptr() as usize + flash.len() - 1;
1134
1135        (flash_end - offset) >= length
1136    }
1137
1138    /// Function to compute an available address for the new application binary.
1139    pub fn check_flash_for_new_address(
1140        &self,
1141        new_app_size: usize,
1142    ) -> Result<(usize, PaddingRequirement, usize, usize), ProcessBinaryError> {
1143        const MAX_PROCS: usize = 10;
1144        let mut pb_start_address: [usize; MAX_PROCS] = [0; MAX_PROCS];
1145        let mut pb_end_address: [usize; MAX_PROCS] = [0; MAX_PROCS];
1146        match self.check_flash_for_valid_address(
1147            new_app_size,
1148            &mut pb_start_address,
1149            &mut pb_end_address,
1150        ) {
1151            Ok(app_address) => {
1152                let (pr, prev_app_addr, next_app_addr) = self
1153                    .compute_padding_requirement_and_neighbors(
1154                        app_address,
1155                        new_app_size,
1156                        &pb_start_address,
1157                        &pb_end_address,
1158                    );
1159                let (padding_requirement, previous_app_end_addr, next_app_start_addr) =
1160                    (pr, prev_app_addr, next_app_addr);
1161                Ok((
1162                    app_address,
1163                    padding_requirement,
1164                    previous_app_end_addr,
1165                    next_app_start_addr,
1166                ))
1167            }
1168            Err(e) => Err(e),
1169        }
1170    }
1171
1172    /// Function to check if the app binary at address `app_address` is valid.
1173    fn check_new_binary_validity(&self, app_address: usize) -> bool {
1174        let flash = self.flash_bank.get();
1175        // Pass the first eight bytes of the tbfheader to parse out the
1176        // length of the tbf header and app. We then use those values to see
1177        // if we have enough flash remaining to parse the remainder of the
1178        // header.
1179        let binary_header = match flash.get(app_address..app_address + 8) {
1180            Some(slice) if slice.len() == 8 => slice,
1181            _ => return false, // Ensure exactly 8 bytes are available
1182        };
1183
1184        let binary_header_array: &[u8; 8] = match binary_header.try_into() {
1185            Ok(arr) => arr,
1186            Err(_) => return false,
1187        };
1188
1189        match tock_tbf::parse::parse_tbf_header_lengths(binary_header_array) {
1190            Ok((_version, _header_length, _entry_length)) => true,
1191            Err(tock_tbf::types::InitialTbfParseError::InvalidHeader(_entry_length)) => false,
1192            Err(tock_tbf::types::InitialTbfParseError::UnableToParse) => false,
1193        }
1194    }
1195
1196    /// Function to start loading the new application at address `app_address` with size
1197    /// `app_size`.
1198    pub fn load_new_process_binary(
1199        &self,
1200        app_address: usize,
1201        app_size: usize,
1202    ) -> Result<(), ProcessLoadError> {
1203        let flash = self.flash_bank.get();
1204        let process_address = app_address - flash.as_ptr() as usize;
1205        let process_flash = flash.get(process_address..process_address + app_size);
1206        let result = self.check_new_binary_validity(process_address);
1207        match result {
1208            true => {
1209                if let Some(flash) = process_flash {
1210                    self.flash.set(flash);
1211                } else {
1212                    return Err(ProcessLoadError::BinaryError(
1213                        ProcessBinaryError::TbfHeaderNotFound,
1214                    ));
1215                }
1216
1217                self.state
1218                    .set(SequentialProcessLoaderMachineState::DiscoverProcessBinaries);
1219
1220                self.run_mode
1221                    .set(SequentialProcessLoaderMachineRunMode::RuntimeMode);
1222                // Start an asynchronous flow so we can issue a callback on error.
1223                self.deferred_call.set();
1224
1225                Ok(())
1226            }
1227            false => Err(ProcessLoadError::BinaryError(
1228                ProcessBinaryError::TbfHeaderNotFound,
1229            )),
1230        }
1231    }
1232}
1233
1234impl<'a, C: Chip, D: ProcessStandardDebug> ProcessLoadingAsync<'a>
1235    for SequentialProcessLoaderMachine<'a, C, D>
1236{
1237    fn set_client(&self, client: &'a dyn ProcessLoadingAsyncClient) {
1238        self.boot_client.set(client);
1239    }
1240
1241    fn set_policy(&self, policy: &'a dyn AppIdPolicy) {
1242        self.policy.replace(policy);
1243    }
1244
1245    fn start(&self) {
1246        self.state
1247            .set(SequentialProcessLoaderMachineState::DiscoverProcessBinaries);
1248        self.run_mode
1249            .set(SequentialProcessLoaderMachineRunMode::BootMode);
1250        // Start an asynchronous flow so we can issue a callback on error.
1251        self.deferred_call.set();
1252    }
1253}
1254
1255impl<C: Chip, D: ProcessStandardDebug> DeferredCallClient
1256    for SequentialProcessLoaderMachine<'_, C, D>
1257{
1258    fn handle_deferred_call(&self) {
1259        // We use deferred calls to start the operation in the async loop.
1260        match self.state.get() {
1261            Some(SequentialProcessLoaderMachineState::DiscoverProcessBinaries) => {
1262                self.load_and_check();
1263            }
1264            Some(SequentialProcessLoaderMachineState::LoadProcesses) => {
1265                let ret = self.load_process_objects();
1266                match ret {
1267                    Ok(()) => {}
1268                    Err(()) => {
1269                        // If this failed for some reason, we still need to
1270                        // signal that process loading has finished.
1271                        self.get_current_client().map(|client| {
1272                            client.process_loading_finished();
1273                        });
1274                    }
1275                }
1276            }
1277            None => {}
1278        }
1279    }
1280
1281    fn register(&'static self) {
1282        self.deferred_call.register(self);
1283    }
1284}
1285
1286impl<C: Chip, D: ProcessStandardDebug> crate::process_checker::ProcessCheckerMachineClient
1287    for SequentialProcessLoaderMachine<'_, C, D>
1288{
1289    fn done(
1290        &self,
1291        process_binary: ProcessBinary,
1292        result: Result<Option<AcceptedCredential>, crate::process_checker::ProcessCheckError>,
1293    ) {
1294        // Check if this process was approved by the checker.
1295        match result {
1296            Ok(optional_credential) => {
1297                if config::CONFIG.debug_load_processes {
1298                    debug!(
1299                        "Loading: Check succeeded for process {}",
1300                        process_binary.header.get_package_name().unwrap_or("")
1301                    );
1302                }
1303                // Save the checked process binary now that we know it is valid.
1304                match self.find_open_process_binary_slot() {
1305                    Some(index) => {
1306                        self.proc_binaries.map(|proc_binaries| {
1307                            process_binary.credential.insert(optional_credential);
1308                            proc_binaries[index] = Some(process_binary);
1309                        });
1310                    }
1311                    None => {
1312                        self.get_current_client().map(|client| {
1313                            client.process_loaded(Err(ProcessLoadError::NoProcessSlot));
1314                        });
1315                    }
1316                }
1317            }
1318            Err(e) => {
1319                if config::CONFIG.debug_load_processes {
1320                    debug!(
1321                        "Loading: Process {} check failed {:?}",
1322                        process_binary.header.get_package_name().unwrap_or(""),
1323                        e
1324                    );
1325                }
1326                // Signal error and call try next
1327                self.get_current_client().map(|client| {
1328                    client.process_loaded(Err(ProcessLoadError::CheckError(e)));
1329                });
1330            }
1331        }
1332
1333        // Try to load the next process in flash.
1334        self.deferred_call.set();
1335    }
1336}