1#![allow(clippy::missing_safety_doc)]
17#![allow(clippy::result_unit_err)]
18#![allow(clippy::type_complexity)]
19#![allow(clippy::too_many_arguments)]
20#![allow(clippy::needless_doctest_main)]
21#![doc(html_root_url = "https://dev-rust.binary.ninja/")]
22#![doc(html_favicon_url = "/brand/favicon-32x32.png")]
23#![doc(html_logo_url = "/brand/logo-vertical-dark.svg")]
24#![doc(issue_tracker_base_url = "https://github.com/Vector35/binaryninja-api/issues/")]
25#![doc = include_str!("../README.md")]
26
27#[macro_use]
28mod ffi;
29
30pub mod architecture;
31pub mod background_task;
32pub mod base_detection;
33pub mod basic_block;
34pub mod binary_view;
35pub mod calling_convention;
36pub mod collaboration;
37pub mod command;
38pub mod component;
39pub mod confidence;
40pub mod data_buffer;
41pub mod data_notification;
42pub mod data_renderer;
43pub mod database;
44pub mod debuginfo;
45pub mod demangle;
46pub mod disassembly;
47pub mod download;
48pub mod enterprise;
49pub mod external_library;
50pub mod file_accessor;
51pub mod file_metadata;
52pub mod flowgraph;
53pub mod function;
54pub mod function_recognizer;
55pub mod headless;
56pub mod high_level_il;
57pub mod interaction;
58pub mod language_representation;
59pub mod line_formatter;
60pub mod linear_view;
61pub mod llvm;
62pub mod logger;
63pub mod low_level_il;
64pub mod main_thread;
65pub mod mcp;
66pub mod medium_level_il;
67pub mod metadata;
68pub mod object_destructor;
69pub mod platform;
70pub mod progress;
71pub mod project;
72pub mod qualified_name;
73pub mod rc;
74pub mod references;
75pub mod relocation;
76pub mod render_layer;
77pub mod repository;
78pub mod scripting_provider;
79pub mod secrets_provider;
80pub mod section;
81pub mod segment;
82pub mod settings;
83pub mod similarity;
84pub mod string;
85pub mod string_detection;
86pub mod symbol;
87pub mod tags;
88pub mod tracing;
89pub mod transform;
90pub mod types;
91pub mod update;
92pub mod variable;
93pub mod websocket;
94pub mod worker_thread;
95pub mod workflow;
96
97use crate::progress::{NoProgressCallback, ProgressCallback};
98use crate::string::raw_to_string;
99use binary_view::BinaryView;
100use binaryninjacore_sys::*;
101use rc::Ref;
102use std::cmp;
103use std::collections::HashMap;
104use std::ffi::{c_char, c_void, CStr};
105use std::fmt::{Display, Formatter};
106use std::path::{Path, PathBuf};
107use string::BnString;
108use string::IntoCStr;
109use string::IntoJson;
110
111use crate::project::file::ProjectFile;
112pub use binaryninjacore_sys::BNDataFlowQueryOption as DataFlowQueryOption;
113pub use binaryninjacore_sys::BNEndianness as Endianness;
114pub use binaryninjacore_sys::BNILBranchDependence as ILBranchDependence;
115
116pub const BN_FULL_CONFIDENCE: u8 = u8::MAX;
117pub const BN_INVALID_EXPR: usize = usize::MAX;
118pub const BN_INVALID_OPERAND: usize = u32::MAX as usize;
119
120pub fn fuzzy_match_single(target: &str, query: &str) -> Option<usize> {
123 let target = target.to_cstr();
124 let query = query.to_cstr();
125 let score = unsafe { BNFuzzyMatchSingle(target.as_ptr(), query.as_ptr()) };
126 (score != 0).then_some(score)
127}
128
129pub fn fuzzy_match_contextual(target: &str, query: &str) -> Option<usize> {
134 let target = target.to_cstr();
135 let query = query.to_cstr();
136 let score = unsafe { BNFuzzyMatchContextual(target.as_ptr(), query.as_ptr()) };
137 (score != 0).then_some(score)
138}
139
140pub fn load(file_path: impl AsRef<Path>) -> Option<Ref<BinaryView>> {
142 load_with_progress(file_path, NoProgressCallback)
143}
144
145pub fn load_with_progress<P: ProgressCallback>(
149 file_path: impl AsRef<Path>,
150 mut progress: P,
151) -> Option<Ref<BinaryView>> {
152 let file_path = file_path.as_ref().to_cstr();
153 let options = c"";
154 let handle = unsafe {
155 BNLoadFilename(
156 file_path.as_ptr() as *mut _,
157 true,
158 options.as_ptr() as *mut c_char,
159 Some(P::cb_progress_callback),
160 &mut progress as *mut P as *mut c_void,
161 )
162 };
163
164 if handle.is_null() {
165 None
166 } else {
167 Some(unsafe { BinaryView::ref_from_raw(handle) })
168 }
169}
170
171pub fn load_with_options<O>(
189 file_path: impl AsRef<Path>,
190 update_analysis_and_wait: bool,
191 options: Option<O>,
192) -> Option<Ref<BinaryView>>
193where
194 O: IntoJson,
195{
196 load_with_options_and_progress(
197 file_path,
198 update_analysis_and_wait,
199 options,
200 NoProgressCallback,
201 )
202}
203
204pub fn load_with_options_and_progress<O, P>(
208 file_path: impl AsRef<Path>,
209 update_analysis_and_wait: bool,
210 options: Option<O>,
211 mut progress: P,
212) -> Option<Ref<BinaryView>>
213where
214 O: IntoJson,
215 P: ProgressCallback,
216{
217 let file_path = file_path.as_ref().to_cstr();
218 let options_or_default = if let Some(opt) = options {
219 opt.get_json_string()
220 .ok()?
221 .to_cstr()
222 .to_bytes_with_nul()
223 .to_vec()
224 } else {
225 "{}".to_cstr().to_bytes_with_nul().to_vec()
226 };
227 let handle = unsafe {
228 BNLoadFilename(
229 file_path.as_ptr() as *mut _,
230 update_analysis_and_wait,
231 options_or_default.as_ptr() as *mut c_char,
232 Some(P::cb_progress_callback),
233 &mut progress as *mut P as *mut c_void,
234 )
235 };
236
237 if handle.is_null() {
238 None
239 } else {
240 Some(unsafe { BinaryView::ref_from_raw(handle) })
241 }
242}
243
244pub fn load_view<O>(
245 bv: &BinaryView,
246 update_analysis_and_wait: bool,
247 options: Option<O>,
248) -> Option<Ref<BinaryView>>
249where
250 O: IntoJson,
251{
252 load_view_with_progress(bv, update_analysis_and_wait, options, NoProgressCallback)
253}
254
255pub fn load_view_with_progress<O, P>(
257 bv: &BinaryView,
258 update_analysis_and_wait: bool,
259 options: Option<O>,
260 mut progress: P,
261) -> Option<Ref<BinaryView>>
262where
263 O: IntoJson,
264 P: ProgressCallback,
265{
266 let options_or_default = if let Some(opt) = options {
267 opt.get_json_string()
268 .ok()?
269 .to_cstr()
270 .to_bytes_with_nul()
271 .to_vec()
272 } else {
273 "{}".to_cstr().to_bytes_with_nul().to_vec()
274 };
275 let handle = unsafe {
276 BNLoadBinaryView(
277 bv.handle as *mut _,
278 update_analysis_and_wait,
279 options_or_default.as_ptr() as *mut c_char,
280 Some(P::cb_progress_callback),
281 &mut progress as *mut P as *mut c_void,
282 )
283 };
284
285 if handle.is_null() {
286 None
287 } else {
288 Some(unsafe { BinaryView::ref_from_raw(handle) })
289 }
290}
291
292pub fn load_project_file<O>(
293 file: &ProjectFile,
294 update_analysis_and_wait: bool,
295 options: Option<O>,
296) -> Option<Ref<BinaryView>>
297where
298 O: IntoJson,
299{
300 load_project_file_with_progress(file, update_analysis_and_wait, options, NoProgressCallback)
301}
302
303pub fn load_project_file_with_progress<O, P>(
305 file: &ProjectFile,
306 update_analysis_and_wait: bool,
307 options: Option<O>,
308 mut progress: P,
309) -> Option<Ref<BinaryView>>
310where
311 O: IntoJson,
312 P: ProgressCallback,
313{
314 let options_or_default = if let Some(opt) = options {
315 opt.get_json_string()
316 .ok()?
317 .to_cstr()
318 .to_bytes_with_nul()
319 .to_vec()
320 } else {
321 "{}".to_cstr().to_bytes_with_nul().to_vec()
322 };
323 let handle = unsafe {
324 BNLoadProjectFile(
325 file.handle.as_ptr(),
326 update_analysis_and_wait,
327 options_or_default.as_ptr() as *mut c_char,
328 Some(P::cb_progress_callback),
329 &mut progress as *mut P as *mut c_void,
330 )
331 };
332
333 if handle.is_null() {
334 None
335 } else {
336 Some(unsafe { BinaryView::ref_from_raw(handle) })
337 }
338}
339
340pub fn install_directory() -> PathBuf {
341 let install_dir_ptr: *mut c_char = unsafe { BNGetInstallDirectory() };
342 assert!(!install_dir_ptr.is_null());
343 let install_dir_str = unsafe { BnString::into_string(install_dir_ptr) };
344 PathBuf::from(install_dir_str)
345}
346
347pub fn bundled_plugin_directory() -> Result<PathBuf, ()> {
348 let s: *mut c_char = unsafe { BNGetBundledPluginDirectory() };
349 if s.is_null() {
350 return Err(());
351 }
352 Ok(PathBuf::from(unsafe { BnString::into_string(s) }))
353}
354
355pub fn set_bundled_plugin_directory(new_dir: impl AsRef<Path>) {
356 let new_dir = new_dir.as_ref().to_cstr();
357 unsafe { BNSetBundledPluginDirectory(new_dir.as_ptr()) };
358}
359
360pub fn user_directory() -> PathBuf {
361 let user_dir_ptr: *mut c_char = unsafe { BNGetUserDirectory() };
362 assert!(!user_dir_ptr.is_null());
363 let user_dir_str = unsafe { BnString::into_string(user_dir_ptr) };
364 PathBuf::from(user_dir_str)
365}
366
367pub fn user_plugin_directory() -> Result<PathBuf, ()> {
368 let s: *mut c_char = unsafe { BNGetUserPluginDirectory() };
369 if s.is_null() {
370 return Err(());
371 }
372 let user_plugin_dir_str = unsafe { BnString::into_string(s) };
373 Ok(PathBuf::from(user_plugin_dir_str))
374}
375
376pub fn repositories_directory() -> Result<PathBuf, ()> {
377 let s: *mut c_char = unsafe { BNGetRepositoriesDirectory() };
378 if s.is_null() {
379 return Err(());
380 }
381 let repo_dir_str = unsafe { BnString::into_string(s) };
382 Ok(PathBuf::from(repo_dir_str))
383}
384
385pub fn settings_file_path() -> PathBuf {
386 let settings_file_name_ptr: *mut c_char = unsafe { BNGetSettingsFileName() };
387 assert!(!settings_file_name_ptr.is_null());
388 let settings_file_path_str = unsafe { BnString::into_string(settings_file_name_ptr) };
389 PathBuf::from(settings_file_path_str)
390}
391
392pub fn save_last_run() {
396 unsafe { BNSaveLastRun() };
397}
398
399pub fn path_relative_to_bundled_plugin_directory(path: impl AsRef<Path>) -> Result<PathBuf, ()> {
400 let path_raw = path.as_ref().to_cstr();
401 let s: *mut c_char = unsafe { BNGetPathRelativeToBundledPluginDirectory(path_raw.as_ptr()) };
402 if s.is_null() {
403 return Err(());
404 }
405 Ok(PathBuf::from(unsafe { BnString::into_string(s) }))
406}
407
408pub fn path_relative_to_user_plugin_directory(path: impl AsRef<Path>) -> Result<PathBuf, ()> {
409 let path_raw = path.as_ref().to_cstr();
410 let s: *mut c_char = unsafe { BNGetPathRelativeToUserPluginDirectory(path_raw.as_ptr()) };
411 if s.is_null() {
412 return Err(());
413 }
414 Ok(PathBuf::from(unsafe { BnString::into_string(s) }))
415}
416
417pub fn path_relative_to_user_directory(path: impl AsRef<Path>) -> Result<PathBuf, ()> {
418 let path_raw = path.as_ref().to_cstr();
419 let s: *mut c_char = unsafe { BNGetPathRelativeToUserDirectory(path_raw.as_ptr()) };
420 if s.is_null() {
421 return Err(());
422 }
423 Ok(PathBuf::from(unsafe { BnString::into_string(s) }))
424}
425
426pub fn is_main_thread() -> bool {
430 unsafe { BNIsMainThread() }
431}
432
433pub fn memory_info() -> HashMap<String, u64> {
434 let mut count = 0;
435 let mut usage = HashMap::new();
436 unsafe {
437 let info_ptr = BNGetMemoryUsageInfo(&mut count);
438 let info_list = std::slice::from_raw_parts(info_ptr, count);
439 for info in info_list {
440 let info_name = CStr::from_ptr(info.name).to_str().unwrap().to_string();
441 usage.insert(info_name, info.value);
442 }
443 BNFreeMemoryUsageInfo(info_ptr, count);
444 }
445 usage
446}
447
448pub fn version() -> String {
449 unsafe { BnString::into_string(BNGetVersionString()) }
450}
451
452pub fn build_id() -> u32 {
453 unsafe { BNGetBuildId() }
454}
455
456#[derive(Clone, PartialEq, Eq, Hash, Debug)]
457pub struct VersionInfo {
458 pub major: u32,
459 pub minor: u32,
460 pub build: u32,
461 pub channel: String,
462}
463
464impl VersionInfo {
465 pub(crate) fn from_raw(value: &BNVersionInfo) -> Self {
466 Self {
467 major: value.major,
468 minor: value.minor,
469 build: value.build,
470 channel: raw_to_string(value.channel).unwrap_or_default(),
472 }
473 }
474
475 pub(crate) fn from_owned_raw(value: BNVersionInfo) -> Self {
476 let owned = Self::from_raw(&value);
477 Self::free_raw(value);
478 owned
479 }
480
481 pub(crate) fn into_owned_raw(value: &Self) -> BNVersionInfo {
482 BNVersionInfo {
483 major: value.major,
484 minor: value.minor,
485 build: value.build,
486 channel: value.channel.as_ptr() as *mut c_char,
487 }
488 }
489
490 pub(crate) fn free_raw(value: BNVersionInfo) {
491 unsafe { BnString::free_raw(value.channel) };
492 }
493}
494
495impl TryFrom<&str> for VersionInfo {
496 type Error = ();
497
498 fn try_from(value: &str) -> Result<Self, Self::Error> {
499 let string = value.to_cstr();
500 let result = unsafe { BNParseVersionString(string.as_ptr()) };
501 if result.build == 0 && result.channel.is_null() && result.major == 0 && result.minor == 0 {
502 return Err(());
503 }
504 Ok(Self::from_owned_raw(result))
505 }
506}
507
508impl PartialOrd for VersionInfo {
509 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
510 Some(self.cmp(other))
511 }
512}
513
514impl Ord for VersionInfo {
515 fn cmp(&self, other: &Self) -> cmp::Ordering {
516 if self == other {
517 return cmp::Ordering::Equal;
518 }
519 let bn_version_0 = VersionInfo::into_owned_raw(self);
520 let bn_version_1 = VersionInfo::into_owned_raw(other);
521 if unsafe { BNVersionLessThan(bn_version_0, bn_version_1) } {
522 cmp::Ordering::Less
523 } else {
524 cmp::Ordering::Greater
525 }
526 }
527}
528
529impl Display for VersionInfo {
530 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
531 if self.channel.is_empty() {
532 write!(f, "{}.{}.{}", self.major, self.minor, self.build)
533 } else {
534 write!(
535 f,
536 "{}.{}.{}-{}",
537 self.major, self.minor, self.build, self.channel
538 )
539 }
540 }
541}
542
543pub fn version_info() -> VersionInfo {
544 let info_raw = unsafe { BNGetVersionInfo() };
545 VersionInfo::from_owned_raw(info_raw)
546}
547
548pub fn serial_number() -> String {
549 unsafe { BnString::into_string(BNGetSerialNumber()) }
550}
551
552pub fn is_license_validated() -> bool {
553 unsafe { BNIsLicenseValidated() }
554}
555
556pub fn licensed_user_email() -> String {
557 unsafe { BnString::into_string(BNGetLicensedUserEmail()) }
558}
559
560pub fn license_path() -> PathBuf {
561 user_directory().join("license.dat")
562}
563
564pub fn license_count() -> i32 {
565 unsafe { BNGetLicenseCount() }
566}
567
568#[derive(Clone, Debug, Eq, PartialEq)]
569pub struct LicenseAddon {
570 pub id: String,
571 pub license_serial: String,
572 pub product: String,
573 pub created: String,
574 pub created_timestamp: u64,
575 pub expiration: String,
576 pub expiration_timestamp: u64,
577 pub signature: String,
578}
579
580pub fn license_addons() -> Vec<LicenseAddon> {
581 let mut count = 0;
582 let addons = unsafe { BNGetLicenseAddons(&mut count) };
583 if addons.is_null() {
584 return Vec::new();
585 }
586
587 let result = unsafe { std::slice::from_raw_parts(addons, count) }
588 .iter()
589 .map(|addon| LicenseAddon {
590 id: unsafe { CStr::from_ptr(addon.id).to_string_lossy().into_owned() },
591 license_serial: unsafe {
592 CStr::from_ptr(addon.licenseSerial)
593 .to_string_lossy()
594 .into_owned()
595 },
596 product: unsafe { CStr::from_ptr(addon.product).to_string_lossy().into_owned() },
597 created: unsafe { CStr::from_ptr(addon.created).to_string_lossy().into_owned() },
598 created_timestamp: addon.createdTimestamp,
599 expiration: unsafe {
600 CStr::from_ptr(addon.expiration)
601 .to_string_lossy()
602 .into_owned()
603 },
604 expiration_timestamp: addon.expirationTimestamp,
605 signature: unsafe {
606 CStr::from_ptr(addon.signature)
607 .to_string_lossy()
608 .into_owned()
609 },
610 })
611 .collect();
612 unsafe { BNFreeLicenseAddons(addons, count) };
613 result
614}
615
616#[cfg(not(feature = "demo"))]
622pub fn set_license(license: Option<&str>) {
623 let license = license.unwrap_or_default().to_cstr();
624 unsafe { BNSetLicense(license.as_ptr()) }
625}
626
627#[cfg(feature = "demo")]
628pub fn set_license(_license: Option<&str>) {}
629
630pub fn product() -> String {
631 unsafe { BnString::into_string(BNGetProduct()) }
632}
633
634pub fn product_type() -> String {
635 unsafe { BnString::into_string(BNGetProductType()) }
636}
637
638pub fn license_expiration_time() -> std::time::SystemTime {
639 let m = std::time::Duration::from_secs(unsafe { BNGetLicenseExpirationTime() });
640 std::time::UNIX_EPOCH + m
641}
642
643pub fn is_ui_enabled() -> bool {
644 unsafe { BNIsUIEnabled() }
645}
646
647pub fn is_database(file: &Path) -> bool {
648 let filename = file.to_cstr();
649 unsafe { BNIsDatabase(filename.as_ptr()) }
650}
651
652pub fn plugin_abi_version() -> u32 {
653 BN_CURRENT_CORE_ABI_VERSION
654}
655
656pub fn plugin_abi_minimum_version() -> u32 {
657 BN_MINIMUM_CORE_ABI_VERSION
658}
659
660pub fn core_abi_version() -> u32 {
661 unsafe { BNGetCurrentCoreABIVersion() }
662}
663
664pub fn core_abi_minimum_version() -> u32 {
665 unsafe { BNGetMinimumCoreABIVersion() }
666}
667
668pub fn plugin_ui_abi_version() -> u32 {
669 BN_CURRENT_UI_ABI_VERSION
670}
671
672pub fn plugin_ui_abi_minimum_version() -> u32 {
673 BN_MINIMUM_UI_ABI_VERSION
674}
675
676pub fn add_required_plugin_dependency(name: &str) {
677 let raw_name = name.to_cstr();
678 unsafe { BNAddRequiredPluginDependency(raw_name.as_ptr()) };
679}
680
681pub fn add_optional_plugin_dependency(name: &str) {
682 let raw_name = name.to_cstr();
683 unsafe { BNAddOptionalPluginDependency(raw_name.as_ptr()) };
684}
685
686#[cfg(not(feature = "no_exports"))]
688#[no_mangle]
689#[allow(non_snake_case)]
690pub extern "C" fn CorePluginABIVersion() -> u32 {
691 plugin_abi_version()
692}
693
694#[cfg(not(feature = "no_exports"))]
696#[no_mangle]
697pub extern "C" fn UIPluginABIVersion() -> u32 {
698 plugin_ui_abi_version()
699}