nimrod 0.3.0

Parse and inspect Nim-compiled native binaries
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
//! TNimType (refc GC) reader.
//!
//! Reads all fields of a legacy `TNimType` struct from binary data
//! (RESEARCH.md §3.1). Also walks the `TNimNode` tree to recover field
//! names for object/tuple/enum types.

use crate::{
    container::{Arch, Container},
    rtti::v2::{read_cstring_at_va, read_ptr, va_to_offset},
};

/// `TNimKind` — mirrors `ast.TTypeKind` from `lib/system/hti.nim`.
///
/// Values are the ordinal positions in the enum (0-based). Only the
/// commonly encountered kinds are named; the rest are captured as
/// `Other(u8)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NimKind {
    /// `tyNone` (0)
    None,
    /// `tyBool` (1)
    Bool,
    /// `tyChar` (2)
    Char,
    /// `tyEnum` (14)
    Enum,
    /// `tyArray` (16)
    Array,
    /// `tyObject` (17)
    Object,
    /// `tyTuple` (18)
    Tuple,
    /// `tySet` (19)
    Set,
    /// `tyRange` (20)
    Range,
    /// `tyPtr` (21)
    Ptr,
    /// `tyRef` (22)
    Ref,
    /// `tySequence` (24)
    Sequence,
    /// `tyProc` (25)
    Proc,
    /// `tyPointer` (26)
    Pointer,
    /// `tyString` (28)
    String,
    /// `tyCstring` (29)
    Cstring,
    /// `tyInt` (31)
    Int,
    /// `tyInt8` (32)
    Int8,
    /// `tyInt16` (33)
    Int16,
    /// `tyInt32` (34)
    Int32,
    /// `tyInt64` (35)
    Int64,
    /// `tyFloat` (36)
    Float,
    /// `tyFloat32` (37)
    Float32,
    /// `tyFloat64` (38)
    Float64,
    /// `tyFloat128` (39)
    Float128,
    /// `tyUInt` (40)
    UInt,
    /// `tyUInt8` (41)
    UInt8,
    /// `tyUInt16` (42)
    UInt16,
    /// `tyUInt32` (43)
    UInt32,
    /// `tyUInt64` (44)
    UInt64,
    /// Any other kind not explicitly listed.
    Other(u8),
}

impl NimKind {
    /// Converts a raw ordinal to a `NimKind`.
    pub fn from_raw(raw: u8) -> Self {
        match raw {
            0 => Self::None,
            1 => Self::Bool,
            2 => Self::Char,
            14 => Self::Enum,
            16 => Self::Array,
            17 => Self::Object,
            18 => Self::Tuple,
            19 => Self::Set,
            20 => Self::Range,
            21 => Self::Ptr,
            22 => Self::Ref,
            24 => Self::Sequence,
            25 => Self::Proc,
            26 => Self::Pointer,
            28 => Self::String,
            29 => Self::Cstring,
            31 => Self::Int,
            32 => Self::Int8,
            33 => Self::Int16,
            34 => Self::Int32,
            35 => Self::Int64,
            36 => Self::Float,
            37 => Self::Float32,
            38 => Self::Float64,
            39 => Self::Float128,
            40 => Self::UInt,
            41 => Self::UInt8,
            42 => Self::UInt16,
            43 => Self::UInt32,
            44 => Self::UInt64,
            n => Self::Other(n),
        }
    }

    /// Returns the stable string identifier for this kind.
    ///
    /// [`NimKind::Other`] returns `"Other"`; the raw ordinal is available via
    /// [`TNimTypeFields::kind_raw`].
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::None => "None",
            Self::Bool => "Bool",
            Self::Char => "Char",
            Self::Enum => "Enum",
            Self::Array => "Array",
            Self::Object => "Object",
            Self::Tuple => "Tuple",
            Self::Set => "Set",
            Self::Range => "Range",
            Self::Ptr => "Ptr",
            Self::Ref => "Ref",
            Self::Sequence => "Sequence",
            Self::Proc => "Proc",
            Self::Pointer => "Pointer",
            Self::String => "String",
            Self::Cstring => "Cstring",
            Self::Int => "Int",
            Self::Int8 => "Int8",
            Self::Int16 => "Int16",
            Self::Int32 => "Int32",
            Self::Int64 => "Int64",
            Self::Float => "Float",
            Self::Float32 => "Float32",
            Self::Float64 => "Float64",
            Self::Float128 => "Float128",
            Self::UInt => "UInt",
            Self::UInt8 => "UInt8",
            Self::UInt16 => "UInt16",
            Self::UInt32 => "UInt32",
            Self::UInt64 => "UInt64",
            Self::Other(_) => "Other",
        }
    }
}

impl core::fmt::Display for NimKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// `TNimTypeFlag` — from `lib/system/hti.nim`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NimTypeFlag {
    /// `ntfNoRefs` (bit 0) — type contains no tyRef/tySequence/tyString.
    NoRefs,
    /// `ntfAcyclic` (bit 1) — type cannot form a cycle.
    Acyclic,
    /// `ntfEnumHole` (bit 2) — enum has holes; `$` needs the slow path.
    EnumHole,
}

/// Parsed fields of a legacy `TNimType` RTTI record.
#[derive(Debug, Clone)]
pub struct TNimTypeFields {
    /// Size of the described type in bytes.
    pub size: u64,
    /// Alignment.
    pub align: u64,
    /// Type kind.
    pub kind: NimKind,
    /// Raw kind byte (for round-tripping when `NimKind::Other`).
    pub kind_raw: u8,
    /// Type flags (raw byte, bits 0–2 are `TNimTypeFlag`).
    pub flags_raw: u8,
    /// Parsed type flags.
    pub flags: Vec<NimTypeFlag>,
    /// Virtual address of `base` (parent type), if non-null.
    pub base_addr: Option<u64>,
    /// Virtual address of the `node` (`TNimNode` tree root), if non-null.
    pub node_addr: Option<u64>,
    /// Virtual address of the `finalizer`, if non-null.
    pub finalizer_addr: Option<u64>,
    /// Virtual address of the `marker` proc, if non-null.
    pub marker_addr: Option<u64>,
    /// Virtual address of the `deepcopy` proc, if non-null.
    pub deepcopy_addr: Option<u64>,
    /// The `name` cstring if present (`nimTypeNames` defined).
    pub name: Option<String>,
    /// Field names recovered by walking the `TNimNode` tree (if the node
    /// pointer was valid and the tree was walkable).
    pub node_fields: Vec<NodeField>,
}

/// A field recovered from the `TNimNode` tree.
#[derive(Debug, Clone)]
pub struct NodeField {
    /// Field name (from the `name: cstring` in `TNimNode`).
    pub name: String,
    /// Byte offset of the field within the parent struct.
    pub offset: u64,
    /// Virtual address of the `TNimType` pointer for this field's type,
    /// if non-null.
    pub type_addr: Option<u64>,
}

/// `TNimNodeKind` — from `lib/system/hti.nim`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NodeKind {
    None, // 0
    Slot, // 1
    List, // 2
    Case, // 3
}

impl NodeKind {
    fn from_raw(raw: u8) -> Self {
        match raw {
            0 => Self::None,
            1 => Self::Slot,
            2 => Self::List,
            3 => Self::Case,
            _ => Self::None,
        }
    }
}

/// Reads a `TNimType` struct and optionally walks its `TNimNode` tree.
///
/// The struct layout depends on compile-time flags. We parse the common
/// layout (no `gcHooks`):
///
/// ```text
/// size:      NI
/// align:     NI
/// kind:      u8  (TNimKind)
/// flags:     u8  (set[TNimTypeFlag])
/// <pad to ptr alignment>
/// base:      ptr TNimType
/// node:      ptr TNimNode
/// finalizer: ptr
/// marker:    ptr (proc)
/// deepcopy:  ptr (proc)
/// // conditional fields follow:
/// // typeInfoV2: ptr   (if nimSeqsV2)
/// // name:  cstring    (if nimTypeNames)
/// // nextType: ptr     (if nimTypeNames)
/// // instances: NI     (if nimTypeNames)
/// // sizes: NI         (if nimTypeNames)
/// ```
pub fn read(container: &Container<'_>, va: u64) -> Option<TNimTypeFields> {
    let is_64 = matches!(
        container.arch(),
        Arch::Amd64 | Arch::Aarch64 | Arch::PowerPc64 | Arch::Riscv64
    );
    let ptr_size: usize = if is_64 { 8 } else { 4 };

    let bytes = container.bytes();
    let offset = va_to_offset(container, va)?;

    // Need at least: size + align + kind + flags + pad + 5 pointers
    let min = ptr_size.saturating_mul(7).saturating_add(2);
    if offset.checked_add(min)? > bytes.len() {
        return None;
    }

    let mut pos = offset;

    let size = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let align = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let kind_raw = bytes.get(pos).copied().unwrap_or(0);
    pos = pos.saturating_add(1);

    let flags_raw = bytes.get(pos).copied().unwrap_or(0);
    pos = pos.saturating_add(1);

    // Padding to pointer alignment.
    let misalign = pos.wrapping_sub(offset).checked_rem(ptr_size).unwrap_or(0);
    if misalign != 0 {
        pos = pos.saturating_add(ptr_size.saturating_sub(misalign));
    }

    let base = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let node = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let finalizer = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let marker = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let deepcopy = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    // Try to find the `name` cstring. There may be a `typeInfoV2` pointer
    // first (if nimSeqsV2 is defined). We probe both positions.
    let name = try_read_name(container, bytes, pos, is_64).or_else(|| {
        pos.checked_add(ptr_size)
            .and_then(|p| try_read_name(container, bytes, p, is_64))
    });

    // Parse flags.
    let mut flags = Vec::new();
    if flags_raw & (1 << 0) != 0 {
        flags.push(NimTypeFlag::NoRefs);
    }
    if flags_raw & (1 << 1) != 0 {
        flags.push(NimTypeFlag::Acyclic);
    }
    if flags_raw & (1 << 2) != 0 {
        flags.push(NimTypeFlag::EnumHole);
    }

    // Walk the TNimNode tree for field names.
    let node_fields = if node != 0 {
        walk_node_tree(container, bytes, node, is_64, ptr_size, 0)
    } else {
        Vec::new()
    };

    Some(TNimTypeFields {
        size,
        align,
        kind: NimKind::from_raw(kind_raw),
        kind_raw,
        flags_raw,
        flags,
        base_addr: if base != 0 { Some(base) } else { None },
        node_addr: if node != 0 { Some(node) } else { None },
        finalizer_addr: if finalizer != 0 {
            Some(finalizer)
        } else {
            None
        },
        marker_addr: if marker != 0 { Some(marker) } else { None },
        deepcopy_addr: if deepcopy != 0 { Some(deepcopy) } else { None },
        name,
        node_fields,
    })
}

fn try_read_name(
    container: &Container<'_>,
    bytes: &[u8],
    pos: usize,
    is_64: bool,
) -> Option<String> {
    let name_ptr = read_ptr(bytes, pos, is_64);
    let name = read_cstring_at_va(container, bytes, name_ptr)?;
    // Basic validation: type names should be printable ASCII.
    if name.bytes().all(|b| (0x20..0x7F).contains(&b)) && !name.is_empty() {
        Some(name)
    } else {
        None
    }
}

/// Recursively walks a `TNimNode` tree, collecting field entries.
///
/// `TNimNode` layout:
/// ```text
/// kind:   u8 (TNimNodeKind: 0=nkNone, 1=nkSlot, 2=nkList, 3=nkCase)
/// <pad>
/// offset: NI
/// typ:    ptr TNimType
/// name:   cstring
/// len:    NI
/// sons:   ptr array[0x7fff, ptr TNimNode]
/// ```
fn walk_node_tree(
    container: &Container<'_>,
    bytes: &[u8],
    node_va: u64,
    is_64: bool,
    ptr_size: usize,
    depth: usize,
) -> Vec<NodeField> {
    // Guard against infinite recursion on malformed data.
    if depth > 16 {
        return Vec::new();
    }

    let Some(off) = va_to_offset(container, node_va) else {
        return Vec::new();
    };

    // Minimum node size: kind(1) + pad + offset + typ + name + len + sons
    let min = ptr_size.saturating_mul(5).saturating_add(1);
    let Some(end) = off.checked_add(min) else {
        return Vec::new();
    };
    if end > bytes.len() {
        return Vec::new();
    }

    let mut pos = off;

    let kind_raw = bytes.get(pos).copied().unwrap_or(0);
    let kind = NodeKind::from_raw(kind_raw);
    pos = pos.saturating_add(1);

    // Pad to pointer alignment.
    let misalign = pos.wrapping_sub(off).checked_rem(ptr_size).unwrap_or(0);
    if misalign != 0 {
        pos = pos.saturating_add(ptr_size.saturating_sub(misalign));
    }

    let field_offset = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let typ = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let name_ptr = read_ptr(bytes, pos, is_64);
    pos = pos.saturating_add(ptr_size);

    let len = read_ptr(bytes, pos, is_64) as usize;
    pos = pos.saturating_add(ptr_size);

    let sons_ptr = read_ptr(bytes, pos, is_64);

    let mut result = Vec::new();

    match kind {
        NodeKind::Slot => {
            // A single field.
            if let Some(name) = read_cstring_at_va(container, bytes, name_ptr) {
                result.push(NodeField {
                    name,
                    offset: field_offset,
                    type_addr: if typ != 0 { Some(typ) } else { None },
                });
            }
        }
        NodeKind::List => {
            // A list of child nodes. `len` is the count, `sons` points to
            // an array of `len` pointers to TNimNode.
            if sons_ptr != 0
                && len > 0
                && len <= 4096
                && let Some(sons_off) = va_to_offset(container, sons_ptr)
            {
                for i in 0..len {
                    let Some(child_ptr_off) = i
                        .checked_mul(ptr_size)
                        .and_then(|d| sons_off.checked_add(d))
                    else {
                        break;
                    };
                    let child_va = read_ptr(bytes, child_ptr_off, is_64);
                    if child_va != 0 {
                        let child_fields = walk_node_tree(
                            container,
                            bytes,
                            child_va,
                            is_64,
                            ptr_size,
                            depth.saturating_add(1),
                        );
                        result.extend(child_fields);
                    }
                }
            }
        }
        NodeKind::Case => {
            // A variant/case node. The `sons` array contains branches.
            // We walk all branches to collect all possible fields.
            if sons_ptr != 0
                && len > 0
                && len <= 4096
                && let Some(sons_off) = va_to_offset(container, sons_ptr)
            {
                for i in 0..len {
                    let Some(child_ptr_off) = i
                        .checked_mul(ptr_size)
                        .and_then(|d| sons_off.checked_add(d))
                    else {
                        break;
                    };
                    let child_va = read_ptr(bytes, child_ptr_off, is_64);
                    if child_va != 0 {
                        let child_fields = walk_node_tree(
                            container,
                            bytes,
                            child_va,
                            is_64,
                            ptr_size,
                            depth.saturating_add(1),
                        );
                        result.extend(child_fields);
                    }
                }
            }
        }
        NodeKind::None => {}
    }

    result
}