monistode_binutils/executable/segments/
common.rs

1use bitvec::vec::BitVec;
2
3use super::flags::SegmentFlags;
4use super::header::SegmentHeader;
5use crate::{SerializationError, Symbol};
6
7#[derive(Debug, Clone)]
8pub struct Segment {
9    pub address_space_start: u64, // These are the addresses - in bytes
10    pub address_space_size: u64,
11    pub disk_bit_count: usize,
12    pub flags: SegmentFlags,
13    pub data: BitVec,
14    symbols: Vec<Symbol>,
15}
16
17impl Segment {
18    pub fn new(
19        address_space_start: u64,
20        address_space_size: u64,
21        disk_bit_count: usize,
22        flags: SegmentFlags,
23        data: BitVec,
24        symbols: Vec<Symbol>,
25    ) -> Self {
26        Segment {
27            address_space_start,
28            address_space_size,
29            disk_bit_count,
30            flags,
31            data,
32            symbols,
33        }
34    }
35
36    pub fn serialize(&self) -> (SegmentHeader, Vec<u8>) {
37        let mut bytes = Vec::new();
38        for i in 0..((self.data.len() + 7) / 8) {
39            let mut byte = 0u8;
40            for j in 0..8 {
41                if i * 8 + j < self.data.len() && self.data[i * 8 + j] {
42                    byte |= 1 << j;
43                }
44            }
45            bytes.push(byte);
46        }
47        (
48            SegmentHeader {
49                address_space_start: self.address_space_start,
50                address_space_size: self.address_space_size,
51                disk_bit_count: self.disk_bit_count,
52                flags: self.flags,
53            },
54            bytes,
55        )
56    }
57
58    pub fn deserialize(
59        header: &SegmentHeader,
60        data: &[u8],
61        symbols: Vec<Symbol>,
62    ) -> Result<(usize, Self), SerializationError> {
63        let required_bytes = (header.disk_bit_count + 7) / 8;
64        if data.len() < required_bytes {
65            return Err(SerializationError::DataTooShort);
66        }
67
68        let mut bits = BitVec::new();
69        for i in 0..header.disk_bit_count {
70            let bit = data[i / 8] & (1 << (i % 8)) != 0;
71            bits.push(bit);
72        }
73        let bytes_read = (header.disk_bit_count + 7) / 8;
74        Ok((
75            bytes_read,
76            Segment {
77                address_space_start: header.address_space_start,
78                address_space_size: header.address_space_size,
79                disk_bit_count: header.disk_bit_count,
80                flags: header.flags,
81                data: bits,
82                symbols,
83            },
84        ))
85    }
86
87    pub fn symbols(&self) -> Vec<Symbol> {
88        self.symbols.clone()
89    }
90}