summaryrefslogtreecommitdiff
path: root/plugins/workflow_objc/src/metadata/global_state.rs
blob: db29af49816640bd6de1f15f2873dfed8a626e63 (plain)
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
use binaryninja::file_metadata::SessionId;
use binaryninja::{
    binary_view::{BinaryView, BinaryViewBase, BinaryViewExt},
    file_metadata::FileMetadata,
    metadata::Metadata,
    rc::Ref,
    settings::{QueryOptions, Settings},
    ObjectDestructor,
};
use dashmap::DashMap;
use once_cell::sync::Lazy;
use std::{
    collections::{HashMap, HashSet},
    ops::Range,
    sync::{Arc, RwLock},
};

pub struct AnalysisInfo {
    pub image_base: u64,
    pub objc_stubs: Option<Range<u64>>,
    pub should_rewrite_to_direct_calls: bool,
    selector_impls: RwLock<SelectorImplsState>,
}

enum SelectorImplsState {
    NotLoaded,
    Loaded(Option<SelectorImplementations>),
}

struct SelectorImplementations {
    sel_ref_to_impl: HashMap<u64, Vec<u64>>,
    sel_to_impl: HashMap<u64, Vec<u64>>,
}

static VIEW_INFOS: Lazy<DashMap<SessionId, Arc<AnalysisInfo>>> = Lazy::new(DashMap::new);
static IGNORED_VIEWS: Lazy<DashMap<SessionId, bool>> = Lazy::new(DashMap::new);

struct ObjectLifetimeObserver;

impl ObjectDestructor for ObjectLifetimeObserver {
    fn destruct_file_metadata(&self, metadata: &FileMetadata) {
        let id = metadata.session_id();
        VIEW_INFOS.remove(&id);
        IGNORED_VIEWS.remove(&id);
    }
}

static SUPPORTED_ARCHS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
    let mut m = HashSet::new();
    m.insert("aarch64");
    m.insert("x86_64");
    m.insert("armv7");
    m.insert("thumb2");
    m
});

fn is_supported_arch(bv: &BinaryView) -> bool {
    let arch_name = bv
        .default_arch()
        .map(|arch| arch.name())
        .unwrap_or_default();
    SUPPORTED_ARCHS.contains(&arch_name as &str)
}

pub struct GlobalState;

impl GlobalState {
    pub fn register_cleanup() {
        let observer = Box::leak(Box::new(ObjectLifetimeObserver));
        observer.register();
    }

    fn id(bv: &BinaryView) -> SessionId {
        bv.file().session_id()
    }

    pub fn analysis_info(bv: &BinaryView) -> Option<Arc<AnalysisInfo>> {
        let id = Self::id(bv);

        if let Some(info) = VIEW_INFOS.get(&id) {
            if bv.start() == info.image_base {
                return Some(info.clone());
            }
        }

        let info = Arc::new(AnalysisInfo::from_view(bv)?);
        VIEW_INFOS.insert(id, info.clone());
        Some(info)
    }

    pub fn should_ignore_view(bv: &BinaryView) -> bool {
        if let Some(ignore) = IGNORED_VIEWS.get(&Self::id(bv)) {
            return *ignore;
        }

        let ignore = !(is_supported_arch(bv) && AnalysisInfo::has_metadata(bv));
        IGNORED_VIEWS.insert(Self::id(bv), ignore);
        ignore
    }
}

impl AnalysisInfo {
    fn from_view(bv: &BinaryView) -> Option<Self> {
        let should_rewrite_to_direct_calls = Settings::new().get_bool_with_opts(
            "analysis.objectiveC.resolveDynamicDispatch",
            &mut QueryOptions::new_with_view(bv),
        );
        let info = AnalysisInfo {
            image_base: bv.start(),
            objc_stubs: bv
                .section_by_name("__objc_stubs")
                .map(|section| section.start()..section.end()),
            should_rewrite_to_direct_calls,
            selector_impls: RwLock::new(SelectorImplsState::NotLoaded),
        };
        if !Self::has_metadata(bv) {
            return None;
        }
        Some(info)
    }

    fn has_metadata(bv: &BinaryView) -> bool {
        bv.query_metadata("Objective-C").is_some()
    }

    pub fn get_selector_impl(&self, bv: &BinaryView, selector_addr: u64) -> Option<u64> {
        let get = |impls: &SelectorImplementations| {
            impls
                .sel_ref_to_impl
                .get(&selector_addr)
                .or_else(|| impls.sel_to_impl.get(&selector_addr))
                .and_then(|v| v.first().copied())
                .filter(|&addr| addr != 0)
        };

        let cache = self.selector_impls.read().unwrap();
        match &*cache {
            SelectorImplsState::Loaded(Some(impls)) => return get(impls),
            SelectorImplsState::Loaded(None) => return None,
            SelectorImplsState::NotLoaded => {}
        }
        drop(cache);

        let mut cache = self.selector_impls.write().unwrap();
        if let SelectorImplsState::NotLoaded = &*cache {
            *cache = SelectorImplsState::Loaded(self.load_selector_impls(bv));
        }

        if let SelectorImplsState::Loaded(Some(impls)) = &*cache {
            get(impls)
        } else {
            None
        }
    }

    fn load_selector_impls(&self, bv: &BinaryView) -> Option<SelectorImplementations> {
        let Some(Ok(meta)) = bv.get_metadata::<HashMap<String, Ref<Metadata>>>("Objective-C")
        else {
            return None;
        };
        let version_meta = meta.get("version")?;
        if version_meta.get_unsigned_integer()? != 1 {
            tracing::error!(
                "workflow_objc: Unexpected Objective-C metadata version. Expected 1, got {}.",
                version_meta.get_unsigned_integer()?
            );
            return None;
        }

        let mut sel_ref_to_impl = HashMap::new();
        if let Some(sel_ref_to_impl_meta) = meta.get("selRefImplementations") {
            if let Some(map) = Self::parse_selector_impls(sel_ref_to_impl_meta) {
                sel_ref_to_impl = map;
            }
        }

        let mut sel_to_impl = HashMap::new();
        if let Some(sel_to_impl_meta) = meta.get("selImplementations") {
            if let Some(map) = Self::parse_selector_impls(sel_to_impl_meta) {
                sel_to_impl = map;
            }
        }

        Some(SelectorImplementations {
            sel_ref_to_impl,
            sel_to_impl,
        })
    }

    fn parse_selector_impls(meta: &Metadata) -> Option<HashMap<u64, Vec<u64>>> {
        let array = meta.get_array()?;
        let mut result = HashMap::new();
        for item in &array {
            let item = item.get_array()?;
            if item.len() != 2 {
                tracing::warn!(
                    "Expected selector implementation metadata to have 2 items, found {}",
                    item.len()
                );
                return None;
            }
            let selector = item.get(0).get_unsigned_integer()?;
            let impls_meta = item.get(1).get_unsigned_integer_list()?;
            result.insert(selector, impls_meta);
        }
        Some(result)
    }
}