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
use core::{ffi, mem, ptr};

use binaryninjacore_sys::*;

use crate::project::ProjectFile;
use crate::rc::{CoreArrayProvider, CoreArrayProviderInner};
use crate::string::{BnStrCompatible, BnString};
use crate::symbol::Symbol;

/// An ExternalLibrary is an abstraction for a library that is optionally backed
/// by a [ProjectFile].
#[repr(transparent)]
pub struct ExternalLibrary {
    handle: ptr::NonNull<BNExternalLibrary>,
}

impl Drop for ExternalLibrary {
    fn drop(&mut self) {
        unsafe { BNFreeExternalLibrary(self.as_raw()) }
    }
}

impl Clone for ExternalLibrary {
    fn clone(&self) -> Self {
        unsafe {
            Self::from_raw(ptr::NonNull::new(BNNewExternalLibraryReference(self.as_raw())).unwrap())
        }
    }
}

impl ExternalLibrary {
    pub(crate) unsafe fn from_raw(handle: ptr::NonNull<BNExternalLibrary>) -> Self {
        Self { handle }
    }

    pub(crate) unsafe fn ref_from_raw(handle: &*mut BNExternalLibrary) -> &Self {
        assert!(!handle.is_null());
        mem::transmute(handle)
    }

    #[allow(clippy::mut_from_ref)]
    pub(crate) unsafe fn as_raw(&self) -> &mut BNExternalLibrary {
        &mut *self.handle.as_ptr()
    }

    /// Get the name of this external library
    pub fn name(&self) -> BnString {
        let result = unsafe { BNExternalLibraryGetName(self.as_raw()) };
        assert!(!result.is_null());
        unsafe { BnString::from_raw(result) }
    }

    /// Get the file backing this external library
    pub fn backing_file(&self) -> Option<ProjectFile> {
        let result = unsafe { BNExternalLibraryGetBackingFile(self.as_raw()) };
        let handle = ptr::NonNull::new(result)?;
        Some(unsafe { ProjectFile::from_raw(handle) })
    }

    /// Set the file backing this external library
    pub fn set_backing_file(&self, file: Option<&ProjectFile>) {
        let file_handle = file
            .map(|x| unsafe {x.as_raw() as *mut _})
            .unwrap_or(ptr::null_mut());
        unsafe { BNExternalLibrarySetBackingFile(self.as_raw(), file_handle) }
    }
}

impl CoreArrayProvider for ExternalLibrary {
    type Raw = *mut BNExternalLibrary;
    type Context = ();
    type Wrapped<'a> = &'a Self;
}

unsafe impl CoreArrayProviderInner for ExternalLibrary {
    unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
        BNFreeExternalLibraryList(raw, count)
    }

    unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
        Self::ref_from_raw(raw)
    }
}

/// An ExternalLocation is an association from a source symbol in a binary view
/// to a target symbol and/or address in an [ExternalLibrary].
#[repr(transparent)]
pub struct ExternalLocation {
    handle: ptr::NonNull<BNExternalLocation>,
}

impl Drop for ExternalLocation {
    fn drop(&mut self) {
        unsafe { BNFreeExternalLocation(self.as_raw()) }
    }
}

impl Clone for ExternalLocation {
    fn clone(&self) -> Self {
        unsafe {
            Self::from_raw(
                ptr::NonNull::new(BNNewExternalLocationReference(self.as_raw())).unwrap(),
            )
        }
    }
}

impl ExternalLocation {
    pub(crate) unsafe fn from_raw(handle: ptr::NonNull<BNExternalLocation>) -> Self {
        Self { handle }
    }

    pub(crate) unsafe fn ref_from_raw(handle: &*mut BNExternalLocation) -> &Self {
        assert!(!handle.is_null());
        mem::transmute(handle)
    }

    #[allow(clippy::mut_from_ref)]
    pub(crate) unsafe fn as_raw(&self) -> &mut BNExternalLocation {
        &mut *self.handle.as_ptr()
    }

    /// Get the source symbol for this ExternalLocation
    pub fn source_symbol(&self) -> Symbol {
        let result = unsafe { BNExternalLocationGetSourceSymbol(self.as_raw()) };
        assert!(!result.is_null());
        unsafe { Symbol::from_raw(result) }
    }

    /// Get the ExternalLibrary that this ExternalLocation targets
    pub fn library(&self) -> Option<ExternalLibrary> {
        let result = unsafe { BNExternalLocationGetExternalLibrary(self.as_raw()) };
        let handle = ptr::NonNull::new(result)?;
        Some(unsafe { ExternalLibrary::from_raw(handle) })
    }

    /// Set the ExternalLibrary that this ExternalLocation targets
    pub fn set_external_library(&self, lib: Option<&ExternalLibrary>) {
        let lib_handle = lib
            .map(|x| unsafe {x.as_raw() as *mut _})
            .unwrap_or(ptr::null_mut());
        unsafe { BNExternalLocationSetExternalLibrary(self.as_raw(), lib_handle) }
    }

    /// Check if this ExternalLocation has a target address
    pub fn has_target_address(&self) -> bool {
        unsafe { BNExternalLocationHasTargetAddress(self.as_raw()) }
    }

    /// Check if this ExternalLocation has a target symbol
    pub fn has_target_symbol(&self) -> bool {
        unsafe { BNExternalLocationHasTargetSymbol(self.as_raw()) }
    }

    /// Get the address pointed to by this ExternalLocation, if any
    pub fn target_address(&self) -> Option<u64> {
        self.has_target_address()
            .then(|| unsafe { BNExternalLocationGetTargetAddress(self.as_raw()) })
    }

    /// Set the address pointed to by this ExternalLocation.
    /// ExternalLocations must have a valid target address and/or symbol set.
    pub fn set_target_address(&self, mut address: Option<u64>) -> bool {
        let address_ptr = address
            .as_mut()
            .map(|x| x as *mut u64)
            .unwrap_or(ptr::null_mut());
        unsafe { BNExternalLocationSetTargetAddress(self.as_raw(), address_ptr) }
    }

    /// Get the symbol pointed to by this ExternalLocation, if any
    pub fn target_symbol(&self) -> Option<BnString> {
        self.has_target_symbol().then(|| unsafe {
            let result = BNExternalLocationGetTargetSymbol(self.as_raw());
            assert!(!result.is_null());
            BnString::from_raw(result)
        })
    }

    /// Set the symbol pointed to by this ExternalLocation.
    /// ExternalLocations must have a valid target address and/or symbol set.
    pub fn set_target_symbol<S: BnStrCompatible>(&self, symbol: Option<S>) -> bool {
        let symbol = symbol
            .map(|x| x.into_bytes_with_nul().as_ref().as_ptr() as *const ffi::c_char)
            .unwrap_or(ptr::null_mut());
        unsafe {
            BNExternalLocationSetTargetSymbol(
                self.as_raw(),
                symbol,
            )
        }
    }
}

impl CoreArrayProvider for ExternalLocation {
    type Raw = *mut BNExternalLocation;
    type Context = ();
    type Wrapped<'a> = &'a Self;
}

unsafe impl CoreArrayProviderInner for ExternalLocation {
    unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
        BNFreeExternalLocationList(raw, count)
    }

    unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
        Self::ref_from_raw(raw)
    }
}