Skip to main content

mf4_rs/blocks/
source_block.rs

1use byteorder::{ByteOrder, LittleEndian};
2use crate::blocks::common::BlockHeader;
3use crate::error::MdfError;
4use crate::blocks::common::BlockParse;
5
6/// Represents an SIBLOCK (“##SI”) from the MDF4 file.
7///
8/// - Links:
9///   • si_tx_name    LINK → TXBLOCK (source name)  
10///   • si_tx_path    LINK → TXBLOCK (tool-specific path)  
11///   • si_md_comment LINK → TXBLOCK/MDBLOCK (additional XML/text)
12/// - Data:
13///   • si_type      UINT8 (0=OTHER,1=ECU,2=BUS,3=I/O,4=TOOL,5=USER)  
14///   • si_bus_type  UINT8 (0=NONE,1=OTHER,2=CAN,3=LIN,…,8=USB)  
15///   • si_flags     UINT8 (bit 0 = simulated)  
16///   • si_reserved  BYTE[5] (padding)
17#[derive(Debug)]
18pub struct SourceBlock {
19    pub header:        BlockHeader,
20    /// Link to a TXBLOCK containing the human-readable source name
21    pub name_addr:     u64,
22    /// Link to a TXBLOCK containing a tool-specific path/namespace
23    pub path_addr:     u64,
24    /// Link to TXBLOCK or MDBLOCK with extended comment/XML
25    pub comment_addr:  u64,
26
27    pub source_type:   u8,
28    pub bus_type:      u8,
29    pub flags:         u8,
30    // 5 bytes reserved for 8-byte alignment
31}
32
33impl BlockParse<'_> for SourceBlock {
34    const ID: &'static str = "##SI";
35    /// Parse an SIBLOCK from its raw bytes (starting at the “##SI…” header).
36    fn from_bytes(bytes: &[u8]) -> Result<Self, MdfError> {
37
38        let header = Self::parse_header(bytes)?;
39
40        // Validate the buffer is long enough for the link section AND the
41        // three data bytes that follow it, before reading anything.
42        // (u64 arithmetic avoids overflow for absurd links_nr values.)
43        let required = 24u64
44            .saturating_add(header.links_nr.saturating_mul(8))
45            .saturating_add(3);
46        if (bytes.len() as u64) < required {
47            return Err(MdfError::TooShortBuffer {
48                actual:   bytes.len(),
49                expected: usize::try_from(required).unwrap_or(usize::MAX),
50                file:     file!(),
51                line:     line!(),
52            });
53        }
54        let link_count = header.links_nr as usize;
55
56        // Link section: one LINK (u64 LE) per link_count (max 3 meaningful)
57        let mut name_addr    = 0;
58        let mut path_addr    = 0;
59        let mut comment_addr = 0;
60        for i in 0..link_count.min(3) {
61            let off = 24 + i * 8;
62            let link = LittleEndian::read_u64(&bytes[off..off + 8]);
63            match i {
64                0 => name_addr    = link,
65                1 => path_addr    = link,
66                2 => comment_addr = link,
67                _ => {}
68            }
69        }
70
71        // Data section immediately after all links:
72        let data_start = 24 + link_count * 8;
73        let source_type = bytes[data_start];
74        let bus_type    = bytes[data_start + 1];
75        let flags       = bytes[data_start + 2];
76        // bytes [data_start+3 .. data_start+8] are reserved/padding
77
78        Ok(SourceBlock {
79            header,
80            name_addr,
81            path_addr,
82            comment_addr,
83            source_type,
84            bus_type,
85            flags,
86        })
87    }
88}
89
90/// Read an [`SIBLOCK`](SourceBlock) from the memory mapped file.
91///
92/// # Arguments
93/// * `mmap` - The entire MDF file mapped into memory.
94/// * `address` - File offset of the `##SI` block.
95///
96/// # Returns
97/// The parsed [`SourceBlock`] or an [`MdfError`] if decoding fails.
98pub fn read_source_block(mmap: &[u8], address: u64) -> Result<SourceBlock, MdfError> {
99
100    let start = address as usize;
101    if start.checked_add(24).is_none_or(|end| end > mmap.len()) {
102        return Err(MdfError::TooShortBuffer {
103            actual:   mmap.len(),
104            expected: start.saturating_add(24),
105            file:     file!(),
106            line:     line!(),
107        });
108    }
109    let header = BlockHeader::from_bytes(&mmap[start..start + 24])?;
110    // We know the total length from the header:
111    let total_len = header.block_len as usize;
112    let end = start.checked_add(total_len).ok_or(MdfError::TooShortBuffer {
113        actual:   mmap.len(),
114        expected: usize::MAX,
115        file:     file!(),
116        line:     line!(),
117    })?;
118    if end > mmap.len() {
119        return Err(MdfError::TooShortBuffer {
120            actual:   mmap.len(),
121            expected: end,
122            file:     file!(),
123            line:     line!(),
124        });
125    }
126    let slice = &mmap[start..end];
127    SourceBlock::from_bytes(slice)
128}