idakit 0.1.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
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
//! The crate's kernel-global FFI boundary, as private [`Database`] methods.
//!
//! Every `idakit-sys` call that operates on the implicit current database lives
//! here as one thin wrapper. The handle-scoped calls (`DecompiledFunction`) stay on
//! that type, since it owns the handle it acts on.
//!
//! # Safety
//!
//! Every method below is sound by one invariant, discharged here once. A [`Database`]
//! is `!Send` and constructed only inside the kernel-thread pump of
//! [`Ida::run`](crate::Ida::run), so holding `&self` proves we are on the kernel
//! thread with the library initialized and a database open, exactly the
//! thread-affinity and live-database preconditions the kernel demands. `&mut self`
//! adds exclusivity for writes. Raw buffer pointers are valid for the call, and
//! string getters fill `(buf, cap)` and return the value's full length.

use std::ffi::{c_char, c_int, c_void};

use idakit_sys as sys;

use crate::Database;
use crate::address::Address;
use crate::error::Qerrno;
use crate::ffi::cstr;

impl Database {
    // The three error helpers below read *thread-local* kernel state; `&self` is the
    // kernel-thread token (see module note), not a source of instance state.

    /// IDA's thread-local last error code.
    pub(crate) fn qerrno(&self) -> Qerrno {
        Qerrno::from_code(unsafe { sys::get_qerrno() })
    }

    /// Human-readable reason for `code`; the C `errno` text is already folded in for an
    /// OS error. Never empty, since it falls back to the raw error code.
    pub(crate) fn error_reason(&self, code: Qerrno) -> String {
        // SAFETY: qstrerror returns a borrowed thread-local string; copied now.
        let reason = unsafe { cstr(sys::qstrerror(code.code())) };
        if reason.is_empty() {
            format!("error_t {}", code.code())
        } else {
            reason
        }
    }

    /// The current [`Qerrno`] plus its reason, but `None` reason when it is [`Qerrno::Ok`].
    ///
    /// A failing path that set no code would otherwise borrow a stale, misleading reason.
    pub(crate) fn last_reason(&self) -> (Qerrno, Option<String>) {
        let qerrno = self.qerrno();
        let reason = match qerrno {
            Qerrno::Ok => None,
            code => Some(self.error_reason(code)),
        };
        (qerrno, reason)
    }

    /// Opens via the facade's guarded wrapper.
    ///
    /// IDA's fatal `exit()` path (an unaccepted license, a corrupt input it refuses) is
    /// trapped and surfaced as the [`sys::IDAKIT_EXIT_TRAPPED`] sentinel instead of killing
    /// the process.
    pub(crate) fn open_database(&mut self, path: *const c_char, run_auto: bool) -> c_int {
        unsafe { sys::idakit_guarded_open(path, run_auto as c_int) }
    }

    /// The exit code IDA passed to `exit()` on the last trapped fatal open.
    pub(crate) fn last_exit_code(&self) -> c_int {
        unsafe { sys::idakit_last_exit_code() }
    }

    /// The stdout+stderr IDA emitted during the last guarded open, captured by the
    /// facade instead of leaking to the caller's console.
    pub(crate) fn last_output(&self) -> String {
        crate::ffi::read_string(|buf, cap| unsafe { sys::idakit_last_output(buf, cap) as i64 })
            .unwrap_or_default()
    }

    /// Records EULA acceptance in IDA's registry, and returns whether it now reads accepted.
    pub(crate) fn reg_accept_eula(&self) -> bool {
        unsafe { sys::idakit_accept_eula() != 0 }
    }

    /// Blocks until the auto-analysis queue drains. Only meaningful after an
    /// `open_database(run_auto = true)`, which enables but does not await analysis.
    /// Guarded: returns [`sys::IDAKIT_EXIT_TRAPPED`] if analysis hit a fatal exit().
    pub(crate) fn auto_wait(&self) -> c_int {
        unsafe { sys::idakit_guarded_auto_wait() }
    }

    /// Guarded close, where a fatal during a save is trapped (returns the sentinel) rather
    /// than killing the process. Best-effort, since by the time we close, the result is
    /// moot.
    pub(crate) fn close_database(&mut self, save: bool) {
        unsafe { sys::idakit_guarded_close(save as c_int) };
    }

    /// Whether the most recent guarded facade call trapped a fatal exit().
    pub(crate) fn was_trapped(&self) -> bool {
        unsafe { sys::idakit_was_trapped() != 0 }
    }

    /// Zero-alloc read into `buf`; the generated `get_bytes` returns an owned `Vec`, so it can't
    /// back this buffer-fill twin, which stays on the raw facade. [`get_bytes_owned`] is the
    /// owning generated path.
    ///
    /// [`get_bytes_owned`]: Self::get_bytes_owned
    pub(crate) fn get_bytes(&self, address: Address, buf: *mut c_void, size: usize) -> i64 {
        unsafe { sys::idakit_get_bytes(address.get(), buf, size) }
    }

    pub(crate) fn get_bytes_owned(&self, address: Address, size: usize) -> Option<Vec<u8>> {
        sys::get_bytes(address.get(), size).ok()
    }

    pub(crate) fn get_u8(&self, address: Address) -> Option<u8> {
        sys::get_u8(address.get()).ok()
    }

    pub(crate) fn get_u16(&self, address: Address) -> Option<u16> {
        sys::get_u16(address.get()).ok()
    }

    pub(crate) fn get_u32(&self, address: Address) -> Option<u32> {
        sys::get_u32(address.get()).ok()
    }

    pub(crate) fn get_u64(&self, address: Address) -> Option<u64> {
        sys::get_u64(address.get()).ok()
    }

    pub(crate) fn get_strlit(&self, address: Address, strtype: c_int) -> Option<String> {
        sys::get_strlit(address.get(), strtype).ok()
    }

    pub(crate) fn decode_insn(&self, address: Address) -> sys::InstructionData {
        sys::decode_insn(address.get())
    }

    pub(crate) fn get_flags(&self, address: Address) -> u64 {
        sys::get_flags(address.get())
    }

    pub(crate) fn get_item_head(&self, address: Address) -> sys::Address {
        sys::get_item_head(address.get())
    }

    pub(crate) fn get_item_end(&self, address: Address) -> sys::Address {
        sys::get_item_end(address.get())
    }

    pub(crate) fn get_next_head(&self, address: Address, maxea: Address) -> sys::Address {
        sys::get_next_head(address.get(), maxea.get())
    }

    pub(crate) fn get_prev_head(&self, address: Address, minea: Address) -> sys::Address {
        sys::get_prev_head(address.get(), minea.get())
    }

    pub(crate) fn bitness_bits(&self) -> c_int {
        sys::bitness()
    }

    pub(crate) fn image_base(&self) -> sys::Address {
        sys::image_base()
    }

    pub(crate) fn min_ea(&self) -> sys::Address {
        sys::min_ea()
    }

    pub(crate) fn max_ea(&self) -> sys::Address {
        sys::max_ea()
    }

    pub(crate) fn proc_name(&self) -> Option<String> {
        sys::proc_name().ok()
    }

    pub(crate) fn file_type_name(&self) -> Option<String> {
        sys::file_type_name().ok()
    }

    pub(crate) fn input_path(&self) -> Option<String> {
        sys::input_path().ok()
    }

    pub(crate) fn root_filename(&self) -> Option<String> {
        sys::root_filename().ok()
    }

    pub(crate) fn get_ea_name(&self, address: Address) -> Option<String> {
        sys::get_ea_name(address.get()).ok()
    }

    pub(crate) fn get_name_ea(&self, name: &str) -> sys::Address {
        sys::get_name_ea(name)
    }

    pub(crate) fn demangle_name(&self, name: &str) -> Option<String> {
        sys::demangle_name(name).ok()
    }

    pub(crate) fn nlist_size(&self) -> usize {
        sys::nlist_size()
    }

    pub(crate) fn nlist_ea(&self, idx: usize) -> sys::Address {
        sys::nlist_ea(idx)
    }

    pub(crate) fn nlist_name(&self, idx: usize) -> Option<String> {
        sys::nlist_name(idx).ok()
    }

    /// Every cross-reference edge at `address`, as an owned snapshot.
    ///
    /// `is_to` selects xrefs targeting `address` vs originating at it. The [`Xrefs`] iterator owns
    /// the returned `Vec` and needs no kernel access to walk it.
    ///
    /// [`Xrefs`]: crate::Xrefs
    pub(crate) fn xrefs_build(&self, address: Address, is_to: bool) -> Vec<sys::XrefRec> {
        sys::xrefs_build(address.get(), is_to)
    }

    pub(crate) fn hexrays_init(&self) -> c_int {
        unsafe { sys::idakit_hexrays_init() }
    }

    pub(crate) fn set_name(&mut self, address: Address, name: *const c_char) -> bool {
        unsafe { sys::set_name(address.get(), name, 0) }
    }

    pub(crate) fn set_cmt(
        &mut self,
        address: Address,
        comment: *const c_char,
        repeatable: bool,
    ) -> bool {
        unsafe { sys::set_cmt(address.get(), comment, repeatable) }
    }

    pub(crate) fn get_cmt(&self, address: Address, repeatable: bool) -> Option<String> {
        sys::get_cmt(address.get(), repeatable).ok()
    }

    pub(crate) fn patch_bytes(
        &mut self,
        address: Address,
        buf: *const c_void,
        size: usize,
    ) -> c_int {
        unsafe { sys::idakit_patch_bytes(address.get(), buf, size) }
    }

    pub(crate) fn func_qty(&self) -> usize {
        sys::func_qty()
    }

    pub(crate) fn func_ea(&self, n: usize) -> sys::Address {
        sys::func_ea(n)
    }

    pub(crate) fn func_name(&self, address: Address) -> Option<String> {
        sys::func_name(address.get()).ok()
    }

    /// Every chunk of the function at `address` (entry chunk first), as an owned range snapshot;
    /// empty when no function lives there.
    pub(crate) fn range_all_chunks(&self, address: Address) -> Vec<sys::RangeT> {
        sys::range_all_chunks(address.get()).unwrap_or_default()
    }

    pub(crate) fn func_type(&self, address: Address, buf: *mut c_char, cap: usize) -> i64 {
        unsafe { sys::idakit_func_type(address.get(), buf, cap) }
    }

    pub(crate) fn type_ordinal_limit(&self) -> u32 {
        unsafe { sys::idakit_type_ordinal_limit() }
    }

    pub(crate) fn type_name_at(&self, ordinal: u32, buf: *mut c_char, cap: usize) -> i64 {
        unsafe { sys::idakit_type_name_at(ordinal, buf, cap) }
    }

    pub(crate) fn func_start(&self, address: Address) -> sys::Address {
        sys::func_start(address.get())
    }

    pub(crate) fn func_end(&self, address: Address) -> sys::Address {
        sys::func_end(address.get())
    }

    pub(crate) fn apply_type_decl(
        &mut self,
        address: Address,
        decl: &str,
        flags: c_int,
    ) -> sys::TypeWriteResult {
        sys::apply_type_decl(address.get(), decl, flags)
    }

    pub(crate) fn apply_named_type(
        &mut self,
        address: Address,
        name: &str,
    ) -> sys::TypeWriteResult {
        sys::apply_named_type(address.get(), name)
    }

    pub(crate) fn clear_type(&mut self, address: Address) -> sys::TypeWriteResult {
        sys::clear_type(address.get())
    }

    pub(crate) fn apply_type_recipe(
        &mut self,
        address: Address,
        buf: &[u8],
        flags: c_int,
    ) -> sys::TypeWriteResult {
        sys::apply_type_recipe(address.get(), buf, flags)
    }

    pub(crate) fn apply_tinfo(
        &mut self,
        address: Address,
        handle: &sys::TInfo,
        flags: c_int,
    ) -> sys::TypeWriteResult {
        sys::tinfo_apply(address.get(), handle, flags)
    }

    pub(crate) fn func_set_rettype(
        &mut self,
        address: Address,
        buf: &[u8],
    ) -> sys::TypeWriteResult {
        sys::func_set_rettype(address.get(), buf)
    }

    pub(crate) fn func_set_argtype(
        &mut self,
        address: Address,
        idx: usize,
        buf: &[u8],
    ) -> sys::SigWriteResult {
        sys::func_set_argtype(address.get(), idx, buf)
    }

    pub(crate) fn func_rename_arg(
        &mut self,
        address: Address,
        idx: usize,
        name: &str,
    ) -> sys::SigWriteResult {
        sys::func_rename_arg(address.get(), idx, name)
    }

    pub(crate) fn func_set_cc(&mut self, address: Address, cc: c_int) -> sys::TypeWriteResult {
        sys::func_set_cc(address.get(), cc)
    }

    pub(crate) fn func_prepend_this(
        &mut self,
        address: Address,
        buf: &[u8],
    ) -> sys::TypeWriteResult {
        sys::func_prepend_this(address.get(), buf)
    }

    pub(crate) fn udt_add_member(
        &mut self,
        type_name: &str,
        member_name: &str,
        buf: &[u8],
        member_bit: u64,
    ) -> sys::TypeWriteResult {
        sys::udt_add_member(type_name, member_name, buf, member_bit)
    }

    pub(crate) fn udt_set_member_type(
        &mut self,
        type_name: &str,
        member_name: &str,
        member_bit: u64,
        buf: &[u8],
    ) -> sys::TypeWriteResult {
        sys::udt_set_member_type(type_name, member_name, member_bit, buf)
    }

    pub(crate) fn udt_rename_member(
        &mut self,
        type_name: &str,
        member_name: &str,
        member_bit: u64,
        new_name: &str,
    ) -> sys::TypeWriteResult {
        sys::udt_rename_member(type_name, member_name, member_bit, new_name)
    }

    pub(crate) fn udt_del_member(
        &mut self,
        type_name: &str,
        member_name: &str,
        member_bit: u64,
    ) -> sys::TypeWriteResult {
        sys::udt_del_member(type_name, member_name, member_bit)
    }

    pub(crate) fn enum_add_member(
        &mut self,
        type_name: &str,
        member_name: &str,
        value: u64,
    ) -> sys::TypeWriteResult {
        sys::enum_add_member(type_name, member_name, value)
    }

    pub(crate) fn enum_set_member_value(
        &mut self,
        type_name: &str,
        member_name: &str,
        value: u64,
    ) -> sys::TypeWriteResult {
        sys::enum_set_member_value(type_name, member_name, value)
    }

    pub(crate) fn enum_rename_member(
        &mut self,
        type_name: &str,
        member_name: &str,
        new_name: &str,
    ) -> sys::TypeWriteResult {
        sys::enum_rename_member(type_name, member_name, new_name)
    }

    pub(crate) fn enum_del_member(
        &mut self,
        type_name: &str,
        member_name: &str,
    ) -> sys::TypeWriteResult {
        sys::enum_del_member(type_name, member_name)
    }

    pub(crate) fn define_type(&mut self, input: &str) -> sys::TypeWriteResult {
        sys::define_type(input)
    }

    pub(crate) fn func_flags(&self, address: Address) -> u64 {
        sys::func_flags(address.get())
    }

    pub(crate) fn seg_qty(&self) -> c_int {
        sys::gen_seg_qty() as c_int
    }

    pub(crate) fn seg_name(&self, n: c_int) -> Option<String> {
        sys::gen_seg_name(n).ok()
    }

    pub(crate) fn seg_start(&self, n: c_int) -> sys::Address {
        sys::gen_seg_start(n)
    }

    pub(crate) fn seg_end(&self, n: c_int) -> sys::Address {
        sys::gen_seg_end(n)
    }

    pub(crate) fn seg_perm(&self, n: c_int) -> c_int {
        sys::gen_seg_perm(n)
    }

    pub(crate) fn seg_bitness(&self, n: c_int) -> c_int {
        sys::gen_seg_bitness(n)
    }

    pub(crate) fn seg_class(&self, n: c_int) -> Option<String> {
        sys::gen_seg_class(n).ok()
    }

    pub(crate) fn export_qty(&self) -> usize {
        sys::export_qty()
    }

    pub(crate) fn export_ea(&self, idx: usize) -> sys::Address {
        sys::export_ea(idx)
    }

    pub(crate) fn export_ordinal(&self, idx: usize) -> u64 {
        sys::export_ordinal(idx)
    }

    pub(crate) fn export_name(&self, idx: usize) -> Option<String> {
        sys::export_name(idx).ok()
    }

    pub(crate) fn export_forwarder(&self, idx: usize) -> Option<String> {
        sys::export_forwarder(idx).ok()
    }

    /// The whole import table as an owned snapshot.
    ///
    /// The [`Imports`] iterator owns the returned `Vec` and needs no kernel access to walk it.
    ///
    /// [`Imports`]: crate::Imports
    pub(crate) fn imports_build(&self) -> Vec<sys::ImportRec> {
        sys::imports_build()
    }

    /// (Re)builds IDA's global string list, a query-time scan, not a database mutation.
    pub(crate) fn strlist_build(&self) {
        sys::strlist_build();
    }

    pub(crate) fn strlist_qty(&self) -> usize {
        sys::strlist_qty()
    }

    pub(crate) fn strlist_item(&self, n: usize) -> Option<sys::StrlistItem> {
        sys::strlist_item(n).ok()
    }

    pub(crate) fn strlit_contents(
        &self,
        address: Address,
        len: usize,
        ty: c_int,
    ) -> Option<String> {
        sys::strlit_contents(address.get(), len, ty).ok()
    }
}