forked from Vector35/binaryninja-api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinaryview.py
More file actions
5968 lines (4947 loc) · 190 KB
/
binaryview.py
File metadata and controls
5968 lines (4947 loc) · 190 KB
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-2020 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 traceback
import ctypes
import abc
import numbers
import json
from collections import OrderedDict
# Binary Ninja components
from binaryninja import _binaryninjacore as core
from binaryninja.enums import (AnalysisState, SymbolType, InstructionTextTokenType,
Endianness, ModificationStatus, StringType, SegmentFlag, SectionSemantics, FindFlag, TypeClass)
import binaryninja
from binaryninja import associateddatastore # required for _BinaryViewAssociatedDataStore
from binaryninja import log
from binaryninja import types
from binaryninja import typelibrary
from binaryninja import fileaccessor
from binaryninja import databuffer
from binaryninja import basicblock
from binaryninja import lineardisassembly
from binaryninja import metadata
from binaryninja import highlight
from binaryninja import function
from binaryninja import settings
from binaryninja import pyNativeStr
# 2-3 compatibility
from binaryninja import range
from binaryninja import with_metaclass
from binaryninja import cstr
class BinaryDataNotification(object):
def __init__(self):
pass
def data_written(self, view, offset, length):
pass
def data_inserted(self, view, offset, length):
pass
def data_removed(self, view, offset, length):
pass
def function_added(self, view, func):
pass
def function_removed(self, view, func):
pass
def function_updated(self, view, func):
pass
def function_update_requested(self, view, func):
pass
def data_var_added(self, view, var):
pass
def data_var_removed(self, view, var):
pass
def data_var_updated(self, view, var):
pass
def string_found(self, view, string_type, offset, length):
pass
def string_removed(self, view, string_type, offset, length):
pass
def type_defined(self, view, name, type):
pass
def type_undefined(self, view, name, type):
pass
_decodings = {
StringType.AsciiString: "ascii",
StringType.Utf8String: "utf-8",
StringType.Utf16String: "utf-16",
StringType.Utf32String: "utf-32",
}
class StringReference(object):
def __init__(self, bv, string_type, start, length):
self._type = string_type
self._start = start
self._length = length
self._view = bv
@property
def value(self):
return self._view.read(self._start, self._length).decode(_decodings[self._type])
@property
def raw(self):
return self._view.read(self._start, self._length)
def __str__(self):
return pyNativeStr(self.raw)
def __len__(self):
return self._length
def __repr__(self):
return "<%s: %#x, len %#x>" % (self._type, self._start, self._length)
@property
def type(self):
""" """
return self._type
@type.setter
def type(self, value):
self._type = value
@property
def start(self):
""" """
return self._start
@start.setter
def start(self, value):
self._start = value
@property
def length(self):
""" """
return self._length
@property
def view(self):
""" """
return self._view
_pending_analysis_completion_events = {}
class AnalysisCompletionEvent(object):
"""
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)
>>>
"""
def __init__(self, view, callback):
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)
global _pending_analysis_completion_events
_pending_analysis_completion_events[id(self)] = self
def __del__(self):
global _pending_analysis_completion_events
if id(self) in _pending_analysis_completion_events:
del _pending_analysis_completion_events[id(self)]
core.BNFreeAnalysisCompletionEvent(self.handle)
def _notify(self, ctxt):
global _pending_analysis_completion_events
if id(self) in _pending_analysis_completion_events:
del _pending_analysis_completion_events[id(self)]
try:
self.callback(self)
except:
log.log_error(traceback.format_exc())
def _empty_callback(self):
pass
def cancel(self):
"""
The ``cancel`` method will cancel analysis for an :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)
global _pending_analysis_completion_events
if id(self) in _pending_analysis_completion_events:
del _pending_analysis_completion_events[id(self)]
@property
def view(self):
""" """
return self._view
@view.setter
def view(self, value):
self._view = value
class ActiveAnalysisInfo(object):
def __init__(self, func, analysis_time, update_count, submit_count):
self._func = func
self._analysis_time = analysis_time
self._update_count = update_count
self._submit_count = submit_count
def __repr__(self):
return "<ActiveAnalysisInfo %s, analysis_time %d, update_count %d, submit_count %d>" % (self._func, self._analysis_time, self._update_count, self._submit_count)
@property
def func(self):
""" """
return self._func
@func.setter
def func(self, value):
self._func = value
@property
def analysis_time(self):
""" """
return self._analysis_time
@analysis_time.setter
def analysis_time(self, value):
self._analysis_time = value
@property
def update_count(self):
""" """
return self._update_count
@update_count.setter
def update_count(self, value):
self._update_count = value
@property
def submit_count(self):
""" """
return self._submit_count
@submit_count.setter
def submit_count(self, value):
self._submit_count = value
class AnalysisInfo(object):
def __init__(self, state, analysis_time, active_info):
self._state = AnalysisState(state)
self._analysis_time = analysis_time
self._active_info = active_info
def __repr__(self):
return "<AnalysisInfo %s, analysis_time %d, active_info %s>" % (self._state, self._analysis_time, self._active_info)
@property
def state(self):
""" """
return self._state
@state.setter
def state(self, value):
self._state = value
@property
def analysis_time(self):
""" """
return self._analysis_time
@analysis_time.setter
def analysis_time(self, value):
self._analysis_time = value
@property
def active_info(self):
""" """
return self._active_info
@active_info.setter
def active_info(self, value):
self._active_info = value
class AnalysisProgress(object):
def __init__(self, state, count, total):
self._state = state
self._count = count
self._total = total
def __str__(self):
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)
if self._state == AnalysisState.ExtendedAnalyzeState:
return "Extended Analysis"
return "Idle"
def __repr__(self):
return "<progress: %s>" % str(self)
@property
def state(self):
""" """
return self._state
@state.setter
def state(self, value):
self._state = value
@property
def count(self):
""" """
return self._count
@count.setter
def count(self, value):
self._count = value
@property
def total(self):
""" """
return self._total
@total.setter
def total(self, value):
self._total = value
class DataVariable(object):
def __init__(self, addr, var_type, auto_discovered, view=None):
self._address = addr
self._type = var_type
self._auto_discovered = auto_discovered
self._view = view
@property
def data_refs_from(self):
"""data cross references from this data variable (read-only)"""
return self._view.get_data_refs_from(self._address, max(1, len(self)))
@property
def data_refs(self):
"""data cross references to this data variable (read-only)"""
return self._view.get_data_refs(self._address, max(1, len(self)))
@property
def code_refs(self):
"""code references to this data variable (read-only)"""
return self._view.get_code_refs(self._address, max(1, len(self)))
def __len__(self):
return len(self._type)
def __repr__(self):
return "<var 0x%x: %s>" % (self._address, str(self._type))
@property
def address(self):
""" """
return self._address
@address.setter
def address(self, value):
self._address = value
@property
def type(self):
""" """
return self._type
@type.setter
def type(self, value):
self._type = value
@property
def auto_discovered(self):
""" """
return self._auto_discovered
@auto_discovered.setter
def auto_discovered(self, value):
self._auto_discovered = value
@property
def view(self):
""" """
return self._view
@view.setter
def view(self, value):
self._view = value
class BinaryDataNotificationCallbacks(object):
def __init__(self, view, notify):
self._view = view
self._notify = notify
self._cb = core.BNBinaryDataNotification()
self._cb.context = 0
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.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)
def _register(self):
core.BNRegisterDataNotification(self._view.handle, self._cb)
def _unregister(self):
core.BNUnregisterDataNotification(self._view.handle, self._cb)
def _data_written(self, ctxt, view, offset, length):
try:
self._notify.data_written(self._view, offset, length)
except OSError:
log.log_error(traceback.format_exc())
def _data_inserted(self, ctxt, view, offset, length):
try:
self._notify.data_inserted(self._view, offset, length)
except:
log.log_error(traceback.format_exc())
def _data_removed(self, ctxt, view, offset, length):
try:
self._notify.data_removed(self._view, offset, length)
except:
log.log_error(traceback.format_exc())
def _function_added(self, ctxt, view, func):
try:
self._notify.function_added(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log.log_error(traceback.format_exc())
def _function_removed(self, ctxt, view, func):
try:
self._notify.function_removed(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log.log_error(traceback.format_exc())
def _function_updated(self, ctxt, view, func):
try:
self._notify.function_updated(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log.log_error(traceback.format_exc())
def _function_update_requested(self, ctxt, view, func):
try:
self._notify.function_update_requested(self._view, binaryninja.function.Function(self._view, core.BNNewFunctionReference(func)))
except:
log.log_error(traceback.format_exc())
def _data_var_added(self, ctxt, view, var):
try:
address = var[0].address
var_type = types.Type(core.BNNewTypeReference(var[0].type), platform = self._view.platform, confidence = var[0].typeConfidence)
auto_discovered = var[0].autoDiscovered
self._notify.data_var_added(self._view, DataVariable(address, var_type, auto_discovered, view))
except:
log.log_error(traceback.format_exc())
def _data_var_removed(self, ctxt, view, var):
try:
address = var[0].address
var_type = types.Type(core.BNNewTypeReference(var[0].type), platform = self._view.platform, confidence = var[0].typeConfidence)
auto_discovered = var[0].autoDiscovered
self._notify.data_var_removed(self._view, DataVariable(address, var_type, auto_discovered, view))
except:
log.log_error(traceback.format_exc())
def _data_var_updated(self, ctxt, view, var):
try:
address = var[0].address
var_type = types.Type(core.BNNewTypeReference(var[0].type), platform = self._view.platform, confidence = var[0].typeConfidence)
auto_discovered = var[0].autoDiscovered
self._notify.data_var_updated(self._view, DataVariable(address, var_type, auto_discovered, view))
except:
log.log_error(traceback.format_exc())
def _string_found(self, ctxt, view, string_type, offset, length):
try:
self._notify.string_found(self._view, StringType(string_type), offset, length)
except:
log.log_error(traceback.format_exc())
def _string_removed(self, ctxt, view, string_type, offset, length):
try:
self._notify.string_removed(self._view, StringType(string_type), offset, length)
except:
log.log_error(traceback.format_exc())
def _type_defined(self, ctxt, view, name, type_obj):
try:
qualified_name = types.QualifiedName._from_core_struct(name[0])
self._notify.type_defined(view, qualified_name, types.Type(core.BNNewTypeReference(type_obj), platform = self._view.platform))
except:
log.log_error(traceback.format_exc())
def _type_undefined(self, ctxt, view, name, type_obj):
try:
qualified_name = types.QualifiedName._from_core_struct(name[0])
self._notify.type_undefined(view, qualified_name, types.Type(core.BNNewTypeReference(type_obj), platform = self._view.platform))
except:
log.log_error(traceback.format_exc())
@property
def view(self):
""" """
return self._view
@view.setter
def view(self, value):
self._view = value
@property
def notify(self):
""" """
return self._notify
@notify.setter
def notify(self, value):
self._notify = value
class _BinaryViewTypeMetaclass(type):
@property
def list(self):
"""List all BinaryView types (read-only)"""
binaryninja._init_plugins()
count = ctypes.c_ulonglong()
types = core.BNGetBinaryViewTypes(count)
result = []
for i in range(0, count.value):
result.append(BinaryViewType(types[i]))
core.BNFreeBinaryViewTypeList(types)
return result
def __iter__(self):
binaryninja._init_plugins()
count = ctypes.c_ulonglong()
types = core.BNGetBinaryViewTypes(count)
try:
for i in range(0, count.value):
yield BinaryViewType(types[i])
finally:
core.BNFreeBinaryViewTypeList(types)
def __getitem__(self, value):
binaryninja._init_plugins()
view_type = core.BNGetBinaryViewTypeByName(str(value))
if view_type is None:
raise KeyError("'%s' is not a valid view type" % str(value))
return BinaryViewType(view_type)
class BinaryViewType(with_metaclass(_BinaryViewTypeMetaclass, object)):
def __init__(self, handle):
self.handle = core.handle_of_type(handle, core.BNBinaryViewType)
def __eq__(self, value):
if not isinstance(value, BinaryViewType):
return False
return ctypes.addressof(self.handle.contents) == ctypes.addressof(value.handle.contents)
def __ne__(self, value):
if not isinstance(value, BinaryViewType):
return True
return ctypes.addressof(self.handle.contents) != ctypes.addressof(value.handle.contents)
@property
def list(self):
"""Allow tab completion to discover metaclass list property"""
pass
@property
def name(self):
"""BinaryView name (read-only)"""
return core.BNGetBinaryViewTypeName(self.handle)
@property
def long_name(self):
"""BinaryView long name (read-only)"""
return core.BNGetBinaryViewTypeLongName(self.handle)
def __repr__(self):
return "<view type: '%s'>" % self.name
def create(self, data):
view = core.BNCreateBinaryViewOfType(self.handle, data.handle)
if view is None:
return None
return BinaryView(file_metadata=data.file, handle=view)
def open(self, src, file_metadata=None):
"""
``open`` opens an instance of a particular BinaryViewType and returns it, or None if not possible.
:param str src: path to filename or bndb to open
:param FileMetaData file_metadata: Optional parameter for a :py:class:`FileMetaData` object
:return: returns a :py:class:`BinaryView` object for the given filename
:rtype: :py:class:`BinaryView` or ``None``
"""
data = BinaryView.open(src, file_metadata)
if data is None:
return None
return self.create(data)
@classmethod
def get_view_of_file(cls, filename, update_analysis=True, progress_func=None):
"""
``get_view_of_file`` opens and returns the first available :py:class:`BinaryView`, excluding a Raw :py:class:`BinaryViewType`
:param str filename: path to filename or bndb to open
:param bool update_analysis: whether or not to run :func:`update_analysis_and_wait` after opening a :py:class:`BinaryView`, defaults to ``True``
:param callback progress_func: optional function to be called with the current progress and total count
:return: returns a :py:class:`BinaryView` object for the given filename
:rtype: :py:class:`BinaryView` or ``None``
"""
sqlite = b"SQLite format 3"
isDatabase = filename.endswith(".bndb")
if isDatabase:
f = open(filename, 'rb')
if f is None or f.read(len(sqlite)) != sqlite:
return None
f.close()
view = binaryninja.filemetadata.FileMetadata().open_existing_database(filename, progress_func)
else:
view = BinaryView.open(filename)
if view is None:
return None
for available in view.available_view_types:
if available.name != "Raw":
if isDatabase:
bv = view.get_view_of_type(available.name)
else:
bv = available.open(filename)
break
else:
if isDatabase:
bv = view.get_view_of_type("Raw")
else:
bv = cls["Raw"].open(filename)
if bv is not None and update_analysis:
bv.update_analysis_and_wait()
return bv
@classmethod
def get_view_of_file_with_options(cls, filename, update_analysis=True, progress_func=None, options={}):
"""
``get_view_of_file_with_options`` opens, generates default load options (which are overridable), and returns the first available \
:py:class:`BinaryView`, excluding any ``Raw`` :py:class:`BinaryViewType`
.. note:: Calling this method without providing options is not necessarily equivalent to simply calling :func:`get_view_of_file`. This is because \
:py:class:`BinaryViewType`s are in control of generating load options, this method allows an alternative default way to open a file. For \
example, opening a relocatable object file with :func:`get_view_of_file` sets **'loader.imageBase'** to 0, whereas opening with \
:func:`get_view_of_file_with_options` sets **'loader.imageBase'** to ``0x400000`` for 64-bit binaries, or ``0x10000`` for 32-bit binaries, by default.
:param str filename: path to filename or bndb to open
:param bool update_analysis: whether or not to run :func:`update_analysis_and_wait` after opening a :py:class:`BinaryView`, defaults to ``True``
:param callback progress_func: optional function to be called with the current progress and total count
:param dict options: a dictionary in the form {setting identifier string : object value}
:return: returns a :py:class:`BinaryView` object for the given filename
:rtype: :py:class:`BinaryView` or ``None``
:Example:
>>> BinaryViewType.get_view_of_file_with_options('/bin/ls', options={'loader.imageBase': 0xfffffff0000, 'loader.macho.processFunctionStarts' : False})
<BinaryView: '/bin/ls', start 0xfffffff0000, len 0xa290>
>>>
"""
sqlite = b"SQLite format 3"
isDatabase = filename.endswith(".bndb")
if isDatabase:
f = open(filename, 'rb')
if f is None or f.read(len(sqlite)) != sqlite:
return None
f.close()
view = binaryninja.filemetadata.FileMetadata().open_database_for_configuration(filename)
else:
view = BinaryView.open(filename)
if view is None:
return None
bvt = None
for available in view.available_view_types:
if available.name != "Raw":
bvt = available
break
if bvt is None:
bvt = cls["Mapped"]
load_settings = bvt.get_load_settings_for_data(view)
load_settings.set_resource_id(bvt.name)
view.set_load_settings(bvt.name, load_settings)
for key, value in options.items():
if load_settings.contains(key):
load_settings.set_json(key, json.dumps(value), view)
else:
log.log_warn("Load Setting: {} not available!".format(key))
bv = bvt.create(view)
if bv is not None and update_analysis:
bv.update_analysis_and_wait()
return bv
def is_valid_for_data(self, data):
return core.BNIsBinaryViewTypeValidForData(self.handle, data.handle)
def get_default_load_settings_for_data(self, data):
load_settings = core.BNGetBinaryViewDefaultLoadSettingsForData(self.handle, data.handle)
if load_settings is None:
return None
return settings.Settings(handle=load_settings)
def get_load_settings_for_data(self, data):
view_handle = None
if data is not None:
view_handle = data.handle
load_settings = core.BNGetBinaryViewLoadSettingsForData(self.handle, view_handle)
if load_settings is None:
return None
return settings.Settings(handle=load_settings)
def register_arch(self, ident, endian, arch):
core.BNRegisterArchitectureForViewType(self.handle, ident, endian, arch.handle)
def get_arch(self, ident, endian):
arch = core.BNGetArchitectureForViewType(self.handle, ident, endian)
if arch is None:
return None
return binaryninja.architecture.CoreArchitecture._from_cache(arch)
def register_platform(self, ident, arch, plat):
core.BNRegisterPlatformForViewType(self.handle, ident, arch.handle, plat.handle)
def register_default_platform(self, arch, plat):
core.BNRegisterDefaultPlatformForViewType(self.handle, arch.handle, plat.handle)
def get_platform(self, ident, arch):
plat = core.BNGetPlatformForViewType(self.handle, ident, arch.handle)
if plat is None:
return None
return binaryninja.platform.Platform(handle = plat)
class Segment(object):
def __init__(self, handle):
self.handle = handle
@property
def start(self):
return core.BNSegmentGetStart(self.handle)
@property
def end(self):
return core.BNSegmentGetEnd(self.handle)
@property
def executable(self):
return (core.BNSegmentGetFlags(self.handle) & SegmentFlag.SegmentExecutable) != 0
@property
def writable(self):
return (core.BNSegmentGetFlags(self.handle) & SegmentFlag.SegmentWritable) != 0
@property
def readable(self):
return (core.BNSegmentGetFlags(self.handle) & SegmentFlag.SegmentReadable) != 0
@property
def data_length(self):
return core.BNSegmentGetDataLength(self.handle)
@property
def data_offset(self):
return core.BNSegmentGetDataOffset(self.handle)
@property
def data_end(self):
return core.BNSegmentGetDataEnd(self.handle)
@property
def relocation_count(self):
return core.BNSegmentGetRelocationsCount(self.handle)
@property
def auto_defined(self):
return core.BNSegmentIsAutoDefined(self.handle)
@property
def relocation_ranges(self):
"""List of relocation range tuples (read-only)"""
count = ctypes.c_ulonglong()
ranges = core.BNSegmentGetRelocationRanges(self.handle, count)
result = []
for i in range(0, count.value):
result.append((ranges[i].start, ranges[i].end))
core.BNFreeRelocationRanges(ranges, count)
return result
def relocation_ranges_at(self, addr):
"""List of relocation range tuples (read-only)"""
count = ctypes.c_ulonglong()
ranges = core.BNSegmentGetRelocationRangesAtAddress(self.handle, addr, count)
result = []
for i in range(0, count.value):
result.append((ranges[i].start, ranges[i].end))
core.BNFreeRelocationRanges(ranges, count)
return result
def __del__(self):
core.BNFreeSegment(self.handle)
def __eq__(self, other):
if not isinstance(other, Segment):
return False
return ctypes.addressof(self.handle.contents) == ctypes.addressof(other.handle.contents)
def __ne__(self, other):
if not isinstance(other, Segment):
return False
return ctypes.addressof(self.handle.contents) != ctypes.addressof(other.handle.contents)
def __hash__(self):
return hash(self.handle.contents)
def __len__(self):
return core.BNSegmentGetLength(self.handle)
def __repr__(self):
return "<segment: %#x-%#x, %s%s%s>" % (self.start, self.end,
"r" if self.readable else "-",
"w" if self.writable else "-",
"x" if self.executable else "-")
class Section(object):
def __init__(self, handle):
self.handle = core.handle_of_type(handle, core.BNSection)
@property
def name(self):
return core.BNSectionGetName(self.handle)
@property
def type(self):
return core.BNSectionGetType(self.handle)
@property
def start(self):
return core.BNSectionGetStart(self.handle)
@property
def linked_section(self):
return core.BNSectionGetLinkedSection(self.handle)
@property
def info_section(self):
return core.BNSectionGetInfoSection(self.handle)
@property
def info_data(self):
return core.BNSectionGetInfoData(self.handle)
@property
def align(self):
return core.BNSectionGetAlign(self.handle)
@property
def entry_size(self):
return core.BNSectionGetEntrySize(self.handle)
@property
def semantics(self):
return SectionSemantics(core.BNSectionGetSemantics(self.handle))
@property
def auto_defined(self):
return core.BNSectionIsAutoDefined(self.handle)
@property
def end(self):
return self.start + len(self)
def __del__(self):
core.BNFreeSection(self.handle)
def __eq__(self, other):
if not isinstance(other, Section):
return False
return ctypes.addressof(self.handle.contents) == ctypes.addressof(other.handle.contents)
def __ne__(self, other):
if not isinstance(other, Section):
return False
return ctypes.addressof(self.handle.contents) != ctypes.addressof(other.handle.contents)
def __hash__(self):
return hash(self.handle.contents)
def __len__(self):
return core.BNSectionGetLength(self.handle)
def __repr__(self):
return "<section %s: %#x-%#x>" % (self.name, self.start, self.end)
class AddressRange(object):
def __init__(self, start, end):
self._start = start
self._end = end
def __len__(self):
return self._end - self.start
@property
def length(self):
return self._end - self._start
def __len__(self):
return self._end - self._start
def __repr__(self):
return "<%#x-%#x>" % (self._start, self._end)
@property
def start(self):
""" """
return self._start
@start.setter
def start(self, value):
self._start = value
@property
def end(self):
""" """
return self._end
@end.setter
def end(self, value):
self._end = value
class TagType(object):
def __init__(self, handle):
self.handle = core.handle_of_type(handle, core.BNTagType)
@property
def name(self):
"""Name of the TagType"""
return core.BNTagTypeGetName(self.handle)
@name.setter