Unverified Commit edd68498 by Melvin Klimke Committed by GitHub

Parse strings from Runtime Memory Image (#164)

parent d3e87e55
...@@ -167,6 +167,23 @@ impl RuntimeMemoryImage { ...@@ -167,6 +167,23 @@ impl RuntimeMemoryImage {
Err(anyhow!("Address is not a valid global memory address.")) Err(anyhow!("Address is not a valid global memory address."))
} }
/// Read the contents of memory from a given address onwards until a null byte is reached and checks whether the
/// content is a valid UTF8 string.
pub fn read_string_until_null_terminator(&self, address: &Bitvector) -> Result<&str, Error> {
let address = address.try_to_u64().unwrap();
for segment in self.memory_segments.iter() {
if address >= segment.base_address
&& address <= segment.base_address + segment.bytes.len() as u64
{
let index = (address - segment.base_address) as usize;
let c_str = std::ffi::CStr::from_bytes_with_nul(&segment.bytes[index..])?;
return Ok(c_str.to_str()?);
}
}
Err(anyhow!("Address is not a valid global memory address."))
}
/// Check whether all addresses in the given interval point to a readable segment in the runtime memory image. /// Check whether all addresses in the given interval point to a readable segment in the runtime memory image.
/// ///
/// Returns an error if the address interval intersects more than one memory segment /// Returns an error if the address interval intersects more than one memory segment
...@@ -276,6 +293,17 @@ pub mod tests { ...@@ -276,6 +293,17 @@ pub mod tests {
write_flag: true, write_flag: true,
execute_flag: false, execute_flag: false,
}, },
MemorySegment {
bytes: [
0x01, 0x02, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c,
0x64, 0x00,
]
.to_vec(),
base_address: 0x3000,
read_flag: true,
write_flag: false,
execute_flag: false,
},
], ],
is_little_endian: true, is_little_endian: true,
} }
...@@ -305,4 +333,19 @@ pub mod tests { ...@@ -305,4 +333,19 @@ pub mod tests {
assert_eq!(index, 2); assert_eq!(index, 2);
assert_eq!(&slice[index..], &[0xb2u8, 0xb3, 0xb4]); assert_eq!(&slice[index..], &[0xb2u8, 0xb3, 0xb4]);
} }
#[test]
fn test_read_string_until_null_terminator() {
let mem_image = RuntimeMemoryImage::mock();
// the byte array contains "Hello World".
let expected_string: &str =
std::str::from_utf8(b"\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64").unwrap();
let address = Bitvector::from_u32(0x3002);
assert_eq!(
expected_string,
mem_image
.read_string_until_null_terminator(&address)
.unwrap(),
);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment