forked from Vector35/binaryninja-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinaryview.py
11156 lines (9439 loc) · 420 KB
/
binaryview.py
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright (c) 2015-2025 Vector 35 Inc
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import struct
import threading
import queue
import traceback
import ctypes
import abc
import json
import pprint
import inspect
import os
import uuid
from typing import Callable, Generator, Optional, Union, Tuple, List, Mapping, Any, \
Iterator, Iterable, KeysView, ItemsView, ValuesView, Dict, overload
from dataclasses import dataclass
from enum import IntFlag
import collections
from collections import defaultdict, OrderedDict, deque
# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
from . import decorators
from .enums import (
AnalysisState, SymbolType, Endianness, ModificationStatus, StringType, SegmentFlag, SectionSemantics, FindFlag,
TypeClass, BinaryViewEventType, FunctionGraphType, TagReferenceType, TagTypeType, RegisterValueType, DisassemblyOption,
RelocationType
)
from .exceptions import RelocationWriteException, ExternalLinkException
from . import associateddatastore # required for _BinaryViewAssociatedDataStore
from .log import log_warn, log_error, Logger
from . import typelibrary
from . import fileaccessor
from . import databuffer
from . import basicblock
from . import component
from . import lineardisassembly
from . import metadata
from . import highlight
from . import settings
from . import variable
from . import architecture
from . import filemetadata
from . import lowlevelil
from . import mainthread
from . import mediumlevelil
from . import highlevelil
from . import debuginfo
from . import flowgraph
from . import project
from . import typearchive
# The following are imported as such to allow the type checker disambiguate the module name
# from properties and methods of the same name
from . import workflow as _workflow
from . import function as _function
from . import types as _types
from . import platform as _platform
from . import deprecation
from . import typecontainer
from . import externallibrary
from . import project
from . import undo
PathType = Union[str, os.PathLike]
InstructionsType = Generator[Tuple[List['_function.InstructionTextToken'], int], None, None]
NotificationType = Mapping['BinaryDataNotification', 'BinaryDataNotificationCallbacks']
ProgressFuncType = Callable[[int, int], bool]
DataMatchCallbackType = Callable[[int, 'databuffer.DataBuffer'], bool]
LineMatchCallbackType = Callable[[int, 'lineardisassembly.LinearDisassemblyLine'], bool]
StringOrType = Union[str, '_types.Type', '_types.TypeBuilder']
@dataclass(frozen=True)
class ReferenceSource:
function: Optional['_function.Function']
arch: Optional['architecture.Architecture']
address: int
def __repr__(self):
if self.arch:
return f"<ref: {self.arch.name}@{self.address:#x}>"
else:
return f"<ref: {self.address:#x}>"
@classmethod
def _from_core_struct(cls, view: 'BinaryView', ref: core.BNReferenceSource) -> 'ReferenceSource':
if ref.func:
func = _function.Function(view, core.BNNewFunctionReference(ref.func))
else:
func = None
if ref.arch:
arch = architecture.CoreArchitecture._from_cache(ref.arch)
else:
arch = None
return ReferenceSource(func, arch, ref.addr)
@property
def llil(self) -> Optional[lowlevelil.LowLevelILInstruction]:
"""Returns the low level il instruction at the current location if one exists"""
if self.function is None or self.arch is None:
return None
return self.function.get_low_level_il_at(self.address, self.arch)
@property
def mlil(self) -> Optional[mediumlevelil.MediumLevelILInstruction]:
"""Returns the medium level il instruction at the current location if one exists"""
llil = self.llil
return llil.mlil if llil is not None else None
@property
def hlil(self) -> Optional[highlevelil.HighLevelILInstruction]:
"""Returns the high level il instruction at the current location if one exists"""
mlil = self.mlil
return mlil.hlil if mlil is not None else None
class NotificationType(IntFlag):
NotificationBarrier = 1 << 0
DataWritten = 1 << 1
DataInserted = 1 << 2
DataRemoved = 1 << 3
FunctionAdded = 1 << 4
FunctionRemoved = 1 << 5
FunctionUpdated = 1 << 6
FunctionUpdateRequested = 1 << 7
DataVariableAdded = 1 << 8
DataVariableRemoved = 1 << 9
DataVariableUpdated = 1 << 10
DataMetadataUpdated = 1 << 11
TagTypeUpdated = 1 << 12
TagAdded = 1 << 13
TagRemoved = 1 << 14
TagUpdated = 1 << 15
SymbolAdded = 1 << 16
SymbolRemoved = 1 << 17
SymbolUpdated = 1 << 18
StringFound = 1 << 19
StringRemoved = 1 << 20
TypeDefined = 1 << 21
TypeUndefined = 1 << 22
TypeReferenceChanged = 1 << 23
TypeFieldReferenceChanged = 1 << 24
SegmentAdded = 1 << 25
SegmentRemoved = 1 << 26
SegmentUpdated = 1 << 27
SectionAdded = 1 << 28
SectionRemoved = 1 << 29
SectionUpdated = 1 << 30
ComponentNameUpdated = 1 << 31
ComponentAdded = 1 << 32
ComponentRemoved = 1 << 33
ComponentMoved = 1 << 34
ComponentFunctionAdded = 1 << 35
ComponentFunctionRemoved = 1 << 36
ComponentDataVariableAdded = 1 << 37
ComponentDataVariableRemoved = 1 << 38
ExternalLibraryAdded = 1 << 39
ExternalLibraryRemoved = 1 << 40
ExternalLibraryUpdated = 1 << 41
ExternalLocationAdded = 1 << 42
ExternalLocationRemoved = 1 << 43
ExternalLocationUpdated = 1 << 44
TypeArchiveAttached = 1 << 45
TypeArchiveDetached = 1 << 46
TypeArchiveConnected = 1 << 47
TypeArchiveDisconnected = 1 << 48
UndoEntryAdded = 1 << 49
UndoEntryTaken = 1 << 50
RedoEntryTaken = 1 << 51
BinaryDataUpdates = DataWritten | DataInserted | DataRemoved
FunctionLifetime = FunctionAdded | FunctionRemoved
FunctionUpdates = FunctionLifetime | FunctionUpdated
DataVariableLifetime = DataVariableAdded | DataVariableRemoved
DataVariableUpdates = DataVariableLifetime | DataVariableUpdated
TagLifetime = TagAdded | TagRemoved
TagUpdates = TagLifetime | TagUpdated
SymbolLifetime = SymbolAdded | SymbolRemoved
SymbolUpdates = SymbolLifetime | SymbolUpdated
StringUpdates = StringFound | StringRemoved
TypeLifetime = TypeDefined | TypeUndefined
TypeUpdates = TypeLifetime | TypeReferenceChanged | TypeFieldReferenceChanged
SegmentLifetime = SegmentAdded | SegmentRemoved
SegmentUpdates = SegmentLifetime | SegmentUpdated
SectionLifetime = SectionAdded | SectionRemoved
SectionUpdates = SectionLifetime | SectionUpdated
ComponentUpdates = ComponentAdded | ComponentRemoved | ComponentMoved | ComponentFunctionAdded | ComponentFunctionRemoved | ComponentDataVariableAdded | ComponentDataVariableRemoved
ExternalLibraryLifetime = ExternalLibraryAdded | ExternalLibraryRemoved
ExternalLibraryUpdates = ExternalLibraryLifetime | ExternalLibraryUpdated
ExternalLocationLifetime = ExternalLocationAdded | ExternalLocationRemoved
ExternalLocationUpdates = ExternalLocationLifetime | ExternalLocationUpdated
TypeArchiveUpdates = TypeArchiveAttached | TypeArchiveDetached | TypeArchiveConnected | TypeArchiveDisconnected
UndoUpdates = UndoEntryAdded | UndoEntryTaken | RedoEntryTaken
class BinaryDataNotification:
"""
``class BinaryDataNotification`` provides an interface for receiving event notifications. Usage requires inheriting
from this interface, overriding the relevant event handlers, and registering the `BinaryDataNotification` instance
with a `BinaryView` using the `register_notification` method.
By default, a `BinaryDataNotification` instance receives notifications for all available notification types. It
is recommended for users of this interface to initialize the `BinaryDataNotification` base class with specific
callbacks of interest by passing the appropriate `NotificationType` flags into the `__init__` constructor.
Handlers provided by the user should aim to limit the amount of processing within the callback. The
callback context holds a global lock, preventing other threads from making progress during the callback phase.
While most of the API can be used safely during this time, care must be taken when issuing a call that can block,
as waiting for a thread requiring the global lock can result in deadlock.
The `NotificationBarrier` is a special `NotificationType` that is disabled by default. To enable it, the
`NotificationBarrier` flag must be passed to `__init__`. This notification is designed to facilitate efficient
batch processing of other notification types. The idea is to collect other notifications of interest into a cache,
which can be very efficient as it doesn't require additional locks. After some time, the core generates a
`NotificationBarrier` event, providing a safe context to move the cache for processing by a different thread.
To control the time of the next `NotificationBarrier` event, return the desired number of milliseconds until
the next event from the `NotificationBarrier` callback. Returning zero quiesces future `NotificationBarrier`
events. If the `NotificationBarrier` is quiesced, the reception of a new callback of interest automatically
generates a new `NotificationBarrier` call after that notification is delivered. This mechanism effectively
allows throttling and quiescing when necessary.
.. note:: Note that the core generates a `NotificationBarrier` as part of the `BinaryDataNotification` registration \
process. Registering the same `BinaryDataNotification` instance again results in a gratuitous `NotificationBarrier` \
event, which can be useful in situations requiring a safe context for processing due to some other asynchronous \
event (e.g., user interaction).
:Example:
>>> class NotifyTest(binaryninja.BinaryDataNotification):
... def __init__(self):
... super(NotifyTest, self).__init__(binaryninja.NotificationType.NotificationBarrier | binaryninja.NotificationType.FunctionLifetime | binaryninja.NotificationType.FunctionUpdated)
... self.received_event = False
... def notification_barrier(self, view: 'BinaryView') -> int:
... has_events = self.received_event
... self.received_event = False
... log_info("notification_barrier")
... if has_events:
... return 250
... else:
... return 0
... def function_added(self, view: 'BinaryView', func: '_function.Function') -> None:
... self.received_event = True
... log_info("function_added")
... def function_removed(self, view: 'BinaryView', func: '_function.Function') -> None:
... self.received_event = True
... log_info("function_removed")
... def function_updated(self, view: 'BinaryView', func: '_function.Function') -> None:
... self.received_event = True
... log_info("function_updated")
...
>>>
>>> bv.register_notification(NotifyTest())
>>>
"""
def __init__(self, notifications: NotificationType = None):
self.notifications = notifications
def notification_barrier(self, view: 'BinaryView') -> int:
return 0
def data_written(self, view: 'BinaryView', offset: int, length: int) -> None:
pass
def data_inserted(self, view: 'BinaryView', offset: int, length: int) -> None:
pass
def data_removed(self, view: 'BinaryView', offset: int, length: int) -> None:
pass
def function_added(self, view: 'BinaryView', func: '_function.Function') -> None:
"""
.. note:: `function_updated` will be triggered instead when a user function is added over an auto function.
"""
pass
def function_removed(self, view: 'BinaryView', func: '_function.Function') -> None:
"""
.. note:: `function_updated` will be triggered instead when a user function is removed over an auto function.
"""
pass
def function_updated(self, view: 'BinaryView', func: '_function.Function') -> None:
pass
def function_update_requested(self, view: 'BinaryView', func: '_function.Function') -> None:
pass
def data_var_added(self, view: 'BinaryView', var: 'DataVariable') -> None:
"""
.. note:: `data_var_updated` will be triggered instead when a user data variable is added over an auto data variable.
"""
pass
def data_var_removed(self, view: 'BinaryView', var: 'DataVariable') -> None:
"""
.. note:: `data_var_updated` will be triggered instead when a user data variable is removed over an auto data variable.
"""
pass
def data_var_updated(self, view: 'BinaryView', var: 'DataVariable') -> None:
pass
def data_metadata_updated(self, view: 'BinaryView', offset: int) -> None:
pass
def tag_type_updated(self, view: 'BinaryView', tag_type) -> None:
pass
def tag_added(
self, view: 'BinaryView', tag: 'Tag', ref_type: TagReferenceType, auto_defined: bool,
arch: Optional['architecture.Architecture'], func: Optional[_function.Function], addr: int
) -> None:
pass
def tag_updated(
self, view: 'BinaryView', tag: 'Tag', ref_type: TagReferenceType, auto_defined: bool,
arch: Optional['architecture.Architecture'], func: Optional[_function.Function], addr: int
) -> None:
pass
def tag_removed(
self, view: 'BinaryView', tag: 'Tag', ref_type: TagReferenceType, auto_defined: bool,
arch: Optional['architecture.Architecture'], func: Optional[_function.Function], addr: int
) -> None:
pass
def symbol_added(self, view: 'BinaryView', sym: '_types.CoreSymbol') -> None:
pass
def symbol_updated(self, view: 'BinaryView', sym: '_types.CoreSymbol') -> None:
pass
def symbol_removed(self, view: 'BinaryView', sym: '_types.CoreSymbol') -> None:
pass
def string_found(self, view: 'BinaryView', string_type: StringType, offset: int, length: int) -> None:
pass
def string_removed(self, view: 'BinaryView', string_type: StringType, offset: int, length: int) -> None:
pass
def type_defined(self, view: 'BinaryView', name: '_types.QualifiedName', type: '_types.Type') -> None:
pass
def type_undefined(self, view: 'BinaryView', name: '_types.QualifiedName', type: '_types.Type') -> None:
pass
def type_ref_changed(self, view: 'BinaryView', name: '_types.QualifiedName', type: '_types.Type') -> None:
pass
def type_field_ref_changed(self, view: 'BinaryView', name: '_types.QualifiedName', offset: int) -> None:
pass
def segment_added(self, view: 'BinaryView', segment: 'Segment') -> None:
pass
def segment_updated(self, view: 'BinaryView', segment: 'Segment') -> None:
pass
def segment_removed(self, view: 'BinaryView', segment: 'Segment') -> None:
pass
def section_added(self, view: 'BinaryView', section: 'Section') -> None:
pass
def section_updated(self, view: 'BinaryView', section: 'Section') -> None:
pass
def section_removed(self, view: 'BinaryView', section: 'Section') -> None:
pass
def component_added(self, view: 'BinaryView', _component: component.Component) -> None:
pass
def component_removed(self, view: 'BinaryView', formerParent: component.Component,
_component: component.Component) -> None:
pass
def component_name_updated(self, view: 'BinaryView', previous_name: str, _component: component.Component) -> None:
pass
def component_moved(self, view: 'BinaryView', formerParent: component.Component, newParent: component.Component,
_component: component.Component) -> None:
pass
def component_function_added(self, view: 'BinaryView', _component: component.Component, func: '_function.Function'):
pass
def component_function_removed(self, view: 'BinaryView', _component: component.Component,
func: '_function.Function'):
pass
def component_data_var_added(self, view: 'BinaryView', _component: component.Component, var: 'DataVariable'):
pass
def component_data_var_removed(self, view: 'BinaryView', _component: component.Component, var: 'DataVariable'):
pass
def type_archive_attached(self, view: 'BinaryView', id: str, path: str):
pass
def type_archive_detached(self, view: 'BinaryView', id: str, path: str):
pass
def type_archive_connected(self, view: 'BinaryView', archive: 'typearchive.TypeArchive'):
pass
def type_archive_disconnected(self, view: 'BinaryView', archive: 'typearchive.TypeArchive'):
pass
def undo_entry_added(self, view: 'BinaryView', entry: 'undo.UndoEntry'):
pass
def undo_entry_taken(self, view: 'BinaryView', entry: 'undo.UndoEntry'):
pass
def redo_entry_taken(self, view: 'BinaryView', entry: 'undo.UndoEntry'):
pass
class StringReference:
_decodings = {
StringType.AsciiString: "ascii", StringType.Utf8String: "utf-8", StringType.Utf16String: "utf-16",
StringType.Utf32String: "utf-32",
}
def __init__(self, bv: 'BinaryView', string_type: StringType, start: int, length: int):
self._type = string_type
self._start = start
self._length = length
self._view = bv
def __repr__(self):
return f"<{self._type.name}: {self._start:#x}, len {self._length:#x}>"
def __str__(self):
return self.value
def __len__(self):
return self._length
@property
def value(self) -> str:
return self._view.read(self._start, self._length).decode(self._decodings[self._type])
@property
def raw(self) -> bytes:
return self._view.read(self._start, self._length)
@property
def type(self) -> StringType:
return self._type
@property
def start(self) -> int:
return self._start
@property
def length(self) -> int:
return self._length
@property
def view(self) -> 'BinaryView':
return self._view
class AnalysisCompletionEvent:
"""
The ``AnalysisCompletionEvent`` object provides an asynchronous mechanism for receiving
callbacks when analysis is complete. The callback runs once. A completion event must be added
for each new analysis in order to be notified of each analysis completion. The
AnalysisCompletionEvent class takes responsibility for keeping track of the object's lifetime.
:Example:
>>> def on_complete(self):
... print("Analysis Complete", self._view)
...
>>> evt = AnalysisCompletionEvent(bv, on_complete)
>>>
"""
_pending_analysis_completion_events = {}
def __init__(
self, view: 'BinaryView', callback: Union[Callable[['AnalysisCompletionEvent'], None], Callable[[], None]]
):
self._view = view
self.callback = callback
self._cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._notify)
self.handle = core.BNAddAnalysisCompletionEvent(self._view.handle, None, self._cb)
self.__class__._pending_analysis_completion_events[id(self)] = self
def __del__(self):
if id(self) in self.__class__._pending_analysis_completion_events:
del self.__class__._pending_analysis_completion_events[id(self)]
if core is not None:
core.BNFreeAnalysisCompletionEvent(self.handle)
def _notify(self, ctxt):
if id(self) in self.__class__._pending_analysis_completion_events:
del self.__class__._pending_analysis_completion_events[id(self)]
try:
arg_offset = inspect.ismethod(self.callback)
callback_spec = inspect.getfullargspec(self.callback)
if len(callback_spec.args) > arg_offset:
self.callback(self) # type: ignore
else:
self.callback() # type: ignore
except:
log_error(traceback.format_exc())
def _empty_callback(self):
pass
def cancel(self) -> None:
"""
The ``cancel`` method will cancel analysis for an :py:class:`AnalysisCompletionEvent`.
.. warning:: This method should only be used when the system is being shut down and no further analysis should be done afterward.
"""
self.callback = self._empty_callback
core.BNCancelAnalysisCompletionEvent(self.handle)
if id(self) in self.__class__._pending_analysis_completion_events:
del self.__class__._pending_analysis_completion_events[id(self)]
@property
def view(self) -> 'BinaryView':
return self._view
class BinaryViewEvent:
"""
The ``BinaryViewEvent`` object provides a mechanism for receiving callbacks when a BinaryView
is Finalized or the initial analysis is finished. The BinaryView finalized callbacks run before the
initial analysis starts. The callbacks run one-after-another in the same order as they get registered.
It is a good place to modify the BinaryView to add extra information to it.
For newly opened binaries, the initial analysis completion callbacks run after the initial analysis,
as well as linear sweep and signature matcher (if they are configured to run), completed. For loading
old databases, the callbacks run after the database is loaded, as well as any automatic analysis
update finishes.
The callback function receives a BinaryView as its parameter. It is possible to call
BinaryView.add_analysis_completion_event() on it to set up other callbacks for analysis completion.
:Example:
>>> def callback(bv):
... print('start: 0x%x' % bv.start)
...
>>> BinaryViewType.add_binaryview_finalized_event(callback)
"""
BinaryViewEventCallback = Callable[['BinaryView'], None]
# This has no functional purposes;
# we just need it to stop Python from prematurely freeing the object
_binaryview_events = {}
@classmethod
def register(cls, event_type: BinaryViewEventType, callback: BinaryViewEventCallback) -> None:
callback_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p,
ctypes.POINTER(core.BNBinaryView
))(lambda ctxt, view: cls._notify(view, callback))
core.BNRegisterBinaryViewEvent(event_type, callback_obj, None)
cls._binaryview_events[len(cls._binaryview_events)] = callback_obj
@staticmethod
def _notify(view: core.BNBinaryViewHandle, callback: BinaryViewEventCallback) -> None:
try:
file_metadata = filemetadata.FileMetadata(handle=core.BNGetFileForView(view))
view_obj = BinaryView(file_metadata=file_metadata, handle=core.BNNewViewReference(view))
callback(view_obj)
except:
log_error(traceback.format_exc())
@dataclass(frozen=True)
class ActiveAnalysisInfo:
func: '_function.Function'
analysis_time: int
update_count: int
submit_count: int
def __repr__(self):
return f"<ActiveAnalysisInfo {self.func}, analysis_time {self.analysis_time}, update_count {self.update_count}, submit_count {self.submit_count}>"
@dataclass(frozen=True)
class AnalysisInfo:
state: AnalysisState
analysis_time: int
active_info: List[ActiveAnalysisInfo]
def __repr__(self):
return f"<AnalysisInfo {self.state}, analysis_time {self.analysis_time}, active_info {self.active_info}>"
@dataclass(frozen=True)
class AnalysisProgress:
state: AnalysisState
count: int
total: int
def __str__(self):
if self.state == AnalysisState.InitialState:
return "Initial"
if self.state == AnalysisState.HoldState:
return "Hold"
if self.state == AnalysisState.IdleState:
return "Idle"
if self.state == AnalysisState.DisassembleState:
return "Disassembling (%d/%d)" % (self.count, self.total)
if self.state == AnalysisState.AnalyzeState:
return "Analyzing (%d/%d)" % (self.count, self.total)
return "Extended Analysis"
def __repr__(self):
return f"<progress: {self}>"
class BinaryDataNotificationCallbacks:
def __init__(self, view: 'BinaryView', notify: 'BinaryDataNotification'):
self._view = view
self._notify = notify
self._cb = core.BNBinaryDataNotification()
self._cb.context = 0
if (not hasattr(notify, 'notifications')) or (hasattr(notify, 'notifications') and notify.notifications is None):
self._cb.notificationBarrier = self._cb.notificationBarrier
self._cb.dataWritten = self._cb.dataWritten.__class__(self._data_written)
self._cb.dataInserted = self._cb.dataInserted.__class__(self._data_inserted)
self._cb.dataRemoved = self._cb.dataRemoved.__class__(self._data_removed)
self._cb.functionAdded = self._cb.functionAdded.__class__(self._function_added)
self._cb.functionRemoved = self._cb.functionRemoved.__class__(self._function_removed)
self._cb.functionUpdated = self._cb.functionUpdated.__class__(self._function_updated)
self._cb.functionUpdateRequested = self._cb.functionUpdateRequested.__class__(self._function_update_requested)
self._cb.dataVariableAdded = self._cb.dataVariableAdded.__class__(self._data_var_added)
self._cb.dataVariableRemoved = self._cb.dataVariableRemoved.__class__(self._data_var_removed)
self._cb.dataVariableUpdated = self._cb.dataVariableUpdated.__class__(self._data_var_updated)
self._cb.dataMetadataUpdated = self._cb.dataMetadataUpdated.__class__(self._data_metadata_updated)
self._cb.tagTypeUpdated = self._cb.tagTypeUpdated.__class__(self._tag_type_updated)
self._cb.tagAdded = self._cb.tagAdded.__class__(self._tag_added)
self._cb.tagRemoved = self._cb.tagRemoved.__class__(self._tag_removed)
self._cb.tagUpdated = self._cb.tagUpdated.__class__(self._tag_updated)
self._cb.symbolAdded = self._cb.symbolAdded.__class__(self._symbol_added)
self._cb.symbolRemoved = self._cb.symbolRemoved.__class__(self._symbol_removed)
self._cb.symbolUpdated = self._cb.symbolUpdated.__class__(self._symbol_updated)
self._cb.stringFound = self._cb.stringFound.__class__(self._string_found)
self._cb.stringRemoved = self._cb.stringRemoved.__class__(self._string_removed)
self._cb.typeDefined = self._cb.typeDefined.__class__(self._type_defined)
self._cb.typeUndefined = self._cb.typeUndefined.__class__(self._type_undefined)
self._cb.typeReferenceChanged = self._cb.typeReferenceChanged.__class__(self._type_ref_changed)
self._cb.typeFieldReferenceChanged = self._cb.typeFieldReferenceChanged.__class__(self._type_field_ref_changed)
self._cb.segmentAdded = self._cb.segmentAdded.__class__(self._segment_added)
self._cb.segmentRemoved = self._cb.segmentRemoved.__class__(self._segment_removed)
self._cb.segmentUpdated = self._cb.segmentUpdated.__class__(self._segment_updated)
self._cb.sectionAdded = self._cb.sectionAdded.__class__(self._section_added)
self._cb.sectionRemoved = self._cb.sectionRemoved.__class__(self._section_removed)
self._cb.sectionUpdated = self._cb.sectionUpdated.__class__(self._section_updated)
self._cb.componentNameUpdated = self._cb.componentNameUpdated.__class__(self._component_name_updated)
self._cb.componentAdded = self._cb.componentAdded.__class__(self._component_added)
self._cb.componentRemoved = self._cb.componentRemoved.__class__(self._component_removed)
self._cb.componentMoved = self._cb.componentMoved.__class__(self._component_moved)
self._cb.componentFunctionAdded = self._cb.componentFunctionAdded.__class__(self._component_function_added)
self._cb.componentFunctionRemoved = self._cb.componentFunctionRemoved.__class__(self._component_function_removed)
self._cb.componentDataVariableAdded = self._cb.componentDataVariableAdded.__class__(self._component_data_variable_added)
self._cb.componentDataVariableRemoved = self._cb.componentDataVariableRemoved.__class__(self._component_data_variable_removed)
self._cb.typeArchiveAttached = self._cb.typeArchiveAttached.__class__(self._type_archive_attached)
self._cb.typeArchiveDetached = self._cb.typeArchiveDetached.__class__(self._type_archive_detached)
self._cb.typeArchiveConnected = self._cb.typeArchiveConnected.__class__(self._type_archive_connected)
self._cb.typeArchiveDisconnected = self._cb.typeArchiveDisconnected.__class__(self._type_archive_disconnected)
self._cb.undoEntryAdded = self._cb.undoEntryAdded.__class__(self._undo_entry_added)
self._cb.undoEntryTaken = self._cb.undoEntryTaken.__class__(self._undo_entry_taken)
self._cb.redoEntryTaken = self._cb.redoEntryTaken.__class__(self._redo_entry_taken)
else:
if notify.notifications & NotificationType.NotificationBarrier:
self._cb.notificationBarrier = self._cb.notificationBarrier.__class__(self._notification_barrier)
if notify.notifications & NotificationType.DataWritten:
self._cb.dataWritten = self._cb.dataWritten.__class__(self._data_written)
if notify.notifications & NotificationType.DataInserted:
self._cb.dataInserted = self._cb.dataInserted.__class__(self._data_inserted)
if notify.notifications & NotificationType.DataRemoved:
self._cb.dataRemoved = self._cb.dataRemoved.__class__(self._data_removed)
if notify.notifications & NotificationType.FunctionAdded:
self._cb.functionAdded = self._cb.functionAdded.__class__(self._function_added)
if notify.notifications & NotificationType.FunctionRemoved:
self._cb.functionRemoved = self._cb.functionRemoved.__class__(self._function_removed)
if notify.notifications & NotificationType.FunctionUpdated:
self._cb.functionUpdated = self._cb.functionUpdated.__class__(self._function_updated)
if notify.notifications & NotificationType.FunctionUpdateRequested:
self._cb.functionUpdateRequested = self._cb.functionUpdateRequested.__class__(self._function_update_requested)
if notify.notifications & NotificationType.DataVariableAdded:
self._cb.dataVariableAdded = self._cb.dataVariableAdded.__class__(self._data_var_added)
if notify.notifications & NotificationType.DataVariableRemoved:
self._cb.dataVariableRemoved = self._cb.dataVariableRemoved.__class__(self._data_var_removed)
if notify.notifications & NotificationType.DataVariableUpdated:
self._cb.dataVariableUpdated = self._cb.dataVariableUpdated.__class__(self._data_var_updated)
if notify.notifications & NotificationType.DataMetadataUpdated:
self._cb.dataMetadataUpdated = self._cb.dataMetadataUpdated.__class__(self._data_metadata_updated)
if notify.notifications & NotificationType.TagTypeUpdated:
self._cb.tagTypeUpdated = self._cb.tagTypeUpdated.__class__(self._tag_type_updated)
if notify.notifications & NotificationType.TagAdded:
self._cb.tagAdded = self._cb.tagAdded.__class__(self._tag_added)
if notify.notifications & NotificationType.TagRemoved:
self._cb.tagRemoved = self._cb.tagRemoved.__class__(self._tag_removed)
if notify.notifications & NotificationType.TagUpdated:
self._cb.tagUpdated = self._cb.tagUpdated.__class__(self._tag_updated)
if notify.notifications & NotificationType.SymbolAdded:
self._cb.symbolAdded = self._cb.symbolAdded.__class__(self._symbol_added)
if notify.notifications & NotificationType.SymbolRemoved:
self._cb.symbolRemoved = self._cb.symbolRemoved.__class__(self._symbol_removed)
if notify.notifications & NotificationType.SymbolUpdated:
self._cb.symbolUpdated = self._cb.symbolUpdated.__class__(self._symbol_updated)
if notify.notifications & NotificationType.StringFound:
self._cb.stringFound = self._cb.stringFound.__class__(self._string_found)
if notify.notifications & NotificationType.StringRemoved:
self._cb.stringRemoved = self._cb.stringRemoved.__class__(self._string_removed)
if notify.notifications & NotificationType.TypeDefined:
self._cb.typeDefined = self._cb.typeDefined.__class__(self._type_defined)
if notify.notifications & NotificationType.TypeUndefined:
self._cb.typeUndefined = self._cb.typeUndefined.__class__(self._type_undefined)
if notify.notifications & NotificationType.TypeReferenceChanged:
self._cb.typeReferenceChanged = self._cb.typeReferenceChanged.__class__(self._type_ref_changed)
if notify.notifications & NotificationType.TypeFieldReferenceChanged:
self._cb.typeFieldReferenceChanged = self._cb.typeFieldReferenceChanged.__class__(self._type_field_ref_changed)
if notify.notifications & NotificationType.SegmentAdded:
self._cb.segmentAdded = self._cb.segmentAdded.__class__(self._segment_added)
if notify.notifications & NotificationType.SegmentRemoved:
self._cb.segmentRemoved = self._cb.segmentRemoved.__class__(self._segment_removed)
if notify.notifications & NotificationType.SegmentUpdated:
self._cb.segmentUpdated = self._cb.segmentUpdated.__class__(self._segment_updated)
if notify.notifications & NotificationType.SectionAdded:
self._cb.sectionAdded = self._cb.sectionAdded.__class__(self._section_added)
if notify.notifications & NotificationType.SectionRemoved:
self._cb.sectionRemoved = self._cb.sectionRemoved.__class__(self._section_removed)
if notify.notifications & NotificationType.SectionUpdated:
self._cb.sectionUpdated = self._cb.sectionUpdated.__class__(self._section_updated)
if notify.notifications & NotificationType.ComponentNameUpdated:
self._cb.componentNameUpdated = self._cb.componentNameUpdated.__class__(self._component_name_updated)
if notify.notifications & NotificationType.ComponentAdded:
self._cb.componentAdded = self._cb.componentAdded.__class__(self._component_added)
if notify.notifications & NotificationType.ComponentRemoved:
self._cb.componentRemoved = self._cb.componentRemoved.__class__(self._component_removed)
if notify.notifications & NotificationType.ComponentMoved:
self._cb.componentMoved = self._cb.componentMoved.__class__(self._component_moved)
if notify.notifications & NotificationType.ComponentFunctionAdded:
self._cb.componentFunctionAdded = self._cb.componentFunctionAdded.__class__(self._component_function_added)
if notify.notifications & NotificationType.ComponentFunctionRemoved:
self._cb.componentFunctionRemoved = self._cb.componentFunctionRemoved.__class__(self._component_function_removed)
if notify.notifications & NotificationType.ComponentDataVariableAdded:
self._cb.componentDataVariableAdded = self._cb.componentDataVariableAdded.__class__(self._component_data_variable_added)
if notify.notifications & NotificationType.ComponentDataVariableRemoved:
self._cb.componentDataVariableRemoved = self._cb.componentDataVariableRemoved.__class__(self._component_data_variable_removed)
if notify.notifications & NotificationType.TypeArchiveAttached:
self._cb.typeArchiveAttached = self._cb.typeArchiveAttached.__class__(self._type_archive_attached)
if notify.notifications & NotificationType.TypeArchiveDetached:
self._cb.typeArchiveDetached = self._cb.typeArchiveDetached.__class__(self._type_archive_detached)
if notify.notifications & NotificationType.TypeArchiveConnected:
self._cb.typeArchiveConnected = self._cb.typeArchiveConnected.__class__(self._type_archive_connected)
if notify.notifications & NotificationType.TypeArchiveDisconnected:
self._cb.typeArchiveDisconnected = self._cb.typeArchiveDisconnected.__class__(self._type_archive_disconnected)
if notify.notifications & NotificationType.UndoEntryAdded:
self._cb.undoEntryAdded = self._cb.undoEntryAdded.__class__(self._undo_entry_added)
if notify.notifications & NotificationType.UndoEntryTaken:
self._cb.undoEntryTaken = self._cb.undoEntryTaken.__class__(self._undo_entry_taken)
if notify.notifications & NotificationType.RedoEntryTaken:
self._cb.redoEntryTaken = self._cb.redoEntryTaken.__class__(self._redo_entry_taken)
def _register(self) -> None:
core.BNRegisterDataNotification(self._view.handle, self._cb)
def _unregister(self) -> None:
core.BNUnregisterDataNotification(self._view.handle, self._cb)
def _notification_barrier(self, ctxt, view: core.BNBinaryView) -> int:
try:
return self._notify.notification_barrier(self._view)
except OSError:
log_error(traceback.format_exc())
def _data_written(self, ctxt, view: core.BNBinaryView, offset: int, length: int) -> None:
try:
self._notify.data_written(self._view, offset, length)
except OSError:
log_error(traceback.format_exc())
def _data_inserted(self, ctxt, view: core.BNBinaryView, offset: int, length: int) -> None:
try:
self._notify.data_inserted(self._view, offset, length)
except:
log_error(traceback.format_exc())
def _data_removed(self, ctxt, view: core.BNBinaryView, offset: int, length: int) -> None:
try:
self._notify.data_removed(self._view, offset, length)
except:
log_error(traceback.format_exc())
def _function_added(self, ctxt, view: core.BNBinaryView, func: core.BNFunctionHandle) -> None:
try:
self._notify.function_added(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log_error(traceback.format_exc())
def _function_removed(self, ctxt, view: core.BNBinaryView, func: core.BNFunctionHandle) -> None:
try:
self._notify.function_removed(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log_error(traceback.format_exc())
def _function_updated(self, ctxt, view: core.BNBinaryView, func: core.BNFunctionHandle) -> None:
try:
self._notify.function_updated(self._view, _function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log_error(traceback.format_exc())
def _function_update_requested(self, ctxt, view: core.BNBinaryView, func: core.BNFunctionHandle) -> None:
try:
self._notify.function_update_requested(
self._view, _function.Function(self._view, core.BNNewFunctionReference(func))
)
except:
log_error(traceback.format_exc())
def _data_var_added(self, ctxt, view: core.BNBinaryView, var: core.BNDataVariableHandle) -> None:
try:
self._notify.data_var_added(self._view, DataVariable.from_core_struct(var[0], self._view))
except:
log_error(traceback.format_exc())
def _data_var_removed(self, ctxt, view: core.BNBinaryView, var: core.BNDataVariableHandle) -> None:
try:
self._notify.data_var_removed(self._view, DataVariable.from_core_struct(var[0], self._view))
except:
log_error(traceback.format_exc())
def _data_var_updated(self, ctxt, view: core.BNBinaryView, var: core.BNDataVariableHandle) -> None:
try:
self._notify.data_var_updated(self._view, DataVariable.from_core_struct(var[0], self._view))
except:
log_error(traceback.format_exc())
def _data_metadata_updated(self, ctxt, view: core.BNBinaryView, offset: int) -> None:
try:
self._notify.data_metadata_updated(self._view, offset)
except:
log_error(traceback.format_exc())
def _tag_type_updated(self, ctxt, view: core.BNBinaryView, tag_type: core.BNTagTypeHandle) -> None:
try:
core_tag_type = core.BNNewTagTypeReference(tag_type)
assert core_tag_type is not None, "core.BNNewTagTypeReference returned None"
self._notify.tag_type_updated(self._view, TagType(core_tag_type))
except:
log_error(traceback.format_exc())
def _tag_added(self, ctxt, view: core.BNBinaryView, tag_ref: core.BNTagReferenceHandle) -> None:
try:
ref_type = tag_ref[0].refType
auto_defined = tag_ref[0].autoDefined
core_tag = core.BNNewTagReference(tag_ref[0].tag)
assert core_tag is not None, "core.BNNewTagReference returned None"
tag = Tag(core_tag)
# Null for data tags (not in any arch or function)
if ctypes.cast(tag_ref[0].arch, ctypes.c_void_p).value is None:
arch = None
else:
arch = architecture.CoreArchitecture._from_cache(tag_ref[0].arch)
if ctypes.cast(tag_ref[0].func, ctypes.c_void_p).value is None:
func = None
else:
func = _function.Function(self._view, core.BNNewFunctionReference(tag_ref[0].func))
addr = tag_ref[0].addr
self._notify.tag_added(self._view, tag, ref_type, auto_defined, arch, func, addr)
except:
log_error(traceback.format_exc())
def _tag_updated(self, ctxt, view: core.BNBinaryView, tag_ref: core.BNTagReferenceHandle) -> None:
try:
ref_type = tag_ref[0].refType
auto_defined = tag_ref[0].autoDefined
core_tag = core.BNNewTagReference(tag_ref[0].tag)
assert core_tag is not None
tag = Tag(core_tag)
# Null for data tags (not in any arch or function)
if ctypes.cast(tag_ref[0].arch, ctypes.c_void_p).value is None:
arch = None
else:
arch = architecture.CoreArchitecture._from_cache(tag_ref[0].arch)
if ctypes.cast(tag_ref[0].func, ctypes.c_void_p).value is None:
func = None
else:
func = _function.Function(self._view, core.BNNewFunctionReference(tag_ref[0].func))
addr = tag_ref[0].addr
self._notify.tag_updated(self._view, tag, ref_type, auto_defined, arch, func, addr)
except:
log_error(traceback.format_exc())
def _tag_removed(self, ctxt, view: core.BNBinaryView, tag_ref: core.BNTagReferenceHandle) -> None:
try:
ref_type = tag_ref[0].refType
auto_defined = tag_ref[0].autoDefined
core_tag = core.BNNewTagReference(tag_ref[0].tag)
assert core_tag is not None, "core.BNNewTagReference returned None"
tag = Tag(core_tag)
# Null for data tags (not in any arch or function)
if ctypes.cast(tag_ref[0].arch, ctypes.c_void_p).value is None:
arch = None
else:
arch = architecture.CoreArchitecture._from_cache(tag_ref[0].arch)
if ctypes.cast(tag_ref[0].func, ctypes.c_void_p).value is None:
func = None
else:
func = _function.Function(self._view, core.BNNewFunctionReference(tag_ref[0].func))
addr = tag_ref[0].addr
self._notify.tag_removed(self._view, tag, ref_type, auto_defined, arch, func, addr)
except:
log_error(traceback.format_exc())
def _symbol_added(self, ctxt, view: core.BNBinaryView, sym: core.BNSymbol) -> None:
try:
_handle = core.BNNewSymbolReference(sym)
assert _handle is not None, "core.BNNewSymbolReference returned None"
self._notify.symbol_added(self._view, _types.CoreSymbol(_handle))
except:
log_error(traceback.format_exc())
def _symbol_updated(self, ctxt, view: core.BNBinaryView, sym: core.BNSymbol) -> None:
try:
_handle = core.BNNewSymbolReference(sym)
assert _handle is not None, "core.BNNewSymbolReference returned None"
self._notify.symbol_updated(self._view, _types.CoreSymbol(_handle))
except:
log_error(traceback.format_exc())
def _symbol_removed(self, ctxt, view: core.BNBinaryView, sym: core.BNSymbol) -> None:
try:
_handle = core.BNNewSymbolReference(sym)
assert _handle is not None, "core.BNNewSymbolReference returned None"
self._notify.symbol_removed(self._view, _types.CoreSymbol(_handle))
except:
log_error(traceback.format_exc())
def _string_found(self, ctxt, view: core.BNBinaryView, string_type: int, offset: int, length: int) -> None:
try:
self._notify.string_found(self._view, StringType(string_type), offset, length)
except:
log_error(traceback.format_exc())
def _string_removed(self, ctxt, view: core.BNBinaryView, string_type: int, offset: int, length: int) -> None:
try:
self._notify.string_removed(self._view, StringType(string_type), offset, length)
except:
log_error(traceback.format_exc())
def _type_defined(self, ctxt, view: core.BNBinaryView, name: str, type_obj: '_types.Type') -> None:
try:
qualified_name = _types.QualifiedName._from_core_struct(name[0])
self._notify.type_defined(
self._view, qualified_name,
_types.Type.create(core.BNNewTypeReference(type_obj), platform=self._view.platform)
)
except:
log_error(traceback.format_exc())
def _type_undefined(self, ctxt, view: core.BNBinaryView, name: str, type_obj: '_types.Type') -> None:
try:
qualified_name = _types.QualifiedName._from_core_struct(name[0])
self._notify.type_undefined(
self._view, qualified_name,
_types.Type.create(core.BNNewTypeReference(type_obj), platform=self._view.platform)