Skip to main content

binaryninja/binary_view/
search.rs

1use binaryninjacore_sys::BNDetectSearchMode;
2use serde_derive::{Deserialize, Serialize};
3
4use crate::string::{BnString, IntoCStr};
5
6/// The parser a [`SearchQuery`] pattern is read with.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum SearchType {
10    /// Try FlexHex, then YARA hex, then regex, then a raw string.
11    #[default]
12    Auto,
13    /// Hex bytes with `??` and nibble wildcards, ex. "42 2e ?? 6?".
14    FlexHex,
15    /// A YARA hex string, with jumps, alternation and negation.
16    Yara,
17    /// A byte-level regular expression.
18    Regex,
19    /// A literal string.
20    Raw,
21}
22
23#[derive(Debug, Clone, Default, Serialize, Deserialize)]
24pub struct SearchQuery {
25    /// ex. "42 2e 64 65 ?? 75 67 24"
26    pattern: String,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    start: Option<u64>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    end: Option<u64>,
31    #[serde(rename = "ignoreCase")]
32    ignore_case: bool,
33    raw: bool,
34    overlap: bool,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    align: Option<u64>,
37    /// Force a parser for the pattern; the core auto-detects one when unset.
38    #[serde(rename = "searchType", skip_serializing_if = "Option::is_none")]
39    search_type: Option<SearchType>,
40}
41
42impl SearchQuery {
43    pub fn new(pattern: impl Into<String>) -> Self {
44        Self {
45            pattern: pattern.into(),
46            ..Default::default()
47        }
48    }
49
50    /// Set the starting address for the search
51    pub fn start(mut self, addr: u64) -> Self {
52        self.start = Some(addr);
53        self
54    }
55
56    /// Set the ending address for the search (inclusive)
57    pub fn end(mut self, addr: u64) -> Self {
58        self.end = Some(addr);
59        self
60    }
61
62    /// Set whether to interpret the pattern as a raw string
63    pub fn raw(mut self, raw: bool) -> Self {
64        self.raw = raw;
65        self
66    }
67
68    /// Set whether to perform case-insensitive matching
69    pub fn ignore_case(mut self, ignore_case: bool) -> Self {
70        self.ignore_case = ignore_case;
71        self
72    }
73
74    /// Set whether to allow matches to overlap
75    pub fn overlap(mut self, overlap: bool) -> Self {
76        self.overlap = overlap;
77        self
78    }
79
80    /// Set the alignment of matches (must be a power of 2)
81    pub fn align(mut self, align: u64) -> Self {
82        // Validate that align is a power of 2
83        if align != 0 && (align & (align - 1)) == 0 {
84            self.align = Some(align);
85        }
86        self
87    }
88
89    /// Force the parser the pattern is read with. With an explicit type, a
90    /// pattern that type can't parse is an error rather than falling through
91    /// to another type.
92    pub fn search_type(mut self, search_type: SearchType) -> Self {
93        self.search_type = Some(search_type);
94        self
95    }
96}
97
98impl SearchQuery {
99    /// The name of the parser the core would read the pattern with, ex.
100    /// "FlexHex" or "Regex", or the core's error message when the pattern
101    /// doesn't parse.
102    pub fn detect_mode(&self) -> Result<String, String> {
103        let query = self.to_json().to_cstr();
104        let mode = unsafe { BnString::into_string(BNDetectSearchMode(query.as_ptr())) };
105        match mode.strip_prefix("Error: ") {
106            Some(err) => Err(err.to_owned()),
107            None => Ok(mode),
108        }
109    }
110
111    /// Serialize the query to a JSON string
112    pub fn to_json(&self) -> String {
113        serde_json::to_string(self).expect("failed to serialize search query")
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn test_search_query_builder() {
123        let query = SearchQuery::new("test pattern")
124            .start(0x1000)
125            .end(0x2000)
126            .raw(true)
127            .ignore_case(true)
128            .overlap(false)
129            .align(16);
130
131        assert_eq!(query.pattern, "test pattern");
132        assert_eq!(query.start, Some(0x1000));
133        assert_eq!(query.end, Some(0x2000));
134        assert!(query.raw);
135        assert!(query.ignore_case);
136        assert!(!query.overlap);
137        assert_eq!(query.align, Some(16));
138    }
139
140    #[test]
141    fn test_search_query_json() {
142        let query = SearchQuery::new("test").start(0x1000).align(8);
143
144        let json = query.to_json();
145        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
146
147        assert_eq!(parsed["pattern"], "test");
148        assert_eq!(parsed["start"], 4096);
149        assert_eq!(parsed["align"], 8);
150        assert!(!parsed.as_object().unwrap().contains_key("end"));
151        assert!(!parsed.as_object().unwrap().contains_key("searchType"));
152    }
153
154    #[test]
155    fn test_search_query_search_type_json() {
156        for (search_type, name) in [
157            (SearchType::Auto, "auto"),
158            (SearchType::FlexHex, "flexhex"),
159            (SearchType::Yara, "yara"),
160            (SearchType::Regex, "regex"),
161            (SearchType::Raw, "raw"),
162        ] {
163            let json = SearchQuery::new("test").search_type(search_type).to_json();
164            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
165            assert_eq!(parsed["searchType"], name);
166        }
167    }
168}