idakit 0.2.0

Idiomatic Rust bindings for IDA Pro's idalib kernel
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
//! Walks a database's named types and function prototypes into [`Type`], an owned, `Send`
//! snapshot backed by an interned [`TypeTable`].
//!
//! The structured counterpart to a rendered declaration string. The root [`TypeId`] and every
//! member/parameter it references are real handles into [`types`](Type::types), so a caller
//! inspects a struct's fields or a prototype's parameters by shape, not by parsing text.
//! Materialized on the kernel thread and handed back owned, so it analyzes anywhere: the type
//! analogue of the decompiler's [`Ctree`](crate::decompiler::ctree::Ctree).

use std::cell::OnceCell;
use std::fmt;
use std::hash::{Hash, Hasher};

use idakit_sys as sys;
use serde::{Deserialize, Serialize};

use super::diff::TypeKey;
use super::{
    SinkAdapter, TypeBuilder, TypeId, TypeMember, TypeShape, TypeSink, TypeTable, TypeValue, tid,
};
use crate::Database;
use crate::address::Address;
use crate::decompiler::ctree::ExtractError;
use crate::error::{Error, Result};

impl Database {
    /// Resolves a named type into an owned [`Type`], its structured shape and every member's type
    /// interned in one [`TypeTable`].
    ///
    /// # Errors
    /// [`Error::TypeNotFound`] if no such type exists, or [`Error::Extract`] if the walked table is
    /// malformed.
    #[doc(alias("get_named_type"))]
    pub fn type_named(&self, name: &str) -> Result<Type> {
        crate::claim::ensure_kernel_thread();
        match walk_type(|sink| sys::walk_type_named(name, sink)) {
            Ok(Some(image)) => Ok(image),
            Ok(None) => Err(Error::TypeNotFound {
                name: name.to_owned(),
            }),
            // A malformed local type is near-unreachable and address-less; 0 stands in.
            Err(source) => Err(Error::Extract { address: 0, source }),
        }
    }

    /// Reads and resolves the `tinfo_t` attached to `address` into an owned [`Type`].
    ///
    /// Not restricted to a function entry: `get_tinfo` reports whatever type IDA has attached to
    /// `address`, a function's prototype or a global variable's declared type alike. `Ok(None)` if
    /// the kernel has no type info there.
    ///
    /// ```
    /// # idakit::doctest::with_db(|db| {
    /// use idakit::types::TypeShape;
    ///
    /// let entry = db.functions().next().unwrap().address();
    /// if let Some(ty) = db.type_at(entry)? {
    ///     assert!(matches!(ty.shape(), TypeShape::Function { .. }));
    /// }
    /// # Ok(())
    /// # }).unwrap();
    /// ```
    ///
    /// # Errors
    /// [`Error::Extract`] if the walked type is malformed.
    #[doc(alias("get_tinfo"))]
    pub fn type_at(&self, address: Address) -> Result<Option<Type>> {
        // get_tinfo(address) is address-generic, not function-specific, so this reuses the same
        // driver `Function::prototype_type` does.
        crate::claim::ensure_kernel_thread();
        walk_type(|sink| sys::walk_func_type(address.get(), sink)).map_err(|source| {
            Error::Extract {
                address: address.get(),
                source,
            }
        })
    }
}

/// An owned, `Send` snapshot of one resolved type.
///
/// A [`root`](Self::root) [`TypeId`] into an interned [`TypeTable`] holding it and every type it
/// references. Read from the database through [`Database::type_named`] or
/// [`Function::prototype_type`](crate::function::Function::prototype_type), then walk it via
/// [`shape`](Self::shape)/[`members`](Self::members) and resolve child handles with
/// [`get`](Self::get). Detached from the kernel, so it inspects on any thread.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[doc(alias("tinfo_t"))]
pub struct Type {
    types: TypeTable,
    root: TypeId,
    /// Cached strict [`TypeKey`], computed once on first [`key`](Self::key) (or `==`/`Hash`) and
    /// held in a `OnceCell` so `Type` stays `Send` (see the `assert_send` proof in tests); not
    /// real source data, so it's skipped on serialize and recomputed lazily after deserialize.
    #[serde(skip)]
    key: OnceCell<TypeKey>,
}

impl Type {
    /// This type's stable [`TypeKey`] under the strict policy: the cross-database fingerprint.
    ///
    /// Computed once (walking and hashing the tree) and cached for every later use, including the
    /// equality and hashing below.
    #[must_use]
    pub fn key(&self) -> TypeKey {
        *self.key.get_or_init(|| self.canonical().key())
    }

    /// The handle of the type this image was built for: the named type, or the function prototype
    /// (a [`TypeShape::Function`]).
    #[inline]
    #[must_use]
    pub const fn root(&self) -> TypeId {
        self.root
    }

    /// The interned table backing every handle in this image. Its own arena, materialized on the
    /// kernel thread, so it resolves types on any thread.
    #[inline]
    #[must_use]
    pub const fn types(&self) -> &TypeTable {
        &self.types
    }

    /// Resolve any handle from this image to its type. Handles come from this image's own
    /// [`types`](Self::types) table, so this never panics on a handle taken from `self`.
    #[inline]
    #[must_use]
    pub fn get(&self, id: TypeId) -> &TypeValue {
        self.types.get(id)
    }

    /// The [`root`](Self::root) type's shape: a shortcut for `self.get(self.root()).shape`.
    #[inline]
    #[must_use]
    pub fn shape(&self) -> &TypeShape {
        &self.types.get(self.root).shape
    }

    /// The root type's size in bytes, or `None` for an incomplete/sizeless type.
    #[inline]
    #[must_use]
    pub fn size(&self) -> Option<u64> {
        self.types.get(self.root).size
    }

    /// The root's fields when it is a struct or union, in declaration order; `None` for any other
    /// shape. Each [`TypeMember::ty`] resolves against [`get`](Self::get).
    #[inline]
    #[must_use]
    pub fn members(&self) -> Option<&[TypeMember]> {
        match self.shape() {
            TypeShape::Struct { members, .. } | TypeShape::Union { members, .. } => Some(members),
            _ => None,
        }
    }
}

/// Structural identity. Two `Type`s are equal when their strict canonical [`key`](Type::key)s
/// match, so a type resolved from one database equals the same type from another even though their
/// [`TypeId`] arenas are unrelated.
impl PartialEq for Type {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.key() == other.key()
    }
}

impl Eq for Type {}

impl Hash for Type {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.key().hash(state);
    }
}

impl fmt::Display for Type {
    /// The canonical one-line form (see [`CanonicalType`](crate::types::diff::CanonicalType)).
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.canonical())
    }
}

/// Accumulates a standalone type walk: the shared [`TypeBuilder`] the walker interns into.
struct ResolvedTypeBuilder {
    types: TypeBuilder,
}

impl TypeSink for ResolvedTypeBuilder {
    fn type_builder(&mut self) -> &mut TypeBuilder {
        &mut self.types
    }
}

/// Drive a standalone-type `cxx` walk into a [`Type`]. `run` invokes the chosen driver (a
/// named-type, ordinal, or function-prototype walk) with the sink to intern into, returning the
/// root handle. `Ok(None)` when the driver reports no such type (`None`); `Err` when the walked
/// table is malformed. Callers map the [`ExtractError`] to their own boundary (an address, a type
/// name).
pub(crate) fn walk_type(
    run: impl FnOnce(&mut dyn sys::TypeWalkSink) -> Option<u32>,
) -> core::result::Result<Option<Type>, ExtractError> {
    let mut b = ResolvedTypeBuilder {
        types: TypeBuilder::new(),
    };
    // Scope the adapter so its borrow of `b` ends before the table is validated below.
    let root = run(&mut SinkAdapter(&mut b));
    let Some(root) = root else {
        return Ok(None);
    };
    // The builder is error-type-agnostic (see the ctree walk): surface an over-wide scalar or an
    // unfilled placeholder rather than shipping a malformed table.
    if let Some(bytes) = b.types.too_wide() {
        return Err(ExtractError::ScalarTooWide { bytes });
    }
    let unfilled = b.types.unfilled();
    if unfilled != 0 {
        return Err(ExtractError::UnfilledType { count: unfilled });
    }
    Ok(Some(Type {
        root: tid(root),
        types: b.types.into_table(),
        key: OnceCell::new(),
    }))
}

#[cfg(test)]
mod tests {
    use assert2::assert;

    use super::*;
    use crate::types::diff::{AggregateKind, TypeIdentity};

    const fn assert_send<T: Send>() {}

    // A Type must cross the kernel thread; a later non-Send field would fail this.
    const _: () = assert_send::<Type>();

    fn u32_type(types: &mut TypeTable) -> TypeId {
        types.intern(TypeValue {
            shape: TypeShape::Int {
                bytes: 4,
                signed: false,
            },
            size: Some(4),
        })
    }

    /// A struct root exposes its shape, size, and members, and member handles resolve against the
    /// same table.
    #[test]
    fn image_exposes_root_shape_and_members() {
        let mut types = TypeTable::new();
        let field = u32_type(&mut types);
        let root = types.intern(TypeValue {
            shape: TypeShape::Struct {
                name: Some("pt".into()),
                members: vec![TypeMember {
                    name: "x".into(),
                    bit_offset: 0,
                    ty: field,
                    bitfield_width: None,
                    repr: None,
                }],
            },
            size: Some(4),
        });
        let img = Type {
            types,
            root,
            key: OnceCell::new(),
        };

        assert!(img.root() == root);
        assert!(img.size() == Some(4));
        assert!(let TypeShape::Struct { .. } = img.shape());
        let members = img.members().expect("a struct has members");
        assert!(members.len() == 1);
        assert!(
            img.get(members[0].ty).shape
                == TypeShape::Int {
                    bytes: 4,
                    signed: false,
                }
        );
    }

    /// Structural identity: equal types compare and hash equal, different types differ, and
    /// `Display` renders the canonical form. A no-op `eq`, a flipped `==`, a `hash` that writes
    /// nothing, or an empty `Display` all fail here.
    #[test]
    fn equality_hashing_and_display_track_structure() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        fn scalar_image(signed: bool) -> Type {
            let mut types = TypeTable::new();
            let root = types.intern(TypeValue {
                shape: TypeShape::Int { bytes: 4, signed },
                size: Some(4),
            });
            Type {
                types,
                root,
                key: OnceCell::new(),
            }
        }

        fn hash_of(t: &Type) -> u64 {
            let mut h = DefaultHasher::new();
            t.hash(&mut h);
            h.finish()
        }

        let a = scalar_image(false);
        let b = scalar_image(false);
        let c = scalar_image(true);

        assert!(a == b, "structurally identical types should be equal");
        assert!(a != c, "unsigned and signed should differ");
        assert!(hash_of(&a) == hash_of(&b), "equal types must hash equally");
        assert!(
            hash_of(&a) != hash_of(&c),
            "different types should hash apart"
        );
        assert!(!format!("{a}").is_empty(), "Display should render the type");
    }

    /// A tagged root reports the nominal identity the type catalog keys on, and an anonymous one
    /// reports none, since it is structural and has no name to match across databases.
    #[test]
    fn identity_is_the_root_tag_and_anonymous_roots_have_none() {
        let mut types = TypeTable::new();
        let field = u32_type(&mut types);
        let root = types.intern(TypeValue {
            shape: TypeShape::Struct {
                name: Some("pt".into()),
                members: vec![TypeMember {
                    name: "x".into(),
                    bit_offset: 0,
                    ty: field,
                    bitfield_width: None,
                    repr: None,
                }],
            },
            size: Some(4),
        });
        let tagged = Type {
            types,
            root,
            key: OnceCell::new(),
        };
        assert!(
            tagged.identity()
                == Some(TypeIdentity::Tagged {
                    tag: "pt".into(),
                    kind: AggregateKind::Struct,
                })
        );

        let mut types = TypeTable::new();
        let root = u32_type(&mut types);
        let anonymous = Type {
            types,
            root,
            key: OnceCell::new(),
        };
        assert!(anonymous.identity() == None);
    }

    /// A non-aggregate root has no members.
    #[test]
    fn scalar_root_has_no_members() {
        let mut types = TypeTable::new();
        let root = u32_type(&mut types);
        let img = Type {
            types,
            root,
            key: OnceCell::new(),
        };
        assert!(img.members().is_none());
    }

    /// A clone is an independent value with the same structural key.
    #[test]
    fn type_clone_has_equal_key() {
        let mut types = TypeTable::new();
        let root = u32_type(&mut types);
        let img = Type {
            types,
            root,
            key: OnceCell::new(),
        };
        let cloned = img.clone();
        assert!(cloned.key() == img.key());
    }

    /// A `Type` round trips through JSON: `key` is skipped (not real source data) and
    /// recomputed lazily, landing on the same value as the original.
    #[test]
    fn type_serde_round_trip_recomputes_key() {
        let mut types = TypeTable::new();
        let root = u32_type(&mut types);
        let img = Type {
            types,
            root,
            key: OnceCell::new(),
        };
        // Force the cache to populate before serializing, proving `#[serde(skip)]` really
        // drops it rather than merely leaving it unset by coincidence.
        let original_key = img.key();

        let json = serde_json::to_string(&img).unwrap();
        let round_tripped: Type = serde_json::from_str(&json).unwrap();

        assert!(round_tripped.root() == img.root());
        assert!(round_tripped.key() == original_key);
    }
}