vmi-os-linux 0.13.0

Linux OS specific code for VMI
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! A MapleTree implementation based on the Linux kernel's data structure.
//!
//! The Maple Tree is a data structure used in the Linux kernel for efficiently storing
//! and searching ranges of values. It's particularly used for managing virtual memory
//! areas (VMAs) in the memory management subsystem.
//!
//! # References
//!
//! - [Linux Kernel Source - maple_tree.c](https://elixir.bootlin.com/linux/v6.10.5/source/lib/maple_tree.c)
//! - [Linux Kernel Source - maple_tree.h](https://elixir.bootlin.com/linux/v6.10.5/source/include/linux/maple_tree.h)
//! - [Process Address Space Documentation](https://students.mimuw.edu.pl/ZSO/Wyklady/04_processes2/ProcessAddressSpace.pdf)
//! - [Maple Tree: Storing Ranges](https://blogs.oracle.com/linux/post/maple-tree-storing-ranges)
//! - [Kernel Documentation - Maple Tree](https://docs.kernel.org/core-api/maple_tree.html)

#![allow(dead_code)]
use vmi_core::{Registers as _, Va, VmiError, VmiState, VmiVa, driver::VmiRead};

use crate::{LinuxOs, Offsets, arch::ArchAdapter};

/// Represents different node types in a Maple Tree.
#[derive(Debug)]
enum MapleType {
    /// Dense nodes contain directly addressable slots.
    Dense,

    /// Leaf nodes.
    Leaf64,

    /// Range nodes.
    Range64,

    /// Allocation range nodes.
    Arange64,
}

/// Create an internal entry.
/// @v: Value to turn into an internal entry.
///
/// Internal entries are used for a number of purposes.  Entries 0-255 are
/// used for sibling entries (only 0-62 are used by the current code).  256
/// is used for the retry entry.  257 is used for the reserved / zero entry.
/// Negative internal entries are used to represent errnos.  Node pointers
/// are also tagged as internal entries in some situations.
///
/// Context: Any context.
/// Return: An XArray internal entry corresponding to this value.
const fn xa_mk_internal(v: u64) -> Va {
    Va::new((v << 2) | 2)
}

/// Extract the value from an internal entry.
/// @entry: XArray entry.
///
/// Context: Any context.
/// Return: The value which was stored in the internal entry.
const fn xa_to_internal(entry: Va) -> u64 {
    entry.0 >> 2
}

/// Is the entry an internal entry?
/// @entry: XArray entry.
///
/// Context: Any context.
/// Return: %true if the entry is an internal entry.
const fn xa_is_internal(entry: Va) -> bool {
    (entry.0 & 3) == 2
}

/// Is the entry a zero entry?
/// @entry: Entry retrieved from the XArray
///
/// The normal API will return NULL as the contents of a slot containing
/// a zero entry.  You can only see zero entries by using the advanced API.
///
/// Return: %true if the entry is a zero entry.
const fn xa_is_zero(entry: Va) -> bool {
    const XA_ZERO_ENTRY: Va = xa_mk_internal(257);
    entry.0 == XA_ZERO_ENTRY.0
}

/// Get value stored in an XArray entry.
/// @entry: XArray entry.
///
/// Context: Any context.
/// Return: The value stored in the XArray entry.
const fn xa_to_value(entry: Va) -> u64 {
    entry.0 >> 1
}

/// Determine if an entry is a value.
/// @entry: XArray entry.
///
/// Context: Any context.
/// Return: True if the entry is a value, false if it is a pointer.
const fn xa_is_value(entry: Va) -> bool {
    (entry.0 & 1) == 1
}

const fn xa_is_node(entry: Va) -> bool {
    xa_is_internal(entry) && entry.0 > 4096
}

const fn mt_flags_height(ma_flags: u32) -> u32 {
    const MT_FLAGS_HEIGHT_OFFSET: u32 = 0x02;
    const MT_FLAGS_HEIGHT_MASK: u32 = 0x7C;

    (ma_flags & MT_FLAGS_HEIGHT_MASK) >> MT_FLAGS_HEIGHT_OFFSET
}

/// We also reserve values with the bottom two bits set to '10' which are
/// below 4096
const fn mt_is_reserved(entry: Va /* void* */) -> bool {
    const MAPLE_RESERVED_RANGE: u64 = 4096;
    (entry.0 < MAPLE_RESERVED_RANGE) && xa_is_internal(entry)
}

const fn mt_node_max(entry: Va) -> Option<u64> {
    match mte_node_type(entry) {
        Some(MapleType::Dense) => Some(31),
        Some(MapleType::Leaf64) => Some(u64::MAX),
        Some(MapleType::Range64) => Some(u64::MAX),
        Some(MapleType::Arange64) => Some(u64::MAX),
        None => None,
    }
}

const fn mte_node_type(entry: Va /* maple_enode */) -> Option<MapleType> {
    const MAPLE_NODE_TYPE_MASK: u64 = 0x0F;
    const MAPLE_NODE_TYPE_SHIFT: u64 = 0x03;
    match (entry.0 >> MAPLE_NODE_TYPE_SHIFT) & MAPLE_NODE_TYPE_MASK {
        0x00 => Some(MapleType::Dense),
        0x01 => Some(MapleType::Leaf64),
        0x02 => Some(MapleType::Range64),
        0x03 => Some(MapleType::Arange64),
        _ => None,
    }
}

const fn ma_is_leaf(typ: MapleType) -> bool {
    matches!(typ, MapleType::Dense | MapleType::Leaf64)
}

const fn mte_to_node(entry: Va /* maple_enode */) -> Va {
    const MAPLE_NODE_MASK: u64 = 255;
    Va::new(entry.0 & !MAPLE_NODE_MASK)
}

const fn mte_is_leaf(entry: Va /* maple_enode */) -> bool {
    match mte_node_type(entry) {
        Some(typ) => ma_is_leaf(typ),
        None => false,
    }
}

/// A MapleTree traversal and manipulation implementation.
///
/// This struct provides methods for traversing and inspecting Linux kernel
/// Maple Trees, which are used primarily for managing virtual memory areas.
pub struct MapleTree<'a, Driver>
where
    Driver: VmiRead,
    Driver::Architecture: ArchAdapter<Driver>,
{
    /// The VMI state.
    vmi: VmiState<'a, LinuxOs<Driver>>,

    /// The virtual address of the Maple Tree root.
    root: Va,
}

impl<Driver> VmiVa for MapleTree<'_, Driver>
where
    Driver: VmiRead,
    Driver::Architecture: ArchAdapter<Driver>,
{
    fn va(&self) -> Va {
        self.root
    }
}

impl<'a, Driver> MapleTree<'a, Driver>
where
    Driver: VmiRead,
    Driver::Architecture: ArchAdapter<Driver>,
{
    /// Creates a new MapleTree instance.
    pub fn new(vmi: VmiState<'a, LinuxOs<Driver>>, root: Va) -> Self {
        Self { vmi, root }
    }

    fn offsets(&self) -> &Offsets {
        &self.vmi.underlying_os().offsets
    }

    // region: Enumerate

    /// Enumerates all entries in the Maple Tree.
    ///
    /// Traverses the tree structure and calls the provided callback for each entry found.
    pub fn enumerate(&self, mut callback: impl FnMut(Va) -> bool) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_tree = &offsets.maple_tree;

        let entry = self
            .vmi
            .read_va_native(self.root + __maple_tree.ma_root.offset())?;

        if !xa_is_node(entry) {
            self.enumerate_entry(entry, &mut callback);
        }
        else if !entry.is_null() {
            self.enumerate_node(self.root, entry, 0, u64::MAX, &mut callback)?;
        }

        Ok(())
    }

    fn enumerate_entry(&self, entry: Va, callback: &mut impl FnMut(Va) -> bool) {
        if xa_is_value(entry) {
            callback(Va(xa_to_value(entry)));
        }
        else if xa_is_zero(entry) {
            callback(Va(xa_to_internal(entry)));
        }
        else {
            callback(entry);
        }
    }

    fn enumerate_node(
        &self,
        mt: Va,
        entry: Va,
        min: u64,
        max: u64,
        callback: &mut impl FnMut(Va) -> bool,
    ) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_tree = &offsets.maple_tree;
        let __maple_node = &offsets.maple_node;

        let node = mte_to_node(entry);
        let typ = mte_node_type(entry);

        match typ {
            Some(MapleType::Dense) => {
                // const MAPLE_NODE_SLOTS: u64 = 63;   // 32 bit OS
                const MAPLE_NODE_SLOTS: u64 = 31; // 64 bit OS
                for i in 0..MAPLE_NODE_SLOTS {
                    let slot = self
                        .vmi
                        .read_va_native(node + __maple_node.slot.offset() + i * 8)?;

                    if !slot.is_null() {
                        self.enumerate_entry(slot, callback);
                    }
                }
            }
            Some(MapleType::Leaf64 | MapleType::Range64) => {
                self.enumerate_range64(mt, entry, min, max, callback)?;
            }
            Some(MapleType::Arange64) => {
                self.enumerate_arange64(mt, entry, min, max, callback)?;
            }
            None => tracing::warn!(?typ, "unknown node type"),
        }

        Ok(())
    }

    fn enumerate_range64(
        &self,
        mt: Va,
        entry: Va,
        min: u64,
        max: u64,
        callback: &mut impl FnMut(Va) -> bool,
    ) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_node = &offsets.maple_node;
        let __maple_range_64 = &offsets.maple_range_64;

        let node = mte_to_node(entry) + __maple_node.mr64.offset();
        let leaf = mte_is_leaf(entry);
        let mut first = min;

        const MAPLE_RANGE64_SLOTS_32: u64 = 32; // 32 bit OS
        const MAPLE_RANGE64_SLOTS_64: u64 = 16; // 64 bit OS

        #[expect(non_snake_case)]
        let MAPLE_RANGE64_SLOTS = match self.vmi.registers().address_width() {
            4 => MAPLE_RANGE64_SLOTS_32,
            8 => MAPLE_RANGE64_SLOTS_64,
            _ => 0,
        };

        let __pivot = |i: u64| {
            let offset = i * self.vmi.registers().address_width() as u64;
            self.vmi
                .read_va_native(node + __maple_range_64.pivot.offset() + offset)
                .map(u64::from)
        };

        let __slot = |i: u64| {
            let offset = i * self.vmi.registers().address_width() as u64;
            self.vmi
                .read_va_native(node + __maple_range_64.slot.offset() + offset)
        };

        for i in 0..MAPLE_RANGE64_SLOTS {
            let mut last = max;

            if i < (MAPLE_RANGE64_SLOTS - 1) {
                last = __pivot(i)?;
            }
            else {
                let slot = __slot(i)?;
                if slot.is_null() && Some(max) != mt_node_max(entry) {
                    break;
                }
            }

            if last == 0 && i > 0 {
                break;
            }

            let slot = __slot(i)?;

            if leaf {
                self.enumerate_entry(slot, callback)
            }
            else if !slot.is_null() {
                self.enumerate_node(mt, slot, first, last, callback)?;
            }

            if last == max {
                break;
            }

            first = last + 1;
        }

        Ok(())
    }

    fn enumerate_arange64(
        &self,
        mt: Va,
        entry: Va,
        min: u64,
        max: u64,
        callback: &mut impl FnMut(Va) -> bool,
    ) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_node = &offsets.maple_node;
        let __maple_arange_64 = &offsets.maple_arange_64;

        let node = mte_to_node(entry) + __maple_node.ma64.offset();
        let leaf = mte_is_leaf(entry);
        let mut first = min;

        const MAPLE_ARANGE64_SLOTS_32: u64 = 21; // 32 bit OS
        const MAPLE_ARANGE64_SLOTS_64: u64 = 10; // 64 bit OS

        #[expect(non_snake_case)]
        let MAPLE_ARANGE64_SLOTS = match self.vmi.registers().address_width() {
            4 => MAPLE_ARANGE64_SLOTS_32,
            8 => MAPLE_ARANGE64_SLOTS_64,
            _ => 0,
        };

        let __pivot = |i: u64| {
            let offset = i * self.vmi.registers().address_width() as u64;
            self.vmi
                .read_va_native(node + __maple_arange_64.pivot.offset() + offset)
                .map(u64::from)
        };

        let __slot = |i: u64| {
            let offset = i * self.vmi.registers().address_width() as u64;
            self.vmi
                .read_va_native(node + __maple_arange_64.slot.offset() + offset)
        };

        for i in 0..MAPLE_ARANGE64_SLOTS {
            let mut last = max;

            if i < (MAPLE_ARANGE64_SLOTS - 1) {
                last = __pivot(i)?;
            }
            else {
                let slot = __slot(i)?;
                if slot.is_null() {
                    break;
                }
            }

            if last == 0 && i > 0 {
                break;
            }

            let slot = __slot(i)?;

            if leaf {
                self.enumerate_entry(slot, callback)
            }
            else if !slot.is_null() {
                self.enumerate_node(mt, slot, first, last, callback)?;
            }

            if last == max {
                break;
            }

            first = last + 1;
        }

        Ok(())
    }

    // endregion

    // region: Dump

    /// Dumps the entire Maple Tree structure for debugging.
    pub fn dump(&self) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_tree = &offsets.maple_tree;

        let flags = self
            .vmi
            .read_u32(self.root + __maple_tree.ma_flags.offset())?;
        let entry = self
            .vmi
            .read_va_native(self.root + __maple_tree.ma_root.offset())?;

        println!(
            "maple_tree({}) flags {:X}, height {} root {:X}",
            self.root,
            flags,
            mt_flags_height(flags),
            entry
        );

        if !xa_is_node(entry) {
            self.dump_entry(entry, 0, 0, 0);
        }
        else if !entry.is_null() {
            self.dump_node(self.root, entry, 0, u64::MAX, 0)?;
        }

        Ok(())
    }

    fn dump_range(&self, min: u64, max: u64, depth: u64) {
        if min == max {
            println!("{:width$}{:X}: ", "", min, width = (depth * 2) as usize);
        }
        else {
            println!(
                "{:width$}{:X}-{:X}: ",
                "",
                min,
                max,
                width = (depth * 2) as usize
            );
        }
    }

    fn dump_entry(&self, entry: Va, _min: u64, _max: u64, depth: u64) {
        print!("{:width$}", "", width = (depth * 2) as usize);

        if xa_is_value(entry) {
            println!("Value: {:#x}", xa_to_value(entry));
        }
        else if xa_is_zero(entry) {
            println!("Zero: {:?}", xa_to_internal(entry));
        }
        else if mt_is_reserved(entry) {
            println!("Reserved: {:?}", entry);
        }
        else {
            println!("{:?}", entry);
            if entry.is_null() {
                return;
            }

            let offsets = self.offsets();
            let __vm_area_struct = &offsets.vm_area_struct;

            let start = self
                .vmi
                .read_u64(entry + __vm_area_struct.vm_start.offset());
            let end = self.vmi.read_u64(entry + __vm_area_struct.vm_end.offset());
            let file = self
                .vmi
                .read_va_native(entry + __vm_area_struct.vm_file.offset());
            println!("Range: {:X?}-{:X?}", start, end);

            if let Ok(file) = file
                && !file.is_null()
            {
                let __dentry = &offsets.dentry;
                let __file = &offsets.file;
                let __path = &offsets.path;
                let __qstr = &offsets.qstr;

                let f_path = file + __file.f_path.offset();

                if let Ok(dentry) = self.vmi.read_va_native(f_path + __path.dentry.offset())
                    && let Ok(d_name) = self
                        .vmi
                        .read_va_native(dentry + __dentry.d_name.offset() + __qstr.name.offset())
                {
                    let name = self.vmi.read_string(d_name);
                    println!("    File: {:?}", name);
                }
            }
        }
    }

    fn dump_node(&self, mt: Va, entry: Va, min: u64, max: u64, depth: u64) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_tree = &offsets.maple_tree;
        let __maple_node = &offsets.maple_node;

        let node = mte_to_node(entry);
        let typ = mte_node_type(entry);

        self.dump_range(min, max, depth);

        println!(
            "node {:X} depth {} type {:?} parent {:?}",
            node,
            depth,
            mte_node_type(entry),
            if !node.is_null() {
                self.vmi.read_va_native(node + __maple_node.parent.offset())
            }
            else {
                Ok(Va::default())
            }
        );

        match typ {
            Some(MapleType::Dense) => {
                // const MAPLE_NODE_SLOTS: u64 = 63;   // 32 bit OS
                const MAPLE_NODE_SLOTS: u64 = 31; // 64 bit OS
                for i in 0..MAPLE_NODE_SLOTS {
                    let slot = self
                        .vmi
                        .read_va_native(node + __maple_node.slot.offset() + i * 8)?;

                    if !slot.is_null() {
                        self.dump_entry(slot, min, max, depth);
                    }
                }
            }
            Some(MapleType::Leaf64 | MapleType::Range64) => {
                self.dump_range64(mt, entry, min, max, depth)?;
            }
            Some(MapleType::Arange64) => {
                self.dump_arange64(mt, entry, min, max, depth)?;
            }
            None => tracing::warn!(?typ, "unknown node type"),
        }

        Ok(())
    }

    fn dump_range64(
        &self,
        mt: Va,
        entry: Va,
        min: u64,
        max: u64,
        depth: u64,
    ) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_node = &offsets.maple_node;
        let __maple_range_64 = &offsets.maple_range_64;

        let node = mte_to_node(entry) + __maple_node.mr64.offset();
        let leaf = mte_is_leaf(entry);
        let mut first = min;

        // const MAPLE_RANGE64_SLOTS: u64 = 32;   // 32 bit OS
        const MAPLE_RANGE64_SLOTS: u64 = 16; // 64 bit OS

        let __pivot = |i: u64| {
            let offset = i * size_of::<u64>() as u64;
            self.vmi
                .read_u64(node + __maple_range_64.pivot.offset() + offset)
        };

        let __slot = |i: u64| {
            let offset = i * self.vmi.registers().address_width() as u64;
            self.vmi
                .read_va_native(node + __maple_range_64.slot.offset() + offset)
        };

        for i in 0..MAPLE_RANGE64_SLOTS - 1 {
            println!("pivot {:X} slot {:X}", __pivot(i)?, __slot(i)?);
        }
        println!("slot {:X}", __slot(MAPLE_RANGE64_SLOTS - 1)?);

        for i in 0..MAPLE_RANGE64_SLOTS {
            let mut last = max;

            if i < (MAPLE_RANGE64_SLOTS - 1) {
                last = __pivot(i)?;
            }
            else {
                let slot = __slot(i)?;
                if slot.is_null() && Some(max) != mt_node_max(entry) {
                    break;
                }
            }

            if last == 0 && i > 0 {
                break;
            }

            let slot = __slot(i)?;

            if leaf {
                self.dump_entry(slot, first, last, depth + 1)
            }
            else if !slot.is_null() {
                self.dump_node(mt, slot, first, last, depth + 1)?;
            }

            if last == max {
                break;
            }

            first = last + 1;
        }

        Ok(())
    }

    fn dump_arange64(
        &self,
        mt: Va,
        entry: Va,
        min: u64,
        max: u64,
        depth: u64,
    ) -> Result<(), VmiError> {
        let offsets = self.offsets();
        let __maple_node = &offsets.maple_node;
        let __maple_arange_64 = &offsets.maple_arange_64;

        let node = mte_to_node(entry) + __maple_node.ma64.offset();
        let leaf = mte_is_leaf(entry);
        let mut first = min;

        // const MAPLE_ARANGE64_SLOTS: u64 = 21;   // 32 bit OS
        const MAPLE_ARANGE64_SLOTS: u64 = 10; // 64 bit OS

        let __pivot = |i: u64| {
            let offset = i * size_of::<u64>() as u64;
            self.vmi
                .read_u64(node + __maple_arange_64.pivot.offset() + offset)
        };

        let __slot = |i: u64| {
            let offset = i * self.vmi.registers().address_width() as u64;
            self.vmi
                .read_va_native(node + __maple_arange_64.slot.offset() + offset)
        };

        for i in 0..MAPLE_ARANGE64_SLOTS - 1 {
            println!("pivot {:X} slot {:X}", __pivot(i)?, __slot(i)?);
        }
        println!("slot {:X}", __slot(MAPLE_ARANGE64_SLOTS - 1)?);

        for i in 0..MAPLE_ARANGE64_SLOTS {
            let mut last = max;

            if i < (MAPLE_ARANGE64_SLOTS - 1) {
                last = __pivot(i)?;
            }
            else {
                let slot = __slot(i)?;
                if slot.is_null() {
                    break;
                }
            }

            if last == 0 && i > 0 {
                break;
            }

            let slot = __slot(i)?;

            if leaf {
                self.dump_entry(slot, first, last, depth + 1)
            }
            else if !slot.is_null() {
                self.dump_node(mt, slot, first, last, depth + 1)?;
            }

            if last == max {
                break;
            }

            first = last + 1;
        }

        Ok(())
    }

    // endregion
}