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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//! Describes the root of the Operating System

use super::process::*;
use super::{AddressCallback, ProcessInfo, ProcessInfoCallback};

use crate::prelude::v1::{Result, *};

use crate::cglue::*;
use std::prelude::v1::*;

/// OS supertrait for all possible lifetimes
///
/// Use this for convenience. Chances are, once GAT are implemented, only `OS` will be kept.
///
/// It naturally provides all `OsInner` functions.
pub trait Os: for<'a> OsInner<'a> {}
impl<T: for<'a> OsInner<'a>> Os for T {}

/// High level OS trait implemented by OS layers.
///
/// This trait provides all necessary functions for handling an OS, retrieving processes, and
/// moving resources into processes.
///
/// There are also methods for accessing system level modules.
#[cfg_attr(feature = "plugins", cglue_trait)]
#[int_result]
pub trait OsInner<'a>: Send {
    #[wrap_with_group(crate::plugins::os::ProcessInstance)]
    type ProcessType: crate::os::process::Process + MemoryView + 'a;
    #[wrap_with_group(crate::plugins::os::IntoProcessInstance)]
    type IntoProcessType: crate::os::process::Process + MemoryView + Clone + 'static;

    /// Walks a process list and calls a callback for each process structure address
    ///
    /// The callback is fully opaque. We need this style so that C FFI can work seamlessly.
    fn process_address_list_callback(&mut self, callback: AddressCallback) -> Result<()>;

    /// Retrieves a process address list
    ///
    /// This will be a list of unique internal addresses for underlying process structures
    #[skip_func]
    fn process_address_list(&mut self) -> Result<Vec<Address>> {
        let mut ret = vec![];
        self.process_address_list_callback((&mut ret).into())?;
        Ok(ret)
    }

    /// Walks a process list and calls a callback for each process
    ///
    /// The callback is fully opaque. We need this style so that C FFI can work seamlessly.
    fn process_info_list_callback(&mut self, mut callback: ProcessInfoCallback) -> Result<()> {
        // This is safe, because control will flow back to the callback.
        let sptr = self as *mut Self;
        let inner_callback = &mut |addr| match unsafe { &mut *sptr }.process_info_by_address(addr) {
            Ok(info) => callback.call(info),
            Err(Error(_, ErrorKind::PartialData)) => {
                log::trace!("Partial error when reading process {:x}", addr);
                true
            }
            Err(e) => {
                log::trace!("Error when reading process {:x} {:?}", addr, e);
                false
            }
        };
        unsafe { sptr.as_mut().unwrap() }.process_address_list_callback(inner_callback.into())
    }

    /// Retrieves a process list
    #[skip_func]
    fn process_info_list(&mut self) -> Result<Vec<ProcessInfo>> {
        let mut ret = vec![];
        self.process_info_list_callback((&mut ret).into())?;
        Ok(ret)
    }

    /// Find process information by its internal address
    fn process_info_by_address(&mut self, address: Address) -> Result<ProcessInfo>;

    /// Find process information by its name
    ///
    /// # Remarks:
    ///
    /// This function only returns processes whose state is not [`ProcessState::Dead`].
    fn process_info_by_name(&mut self, name: &str) -> Result<ProcessInfo> {
        let mut ret = Err(Error(ErrorOrigin::OsLayer, ErrorKind::ProcessNotFound));
        let callback = &mut |data: ProcessInfo| {
            if (data.state == ProcessState::Unknown || data.state == ProcessState::Alive)
                && data.name.as_ref() == name
            {
                ret = Ok(data);
                false
            } else {
                true
            }
        };
        self.process_info_list_callback(callback.into())?;
        ret
    }

    /// Find process information by its ID
    fn process_info_by_pid(&mut self, pid: Pid) -> Result<ProcessInfo> {
        let mut ret = Err(Error(ErrorOrigin::OsLayer, ErrorKind::ProcessNotFound));
        let callback = &mut |data: ProcessInfo| {
            if data.pid == pid {
                ret = Ok(data);
                false
            } else {
                true
            }
        };
        self.process_info_list_callback(callback.into())?;
        ret
    }

    /// Construct a process by its info, borrowing the OS
    ///
    /// It will share the underlying memory resources
    fn process_by_info(&'a mut self, info: ProcessInfo) -> Result<Self::ProcessType>;
    /// Construct a process by its info, consuming the OS
    ///
    /// This function will consume the Kernel instance and move its resources into the process
    fn into_process_by_info(self, info: ProcessInfo) -> Result<Self::IntoProcessType>;

    /// Creates a process by its internal address, borrowing the OS
    ///
    /// It will share the underlying memory resources
    ///
    /// If no process with the specified address can be found this function will return an Error.
    ///
    /// This function can be useful for quickly accessing a process.
    fn process_by_address(&'a mut self, addr: Address) -> Result<Self::ProcessType> {
        self.process_info_by_address(addr)
            .and_then(move |i| self.process_by_info(i))
    }

    /// Creates a process by its name, borrowing the OS
    ///
    /// It will share the underlying memory resources
    ///
    /// If no process with the specified name can be found this function will return an Error.
    ///
    /// This function can be useful for quickly accessing a process.
    ///
    /// # Remarks:
    ///
    /// This function only returns processes whose state is not [`ProcessState::Dead`].
    fn process_by_name(&'a mut self, name: &str) -> Result<Self::ProcessType> {
        self.process_info_by_name(name)
            .and_then(move |i| self.process_by_info(i))
    }

    /// Creates a process by its ID, borrowing the OS
    ///
    /// It will share the underlying memory resources
    ///
    /// If no process with the specified ID can be found this function will return an Error.
    ///
    /// This function can be useful for quickly accessing a process.
    fn process_by_pid(&'a mut self, pid: Pid) -> Result<Self::ProcessType> {
        self.process_info_by_pid(pid)
            .and_then(move |i| self.process_by_info(i))
    }

    /// Creates a process by its internal address, consuming the OS
    ///
    /// It will consume the OS and not affect memory usage
    ///
    /// If no process with the specified address can be found this function will return an Error.
    ///
    /// This function can be useful for quickly accessing a process.
    fn into_process_by_address(mut self, addr: Address) -> Result<Self::IntoProcessType>
    where
        Self: Sized,
    {
        self.process_info_by_address(addr)
            .and_then(|i| self.into_process_by_info(i))
    }

    /// Creates a process by its name, consuming the OS
    ///
    /// It will consume the OS and not affect memory usage
    ///
    /// If no process with the specified name can be found this function will return an Error.
    ///
    /// This function can be useful for quickly accessing a process.
    ///
    /// # Remarks:
    ///
    /// This function only returns processes whose state is not [`ProcessState::Dead`].
    fn into_process_by_name(mut self, name: &str) -> Result<Self::IntoProcessType>
    where
        Self: Sized,
    {
        self.process_info_by_name(name)
            .and_then(|i| self.into_process_by_info(i))
    }

    /// Creates a process by its ID, consuming the OS
    ///
    /// It will consume the OS and not affect memory usage
    ///
    /// If no process with the specified ID can be found this function will return an Error.
    ///
    /// This function can be useful for quickly accessing a process.
    fn into_process_by_pid(mut self, pid: Pid) -> Result<Self::IntoProcessType>
    where
        Self: Sized,
    {
        self.process_info_by_pid(pid)
            .and_then(|i| self.into_process_by_info(i))
    }

    /// Walks the OS module list and calls the provided callback for each module structure
    /// address
    ///
    /// # Arguments
    /// * `callback` - where to pass each matching module to. This is an opaque callback.
    fn module_address_list_callback(&mut self, callback: AddressCallback) -> Result<()>;

    /// Walks the OS module list and calls the provided callback for each module
    ///
    /// # Arguments
    /// * `callback` - where to pass each matching module to. This is an opaque callback.
    fn module_list_callback(&mut self, mut callback: ModuleInfoCallback) -> Result<()> {
        // This is safe, because control will flow back to the callback.
        let sptr = self as *mut Self;
        let inner_callback =
            &mut |address: Address| match unsafe { &mut *sptr }.module_by_address(address) {
                Ok(info) => callback.call(info),
                Err(e) => {
                    log::trace!("Error when reading module {:x} {:?}", address, e);
                    true // continue iteration
                }
            };
        unsafe { sptr.as_mut().unwrap() }.module_address_list_callback(inner_callback.into())
    }

    /// Retrieves a module list for the OS
    #[skip_func]
    fn module_list(&mut self) -> Result<Vec<ModuleInfo>> {
        let mut ret = vec![];
        self.module_list_callback((&mut ret).into())?;
        Ok(ret)
    }

    /// Retrieves a module by its structure address
    ///
    /// # Arguments
    /// * `address` - address where module's information resides in
    fn module_by_address(&mut self, address: Address) -> Result<ModuleInfo>;

    /// Finds a OS module by its name
    ///
    /// This function can be useful for quickly accessing a specific module
    fn module_by_name(&mut self, name: &str) -> Result<ModuleInfo> {
        let mut ret = Err(Error(ErrorOrigin::OsLayer, ErrorKind::ProcessNotFound));
        let callback = &mut |data: ModuleInfo| {
            if data.name.as_ref() == name {
                ret = Ok(data);
                false
            } else {
                true
            }
        };
        self.module_list_callback(callback.into())?;
        ret
    }

    /// Retrieves the OS info
    fn info(&self) -> &OsInfo;
}

/// Information block about OS
///
/// This provides some basic information about the OS in question. `base`, and `size` may be
/// omitted in some circumstances (lack of kernel, or privileges). But architecture should always
/// be correct.
#[repr(C)]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "abi_stable", derive(::abi_stable::StableAbi))]
pub struct OsInfo {
    /// Base address of the OS kernel
    pub base: Address,
    /// Size of the OS kernel
    pub size: umem,
    /// System architecture
    pub arch: ArchitectureIdent,
}