monistode_binutils/object_file/sections/
text.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use super::header::TextSectionHeader;
use crate::object_file::relocations::Relocation;
use crate::serializable::SerializationError;
use crate::symbols::Symbol;
use bitvec::prelude::*;

#[derive(Debug, Clone)]
pub struct TextSection {
    pub data: BitVec,
    pub symbols: Vec<Symbol>,
    pub relocations: Vec<Relocation>,
}

impl TextSection {
    pub fn new(data: BitVec, symbols: Vec<Symbol>, relocations: Vec<Relocation>) -> Self {
        TextSection {
            data,
            symbols,
            relocations,
        }
    }

    pub fn serialize(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        for i in 0..((self.data.len() + 7) / 8) {
            let mut byte = 0u8;
            for j in 0..8 {
                if i * 8 + j < self.data.len() && self.data[i * 8 + j] {
                    byte |= 1 << j;
                }
            }
            bytes.push(byte);
        }
        bytes
    }

    pub fn deserialize(
        header: &TextSectionHeader,
        data: &[u8],
        symbols: Vec<Symbol>,
        relocations: Vec<Relocation>,
    ) -> Result<(usize, Self), SerializationError> {
        let required_bytes = (header.bit_length as usize + 7) / 8;
        if data.len() < required_bytes {
            return Err(SerializationError::DataTooShort);
        }

        let mut bits = BitVec::new();
        for i in 0..header.bit_length as usize {
            let bit = data[i / 8] & (1 << (i % 8)) != 0;
            bits.push(bit);
        }
        let bytes_read = (header.bit_length + 7) as usize / 8;
        Ok((
            bytes_read,
            TextSection {
                data: bits,
                symbols,
                relocations,
            },
        ))
    }
}