Eine aufbereitete Darstellung der Quelle

 
     
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung
 
 
 
 

Benutzer

Quelle  plain_image.rs

  Sprache: Rust
 

use anyhow::{anyhow, bail, Result};
use std::path::Path;

// TODO(jrreinhart): Replace anyhow errors with custom error types using thiserror.

/// Represents an NXP "plain image" firmware.
///
/// See RT500RM Table 73. Plain Image Layout
pub struct PlainImage {
    data: Box<[u8]>,
}

impl PlainImage {
    /// Create a plain image from bytes.
    pub fn new<T: Into<Box<[u8]>>>(data: T) -> Result<Self> {
        let data: Box<[u8]> = data.into();
        if data.len() < MIN_IMAGE_SIZE {
            bail!(
                "Invalid image: Only {} bytes; must be >= {} bytes",
                data.as_ref().len(),
                MIN_IMAGE_SIZE
            );
        }

        let image = PlainImage { data: data.into() };

        if image.image_type() != 0 {
            bail!("Invalid image: image type ({}) != 0", image.image_type());
        }

        Ok(image)
    }

    /// Read a plain image from a local file path.
    pub fn read(path: impl AsRef<Path>) -> Result<Self> {
        let data = std::fs::read(path)?;
        let image = PlainImage::new(data)?;

        // For now, only check this in read(), since new() might be used with partial images (just
        // the header).
        if image.data().len() != image.image_length() {
            bail!(
                "Invalid image: actual size ({}) doesn't match size in header ({})",
                image.data().len(),
                image.image_length()
            );
        }

        Ok(image)
    }

    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Get the value of a vector from the vector table.
    pub fn get_vector(&self, n: usize) -> Result<u32> {
        let offset: usize = n * size_of::<u32>();
        let bytes = self
            .data
            .get(offset..offset + 4)
            .ok_or_else(|| anyhow!("Invalid vector number: {n}"))?;
        Ok(u32::from_le_bytes(bytes.try_into().unwrap()))
    }

    pub fn initial_stack_pointer(&self) -> u32 {
        self.get_vector(VECTOR_INITIAL_STACK_PTR).unwrap()
    }

    pub fn reset_vector(&self) -> u32 {
        self.get_vector(VECTOR_RESET).unwrap()
    }

    pub fn image_length(&self) -> usize {
        self.get_vector(VECTOR_IMAGE_LENGTH).unwrap() as usize
    }

    pub fn image_type(&self) -> u32 {
        // RT500RM Table 71. imageType Field
        self.get_vector(VECTOR_IMAGE_TYPE).unwrap()
    }

    pub fn load_address(&self) -> u32 {
        self.get_vector(VECTOR_LOAD_ADDRESS).unwrap()
    }
}

// RT500RM Table 73. Plain Image Layout
const VECTOR_INITIAL_STACK_PTR: usize = 0;
const VECTOR_RESET: usize = 1;
const VECTOR_IMAGE_LENGTH: usize = 8;
const VECTOR_IMAGE_TYPE: usize = 9;
const VECTOR_LOAD_ADDRESS: usize = 13;
const VECTOR_MAX: usize = VECTOR_LOAD_ADDRESS;

const MIN_VECTOR_COUNT: usize = VECTOR_MAX + 1;
const MIN_IMAGE_SIZE: usize = MIN_VECTOR_COUNT * size_of::<u32>();

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

    fn file_from_vector_table(vec_table: &[u32]) -> Result<tempfile::NamedTempFile> {
        let data = vec_table
            .iter()
            .flat_map(|x| x.to_le_bytes())
            .collect::<Vec<u8>>();

        let mut temp_file = tempfile::Builder::new()
            .prefix("plain_image")
            .suffix(".bin")
            .tempfile()?;

        temp_file.write_all(&data)?;
        temp_file.flush()?;

        Ok(temp_file)
    }

    fn image_from_vector_table(vec_table: &[u32]) -> Vec<u8> {
        vec_table
            .iter()
            .flat_map(|x| x.to_le_bytes())
            .collect::<Vec<u8>>()
    }

    const INIT_STACK_PTR: u32 = 0x57ac7000;
    const RESET_VECTOR: u32 = 0xca11ab1e;
    const LOAD_ADDRESS: u32 = 0xba5eadd4;

    #[test]
    fn test_plain_image() -> Result<()> {
        let data = image_from_vector_table(&[
            INIT_STACK_PTR, // 0: Initial stack pointer
            RESET_VECTOR,   // 1: Reset
            0,              // 2
            0,              // 3
            0,              // 4
            0,              // 5
            0,              // 6
            0,              // 7
            20 * 4,         // 8: Image Length
            0,              // 9: Image Type (0 = plain)
            0,              // 10
            0,              // 11
            0,              // 12
            LOAD_ADDRESS,   // 13: Load Address
            0,              // 14
            0,              // 15
            0,              // 16
            0,              // 17
            0,              // 18
            0,              // 19
        ]);

        let img = PlainImage::new(data)?;

        assert_eq!(img.initial_stack_pointer(), INIT_STACK_PTR);
        assert_eq!(img.reset_vector(), RESET_VECTOR);
        assert_eq!(img.image_length(), 20 * 4);
        assert_eq!(img.image_type(), 0);
        assert_eq!(img.load_address(), LOAD_ADDRESS);

        Ok(())
    }

    #[test]
    fn test_plain_image_read() -> Result<()> {
        // Generate a temporary "firmware image" file.
        let temp_file = file_from_vector_table(&[
            INIT_STACK_PTR, // 0: Initial stack pointer
            RESET_VECTOR,   // 1: Reset
            0,              // 2
            0,              // 3
            0,              // 4
            0,              // 5
            0,              // 6
            0,              // 7
            20 * 4,         // 8: Image Length
            0,              // 9: Image Type (0 = plain)
            0,              // 10
            0,              // 11
            0,              // 12
            LOAD_ADDRESS,   // 13: Load Address
            0,              // 14
            0,              // 15
            0,              // 16
            0,              // 17
            0,              // 18
            0,              // 19
        ])?;

        // Read that image.
        let img = PlainImage::read(temp_file.path())?;

        assert_eq!(img.initial_stack_pointer(), INIT_STACK_PTR);
        assert_eq!(img.reset_vector(), RESET_VECTOR);
        assert_eq!(img.image_length(), 20 * 4);
        assert_eq!(img.image_type(), 0);
        assert_eq!(img.load_address(), LOAD_ADDRESS);

        Ok(())
    }

    #[test]
    fn test_image_too_small() -> Result<()> {
        // Generate a temporary "firmware image" file.
        let temp_file = file_from_vector_table(&[
            INIT_STACK_PTR, // 0: Initial stack pointer
            RESET_VECTOR,   // 1: Reset
            0,              // 2
            0,              // 3
            0,              // 4
            0,              // 5
            0,              // 6
            0,              // 7
            13 * 4,         // 8: Image Length
            0,              // 9: Image Type (0 = plain)
            0,              // 10
            0,              // 11
            0,              // 12
        ])?; // 13: Load Address (missing!)

        // Read that image. It should fail (too small).
        let result = PlainImage::read(temp_file.path());
        let error = result.err().unwrap();
        let root = error.root_cause();
        assert!(format!("{root}").starts_with("Invalid image: Only"));

        Ok(())
    }

    #[test]
    fn test_image_bad_type() -> Result<()> {
        // Generate a temporary "firmware image" file.
        let temp_file = file_from_vector_table(&[
            INIT_STACK_PTR, // 0: Initial stack pointer
            RESET_VECTOR,   // 1: Reset
            0,              // 2
            0,              // 3
            0,              // 4
            0,              // 5
            0,              // 6
            0,              // 7
            13 * 4,         // 8: Image Length
            0xBAD,          // 9: Image Type (invalid!)
            0,              // 10
            0,              // 11
            0,              // 12
            LOAD_ADDRESS,   // 13: Load Address
        ])?;

        // Read that image. It should fail (bad type).
        let result = PlainImage::read(temp_file.path());
        let error = result.err().unwrap();
        let root = error.root_cause();
        assert!(format!("{root}").starts_with("Invalid image: image type"));

        Ok(())
    }

    #[test]
    fn test_image_bad_size() -> Result<()> {
        // Generate a temporary "firmware image" file.
        let temp_file = file_from_vector_table(&[
            INIT_STACK_PTR, // 0: Initial stack pointer
            RESET_VECTOR,   // 1: Reset
            0,              // 2
            0,              // 3
            0,              // 4
            0,              // 5
            0,              // 6
            0,              // 7
            0xBAD,          // 8: Image Length
            0,              // 9: Image Type (0 = plain)
            0,              // 10
            0,              // 11
            0,              // 12
            LOAD_ADDRESS,   // 13: Load Address
        ])?;

        // Read that image. It should fail (bad size).
        let result = PlainImage::read(temp_file.path());
        let error = result.err().unwrap();
        let root = error.root_cause();
        assert!(format!("{root}").starts_with("Invalid image: actual size"));

        Ok(())
    }
}

Messung V0.5 in Prozent
C=94 H=94 G=93

¤ Dauer der Verarbeitung: 0.14 Sekunden  (vorverarbeitet am  2026-06-28) ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

PVS Prover

Isabelle Prover

NIST Cobol Testsuite

Cephes Mathematical Library

Vienna Development Method

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.






                                                                                                                                                                                                                                                                                                                                                                                                     


Neuigkeiten

     Aktuelles
     Motto des Tages

Software

     Quellcodebibliothek
     Eigene Quellcodes
     Fremde Quellcodes
     Suchen

Aktivitäten

     Artikel über Sicherheit
     Anleitung zur Aktivierung von SSL

Muße

     Gedichte
     Musik
     Bilder

Jenseits des Üblichen ....
    

Besucherstatistik

Besucherstatistik