Skip to main content

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