summaryrefslogtreecommitdiff
path: root/python/plugin.py
blob: 5dbc4fa7dc4cab1610c6e22a8cb33cf9afe7460e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
# Copyright (c) 2015-2022 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 traceback
import ctypes
import threading

from typing import Optional, Callable

# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
from .enums import PluginCommandType
from . import filemetadata
from . import binaryview
from . import function
from .log import log_error
from . import lowlevelil
from . import mediumlevelil
from . import highlevelil


class PluginCommandContext:
	def __init__(self, view):
		self._view = view
		self._address = 0
		self._length = 0
		self._function = None
		self._instruction = None

	def __len__(self):
		return self._length

	@property
	def view(self):
		return self._view

	@view.setter
	def view(self, value):
		self._view = value

	@property
	def address(self):
		return self._address

	@address.setter
	def address(self, value):
		self._address = value

	@property
	def length(self):
		return self._length

	@length.setter
	def length(self, value):
		self._length = value

	@property
	def function(self):
		return self._function

	@function.setter
	def function(self, value):
		self._function = value

	@property
	def instruction(self):
		return self._instruction

	@instruction.setter
	def instruction(self, value):
		self._instruction = value


class _PluginCommandMetaClass(type):
	def __iter__(self):
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		commands = core.BNGetAllPluginCommands(count)
		assert commands is not None, "core.BNGetAllPluginCommands returned None"
		try:
			for i in range(0, count.value):
				yield PluginCommand(commands[i])
		finally:
			core.BNFreePluginCommandList(commands)


class PluginCommand(metaclass=_PluginCommandMetaClass):
	_registered_commands = []

	def __init__(self, cmd):
		self._command = core.BNPluginCommand()
		ctypes.memmove(ctypes.byref(self._command), ctypes.byref(cmd), ctypes.sizeof(core.BNPluginCommand))
		self._name = str(cmd.name)
		self._description = str(cmd.description)
		self._type = PluginCommandType(cmd.type)

	@staticmethod
	def _default_action(view, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			action(view_obj)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _address_action(view, addr, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			action(view_obj, addr)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _range_action(view, addr, length, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			action(view_obj, addr, length)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _function_action(view, func, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			func_obj = function.Function(view_obj, core.BNNewFunctionReference(func))
			action(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _low_level_il_function_action(view, func, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
			func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
			action(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _low_level_il_instruction_action(view, func, instr, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
			func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
			action(view_obj, func_obj[instr])
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _medium_level_il_function_action(view, func, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
			func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
			action(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _medium_level_il_instruction_action(view, func, instr, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
			func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
			action(view_obj, func_obj[instr])
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _high_level_il_function_action(view, func, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
			func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
			action(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _high_level_il_instruction_action(view, func, instr, action):
		try:
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
			func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
			action(view_obj, func_obj[instr])
		except:
			log_error(traceback.format_exc())

	@staticmethod
	def _default_is_valid(view, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			return is_valid(view_obj)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _address_is_valid(view, addr, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			return is_valid(view_obj, addr)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _range_is_valid(view, addr, length, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			return is_valid(view_obj, addr, length)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _function_is_valid(view, func, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			func_obj = function.Function(view_obj, core.BNNewFunctionReference(func))
			return is_valid(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _low_level_il_function_is_valid(view, func, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
			func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
			return is_valid(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _low_level_il_instruction_is_valid(view, func, instr, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetLowLevelILOwnerFunction(func))
			func_obj = lowlevelil.LowLevelILFunction(owner.arch, core.BNNewLowLevelILFunctionReference(func), owner)
			return is_valid(view_obj, func_obj[instr])
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _medium_level_il_function_is_valid(view, func, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
			func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
			return is_valid(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _medium_level_il_instruction_is_valid(view, func, instr, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetMediumLevelILOwnerFunction(func))
			func_obj = mediumlevelil.MediumLevelILFunction(owner.arch, core.BNNewMediumLevelILFunctionReference(func), owner)
			return is_valid(view_obj, func_obj[instr])
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _high_level_il_function_is_valid(view, func, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
			func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
			return is_valid(view_obj, func_obj)
		except:
			log_error(traceback.format_exc())
			return False

	@staticmethod
	def _high_level_il_instruction_is_valid(view, func, instr, is_valid):
		try:
			if is_valid is None:
				return True
			file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view))
			view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view))
			owner = function.Function(view_obj, core.BNGetHighLevelILOwnerFunction(func))
			func_obj = highlevelil.HighLevelILFunction(owner.arch, core.BNNewHighLevelILFunctionReference(func), owner)
			return is_valid(view_obj, func_obj[instr])
		except:
			log_error(traceback.format_exc())
			return False

	@classmethod
	def register(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView], None],
		is_valid: Optional[Callable[[binaryview.BinaryView], bool]] = None
	):
		r"""
		``register`` Register a plugin

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` as an argument
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._default_action(view, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView))(lambda ctxt, view: cls._default_is_valid(view, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommand(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_address(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, int], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, int], bool]] = None
	):
		r"""
		``register_for_address`` Register a plugin to be called with an address argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and address as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and address to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_address`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong)(lambda ctxt, view, addr: cls._address_action(view, addr, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong)(lambda ctxt, view, addr: cls._address_is_valid(view, addr, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForAddress(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_range(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, int, int], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, int, int], bool]] = None
	):
		r"""
		``register_for_range`` Register a plugin to be called with a range argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView`, start address, and length as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView`, start address, and length to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_range`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong, ctypes.c_ulonglong)(lambda ctxt, view, addr, length: cls._range_action(view, addr, length, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.c_ulonglong, ctypes.c_ulonglong)(lambda ctxt, view, addr, length: cls._range_is_valid(view, addr, length, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForRange(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_function(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, function.Function], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, function.Function], bool]] = None
	):
		r"""
		``register_for_function`` Register a plugin to be called with a function argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~function.Function` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~function.Function` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNFunction))(lambda ctxt, view, func: cls._function_action(view, func, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNFunction))(lambda ctxt, view, func: cls._function_is_valid(view, func, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForFunction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_low_level_il_function(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, lowlevelil.LowLevelILFunction], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, lowlevelil.LowLevelILFunction], bool]] = None
	):
		r"""
		``register_for_low_level_il_function`` Register a plugin to be called with a low level IL function argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~lowlevelil.LowLevelILFunction` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~lowlevelil.LowLevelILFunction` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_low_level_il_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction))(lambda ctxt, view, func: cls._low_level_il_function_action(view, func, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction))(lambda ctxt, view, func: cls._low_level_il_function_is_valid(view, func, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForLowLevelILFunction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_low_level_il_instruction(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, lowlevelil.LowLevelILInstruction], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, lowlevelil.LowLevelILInstruction], bool]] = None
	):
		r"""
		``register_for_low_level_il_instruction`` Register a plugin to be called with a low level IL instruction argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~lowlevelil.LowLevelILInstruction` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~lowlevelil.LowLevelILInstruction` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_low_level_il_instruction`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._low_level_il_instruction_action(view, func, instr, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNLowLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._low_level_il_instruction_is_valid(view, func, instr, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForLowLevelILInstruction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_medium_level_il_function(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILFunction], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILFunction], bool]] = None
	):
		r"""
		``register_for_medium_level_il_function`` Register a plugin to be called with a medium level IL function argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~mediumlevelil.MediumLevelILFunction` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~mediumlevelil.MediumLevelILFunction` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_medium_level_il_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction))(lambda ctxt, view, func: cls._medium_level_il_function_action(view, func, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction))(lambda ctxt, view, func: cls._medium_level_il_function_is_valid(view, func, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForMediumLevelILFunction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_medium_level_il_instruction(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILInstruction], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, mediumlevelil.MediumLevelILInstruction], bool]] = None
	):
		r"""
		``register_for_medium_level_il_instruction`` Register a plugin to be called with a medium level IL instruction argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~mediumlevelil.MediumLevelILInstruction` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~mediumlevelil.MediumLevelILInstruction` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_medium_level_il_instruction`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._medium_level_il_instruction_action(view, func, instr, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNMediumLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._medium_level_il_instruction_is_valid(view, func, instr, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForMediumLevelILInstruction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_high_level_il_function(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, highlevelil.HighLevelILFunction], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, highlevelil.HighLevelILFunction], bool]] = None
	):
		r"""
		``register_for_high_level_il_function`` Register a plugin to be called with a high level IL function argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~highlevelil.HighLevelILFunction` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~highlevelil.HighLevelILFunction` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_high_level_il_function`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction))(lambda ctxt, view, func: cls._high_level_il_function_action(view, func, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction))(lambda ctxt, view, func: cls._high_level_il_function_is_valid(view, func, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForHighLevelILFunction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def register_for_high_level_il_instruction(cls,
		name: str,
		description: str,
		action: Callable[[binaryview.BinaryView, highlevelil.HighLevelILInstruction], None],
		is_valid: Optional[Callable[[binaryview.BinaryView, highlevelil.HighLevelILInstruction], bool]] = None
	):
		r"""
		``register_for_high_level_il_instruction`` Register a plugin to be called with a high level IL instruction argument

		:param str name: name of the plugin (use 'Folder\\Name' to have the menu item nested in a folder)
		:param str description: description of the plugin
		:param callback action: function to call with the :class:`~binaryview.BinaryView` and a :class:`~highlevelil.HighLevelILInstruction` as arguments
		:param callback is_valid: optional argument of a function passed a :class:`~binaryview.BinaryView` and :class:`~highlevelil.HighLevelILInstruction` to determine whether the plugin should be enabled for that view
		:rtype: None

		.. warning:: Calling ``register_for_high_level_il_instruction`` with the same function name will replace the existing function but will leak the memory of the original plugin.
		"""
		binaryninja._init_plugins()
		action_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._high_level_il_instruction_action(view, func, instr, action))
		is_valid_obj = ctypes.CFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.POINTER(core.BNBinaryView), ctypes.POINTER(core.BNHighLevelILFunction), ctypes.c_ulonglong)(lambda ctxt, view, func, instr: cls._high_level_il_instruction_is_valid(view, func, instr, is_valid))
		cls._registered_commands.append((action_obj, is_valid_obj))
		core.BNRegisterPluginCommandForHighLevelILInstruction(name, description, action_obj, is_valid_obj, None)

	@classmethod
	def get_valid_list(cls, context):
		"""Dict of registered plugins"""
		commands = list(cls)
		result = {}
		for cmd in commands:
			if cmd.is_valid(context):
				result[cmd.name] = cmd
		return result

	def is_valid(self, context):
		if context.view is None:
			return False
		if self._command.type == PluginCommandType.DefaultPluginCommand:
			if not self._command.defaultIsValid:
				return True
			return self._command.defaultIsValid(self._command.context, context.view.handle)
		elif self._command.type == PluginCommandType.AddressPluginCommand:
			if not self._command.addressIsValid:
				return True
			return self._command.addressIsValid(self._command.context, context.view.handle, context.address)
		elif self._command.type == PluginCommandType.RangePluginCommand:
			if context.length == 0:
				return False
			if not self._command.rangeIsValid:
				return True
			return self._command.rangeIsValid(self._command.context, context.view.handle, context.address, context.length)
		elif self._command.type == PluginCommandType.FunctionPluginCommand:
			if context.function is None:
				return False
			if not self._command.functionIsValid:
				return True
			return self._command.functionIsValid(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.LowLevelILFunctionPluginCommand:
			if context.function is None:
				return False
			if not self._command.lowLevelILFunctionIsValid:
				return True
			return self._command.lowLevelILFunctionIsValid(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.LowLevelILInstructionPluginCommand:
			if context.instruction is None:
				return False
			if not isinstance(context.instruction, lowlevelil.LowLevelILInstruction):
				return False
			if not self._command.lowLevelILInstructionIsValid:
				return True
			return self._command.lowLevelILInstructionIsValid(self._command.context, context.view.handle,
				context.instruction.function.handle, context.instruction.instr_index)
		elif self._command.type == PluginCommandType.MediumLevelILFunctionPluginCommand:
			if context.function is None:
				return False
			if not self._command.mediumLevelILFunctionIsValid:
				return True
			return self._command.mediumLevelILFunctionIsValid(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.MediumLevelILInstructionPluginCommand:
			if context.instruction is None:
				return False
			if not isinstance(context.instruction, mediumlevelil.MediumLevelILInstruction):
				return False
			if not self._command.mediumLevelILInstructionIsValid:
				return True
			return self._command.mediumLevelILInstructionIsValid(self._command.context, context.view.handle,
				context.instruction.function.handle, context.instruction.instr_index)
		elif self._command.type == PluginCommandType.HighLevelILFunctionPluginCommand:
			if context.function is None:
				return False
			if not self._command.highLevelILFunctionIsValid:
				return True
			return self._command.highLevelILFunctionIsValid(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.HighLevelILInstructionPluginCommand:
			if context.instruction is None:
				return False
			if not isinstance(context.instruction, highlevelil.HighLevelILInstruction):
				return False
			if not self._command.highLevelILInstructionIsValid:
				return True
			return self._command.highLevelILInstructionIsValid(self._command.context, context.view.handle,
				context.instruction.function.handle, context.instruction.instr_index)
		return False

	def execute(self, context):
		r"""
		``execute`` Execute a Plugin

		:param str context: PluginCommandContext to pass the PluginCommand
		:rtype: None

			>>> ctx = PluginCommandContext(bv);
			>>> PluginCommand.get_valid_list(ctx)[r'PDB\Load'].execute(ctx)

		"""
		if not self.is_valid(context):
			return
		if self._command.type == PluginCommandType.DefaultPluginCommand:
			self._command.defaultCommand(self._command.context, context.view.handle)
		elif self._command.type == PluginCommandType.AddressPluginCommand:
			self._command.addressCommand(self._command.context, context.view.handle, context.address)
		elif self._command.type == PluginCommandType.RangePluginCommand:
			self._command.rangeCommand(self._command.context, context.view.handle, context.address, context.length)
		elif self._command.type == PluginCommandType.FunctionPluginCommand:
			self._command.functionCommand(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.LowLevelILFunctionPluginCommand:
			self._command.lowLevelILFunctionCommand(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.LowLevelILInstructionPluginCommand:
			self._command.lowLevelILInstructionCommand(self._command.context, context.view.handle,
				context.instruction.function.handle, context.instruction.instr_index)
		elif self._command.type == PluginCommandType.MediumLevelILFunctionPluginCommand:
			self._command.mediumLevelILFunctionCommand(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.MediumLevelILInstructionPluginCommand:
			self._command.mediumLevelILInstructionCommand(self._command.context, context.view.handle,
				context.instruction.function.handle, context.instruction.instr_index)
		elif self._command.type == PluginCommandType.HighLevelILFunctionPluginCommand:
			self._command.highLevelILFunctionCommand(self._command.context, context.view.handle, context.function.handle)
		elif self._command.type == PluginCommandType.HighLevelILInstructionPluginCommand:
			self._command.highLevelILInstructionCommand(self._command.context, context.view.handle,
				context.instruction.function.handle, context.instruction.instr_index)

	def __repr__(self):
		return "<PluginCommand: %s>" % self._name

	@property
	def command(self):
		return self._command

	@command.setter
	def command(self, value):
		self._command = value

	@property
	def name(self):
		return self._name

	@name.setter
	def name(self, value):
		self._name = value

	@property
	def description(self):
		return self._description

	@description.setter
	def description(self, value):
		self._description = value

	@property
	def type(self):
		return self._type

	@type.setter
	def type(self, value):
		self._type = value


class MainThreadAction:
	def __init__(self, handle):
		self.handle = handle

	def __del__(self):
		if core is not None:
			core.BNFreeMainThreadAction(self.handle)

	def execute(self):
		core.BNExecuteMainThreadAction(self.handle)

	@property
	def done(self):
		return core.BNIsMainThreadActionDone(self.handle)

	def wait(self):
		core.BNWaitForMainThreadAction(self.handle)


class MainThreadActionHandler:
	_main_thread = None

	def __init__(self):
		self._cb = core.BNMainThreadCallbacks()
		self._cb.context = 0
		self._cb.addAction = self._cb.addAction.__class__(self._add_action)

	def register(self):
		self.__class__._main_thread = self
		core.BNRegisterMainThread(self._cb)

	def _add_action(self, ctxt, action):
		try:
			self.add_action(MainThreadAction(action))
		except:
			log_error(traceback.format_exc())

	def add_action(self, action):
		pass


class _BackgroundTaskMetaclass(type):
	def __iter__(self):
		binaryninja._init_plugins()
		count = ctypes.c_ulonglong()
		tasks = core.BNGetRunningBackgroundTasks(count)
		assert tasks is not None, "core.BNGetRunningBackgroundTasks returned None"
		try:
			for i in range(0, count.value):
				yield BackgroundTask(handle=core.BNNewBackgroundTaskReference(tasks[i]))
		finally:
			core.BNFreeBackgroundTaskList(tasks, count.value)


class BackgroundTask(metaclass=_BackgroundTaskMetaclass):
	def __init__(self, initial_progress_text = "", can_cancel = False, handle = None):
		if handle is None:
			self.handle = core.BNBeginBackgroundTask(initial_progress_text, can_cancel)
		else:
			self.handle = handle

	def __del__(self):
		if core is not None:
			core.BNFreeBackgroundTask(self.handle)

	@property
	def progress(self):
		"""Text description of the progress of the background task (displayed in status bar of the UI)"""
		return core.BNGetBackgroundTaskProgressText(self.handle)

	@progress.setter
	def progress(self, value):
		core.BNSetBackgroundTaskProgressText(self.handle, str(value))

	@property
	def can_cancel(self):
		"""Whether the task can be cancelled (read-only)"""
		return core.BNCanCancelBackgroundTask(self.handle)

	@property
	def finished(self):
		"""Whether the task has finished"""
		return core.BNIsBackgroundTaskFinished(self.handle)

	@finished.setter
	def finished(self, value):
		if value:
			self.finish()

	def finish(self):
		core.BNFinishBackgroundTask(self.handle)

	@property
	def cancelled(self):
		"""Whether the task has been cancelled"""
		return core.BNIsBackgroundTaskCancelled(self.handle)

	@cancelled.setter
	def cancelled(self, value):
		if value:
			self.cancel()

	def cancel(self):
		core.BNCancelBackgroundTask(self.handle)


class BackgroundTaskThread(BackgroundTask):
	def __init__(self, initial_progress_text:str="", can_cancel:bool=False):
		class _Thread(threading.Thread):
			def __init__(self, task:'BackgroundTaskThread'):
				threading.Thread.__init__(self)
				self.task = task

			def run(self):
				if self.task is None:
					raise Exception("Can not call run more than once per thread")
				self.task.run()
				self.task.finish()
				self.task = None

		BackgroundTask.__init__(self, initial_progress_text, can_cancel)
		self.thread = _Thread(self)

	def run(self):
		pass

	def start(self):
		self.thread.start()

	def join(self, timeout=None):
		self.thread.join(timeout)