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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//! This cache is a wrapper for connector objects that implement the [`PhysicalMemory`] trait.
//! It enables a configurable caching layer when accessing physical pages.
//!
//! Each page that is being read by the the connector will be placed into a `PageCache` object.
//! If the cache is still valid then for consecutive reads this connector will just return the values from the cache
//! and not issue out a new read. In case the cache is not valid anymore it will do a new read.
//!
//! The cache time is determined by the customizable cache validator.
//! The cache validator has to implement the [`CacheValidator`](../trait.CacheValidator.html) trait.
//!
//! To make it easier and quicker to construct and work with caches this module also contains a cache builder.
//!
//! More examples can be found in the documentations for each of the structs in this module.
//!
//! # Examples
//!
//! Building a simple cache with default settings:
//! ```
//! # const MAGIC_VALUE: u64 = 0x23bd_318f_f3a3_5821;
//! use memflow::prelude::v1::*;
//! use memflow::dummy::DummyMemory;
//! # use memflow::dummy::DummyOs;
//! # use memflow::architecture::x86::x64;
//!
//! # let phys_mem = DummyMemory::new(size::mb(16));
//! # let mut os = DummyOs::new(phys_mem);
//! # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
//! # let phys_mem = os.into_inner();
//! # let translator = x64::new_translator(dtb);
//! let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
//!
//! let mut cached_mem = CachedView::builder(virt_mem)
//!     .arch(x64::ARCH)
//!     .validator(DefaultCacheValidator::default())
//!     .cache_size(size::mb(1))
//!     .build()
//!     .unwrap();
//!
//! let addr = virt_base; // some arbitrary address
//!
//! cached_mem.write(addr, &MAGIC_VALUE).unwrap();
//!
//! let value: u64 = cached_mem.read(addr).unwrap();
//! assert_eq!(value, MAGIC_VALUE);
//! ```

use super::*;
use crate::mem::phys_mem::{page_cache::PageCache, PhysicalMemoryView};

/// Cached memory view.
///
/// This structure allows to build a page cache on top of a memory view.
///
/// Internally this structure uses the [`CachedPhysicalMemory`] cache.
/// It does this by remapping from / to [`PhysicalMemory`].
#[derive(Clone)]
pub struct CachedView<'a, T, Q>
where
    T: MemoryView,
    Q: CacheValidator,
{
    mem: PhysicalMemoryView<CachedPhysicalMemory<'a, PhysicalMemoryOnView<T>, Q>>,
}

impl<'a, T, Q> MemoryView for CachedView<'a, T, Q>
where
    T: MemoryView,
    Q: CacheValidator,
{
    #[inline]
    fn read_raw_iter(&mut self, data: ReadRawMemOps) -> Result<()> {
        self.mem.read_raw_iter(data)
    }

    #[inline]
    fn write_raw_iter(&mut self, data: WriteRawMemOps) -> Result<()> {
        self.mem.write_raw_iter(data)
    }

    #[inline]
    fn metadata(&self) -> MemoryViewMetadata {
        self.mem.metadata()
    }
}

impl<'a, T: MemoryView> CachedView<'a, T, DefaultCacheValidator> {
    /// Returns a new builder for this cache with default settings.
    #[inline]
    pub fn builder(mem: T) -> CachedViewBuilder<T, DefaultCacheValidator> {
        CachedViewBuilder::new(mem)
    }
}

pub struct CachedViewBuilder<T, Q> {
    mem: T,
    validator: Q,
    page_size: Option<usize>,
    cache_size: usize,
}

impl<T: MemoryView> CachedViewBuilder<T, DefaultCacheValidator> {
    /// Creates a new [`CachedView`] builder.
    /// The memory object is mandatory as the [`CachedView`] struct wraps around it.
    ///
    /// This type of cache also is required to know the exact page size of the target system.
    /// This can either be set directly via the `page_size()` method or via the `arch()` method.
    /// If no page size has been set this builder will fail to build the [`CachedView`].
    ///
    /// Without further adjustments this function creates a cache that is 2 megabytes in size and caches
    /// pages that contain pagetable entries as well as read-only pages.
    ///
    /// It is also possible to either let the [`CachedView`] object own or just borrow the underlying memory object.
    ///
    /// # Examples
    /// Moves ownership of a mem object and retrieves it back:
    /// ```
    /// # const MAGIC_VALUE: u64 = 0x23bd_318f_f3a3_5821;
    /// use memflow::prelude::v1::*;
    /// use memflow::dummy::DummyMemory;
    /// # use memflow::dummy::DummyOs;
    /// # use memflow::architecture::x86::x64;
    ///
    /// # let phys_mem = DummyMemory::new(size::mb(16));
    /// # let mut os = DummyOs::new(phys_mem);
    /// # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
    /// # let phys_mem = os.into_inner();
    /// # let translator = x64::new_translator(dtb);
    /// let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
    ///
    /// let mut cached_mem = CachedView::builder(virt_mem)
    ///     .arch(x64::ARCH)
    ///     .build()
    ///     .unwrap();
    ///
    /// let addr = virt_base; // some arbitrary address
    ///
    /// cached_mem.write(addr, &MAGIC_VALUE).unwrap();
    ///
    /// let value: u64 = cached_mem.read(addr).unwrap();
    /// assert_eq!(value, MAGIC_VALUE);
    /// ```
    ///
    /// Borrowing a mem object:
    /// ```
    /// use memflow::prelude::v1::*;
    /// use memflow::dummy::DummyMemory;
    /// # use memflow::dummy::DummyOs;
    /// # use memflow::architecture::x86::x64;
    ///
    /// fn build<T: MemoryView>(mem: Fwd<&mut T>)
    ///     -> impl MemoryView + '_ {
    ///     CachedView::builder(mem)
    ///         .arch(x64::ARCH)
    ///         .build()
    ///         .unwrap()
    /// }
    ///
    /// # let phys_mem = DummyMemory::new(size::mb(16));
    /// # let mut os = DummyOs::new(phys_mem);
    /// # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
    /// # let phys_mem = os.into_inner();
    /// # let translator = x64::new_translator(dtb);
    /// let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
    /// let mut cached_view = build(virt_mem.forward_mut());
    ///
    /// let read = cached_view.read::<u32>(0.into()).unwrap();
    /// ```
    pub fn new(mem: T) -> Self {
        Self {
            mem,
            validator: DefaultCacheValidator::default(),
            page_size: None,
            cache_size: size::mb(2),
        }
    }
}

impl<T: MemoryView, Q: CacheValidator> CachedViewBuilder<T, Q> {
    /// Builds the [`CachedView`] object or returns an error if the page size is not set.
    pub fn build<'a>(self) -> Result<CachedView<'a, T, Q>> {
        let phys_mem = self.mem.into_phys_mem();

        let cache = CachedPhysicalMemory::new(
            phys_mem,
            PageCache::with_page_size(
                self.page_size.ok_or_else(|| {
                    Error(ErrorOrigin::Cache, ErrorKind::Uninitialized)
                        .log_error("page_size must be initialized")
                })?,
                self.cache_size,
                // we do not know pagetypes on virtual memory so we have to apply this cache to all types
                PageType::all(),
                self.validator,
            ),
        );

        Ok(CachedView {
            mem: cache.into_mem_view(),
        })
    }

    /// Sets a custom validator for the cache.
    ///
    /// If this function is not called it will default to a [`DefaultCacheValidator`].
    /// The default validator for std builds is the [`TimedCacheValidator`].
    /// The default validator for no_std builds is the [`CountCacheValidator`].
    ///
    /// The default setting is `DefaultCacheValidator::default()`.
    ///
    /// # Examples:
    ///
    /// ```
    /// # const MAGIC_VALUE: u64 = 0x23bd_318f_f3a3_5821;
    /// use memflow::prelude::v1::*;
    /// use memflow::dummy::DummyMemory;
    /// use std::time::Duration;
    /// # use memflow::dummy::DummyOs;
    /// # use memflow::architecture::x86::x64;
    ///
    /// # let phys_mem = DummyMemory::new(size::mb(16));
    /// # let mut os = DummyOs::new(phys_mem);
    /// # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
    /// # let phys_mem = os.into_inner();
    /// # let translator = x64::new_translator(dtb);
    /// let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
    ///
    /// let mut cached_mem = CachedView::builder(virt_mem)
    ///     .arch(x64::ARCH)
    ///     .validator(DefaultCacheValidator::new(Duration::from_millis(2000).into()))
    ///     .build()
    ///     .unwrap();
    ///
    /// let addr = virt_base; // some arbitrary address
    ///
    /// cached_mem.write(addr, &MAGIC_VALUE).unwrap();
    ///
    /// let value: u64 = cached_mem.read(addr).unwrap();
    /// assert_eq!(value, MAGIC_VALUE);
    /// ```
    pub fn validator<QN: CacheValidator>(self, validator: QN) -> CachedViewBuilder<T, QN> {
        CachedViewBuilder {
            mem: self.mem,
            validator,
            page_size: self.page_size,
            cache_size: self.cache_size,
        }
    }

    /// Changes the page size of the cache.
    ///
    /// The cache has to know the exact page size of the target system internally to give reasonable performance.
    /// The page size can be either set directly via this function or it can be fetched from the `Architecture`
    /// via the `arch()` method of the builder.
    ///
    /// If the page size is not set the builder will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// # const MAGIC_VALUE: u64 = 0x23bd_318f_f3a3_5821;
    /// use memflow::prelude::v1::*;
    /// use memflow::dummy::DummyMemory;
    /// # use memflow::dummy::DummyOs;
    /// # use memflow::architecture::x86::x64;
    ///
    /// # let phys_mem = DummyMemory::new(size::mb(16));
    /// # let mut os = DummyOs::new(phys_mem);
    /// # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
    /// # let phys_mem = os.into_inner();
    /// # let translator = x64::new_translator(dtb);
    /// let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
    ///
    /// let mut cached_mem = CachedView::builder(virt_mem)
    ///     .page_size(size::kb(4))
    ///     .build()
    ///     .unwrap();
    ///
    /// let addr = virt_base; // some arbitrary address
    ///
    /// cached_mem.write(addr, &MAGIC_VALUE).unwrap();
    ///
    /// let value: u64 = cached_mem.read(addr).unwrap();
    /// assert_eq!(value, MAGIC_VALUE);
    /// ```
    pub fn page_size(mut self, page_size: usize) -> Self {
        self.page_size = Some(page_size);
        self
    }

    /// Retrieves the page size for this cache from the given `Architecture`.
    ///
    /// The cache has to know the exact page size of the target system internally to give reasonable performance.
    /// The page size can be either fetched from the `Architecture` via this method or it can be set directly
    /// via the `page_size()` method of the builder.
    ///
    /// If the page size is not set the builder will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// # const MAGIC_VALUE: u64 = 0x23bd_318f_f3a3_5821;
    /// use memflow::prelude::v1::*;
    /// use memflow::dummy::DummyMemory;
    /// # use memflow::dummy::DummyOs;
    /// # use memflow::architecture::x86::x64;
    ///
    /// # let phys_mem = DummyMemory::new(size::mb(16));
    /// # let mut os = DummyOs::new(phys_mem);
    /// # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
    /// # let phys_mem = os.into_inner();
    /// # let translator = x64::new_translator(dtb);
    /// let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
    ///
    /// let mut cached_mem = CachedView::builder(virt_mem)
    ///     .arch(x64::ARCH)
    ///     .build()
    ///     .unwrap();
    ///
    /// let addr = virt_base; // some arbitrary address
    ///
    /// cached_mem.write(addr, &MAGIC_VALUE).unwrap();
    ///
    /// let value: u64 = cached_mem.read(addr).unwrap();
    /// assert_eq!(value, MAGIC_VALUE);
    /// ```
    pub fn arch(mut self, arch: impl Into<ArchitectureObj>) -> Self {
        self.page_size = Some(arch.into().page_size());
        self
    }

    /// Sets the total amount of cache to be used.
    ///
    /// This is the total amount of cache (in bytes) this page cache will allocate.
    /// Ideally you'd want to keep this value low enough so that most of the cache stays in the lower level caches of your cpu.
    ///
    /// The default setting is 2 megabytes.
    ///
    /// This setting can drastically impact the performance of the cache.
    ///
    /// # Examples:
    ///
    /// ```
    /// # const MAGIC_VALUE: u64 = 0x23bd_318f_f3a3_5821;
    /// use memflow::prelude::v1::*;
    /// use memflow::dummy::DummyMemory;
    /// # use memflow::dummy::DummyOs;
    /// # use memflow::architecture::x86::x64;
    ///
    /// # let phys_mem = DummyMemory::new(size::mb(16));
    /// # let mut os = DummyOs::new(phys_mem);
    /// # let (dtb, virt_base) = os.alloc_dtb(size::mb(8), &[]);
    /// # let phys_mem = os.into_inner();
    /// # let translator = x64::new_translator(dtb);
    /// let mut virt_mem = VirtualDma::new(phys_mem, x64::ARCH, translator);
    ///
    /// let mut cached_mem = CachedView::builder(virt_mem)
    ///     .arch(x64::ARCH)
    ///     .cache_size(size::mb(2))
    ///     .build()
    ///     .unwrap();
    ///
    /// let addr = virt_base; // some arbitrary address
    ///
    /// cached_mem.write(addr, &MAGIC_VALUE).unwrap();
    ///
    /// let value: u64 = cached_mem.read(addr).unwrap();
    /// assert_eq!(value, MAGIC_VALUE);
    /// ```
    pub fn cache_size(mut self, cache_size: usize) -> Self {
        self.cache_size = cache_size;
        self
    }
}