binaryninja/
worker_thread.rs

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
use crate::string::BnStrCompatible;
use binaryninjacore_sys::*;
use std::ffi::{c_char, c_void};

pub struct WorkerThreadActionExecutor {
    func: Box<dyn Fn()>,
}

impl WorkerThreadActionExecutor {
    unsafe extern "C" fn cb_execute(ctx: *mut c_void) {
        let f: Box<Self> = Box::from_raw(ctx as *mut Self);
        f.execute();
    }

    pub fn execute(&self) {
        (self.func)();
    }
}

pub fn execute_on_worker_thread<F: Fn() + 'static, S: BnStrCompatible>(name: S, f: F) {
    let boxed_executor = Box::new(WorkerThreadActionExecutor { func: Box::new(f) });
    let raw_executor = Box::into_raw(boxed_executor);
    let name = name.into_bytes_with_nul();
    unsafe {
        BNWorkerEnqueueNamed(
            raw_executor as *mut c_void,
            Some(WorkerThreadActionExecutor::cb_execute),
            name.as_ref().as_ptr() as *const c_char,
        )
    }
}

pub fn execute_on_worker_thread_priority<F: Fn() + 'static, S: BnStrCompatible>(name: S, f: F) {
    let boxed_executor = Box::new(WorkerThreadActionExecutor { func: Box::new(f) });
    let raw_executor = Box::into_raw(boxed_executor);
    let name = name.into_bytes_with_nul();
    unsafe {
        BNWorkerPriorityEnqueueNamed(
            raw_executor as *mut c_void,
            Some(WorkerThreadActionExecutor::cb_execute),
            name.as_ref().as_ptr() as *const c_char,
        )
    }
}

pub fn execute_on_worker_thread_interactive<F: Fn() + 'static, S: BnStrCompatible>(name: S, f: F) {
    let boxed_executor = Box::new(WorkerThreadActionExecutor { func: Box::new(f) });
    let raw_executor = Box::into_raw(boxed_executor);
    let name = name.into_bytes_with_nul();
    unsafe {
        BNWorkerInteractiveEnqueueNamed(
            raw_executor as *mut c_void,
            Some(WorkerThreadActionExecutor::cb_execute),
            name.as_ref().as_ptr() as *const c_char,
        )
    }
}

/// Returns the number of worker threads that are currently running.
/// By default, this is the number of cores on the system minus one
///
/// To set the worker thread count use [`set_worker_thread_count`].
pub fn worker_thread_count() -> usize {
    unsafe { BNGetWorkerThreadCount() }
}

/// Sets the number of worker threads that are currently running.
/// By default, this is the number of cores on the system minus one.
pub fn set_worker_thread_count(count: usize) {
    unsafe { BNSetWorkerThreadCount(count) }
}