idax 0.3.0

Safe, idiomatic Rust bindings for the IDA SDK via idax
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
//! Plugin lifecycle, action registration, and export helpers.
//!
//! Mirrors the C++ `ida::plugin` namespace.

use crate::address::{Address, BAD_ADDRESS};
use crate::error::{self, Error, Result, Status};
use std::collections::HashMap;
use std::ffi::{c_char, c_void, CStr, CString};
use std::sync::{Mutex, OnceLock};

/// Plugin metadata.
#[derive(Debug, Clone)]
pub struct Info {
    pub name: String,
    pub hotkey: String,
    pub comment: String,
    pub help: String,
    pub icon: i32,
}

/// Action context.
#[derive(Debug, Clone)]
pub struct ActionContext {
    pub action_id: String,
    pub widget_title: String,
    pub widget_type: i32,
    pub current_address: Address,
    pub current_value: u64,
    pub has_selection: bool,
    pub is_external_address: bool,
    pub register_name: String,
    pub widget_handle: *mut c_void,
    pub focused_widget_handle: *mut c_void,
    pub decompiler_view_handle: *mut c_void,
}

/// Action descriptor.
#[derive(Debug, Clone)]
pub struct Action {
    pub id: String,
    pub label: String,
    pub hotkey: String,
    pub tooltip: String,
    pub icon: i32,
}

/// Opaque host pointer for a widget.
pub type WidgetHost = *mut c_void;

/// Opaque host pointer for a decompiler view.
pub type DecompilerViewHost = *mut c_void;

fn c_ptr_to_string(ptr: *const c_char) -> String {
    if ptr.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned()
    }
}

fn from_ffi_action_context(ctx: &idax_sys::IdaxPluginActionContext) -> ActionContext {
    ActionContext {
        action_id: c_ptr_to_string(ctx.action_id),
        widget_title: c_ptr_to_string(ctx.widget_title),
        widget_type: ctx.widget_type,
        current_address: ctx.current_address,
        current_value: ctx.current_value,
        has_selection: ctx.has_selection != 0,
        is_external_address: ctx.is_external_address != 0,
        register_name: c_ptr_to_string(ctx.register_name),
        widget_handle: ctx.widget_handle,
        focused_widget_handle: ctx.focused_widget_handle,
        decompiler_view_handle: ctx.decompiler_view_handle,
    }
}

fn with_ffi_action_context<T, F>(context: &ActionContext, f: F) -> Result<T>
where
    F: FnOnce(&idax_sys::IdaxPluginActionContext) -> Result<T>,
{
    let action_id = CString::new(context.action_id.as_str())
        .map_err(|_| Error::validation("invalid action_id"))?;
    let widget_title = CString::new(context.widget_title.as_str())
        .map_err(|_| Error::validation("invalid widget_title"))?;
    let register_name = CString::new(context.register_name.as_str())
        .map_err(|_| Error::validation("invalid register_name"))?;

    let ffi = idax_sys::IdaxPluginActionContext {
        action_id: action_id.as_ptr(),
        widget_title: widget_title.as_ptr(),
        widget_type: context.widget_type,
        current_address: context.current_address,
        current_value: context.current_value,
        has_selection: if context.has_selection { 1 } else { 0 },
        is_external_address: if context.is_external_address { 1 } else { 0 },
        register_name: register_name.as_ptr(),
        widget_handle: context.widget_handle,
        focused_widget_handle: context.focused_widget_handle,
        decompiler_view_handle: context.decompiler_view_handle,
    };

    f(&ffi)
}

struct ActionHandlerContext {
    callback: Box<dyn FnMut(ActionContext) + Send>,
}

struct ActionEnabledContext {
    callback: Box<dyn FnMut(&ActionContext) -> bool + Send>,
}

struct ErasedContext {
    ptr: usize,
    drop_fn: unsafe fn(*mut c_void),
}

struct ActionContextPair {
    handler: Option<ErasedContext>,
    enabled: Option<ErasedContext>,
}

unsafe fn drop_as<T>(ptr: *mut c_void) {
    unsafe { drop(Box::from_raw(ptr as *mut T)) };
}

static ACTION_CONTEXTS: OnceLock<Mutex<HashMap<String, ActionContextPair>>> = OnceLock::new();

fn clear_action_context(action_id: &str) {
    if let Some(pair) = ACTION_CONTEXTS
        .get_or_init(|| Mutex::new(HashMap::new()))
        .lock()
        .expect("plugin action context mutex poisoned")
        .remove(action_id)
    {
        if let Some(handler) = pair.handler {
            unsafe { (handler.drop_fn)(handler.ptr as *mut c_void) };
        }
        if let Some(enabled) = pair.enabled {
            unsafe { (enabled.drop_fn)(enabled.ptr as *mut c_void) };
        }
    }
}

unsafe extern "C" fn action_handler_ex_trampoline(
    context: *mut c_void,
    action_context: *const idax_sys::IdaxPluginActionContext,
) {
    if context.is_null() || action_context.is_null() {
        return;
    }
    let ctx = unsafe { &mut *(context as *mut ActionHandlerContext) };
    let action_ctx = unsafe { from_ffi_action_context(&*action_context) };
    (ctx.callback)(action_ctx);
}

unsafe extern "C" fn action_enabled_ex_trampoline(
    context: *mut c_void,
    action_context: *const idax_sys::IdaxPluginActionContext,
) -> i32 {
    if context.is_null() || action_context.is_null() {
        return 0;
    }
    let ctx = unsafe { &mut *(context as *mut ActionEnabledContext) };
    let action_ctx = unsafe { from_ffi_action_context(&*action_context) };
    if (ctx.callback)(&action_ctx) {
        1
    } else {
        0
    }
}

/// Register a UI action.
pub fn register_action(action: &Action) -> Status {
    let c_id = CString::new(action.id.as_str()).map_err(|_| Error::validation("invalid id"))?;
    let c_label =
        CString::new(action.label.as_str()).map_err(|_| Error::validation("invalid label"))?;
    let c_hotkey =
        CString::new(action.hotkey.as_str()).map_err(|_| Error::validation("invalid hotkey"))?;
    let c_tooltip =
        CString::new(action.tooltip.as_str()).map_err(|_| Error::validation("invalid tooltip"))?;
    let ret = unsafe {
        idax_sys::idax_plugin_register_action(
            c_id.as_ptr(),
            c_label.as_ptr(),
            c_hotkey.as_ptr(),
            c_tooltip.as_ptr(),
            action.icon,
            None,
            std::ptr::null_mut(),
            None,
            std::ptr::null_mut(),
        )
    };
    let status = error::int_to_status(ret, "plugin::register_action failed");
    if status.is_ok() {
        clear_action_context(action.id.as_str());
    }
    status
}

/// Register a UI action with typed action context callbacks.
pub fn register_action_with_context<H, E>(
    action: &Action,
    handler: H,
    enabled_check: Option<E>,
) -> Status
where
    H: FnMut(ActionContext) + Send + 'static,
    E: FnMut(&ActionContext) -> bool + Send + 'static,
{
    let c_id = CString::new(action.id.as_str()).map_err(|_| Error::validation("invalid id"))?;
    let c_label =
        CString::new(action.label.as_str()).map_err(|_| Error::validation("invalid label"))?;
    let c_hotkey =
        CString::new(action.hotkey.as_str()).map_err(|_| Error::validation("invalid hotkey"))?;
    let c_tooltip =
        CString::new(action.tooltip.as_str()).map_err(|_| Error::validation("invalid tooltip"))?;

    let raw_handler = Box::into_raw(Box::new(ActionHandlerContext {
        callback: Box::new(handler),
    }));
    let raw_enabled = enabled_check.map(|cb| {
        Box::into_raw(Box::new(ActionEnabledContext {
            callback: Box::new(cb),
        }))
    });
    let enabled_cb = if raw_enabled.is_some() {
        Some(
            action_enabled_ex_trampoline
                as unsafe extern "C" fn(
                    *mut c_void,
                    *const idax_sys::IdaxPluginActionContext,
                ) -> i32,
        )
    } else {
        None
    };
    let enabled_ctx = raw_enabled
        .map(|p| p as *mut c_void)
        .unwrap_or(std::ptr::null_mut());

    let ret = unsafe {
        idax_sys::idax_plugin_register_action_ex(
            c_id.as_ptr(),
            c_label.as_ptr(),
            c_hotkey.as_ptr(),
            c_tooltip.as_ptr(),
            action.icon,
            None,
            Some(action_handler_ex_trampoline),
            raw_handler as *mut c_void,
            None,
            enabled_cb,
            enabled_ctx,
        )
    };

    if ret != 0 {
        unsafe { drop(Box::from_raw(raw_handler)) };
        if let Some(ptr) = raw_enabled {
            unsafe { drop(Box::from_raw(ptr)) };
        }
        return Err(error::consume_last_error(
            "plugin::register_action_with_context failed",
        ));
    }

    let pair = ActionContextPair {
        handler: Some(ErasedContext {
            ptr: raw_handler as usize,
            drop_fn: drop_as::<ActionHandlerContext>,
        }),
        enabled: raw_enabled.map(|ptr| ErasedContext {
            ptr: ptr as usize,
            drop_fn: drop_as::<ActionEnabledContext>,
        }),
    };

    let mut map = ACTION_CONTEXTS
        .get_or_init(|| Mutex::new(HashMap::new()))
        .lock()
        .expect("plugin action context mutex poisoned");
    if let Some(previous) = map.insert(action.id.clone(), pair) {
        if let Some(handler_ctx) = previous.handler {
            unsafe { (handler_ctx.drop_fn)(handler_ctx.ptr as *mut c_void) };
        }
        if let Some(enabled_ctx) = previous.enabled {
            unsafe { (enabled_ctx.drop_fn)(enabled_ctx.ptr as *mut c_void) };
        }
    }

    Ok(())
}

/// Unregister a UI action.
pub fn unregister_action(action_id: &str) -> Status {
    let c = CString::new(action_id).map_err(|_| Error::validation("invalid id"))?;
    let ret = unsafe { idax_sys::idax_plugin_unregister_action(c.as_ptr()) };
    let status = error::int_to_status(ret, "plugin::unregister_action failed");
    if status.is_ok() {
        clear_action_context(action_id);
    }
    status
}

/// Attach an action to a menu path.
pub fn attach_to_menu(menu_path: &str, action_id: &str) -> Status {
    let c_menu = CString::new(menu_path).map_err(|_| Error::validation("invalid menu path"))?;
    let c_id = CString::new(action_id).map_err(|_| Error::validation("invalid action id"))?;
    let ret = unsafe { idax_sys::idax_plugin_attach_to_menu(c_menu.as_ptr(), c_id.as_ptr()) };
    error::int_to_status(ret, "plugin::attach_to_menu failed")
}

/// Attach an action to a toolbar.
pub fn attach_to_toolbar(toolbar: &str, action_id: &str) -> Status {
    let c_tb = CString::new(toolbar).map_err(|_| Error::validation("invalid toolbar"))?;
    let c_id = CString::new(action_id).map_err(|_| Error::validation("invalid action id"))?;
    let ret = unsafe { idax_sys::idax_plugin_attach_to_toolbar(c_tb.as_ptr(), c_id.as_ptr()) };
    error::int_to_status(ret, "plugin::attach_to_toolbar failed")
}

/// Attach an action to a widget popup/context menu.
pub fn attach_to_popup(widget_title: &str, action_id: &str) -> Status {
    let c_widget =
        CString::new(widget_title).map_err(|_| Error::validation("invalid widget title"))?;
    let c_id = CString::new(action_id).map_err(|_| Error::validation("invalid action id"))?;
    let ret = unsafe { idax_sys::idax_plugin_attach_to_popup(c_widget.as_ptr(), c_id.as_ptr()) };
    error::int_to_status(ret, "plugin::attach_to_popup failed")
}

/// Detach an action from a menu path.
pub fn detach_from_menu(menu_path: &str, action_id: &str) -> Status {
    let c_menu = CString::new(menu_path).map_err(|_| Error::validation("invalid menu path"))?;
    let c_id = CString::new(action_id).map_err(|_| Error::validation("invalid action id"))?;
    let ret = unsafe { idax_sys::idax_plugin_detach_from_menu(c_menu.as_ptr(), c_id.as_ptr()) };
    error::int_to_status(ret, "plugin::detach_from_menu failed")
}

/// Detach an action from a toolbar.
pub fn detach_from_toolbar(toolbar: &str, action_id: &str) -> Status {
    let c_tb = CString::new(toolbar).map_err(|_| Error::validation("invalid toolbar"))?;
    let c_id = CString::new(action_id).map_err(|_| Error::validation("invalid action id"))?;
    let ret = unsafe { idax_sys::idax_plugin_detach_from_toolbar(c_tb.as_ptr(), c_id.as_ptr()) };
    error::int_to_status(ret, "plugin::detach_from_toolbar failed")
}

/// Detach an action from a widget popup/context menu.
pub fn detach_from_popup(widget_title: &str, action_id: &str) -> Status {
    let c_widget =
        CString::new(widget_title).map_err(|_| Error::validation("invalid widget title"))?;
    let c_id = CString::new(action_id).map_err(|_| Error::validation("invalid action id"))?;
    let ret = unsafe { idax_sys::idax_plugin_detach_from_popup(c_widget.as_ptr(), c_id.as_ptr()) };
    error::int_to_status(ret, "plugin::detach_from_popup failed")
}

/// Get the widget host pointer from an action context.
pub fn widget_host(context: &ActionContext) -> Result<WidgetHost> {
    with_ffi_action_context(context, |ffi| {
        let mut out: *mut c_void = std::ptr::null_mut();
        let ret = unsafe { idax_sys::idax_plugin_action_context_widget_host(ffi, &mut out) };
        if ret != 0 {
            Err(error::consume_last_error("plugin::widget_host failed"))
        } else {
            Ok(out)
        }
    })
}

/// Execute a callback with a widget host pointer from an action context.
pub fn with_widget_host<F>(context: &ActionContext, callback: F) -> Status
where
    F: FnOnce(WidgetHost) -> Status,
{
    let host = widget_host(context)?;
    callback(host)
}

/// Get the decompiler-view host pointer from an action context.
pub fn decompiler_view_host(context: &ActionContext) -> Result<DecompilerViewHost> {
    with_ffi_action_context(context, |ffi| {
        let mut out: *mut c_void = std::ptr::null_mut();
        let ret =
            unsafe { idax_sys::idax_plugin_action_context_decompiler_view_host(ffi, &mut out) };
        if ret != 0 {
            Err(error::consume_last_error(
                "plugin::decompiler_view_host failed",
            ))
        } else {
            Ok(out)
        }
    })
}

/// Execute a callback with a decompiler-view host pointer from an action context.
pub fn with_decompiler_view_host<F>(context: &ActionContext, callback: F) -> Status
where
    F: FnOnce(DecompilerViewHost) -> Status,
{
    let host = decompiler_view_host(context)?;
    callback(host)
}

impl Default for ActionContext {
    fn default() -> Self {
        Self {
            action_id: String::new(),
            widget_title: String::new(),
            widget_type: -1,
            current_address: BAD_ADDRESS,
            current_value: 0,
            has_selection: false,
            is_external_address: false,
            register_name: String::new(),
            widget_handle: std::ptr::null_mut(),
            focused_widget_handle: std::ptr::null_mut(),
            decompiler_view_handle: std::ptr::null_mut(),
        }
    }
}