gdb_command/
memory.rs

1//! The `MemoryObject` represents raw data in memory.
2use crate::error;
3
4/// `MemoryObject` represents raw data in memory.
5#[derive(Clone, Debug, Default)]
6pub struct MemoryObject {
7    /// Memory start address
8    pub address: u64,
9    /// Memory contents
10    pub data: Vec<u8>,
11}
12
13impl MemoryObject {
14    /// Construct `MemoryObject` from string
15    ///
16    /// # Arguments
17    ///
18    /// * 'memory' - gdb output string with memory contents (0xdeadbeaf: 0x01 0x02)
19    pub fn from_gdb<T: AsRef<str>>(memory: T) -> error::Result<MemoryObject> {
20        let mut mem = MemoryObject {
21            address: 0,
22            data: Vec::new(),
23        };
24        let mut lines = memory.as_ref().lines();
25        if let Some(first) = lines.next() {
26            // Get start address
27            if let Some((address, data)) = first.split_once(':') {
28                if let Some(address_part) = address.split_whitespace().next() {
29                    mem.address = u64::from_str_radix(address_part.get(2..).unwrap_or(""), 16)?;
30
31                    // Get memory
32                    for b in data.split_whitespace() {
33                        mem.data
34                            .push(u8::from_str_radix(b.get(2..).unwrap_or(""), 16)?);
35                    }
36                } else {
37                    return Err(error::Error::MemoryObjectParse(format!(
38                        "Coudn't parse memory string: {first}"
39                    )));
40                }
41            } else {
42                return Err(error::Error::MemoryObjectParse(format!(
43                    "Coudn't parse memory string: {first}"
44                )));
45            }
46
47            for line in lines {
48                if let Some((_, data)) = line.split_once(':') {
49                    for b in data.split_whitespace() {
50                        mem.data
51                            .push(u8::from_str_radix(b.get(2..).unwrap_or(""), 16)?);
52                    }
53                } else {
54                    return Err(error::Error::MemoryObjectParse(format!(
55                        "No memory values: {line}"
56                    )));
57                }
58            }
59        }
60        Ok(mem)
61    }
62}