use once_cell::unsync::OnceCell;
use vmi_core::{
MemoryAccess, Va, VmiError, VmiState, VmiVa,
driver::VmiRead,
os::{VmiOsRegion, VmiOsRegionKind},
};
use super::macros::impl_offsets;
use crate::{ArchAdapter, LinuxOs};
pub struct LinuxVmAreaStruct<'a, Driver>
where
Driver: VmiRead,
Driver::Architecture: ArchAdapter<Driver>,
{
vmi: VmiState<'a, LinuxOs<Driver>>,
va: Va,
flags: OnceCell<u64>,
}
impl<Driver> VmiVa for LinuxVmAreaStruct<'_, Driver>
where
Driver: VmiRead,
Driver::Architecture: ArchAdapter<Driver>,
{
fn va(&self) -> Va {
self.va
}
}
impl<Driver> std::fmt::Debug for LinuxVmAreaStruct<'_, Driver>
where
Driver: VmiRead,
Driver::Architecture: ArchAdapter<Driver>,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let start = self.start();
let end = self.end();
let protection = self.protection();
f.debug_struct("LinuxVmAreaStruct")
.field("start", &start)
.field("end", &end)
.field("protection", &protection)
.finish()
}
}
impl<'a, Driver> LinuxVmAreaStruct<'a, Driver>
where
Driver: VmiRead,
Driver::Architecture: ArchAdapter<Driver>,
{
impl_offsets!();
pub fn new(vmi: VmiState<'a, LinuxOs<Driver>>, vad: Va) -> Self {
Self {
vmi,
va: vad,
flags: OnceCell::new(),
}
}
pub fn flags(&self) -> Result<u64, VmiError> {
self.flags
.get_or_try_init(|| {
let offsets = self.offsets();
let __vm_area_struct = &offsets.vm_area_struct;
self.vmi.read_field(self.va, &__vm_area_struct.vm_flags)
})
.copied()
}
}
impl<'a, Driver> VmiOsRegion<'a, Driver> for LinuxVmAreaStruct<'a, Driver>
where
Driver: VmiRead,
Driver::Architecture: ArchAdapter<Driver>,
{
type Os = LinuxOs<Driver>;
fn start(&self) -> Result<Va, VmiError> {
let offsets = self.offsets();
let __vm_area_struct = &offsets.vm_area_struct;
self.vmi
.read_va_native(self.va + __vm_area_struct.vm_start.offset())
}
fn end(&self) -> Result<Va, VmiError> {
let offsets = self.offsets();
let __vm_area_struct = &offsets.vm_area_struct;
self.vmi
.read_va_native(self.va + __vm_area_struct.vm_end.offset())
}
fn protection(&self) -> Result<MemoryAccess, VmiError> {
const VM_READ: u64 = 0x00000001;
const VM_WRITE: u64 = 0x00000002;
const VM_EXEC: u64 = 0x00000004;
let flags = self.flags()?;
let mut protection = MemoryAccess::default();
if flags & VM_READ != 0 {
protection |= MemoryAccess::R;
}
if flags & VM_WRITE != 0 {
protection |= MemoryAccess::W;
}
if flags & VM_EXEC != 0 {
protection |= MemoryAccess::X;
}
Ok(protection)
}
fn kind(&self) -> Result<VmiOsRegionKind<'a, Self::Os>, VmiError> {
let offsets = self.offsets();
let __vm_area_struct = &offsets.vm_area_struct;
let file = self
.vmi
.read_va_native(self.va + __vm_area_struct.vm_file.offset())?;
if file.is_null() {
return Ok(VmiOsRegionKind::Private);
}
unimplemented!()
}
}