Skip to main content

vmi_os_linux/comps/
task_struct.rs

1use once_cell::unsync::OnceCell;
2use vmi_core::{
3    Pa, Va, VmiError, VmiOs, VmiState, VmiVa,
4    driver::VmiRead,
5    os::{ProcessId, ProcessObject, VmiOsImageArchitecture, VmiOsProcess},
6};
7
8use super::{LinuxFsStruct, LinuxMmStruct, LinuxPath, LinuxVmAreaStruct, macros::impl_offsets};
9use crate::{ArchAdapter, LinuxError, LinuxOs};
10
11/// A Linux task struct.
12///
13/// The `task_struct` is the process descriptor in the Linux kernel,
14/// representing a task (process or thread).
15///
16/// # Implementation Details
17///
18/// Corresponds to `task_struct`.
19pub struct LinuxTaskStruct<'a, Driver>
20where
21    Driver: VmiRead,
22    Driver::Architecture: ArchAdapter<Driver>,
23{
24    /// The VMI state.
25    vmi: VmiState<'a, LinuxOs<Driver>>,
26
27    /// The virtual address of the `task_struct` structure.
28    va: Va,
29
30    /// Cached flags.
31    flags: OnceCell<u32>,
32}
33
34impl<Driver> VmiVa for LinuxTaskStruct<'_, Driver>
35where
36    Driver: VmiRead,
37    Driver::Architecture: ArchAdapter<Driver>,
38{
39    fn va(&self) -> Va {
40        self.va
41    }
42}
43
44impl<'a, Driver> LinuxTaskStruct<'a, Driver>
45where
46    Driver: VmiRead,
47    Driver::Architecture: ArchAdapter<Driver>,
48{
49    impl_offsets!();
50
51    /// Creates a new Linux task struct.
52    pub fn new(vmi: VmiState<'a, LinuxOs<Driver>>, process: ProcessObject) -> Self {
53        Self {
54            vmi,
55            va: process.0,
56            flags: OnceCell::new(),
57        }
58    }
59
60    /// Returns the process flags.
61    ///
62    /// Process flags in Linux include information about the process state,
63    /// such as whether it's exiting, a kernel thread, etc.
64    ///
65    /// # Implementation Details
66    ///
67    /// Corresponds to `task_struct.flags`.
68    pub fn flags(&self) -> Result<u32, VmiError> {
69        self.flags
70            .get_or_try_init(|| {
71                let offsets = self.offsets();
72                let __task_struct = &offsets.task_struct;
73
74                self.vmi.read_u32(self.va + __task_struct.flags.offset())
75            })
76            .copied()
77    }
78
79    /// Returns the memory descriptor (`mm_struct`) of the user-mode process.
80    ///
81    /// The `mm_struct` contains the memory management information for a process.
82    /// Kernel threads don't have an `mm_struct` and return `None`.
83    ///
84    /// # Implementation Details
85    ///
86    /// Corresponds to `task_struct->mm`.
87    pub fn mm(&self) -> Result<Option<LinuxMmStruct<'a, Driver>>, VmiError> {
88        let offsets = self.offsets();
89        let __task_struct = &offsets.task_struct;
90
91        let mm = self
92            .vmi
93            .read_va_native(self.va + __task_struct.mm.offset())?;
94
95        if mm.is_null() {
96            return Ok(None);
97        }
98
99        Ok(Some(LinuxMmStruct::new(self.vmi, mm)))
100    }
101
102    /// Returns the active memory context (`mm_struct`) of the process.
103    ///
104    /// Used by kernel threads to reference the last used `mm_struct` before
105    /// entering kernel mode.
106    ///
107    /// If a kernel thread ([`mm()`] is `None`) needs memory access,
108    /// it temporarily borrows `active_mm` from the last scheduled user-space
109    /// process.
110    ///
111    /// When the kernel thread exits, the original `mm_struct` is restored.
112    ///
113    /// # Implementation Details
114    ///
115    /// Corresponds to `task_struct->active_mm`.
116    ///
117    /// [`mm()`]: Self::mm
118    pub fn active_mm(&self) -> Result<LinuxMmStruct<'a, Driver>, VmiError> {
119        let offsets = self.offsets();
120        let __task_struct = &offsets.task_struct;
121
122        let mm = self
123            .vmi
124            .read_va_native(self.va + __task_struct.active_mm.offset())?;
125
126        if mm.is_null() {
127            return Err(LinuxError::CorruptedStruct("task_struct->active_mm").into());
128        }
129
130        Ok(LinuxMmStruct::new(self.vmi, mm))
131    }
132
133    /// Returns the filesystem context (`fs_struct`) of the process.
134    ///
135    /// `fs_struct` contains:
136    ///   - [`root`]: The process’s root directory (used for chroot).
137    ///   - [`pwd`]: The current working directory.
138    ///
139    /// All threads in the same process share the same `fs_struct`, unless
140    /// explicitly changed.
141    ///
142    /// Kernel threads don't have an `fs_struct` and return `None`.
143    ///
144    /// # Implementation Details
145    ///
146    /// Corresponds to `task_struct->fs`.
147    ///
148    /// [`root`]: LinuxFsStruct::root
149    /// [`pwd`]: LinuxFsStruct::pwd
150    pub fn fs(&self) -> Result<Option<LinuxFsStruct<'a, Driver>>, VmiError> {
151        let offsets = self.offsets();
152        let __task_struct = &offsets.task_struct;
153        let __fs_struct = &offsets.fs_struct;
154
155        let fs = self
156            .vmi
157            .read_va_native(self.va + __task_struct.fs.offset())?;
158
159        if fs.is_null() {
160            return Ok(None);
161        }
162
163        Ok(Some(LinuxFsStruct::new(self.vmi, fs)))
164    }
165
166    /// Constructs the absolute path from a `path` structure.
167    ///
168    /// Takes into account the process's filesystem root when constructing the
169    /// absolute path.
170    ///
171    /// Returns the resolved path as a string if successful, or `None` if the path
172    /// could not be resolved (e.g., if the root is null).
173    ///
174    /// # Implementation Details
175    ///
176    /// Concatenates `task_struct->fs->root` with the `path` structure to construct
177    /// the absolute path.
178    pub fn d_path(&self, path: &LinuxPath<Driver>) -> Result<Option<String>, VmiError> {
179        let root = match self.fs()? {
180            Some(root) => root.root()?,
181            None => return Ok(None),
182        };
183
184        Ok(Some(LinuxOs::<Driver>::construct_path(
185            self.vmi, path, &root,
186        )?))
187    }
188
189    /// Returns the path of the executable image for a process.
190    ///
191    /// Returns the executable path as a string, or `None` for special processes
192    /// like kernel threads or those in the process of exiting.
193    ///
194    /// # Implementation Details
195    ///
196    /// Corresponds to `d_path(task->mm->exe_file->f_path)`.
197    pub fn image_path(&self) -> Result<Option<String>, VmiError> {
198        let flags = self.flags()?;
199
200        const PF_EXITING: u32 = 0x00000004; // getting shut down
201        const PF_KTHREAD: u32 = 0x00200000; // kernel thread
202
203        if flags & PF_KTHREAD != 0 {
204            return Ok(None);
205        }
206
207        if flags & PF_EXITING != 0 {
208            return Ok(None);
209        }
210
211        let mm = match self.mm()? {
212            Some(mm) => mm,
213            None => return Ok(None),
214        };
215
216        let exe_file = match mm.exe_file()? {
217            Some(exe_file) => exe_file,
218            None => return Ok(None),
219        };
220
221        self.d_path(&exe_file.path()?)
222    }
223}
224
225impl<'a, Driver> VmiOsProcess<'a, Driver> for LinuxTaskStruct<'a, Driver>
226where
227    Driver: VmiRead,
228    Driver::Architecture: ArchAdapter<Driver>,
229{
230    type Os = LinuxOs<Driver>;
231
232    fn id(&self) -> Result<ProcessId, VmiError> {
233        let offsets = self.offsets();
234        let __task_struct = &offsets.task_struct;
235
236        let result = self.vmi.read_u32(self.va + __task_struct.tgid.offset())?;
237
238        Ok(ProcessId(result))
239    }
240
241    fn object(&self) -> Result<ProcessObject, VmiError> {
242        Ok(ProcessObject(self.va))
243    }
244
245    fn name(&self) -> Result<String, VmiError> {
246        let task_struct_comm_offset = 0xBC0;
247
248        self.vmi.read_string(self.va + task_struct_comm_offset)
249    }
250
251    fn parent_id(&self) -> Result<ProcessId, VmiError> {
252        unimplemented!()
253    }
254
255    fn architecture(&self) -> Result<VmiOsImageArchitecture, VmiError> {
256        unimplemented!()
257    }
258
259    fn translation_root(&self) -> Result<Pa, VmiError> {
260        unimplemented!()
261    }
262
263    fn user_translation_root(&self) -> Result<Pa, VmiError> {
264        unimplemented!()
265    }
266
267    fn image_base(&self) -> Result<Va, VmiError> {
268        unimplemented!()
269    }
270
271    fn regions(
272        &self,
273    ) -> Result<
274        impl Iterator<Item = Result<<Self::Os as VmiOs>::Region<'a>, VmiError>> + use<'a, Driver>,
275        VmiError,
276    > {
277        let mut result = Vec::new();
278
279        let mm = match self.mm()? {
280            Some(mm) => mm,
281            None => return Ok(result.into_iter()),
282        };
283
284        let vmi = self.vmi;
285        let mt = mm.mm_mt()?;
286        mt.enumerate(|node| {
287            println!("XXXNode: {}", node);
288            if !node.is_null() {
289                result.push(Ok(LinuxVmAreaStruct::new(vmi, node)));
290            }
291            true
292        })?;
293
294        Ok(result.into_iter())
295    }
296
297    fn lookup_region(
298        &self,
299        _address: Va,
300    ) -> Result<Option<<Self::Os as VmiOs>::Region<'a>>, VmiError> {
301        unimplemented!()
302    }
303
304    fn user_modules(
305        &self,
306    ) -> Result<
307        impl Iterator<Item = Result<<Self::Os as VmiOs>::UserModule<'a>, VmiError>> + use<'a, Driver>,
308        VmiError,
309    > {
310        #[allow(unreachable_code)]
311        {
312            unimplemented!() as Result<std::iter::Empty<_>, VmiError>
313        }
314    }
315
316    fn lookup_user_module(
317        &self,
318        _address: Va,
319    ) -> Result<Option<<Self::Os as VmiOs>::UserModule<'a>>, VmiError> {
320        unimplemented!()
321    }
322
323    fn threads(
324        &self,
325    ) -> Result<
326        impl Iterator<Item = Result<<Self::Os as VmiOs>::Thread<'a>, VmiError>> + use<'a, Driver>,
327        VmiError,
328    > {
329        #[allow(unreachable_code)]
330        {
331            unimplemented!() as Result<std::iter::Empty<_>, VmiError>
332        }
333    }
334
335    fn is_valid_address(&self, _address: Va) -> Result<Option<bool>, VmiError> {
336        unimplemented!()
337    }
338}