binaryninja/database/
snapshot.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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use crate::data_buffer::DataBuffer;
use crate::database::kvs::KeyValueStore;
use crate::database::undo::UndoEntry;
use crate::database::Database;
use crate::progress::ProgressCallback;
use crate::rc::{Array, CoreArrayProvider, CoreArrayProviderInner, Guard, Ref, RefCountable};
use crate::string::{BnStrCompatible, BnString};
use binaryninjacore_sys::{
    BNCollaborationFreeSnapshotIdList, BNFreeSnapshot, BNFreeSnapshotList, BNGetSnapshotChildren,
    BNGetSnapshotDatabase, BNGetSnapshotFileContents, BNGetSnapshotFileContentsHash,
    BNGetSnapshotFirstParent, BNGetSnapshotId, BNGetSnapshotName, BNGetSnapshotParents,
    BNGetSnapshotUndoData, BNGetSnapshotUndoEntries, BNGetSnapshotUndoEntriesWithProgress,
    BNIsSnapshotAutoSave, BNNewSnapshotReference, BNReadSnapshotData,
    BNReadSnapshotDataWithProgress, BNSetSnapshotName, BNSnapshot, BNSnapshotHasAncestor,
    BNSnapshotHasContents, BNSnapshotHasUndo, BNSnapshotStoreData,
};
use std::ffi::{c_char, c_void};
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::ptr::NonNull;

pub struct Snapshot {
    pub(crate) handle: NonNull<BNSnapshot>,
}

impl Snapshot {
    pub(crate) unsafe fn from_raw(handle: NonNull<BNSnapshot>) -> Self {
        Self { handle }
    }

    pub(crate) unsafe fn ref_from_raw(handle: NonNull<BNSnapshot>) -> Ref<Self> {
        Ref::new(Self { handle })
    }

    /// Get the owning database
    pub fn database(&self) -> Database {
        unsafe {
            Database::from_raw(NonNull::new(BNGetSnapshotDatabase(self.handle.as_ptr())).unwrap())
        }
    }

    /// Get the numerical id
    pub fn id(&self) -> SnapshotId {
        SnapshotId(unsafe { BNGetSnapshotId(self.handle.as_ptr()) })
    }

    /// Get the displayed snapshot name
    pub fn name(&self) -> BnString {
        unsafe { BnString::from_raw(BNGetSnapshotName(self.handle.as_ptr())) }
    }

    /// Set the displayed snapshot name
    pub fn set_name<S: BnStrCompatible>(&self, value: S) {
        let value_raw = value.into_bytes_with_nul();
        let value_ptr = value_raw.as_ref().as_ptr() as *const c_char;
        unsafe { BNSetSnapshotName(self.handle.as_ptr(), value_ptr) }
    }

    /// If the snapshot was the result of an auto-save
    pub fn is_auto_save(&self) -> bool {
        unsafe { BNIsSnapshotAutoSave(self.handle.as_ptr()) }
    }

    /// If the snapshot has contents, and has not been trimmed
    pub fn has_contents(&self) -> bool {
        unsafe { BNSnapshotHasContents(self.handle.as_ptr()) }
    }

    /// If the snapshot has undo data
    pub fn has_undo(&self) -> bool {
        unsafe { BNSnapshotHasUndo(self.handle.as_ptr()) }
    }

    /// Get the first parent of the snapshot, or None if it has no parents
    pub fn first_parent(&self) -> Option<Snapshot> {
        let result = unsafe { BNGetSnapshotFirstParent(self.handle.as_ptr()) };
        NonNull::new(result).map(|s| unsafe { Snapshot::from_raw(s) })
    }

    /// Get a list of all parent snapshots of the snapshot
    pub fn parents(&self) -> Array<Snapshot> {
        let mut count = 0;
        let result = unsafe { BNGetSnapshotParents(self.handle.as_ptr(), &mut count) };
        assert!(!result.is_null());
        unsafe { Array::new(result, count, ()) }
    }

    /// Get a list of all child snapshots of the snapshot
    pub fn children(&self) -> Array<Snapshot> {
        let mut count = 0;
        let result = unsafe { BNGetSnapshotChildren(self.handle.as_ptr(), &mut count) };
        assert!(!result.is_null());
        unsafe { Array::new(result, count, ()) }
    }

    /// Get a buffer of the raw data at the time of the snapshot
    pub fn file_contents(&self) -> Option<DataBuffer> {
        self.has_contents().then(|| unsafe {
            let result = BNGetSnapshotFileContents(self.handle.as_ptr());
            assert!(!result.is_null());
            DataBuffer::from_raw(result)
        })
    }

    /// Get a hash of the data at the time of the snapshot
    pub fn file_contents_hash(&self) -> Option<DataBuffer> {
        self.has_contents().then(|| unsafe {
            let result = BNGetSnapshotFileContentsHash(self.handle.as_ptr());
            assert!(!result.is_null());
            DataBuffer::from_raw(result)
        })
    }

    /// Get a list of undo entries at the time of the snapshot
    pub fn undo_entries(&self) -> Array<UndoEntry> {
        assert!(self.has_undo());
        let mut count = 0;
        let result = unsafe { BNGetSnapshotUndoEntries(self.handle.as_ptr(), &mut count) };
        assert!(!result.is_null());
        unsafe { Array::new(result, count, ()) }
    }

    pub fn undo_entries_with_progress<P: ProgressCallback>(
        &self,
        mut progress: P,
    ) -> Array<UndoEntry> {
        assert!(self.has_undo());
        let mut count = 0;

        let result = unsafe {
            BNGetSnapshotUndoEntriesWithProgress(
                self.handle.as_ptr(),
                &mut progress as *mut P as *mut c_void,
                Some(P::cb_progress_callback),
                &mut count,
            )
        };

        assert!(!result.is_null());
        unsafe { Array::new(result, count, ()) }
    }

    /// Get the backing kvs data with snapshot fields
    pub fn read_data(&self) -> Ref<KeyValueStore> {
        let result = unsafe { BNReadSnapshotData(self.handle.as_ptr()) };
        unsafe { KeyValueStore::ref_from_raw(NonNull::new(result).unwrap()) }
    }

    pub fn read_data_with_progress<P: ProgressCallback>(
        &self,
        mut progress: P,
    ) -> Ref<KeyValueStore> {
        let result = unsafe {
            BNReadSnapshotDataWithProgress(
                self.handle.as_ptr(),
                &mut progress as *mut P as *mut c_void,
                Some(P::cb_progress_callback),
            )
        };

        unsafe { KeyValueStore::ref_from_raw(NonNull::new(result).unwrap()) }
    }

    pub fn undo_data(&self) -> DataBuffer {
        let result = unsafe { BNGetSnapshotUndoData(self.handle.as_ptr()) };
        assert!(!result.is_null());
        DataBuffer::from_raw(result)
    }

    pub fn store_data(&self, data: &KeyValueStore) -> bool {
        unsafe {
            BNSnapshotStoreData(
                self.handle.as_ptr(),
                data.handle.as_ptr(),
                std::ptr::null_mut(),
                None,
            )
        }
    }

    pub fn store_data_with_progress<P: ProgressCallback>(
        &self,
        data: &KeyValueStore,
        mut progress: P,
    ) -> bool {
        unsafe {
            BNSnapshotStoreData(
                self.handle.as_ptr(),
                data.handle.as_ptr(),
                &mut progress as *mut P as *mut c_void,
                Some(P::cb_progress_callback),
            )
        }
    }

    /// Determine if this snapshot has another as an ancestor
    pub fn has_ancestor(self, other: &Snapshot) -> bool {
        unsafe { BNSnapshotHasAncestor(self.handle.as_ptr(), other.handle.as_ptr()) }
    }
}

impl Debug for Snapshot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Snapshot")
            .field("id", &self.id())
            .field("name", &self.name())
            .field("is_auto_save", &self.is_auto_save())
            .field("has_contents", &self.has_contents())
            .field("has_undo", &self.has_undo())
            // TODO: This might be too much.
            .field("children", &self.children().to_vec())
            .finish()
    }
}

impl ToOwned for Snapshot {
    type Owned = Ref<Self>;

    fn to_owned(&self) -> Self::Owned {
        unsafe { RefCountable::inc_ref(self) }
    }
}

unsafe impl RefCountable for Snapshot {
    unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
        Ref::new(Self {
            handle: NonNull::new(BNNewSnapshotReference(handle.handle.as_ptr())).unwrap(),
        })
    }

    unsafe fn dec_ref(handle: &Self) {
        BNFreeSnapshot(handle.handle.as_ptr());
    }
}

impl CoreArrayProvider for Snapshot {
    type Raw = *mut BNSnapshot;
    type Context = ();
    type Wrapped<'a> = Guard<'a, Snapshot>;
}

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

    unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> {
        let raw_ptr = NonNull::new(*raw).unwrap();
        Guard::new(Self::from_raw(raw_ptr), context)
    }
}

#[repr(transparent)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SnapshotId(pub i64);

impl Display for SnapshotId {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("{}", self.0))
    }
}

impl CoreArrayProvider for SnapshotId {
    type Raw = i64;
    type Context = ();
    type Wrapped<'a> = SnapshotId;
}

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

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