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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use memflow_ffi::mem::phys_mem::CloneablePhysicalMemoryObj;
use memflow_ffi::util::*;
use memflow_win32::kernel::Win32Version;
use memflow_win32::win32::{kernel, Win32ProcessInfo, Win32VirtualTranslate};

use memflow::mem::{
    cache::{CachedMemoryAccess, CachedVirtualTranslate, TimedCacheValidator},
    CloneablePhysicalMemory, DirectTranslate, VirtualDMA,
};

use memflow::iter::FnExtend;
use memflow::process::PID;
use memflow::types::{size, Address, PageType};

use super::process::Win32Process;
use crate::kernel::start_block::StartBlock;

use std::ffi::CStr;
use std::os::raw::c_char;
use std::time::Duration;

pub(crate) type FFIMemory =
    CachedMemoryAccess<'static, Box<dyn CloneablePhysicalMemory>, TimedCacheValidator>;
pub(crate) type FFIVirtualTranslate = CachedVirtualTranslate<DirectTranslate, TimedCacheValidator>;

pub(crate) type FFIVirtualMemory =
    VirtualDMA<FFIMemory, FFIVirtualTranslate, Win32VirtualTranslate>;

pub type Kernel = kernel::Kernel<FFIMemory, FFIVirtualTranslate>;

/// Build a cloneable kernel object with default caching parameters
///
/// This function will take ownership of the input `mem` object.
///
/// # Safety
///
/// `mem` must be a heap allocated memory reference, created by one of the API's functions.
/// Reference to it becomes invalid.
#[no_mangle]
pub unsafe extern "C" fn kernel_build(
    mem: &'static mut CloneablePhysicalMemoryObj,
) -> Option<&'static mut Kernel> {
    let mem: Box<dyn CloneablePhysicalMemory> = Box::from_raw(*Box::from_raw(mem));
    kernel::Kernel::builder(mem)
        .build_default_caches()
        .build()
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

/// Build a cloneable kernel object with custom caching parameters
///
/// This function will take ownership of the input `mem` object.
///
/// vat_cache_entries must be positive, or the program will panic upon memory reads or writes.
///
/// # Safety
///
/// `mem` must be a heap allocated memory reference, created by one of the API's functions.
/// Reference to it becomes invalid.
#[no_mangle]
pub unsafe extern "C" fn kernel_build_custom(
    mem: &'static mut CloneablePhysicalMemoryObj,
    page_cache_time_ms: u64,
    page_cache_flags: PageType,
    page_cache_size_kb: usize,
    vat_cache_time_ms: u64,
    vat_cache_entries: usize,
) -> Option<&'static mut Kernel> {
    let mem: Box<dyn CloneablePhysicalMemory> = Box::from_raw(*Box::from_raw(mem));
    kernel::Kernel::builder(mem)
        .build_page_cache(move |connector, arch| {
            CachedMemoryAccess::builder(connector)
                .arch(arch)
                .validator(TimedCacheValidator::new(
                    Duration::from_millis(page_cache_time_ms).into(),
                ))
                .page_type_mask(page_cache_flags)
                .cache_size(size::kb(page_cache_size_kb))
                .build()
                .unwrap()
        })
        .build_vat_cache(move |vat, arch| {
            CachedVirtualTranslate::builder(vat)
                .arch(arch)
                .validator(TimedCacheValidator::new(
                    Duration::from_millis(vat_cache_time_ms).into(),
                ))
                .entries(vat_cache_entries)
                .build()
                .unwrap()
        })
        .build()
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

#[no_mangle]
pub extern "C" fn kernel_clone(kernel: &Kernel) -> &'static mut Kernel {
    Box::leak(Box::new((*kernel).clone()))
}

/// Free a kernel object
///
/// This will free the input `kernel` object (including the underlying memory object)
///
/// # Safety
///
/// `kernel` must be a valid reference heap allocated by one of the above functions.
#[no_mangle]
pub unsafe extern "C" fn kernel_free(kernel: &'static mut Kernel) {
    let _ = Box::from_raw(kernel);
}

/// Destroy a kernel object and return its underlying memory object
///
/// This will free the input `kernel` object, and return the underlying memory object. It will free
/// the object from any additional caching that `kernel` had in place.
///
/// # Safety
///
/// `kernel` must be a valid reference heap allocated by one of the above functions.
#[no_mangle]
pub unsafe extern "C" fn kernel_destroy(
    kernel: &'static mut Kernel,
) -> &'static mut CloneablePhysicalMemoryObj {
    let kernel = Box::from_raw(kernel);
    Box::leak(Box::new(Box::leak(kernel.destroy().destroy())))
}

#[no_mangle]
pub extern "C" fn kernel_start_block(kernel: &Kernel) -> StartBlock {
    kernel.kernel_info.start_block.into()
}

#[no_mangle]
pub extern "C" fn kernel_winver(kernel: &Kernel) -> Win32Version {
    kernel.kernel_info.kernel_winver.mask_build_number()
}

#[no_mangle]
pub extern "C" fn kernel_winver_unmasked(kernel: &Kernel) -> Win32Version {
    kernel.kernel_info.kernel_winver
}

/// Retrieve a list of peorcess addresses
///
/// # Safety
///
/// `buffer` must be a valid buffer of size at least `max_size`
#[no_mangle]
pub unsafe extern "C" fn kernel_eprocess_list(
    kernel: &'static mut Kernel,
    buffer: *mut Address,
    max_size: usize,
) -> usize {
    let mut ret = 0;

    let buffer = std::slice::from_raw_parts_mut(buffer, max_size);

    let mut extend_fn = FnExtend::new(|addr| {
        if ret < max_size {
            buffer[ret] = addr;
            ret += 1;
        }
    });

    kernel
        .eprocess_list_extend(&mut extend_fn)
        .map_err(inspect_err)
        .ok()
        .map(|_| ret)
        .unwrap_or_default()
}

/// Retrieve a list of processes
///
/// This will fill `buffer` with a list of win32 process information. These processes will need to be
/// individually freed with `process_info_free`
///
/// # Safety
///
/// `buffer` must be a valid that can contain at least `max_size` references to `Win32ProcessInfo`.
#[no_mangle]
pub unsafe extern "C" fn kernel_process_info_list(
    kernel: &'static mut Kernel,
    buffer: *mut &'static mut Win32ProcessInfo,
    max_size: usize,
) -> usize {
    let mut ret = 0;

    let buffer = std::slice::from_raw_parts_mut(buffer, max_size);

    let mut extend_fn = FnExtend::new(|info| {
        if ret < max_size {
            buffer[ret] = Box::leak(Box::new(info));
            ret += 1;
        }
    });

    kernel
        .process_info_list_extend(&mut extend_fn)
        .map_err(inspect_err)
        .ok()
        .map(|_| ret)
        .unwrap_or_default()
}

// Process info

#[no_mangle]
pub extern "C" fn kernel_kernel_process_info(
    kernel: &'static mut Kernel,
) -> Option<&'static mut Win32ProcessInfo> {
    kernel
        .kernel_process_info()
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

#[no_mangle]
pub extern "C" fn kernel_process_info_from_eprocess(
    kernel: &'static mut Kernel,
    eprocess: Address,
) -> Option<&'static mut Win32ProcessInfo> {
    kernel
        .process_info_from_eprocess(eprocess)
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

/// Retrieve process information by name
///
/// # Safety
///
/// `name` must be a valid null terminated string
#[no_mangle]
pub unsafe extern "C" fn kernel_process_info(
    kernel: &'static mut Kernel,
    name: *const c_char,
) -> Option<&'static mut Win32ProcessInfo> {
    let name = CStr::from_ptr(name).to_string_lossy();
    kernel
        .process_info(&name)
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

#[no_mangle]
pub extern "C" fn kernel_process_info_pid(
    kernel: &'static mut Kernel,
    pid: PID,
) -> Option<&'static mut Win32ProcessInfo> {
    kernel
        .process_info_pid(pid)
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

// Process conversion

/// Create a process by looking up its name
///
/// This will consume `kernel` and free it later on.
///
/// # Safety
///
/// `name` must be a valid null terminated string
///
/// `kernel` must be a valid reference to `Kernel`. After the function the reference to it becomes
/// invalid.
#[no_mangle]
pub unsafe extern "C" fn kernel_into_process(
    kernel: &'static mut Kernel,
    name: *const c_char,
) -> Option<&'static mut Win32Process> {
    let kernel = Box::from_raw(kernel);
    let name = CStr::from_ptr(name).to_string_lossy();
    kernel
        .into_process(&name)
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

/// Create a process by looking up its PID
///
/// This will consume `kernel` and free it later on.
///
/// # Safety
///
/// `kernel` must be a valid reference to `Kernel`. After the function the reference to it becomes
/// invalid.
#[no_mangle]
pub unsafe extern "C" fn kernel_into_process_pid(
    kernel: &'static mut Kernel,
    pid: PID,
) -> Option<&'static mut Win32Process> {
    let kernel = Box::from_raw(kernel);
    kernel
        .into_process_pid(pid)
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}

/// Create a kernel process insatance
///
/// This will consume `kernel` and free it later on.
///
/// # Safety
///
/// `kernel` must be a valid reference to `Kernel`. After the function the reference to it becomes
/// invalid.
#[no_mangle]
pub unsafe extern "C" fn kernel_into_kernel_process(
    kernel: &'static mut Kernel,
) -> Option<&'static mut Win32Process> {
    let kernel = Box::from_raw(kernel);
    kernel
        .into_kernel_process()
        .map_err(inspect_err)
        .ok()
        .map(to_heap)
}