-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy patharchitecture.py
More file actions
3547 lines (3089 loc) · 143 KB
/
architecture.py
File metadata and controls
3547 lines (3089 loc) · 143 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
# Copyright (c) 2015-2026 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
from typing import Generator, Union, List, Optional, Mapping, Tuple, NewType, Dict, Set, Any
from dataclasses import dataclass, field
# Binary Ninja components
import binaryninja
from . import _binaryninjacore as core
from .enums import (
Endianness, ImplicitRegisterExtend, BranchType, LowLevelILFlagCondition, FlagRole, LowLevelILOperation,
InstructionTextTokenType, InstructionTextTokenContext, IntrinsicClass
)
from .log import log_error_for_exception, log_debug_for_exception
from . import lowlevelil
from . import types
from . import databuffer
from . import platform
from . import callingconvention
from . import typelibrary
from . import function
from . import binaryview
from . import variable
from . import basicblock
from . import log
from . import relocation
RegisterIndex = NewType('RegisterIndex', int)
RegisterStackIndex = NewType('RegisterStackIndex', int)
FlagIndex = NewType('FlagIndex', int)
SemanticClassIndex = NewType('SemanticClassIndex', int)
SemanticGroupIndex = NewType('SemanticGroupIndex', int)
IntrinsicIndex = NewType('IntrinsicIndex', int)
FlagWriteTypeIndex = NewType('FlagWriteTypeIndex', int)
RegisterName = NewType('RegisterName', str)
RegisterStackName = NewType('RegisterStackName', str)
FlagName = NewType('FlagName', str)
SemanticClassName = NewType('SemanticClassName', str)
SemanticGroupName = NewType('SemanticGroupName', str)
IntrinsicName = NewType('IntrinsicName', str)
FlagWriteTypeName = NewType('FlagWriteTypeName', str)
RegisterType = Union[RegisterName, 'lowlevelil.ILRegister', RegisterIndex]
FlagType = Union[FlagName, 'lowlevelil.ILFlag', FlagIndex]
FlagWriteType = Union[FlagWriteTypeName, FlagWriteTypeIndex]
RegisterStackType = Union[RegisterStackName, 'lowlevelil.ILRegisterStack', RegisterStackIndex]
SemanticClassType = Union[SemanticClassName, 'lowlevelil.ILSemanticFlagClass', SemanticClassIndex]
SemanticGroupType = Union[SemanticGroupName, 'lowlevelil.ILSemanticFlagGroup', SemanticGroupIndex]
IntrinsicType = Union[IntrinsicName, 'lowlevelil.ILIntrinsic', IntrinsicIndex]
@dataclass
class BasicBlockAnalysisContext:
"""Used by ``analyze_basic_blocks`` and contains analysis settings and other contextual information.
.. note:: This class is meant to be used by Architecture plugins only
"""
_handle: core.BNBasicBlockAnalysisContext
_function: "function.Function"
_contextual_returns_dirty: bool
# In
_indirect_branches: List["variable.IndirectBranchInfo"]
_indirect_no_return_calls: Set["function.ArchAndAddr"]
_analysis_skip_override: core.FunctionAnalysisSkipOverride
_guided_analysis_mode: bool
_trigger_guided_on_invalid_instruction: bool
_translate_tail_calls: bool
_disallow_branch_to_string: bool
_max_function_size: int
# In/Out
_max_size_reached: bool
_contextual_returns: Dict["function.ArchAndAddr", bool]
# Out
_direct_code_references: Dict[int, "function.ArchAndAddr"]
_direct_no_return_calls: Set["function.ArchAndAddr"]
_halted_disassembly_addresses: Set["function.ArchAndAddr"]
@staticmethod
def from_core_struct(bn_bb_context: core.BNBasicBlockAnalysisContext) -> "BasicBlockAnalysisContext":
"""Create a BasicBlockAnalysisContext from a core.BNBasicBlockAnalysisContext structure."""
indirect_branches = []
for i in range(0, bn_bb_context.indirectBranchesCount):
ibi = variable.IndirectBranchInfo(
source_arch=CoreArchitecture._from_cache(bn_bb_context.indirectBranches[i].sourceArch),
source_addr=bn_bb_context.indirectBranches[i].sourceAddr,
dest_arch=CoreArchitecture._from_cache(bn_bb_context.indirectBranches[i].destArch),
dest_addr=bn_bb_context.indirectBranches[i].destAddr,
auto_defined=bn_bb_context.indirectBranches[i].autoDefined,
)
indirect_branches.append(ibi)
indirect_no_return_calls = set()
for i in range(0, bn_bb_context.indirectNoReturnCallsCount):
loc = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_bb_context.indirectNoReturnCalls[i].arch),
bn_bb_context.indirectNoReturnCalls[i].address,
)
indirect_no_return_calls.add(loc)
contextual_returns = {}
for i in range(0, bn_bb_context.contextualFunctionReturnCount):
loc = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_bb_context.contextualFunctionReturnLocations[i].arch),
bn_bb_context.contextualFunctionReturnLocations[i].address,
)
contextual_returns[loc] = bn_bb_context._contextualFunctionReturnValues[i]
direct_code_references = {}
for i in range(0, bn_bb_context.directRefCount):
src = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_bb_context.directRefSources[i].arch),
bn_bb_context.directRefSources[i].address,
)
direct_code_references[bn_bb_context.directRefTargets[i]] = src
direct_no_return_calls = set()
for i in range(0, bn_bb_context.directNoReturnCallsCount):
loc = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_bb_context.directNoReturnCallLocations[i].arch),
bn_bb_context.directNoReturnCallLocations[i].address,
)
direct_no_return_calls.add(loc)
halted_disassembly_addresses = set()
for i in range(0, bn_bb_context.haltedDisassemblyAddressesCount):
addr = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_bb_context.haltedDisassemblyAddresses[i].arch),
bn_bb_context.haltedDisassemblyAddresses[i].address,
)
halted_disassembly_addresses.add(addr)
view = binaryview.BinaryView(handle=core.BNGetFunctionData(bn_bb_context.function))
return BasicBlockAnalysisContext(
_handle=bn_bb_context,
_function=function.Function(view, core.BNNewFunctionReference(bn_bb_context.function)),
_indirect_branches=indirect_branches, _indirect_no_return_calls=indirect_no_return_calls,
_analysis_skip_override=bn_bb_context.analysisSkipOverride,
_guided_analysis_mode=bn_bb_context.guidedAnalysisMode,
_trigger_guided_on_invalid_instruction=bn_bb_context.triggerGuidedOnInvalidInstruction,
_translate_tail_calls=bn_bb_context.translateTailCalls,
_disallow_branch_to_string=bn_bb_context.disallowBranchToString,
_max_function_size=bn_bb_context.maxFunctionSize, _max_size_reached=bn_bb_context.maxSizeReached,
_contextual_returns=contextual_returns, _contextual_returns_dirty=False,
_direct_code_references=direct_code_references, _direct_no_return_calls=direct_no_return_calls,
_halted_disassembly_addresses=halted_disassembly_addresses,
)
@property
def indirect_branches(self) -> List["variable.IndirectBranchInfo"]:
"""Get the list of indirect branches in this context."""
return self._indirect_branches
@property
def indirect_no_return_calls(self) -> Set["function.ArchAndAddr"]:
"""Get the set of indirect no-return calls in this context."""
return self._indirect_no_return_calls
@property
def analysis_skip_override(self) -> core.FunctionAnalysisSkipOverride:
"""Get the analysis skip override setting for this context."""
return self._analysis_skip_override
@property
def guided_analysis_mode(self) -> bool:
"""Get the setting that determines if functions start in guided analysis mode."""
return self._guided_analysis_mode
@property
def trigger_guided_on_invalid_instruction(self) -> bool:
"""Get the setting that determines if guided mode should be triggered on invalid instructions."""
return self._trigger_guided_on_invalid_instruction
@property
def translate_tail_calls(self) -> bool:
"""Get setting from context that determines if tail calls should be translated."""
return self._translate_tail_calls
@property
def disallow_branch_to_string(self) -> bool:
"""Get setting from context that determines if branches to string addresses should be disallowed."""
return self._disallow_branch_to_string
@property
def max_function_size(self) -> int:
"""Get the maximum function size setting for this context."""
return self._max_function_size
@property
def halt_on_invalid_instruction(self) -> bool:
"""Get the setting from context that determines if analysis should halt on invalid instructions."""
return self._halt_on_invalid_instruction
@property
def max_size_reached(self) -> bool:
"""Get boolean that indicates if the maximum function size has been reached."""
return self._max_size_reached
@max_size_reached.setter
def max_size_reached(self, value: bool) -> None:
"""Set boolean that indicates if the maximum function size has been reached.
:param bool value: The new value for max_size_reached
"""
if not isinstance(value, bool):
raise TypeError("value must be a boolean")
self._max_size_reached = value
@property
def contextual_returns(self) -> Dict["function.ArchAndAddr", bool]:
"""Get the mapping of contextual function return locations to their values."""
return self._contextual_returns
def add_contextual_return(self, loc: "function.ArchAndAddr", value: bool) -> None:
"""
``add_contextual_return`` adds a contextual function return location and its value to the current function.
:param function.ArchAndAddr loc: The location of the contextual function return
:param bool value: The value of the contextual function return
"""
if not isinstance(value, bool):
raise TypeError("value must be a boolean")
if not isinstance(loc, function.ArchAndAddr):
raise TypeError("loc must be an instance of function.ArchAndAddr")
# Update existing value if it exists
if loc in self._contextual_returns:
if self._contextual_returns[loc] == value:
return
self._contextual_returns[loc] = value
self._contextual_returns_dirty = True
@property
def direct_code_references(self) -> Dict[int, "function.ArchAndAddr"]:
"""Get the mapping of direct code reference targets to their source locations."""
return self._direct_code_references
def add_direct_code_reference(self, target: int, source: "function.ArchAndAddr") -> None:
"""
``add_direct_code_reference`` adds a direct code reference to the current function.
:param int target: The target address of the direct code reference
:param function.ArchAndAddr source: The source location of the direct code reference
"""
if not isinstance(target, int):
raise TypeError("target must be an integer")
if not isinstance(source, function.ArchAndAddr):
raise TypeError("source must be an instance of function.ArchAndAddr")
self._direct_code_references[target] = source
@property
def direct_no_return_calls(self) -> Set["function.ArchAndAddr"]:
"""Get the set of direct no-return call locations in this context."""
return self._direct_no_return_calls
def add_direct_no_return_call(self, loc: "function.ArchAndAddr") -> None:
"""
``add_direct_no_return_call`` adds a direct no-return call location to the current function.
:param function.ArchAndAddr loc: The location of the direct no-return call
"""
if not isinstance(loc, function.ArchAndAddr):
raise TypeError("loc must be an instance of function.ArchAndAddr")
self._direct_no_return_calls.add(loc)
@property
def halted_disassembly_addresses(self) -> Set["function.ArchAndAddr"]:
"""Get the set of addresses where disassembly has been halted."""
return self._halted_disassembly_addresses
def add_halted_disassembly_address(self, loc: "function.ArchAndAddr") -> None:
"""
``add_halted_disassembly_address`` adds an address to the set of halted disassembly addresses.
:param function.ArchAndAddr loc: The location of the halted disassembly address
"""
if not isinstance(loc, function.ArchAndAddr):
raise TypeError("loc must be an instance of function.ArchAndAddr")
self._halted_disassembly_addresses.add(loc)
@property
def function_arch_context(self) -> Any:
"""Get the function architecture context"""
tok = int(self._handle.functionArchContext or 0)
if tok == 0:
return None
return self._function.arch.function_arch_contexts.get(tok, None)
@function_arch_context.setter
def function_arch_context(self, value: Any) -> None:
"""Set the function architecture context"""
if self._handle.functionArchContext:
raise ValueError("Function architecture context has already been set")
token = self._function.start
self._function.arch.function_arch_contexts[token] = value
self._handle.functionArchContext = ctypes.c_void_p(token)
def create_basic_block(self, arch: "Architecture", start: int) -> Optional["basicblock.BasicBlock"]:
"""
``create_basic_block`` creates a new BasicBlock at the specified address for the given Architecture.
:param Architecture arch: Architecture of the BasicBlock to create
:param int start: Address of the BasicBlock to create
"""
if not isinstance(arch, Architecture):
raise TypeError("arch must be an instance of architecture.Architecture")
bnblock = core.BNAnalyzeBasicBlocksContextCreateBasicBlock(self._handle, arch.handle, start)
if not bnblock:
return None
view = binaryview.BinaryView(handle=core.BNGetFunctionData(self._function.handle))
return basicblock.BasicBlock(bnblock, view)
def add_basic_block(self, block: "basicblock.BasicBlock") -> None:
"""
``add_basic_block`` adds a BasicBlock to the current function.
:param basicblock.BasicBlock block: The BasicBlock to add
"""
if not isinstance(block, basicblock.BasicBlock):
raise TypeError("block must be an instance of basicblock.BasicBlock")
core.BNAnalyzeBasicBlocksContextAddBasicBlockToFunction(self._handle, block.handle)
def add_temp_outgoing_reference(self, target: "function.Function") -> None:
"""
``add_temp_outgoing_reference`` adds a temporary outgoing reference to the specified function.
:param function.Function target: The target function to add a temporary outgoing reference to
"""
if not isinstance(target, function.Function):
raise TypeError("target must be an instance of function.Function")
core.BNAnalyzeBasicBlocksContextAddTempReference(self._handle, target.handle)
def finalize(self) -> None:
"""
``finalize`` finalizes the function's basic block analysis
"""
if self._direct_code_references:
total = len(self._direct_code_references)
sources = (core.BNArchitectureAndAddress * total)()
targets = (ctypes.c_ulonglong * total)()
for i, (target, src) in enumerate(self._direct_code_references.items()):
sources[i].arch = src.arch.handle
sources[i].address = src.addr
targets[i] = target
core.BNAnalyzeBasicBlocksContextSetDirectCodeReferences(self._handle, sources, targets, total)
if self._direct_no_return_calls:
total = len(self._direct_no_return_calls)
direct_no_return_calls = (core.BNArchitectureAndAddress * total)()
for i, loc in enumerate(self._direct_no_return_calls):
direct_no_return_calls[i].arch = loc.arch.handle
direct_no_return_calls[i].address = loc.addr
core.BNAnalyzeBasicBlocksContextSetDirectNoReturnCalls(self._handle, direct_no_return_calls, total)
if self._halted_disassembly_addresses:
total = len(self._halted_disassembly_addresses)
halted_addresses = (core.BNArchitectureAndAddress * total)()
for i, loc in enumerate(self._halted_disassembly_addresses):
halted_addresses[i].arch = loc.arch.handle
halted_addresses[i].address = loc.addr
core.BNAnalyzeBasicBlocksContextSetHaltedDisassemblyAddresses(self._handle, halted_addresses, total)
self._handle.maxSizeReached = ctypes.c_bool(self._max_size_reached)
if self._contextual_returns_dirty:
total = len(self._contextual_returns)
values = (ctypes.c_bool * total)()
returns = (core.BNArchitectureAndAddress * total)()
for i, (loc, value) in enumerate(self._contextual_returns.items()):
returns[i].arch = loc.arch.handle
returns[i].address = loc.addr
values[i] = value
core.BNAnalyzeBasicBlocksContextSetContextualFunctionReturns(self._handle, returns, values, total)
@dataclass
class FunctionLifterContext:
"""Used by ``lift_function`` and contains contextual information for function-level lifting
.. note:: This class is meant to be used by Architecture plugins only
"""
_handle: core.BNFunctionLifterContext
_function: "function.Function"
_platform: "platform.Platform"
_logger: "log.Logger"
_blocks: List["basicblock.BasicBlock"]
_contextual_returns: Dict["function.ArchAndAddr", bool]
_inline_remapping: Dict["function.ArchAndAddr", "function.ArchAndAddr"]
_user_indirect_branches: Dict["function.ArchAndAddr", Set["function.ArchAndAddr"]]
_auto_indirect_branches: Dict["function.ArchAndAddr", Set["function.ArchAndAddr"]]
_inlined_calls: Set[int]
_function_arch_context_token: int
@staticmethod
def from_core_struct(
func: core.BNLowLevelILFunction, bn_fl_context: core.BNFunctionLifterContext
) -> "FunctionLifterContext":
"""Create a FunctionLifterContext from a core.BNFunctionLifterContext structure."""
session_id = core.BNLoggerGetSessionId(bn_fl_context.logger)
name = core.BNLoggerGetName(bn_fl_context.logger)
logger = log.Logger(session_id, name, handle=core.BNNewLoggerReference(bn_fl_context.logger))
plat = platform.CorePlatform._from_cache(core.BNNewPlatformReference(bn_fl_context.platform))
blocks = []
for i in range(0, bn_fl_context.basicBlockCount):
blocks.append(basicblock.BasicBlock(core.BNNewBasicBlockReference(bn_fl_context.basicBlocks[i])))
contextual_returns = {}
for i in range(0, bn_fl_context.contextualFunctionReturnCount):
loc = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_fl_context.contextualFunctionReturnLocations[i].arch),
bn_fl_context.contextualFunctionReturnLocations[i].address,
)
contextual_returns[loc] = bn_fl_context._contextualFunctionReturnValues[i]
inline_remapping = {}
for i in range(0, bn_fl_context.inlinedRemappingEntryCount):
key = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_fl_context.inlinedRemappingKeys[i].arch),
bn_fl_context.inlinedRemappingKeys[i].address,
)
dest = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_fl_context.inlinedRemappingEntries[i].destination.arch),
bn_fl_context.inlinedRemappingEntries[i].destination.address,
)
inline_remapping[src] = dest
user_indirect_branches = {}
auto_indirect_branches = {}
for i in range(0, bn_fl_context.indirectBranchesCount):
src = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_fl_context.indirectBranches[i].sourceArch),
bn_fl_context.indirectBranches[i].sourceAddr,
)
dest = function.ArchAndAddr(
CoreArchitecture._from_cache(bn_fl_context.indirectBranches[i].destArch),
bn_fl_context.indirectBranches[i].destAddr,
)
if bn_fl_context.indirectBranches[i].autoDefined:
if src not in auto_indirect_branches:
auto_indirect_branches[src] = set()
auto_indirect_branches[src].add(dest)
else:
if src not in user_indirect_branches:
user_indirect_branches[src] = set()
user_indirect_branches[src].add(dest)
inlined_calls = set()
for i in range(0, bn_fl_context.inlinedCallsCount):
inlined_calls.add(bn_fl_context.inlinedCalls[i])
return FunctionLifterContext(
_handle=bn_fl_context,
_function=lowlevelil.LowLevelILFunction(plat.arch,
core.BNNewLowLevelILFunctionReference(func)), _platform=plat,
_logger=logger, _blocks=blocks, _contextual_returns=contextual_returns, _inline_remapping=inline_remapping,
_user_indirect_branches=user_indirect_branches, _auto_indirect_branches=auto_indirect_branches,
_inlined_calls=inlined_calls, _function_arch_context_token=bn_fl_context.functionArchContext,
)
def prepare_block_translation(self, function, arch, address):
"""Prepare the basic block for translation"""
core.BNPrepareBlockTranslation(function.handle, arch.handle, address)
@property
def blocks(self) -> List["basicblock.BasicBlock"]:
"""Get the list of basic blocks in this context"""
return self._blocks
@property
def function_arch_context(self) -> Any:
"""Get the function architecture context"""
return self._function.arch.function_arch_contexts.get(self._function_arch_context_token, None)
@dataclass(frozen=True)
class RegisterInfo:
full_width_reg: RegisterName
size: int
offset: int = 0
extend: ImplicitRegisterExtend = ImplicitRegisterExtend.NoExtend
index: Optional[RegisterIndex] = None
def __repr__(self):
if self.extend == ImplicitRegisterExtend.ZeroExtendToFullWidth:
extend = ", zero extend"
elif self.extend == ImplicitRegisterExtend.SignExtendToFullWidth:
extend = ", sign extend"
else:
extend = ""
return f"<reg: size {self.size}, offset {self.offset} in {self.full_width_reg}{extend}>"
@dataclass(frozen=True)
class RegisterStackInfo:
storage_regs: List[RegisterName]
top_relative_regs: List[RegisterName]
stack_top_reg: RegisterName
index: Optional[RegisterStackIndex] = None
def __repr__(self):
return f"<reg stack: {len(self.storage_regs)} regs, stack top in {self.stack_top_reg}>"
@dataclass(frozen=True)
class IntrinsicInput:
type: 'types.Type'
name: str = ""
def __repr__(self):
if len(self.name) == 0:
return f"<input: {self.type}>"
return f"<input: {self.type} {self.name}>"
@dataclass(frozen=True)
class IntrinsicInfo:
inputs: List[IntrinsicInput]
outputs: List['types.Type']
index: Optional[int] = None
def __repr__(self):
return f"<intrinsic: {repr(self.inputs)} -> {repr(self.outputs)}>"
@dataclass(frozen=True)
class InstructionBranch:
type: BranchType
target: int
arch: Optional['Architecture']
def __repr__(self):
if self.arch is not None:
return f"<{self.type.name}: {self.arch.name}@{self.target:#x}>"
return f"<{self.type}: {self.target:#x}>"
@dataclass(frozen=False)
class InstructionInfo:
length: int = 0
arch_transition_by_target_addr: bool = False
branch_delay: int = 0
branches: List[InstructionBranch] = field(default_factory=list)
def add_branch(self, branch_type: BranchType, target: int = 0, arch: Optional['Architecture'] = None) -> None:
self.branches.append(InstructionBranch(branch_type, target, arch))
def __len__(self):
return self.length
def __repr__(self):
branch_delay = ""
if self.branch_delay:
branch_delay = ", delay slot"
return f"<instr: {self.length} bytes{branch_delay}, {repr(self.branches)}>"
class _ArchitectureMetaClass(type):
def __iter__(self) -> Generator['Architecture', None, None]:
binaryninja._init_plugins()
count = ctypes.c_ulonglong()
archs = core.BNGetArchitectureList(count)
if archs is None:
return
try:
for i in range(0, count.value):
yield CoreArchitecture._from_cache(archs[i])
finally:
core.BNFreeArchitectureList(archs)
def __getitem__(cls: '_ArchitectureMetaClass', name: str) -> 'Architecture':
binaryninja._init_plugins()
arch = core.BNGetArchitectureByName(name)
if arch is None:
raise KeyError(f"'{name}' is not a valid architecture")
return CoreArchitecture._from_cache(arch)
def __contains__(cls: '_ArchitectureMetaClass', name: object) -> bool:
if not isinstance(name, str):
return False
try:
cls[name]
return True
except KeyError:
return False
def get(cls: '_ArchitectureMetaClass', name: str, default: Any = None) -> Optional['Architecture']:
try:
return cls[name]
except KeyError:
if default is not None:
return default
return None
class Architecture(metaclass=_ArchitectureMetaClass):
"""
``class Architecture`` is the parent class for all CPU architectures. Subclasses of Architecture implement assembly,
disassembly, IL lifting, and patching.
``class Architecture`` has a metaclass with the additional methods ``register``, and supports
iteration::
>>> #List the architectures
>>> list(Architecture)
[<arch: aarch64>, <arch: armv7>, <arch: thumb2>, <arch: armv7eb>, <arch: thumb2eb>, <arch: mipsel32>, <arch: mips32>, <arch: ppc>, <arch: ppc64>, <arch: ppc_le>, <arch: ppc64_le>, <arch: x86_16>, <arch: x86>, <arch: x86_64>]
>>> #Register a new Architecture
>>> class MyArch(Architecture):
... name = "MyArch"
...
>>> MyArch.register()
>>> list(Architecture)
[<arch: aarch64>, <arch: armv7>, <arch: thumb2>, <arch: armv7eb>, <arch: thumb2eb>, <arch: mipsel32>, <arch: mips32>, <arch: ppc>, <arch: ppc64>, <arch: ppc_le>, <arch: ppc64_le>, <arch: x86_16>, <arch: x86>, <arch: x86_64>, <arch: MyArch>]
>>>
For the purposes of this documentation the variable ``arch`` will be used in the following context ::
>>> from binaryninja import *
>>> arch = Architecture['x86']
.. note:: The `max_instr_length` property of an architecture is not necessarily representative of the maximum instruction size of the associated CPU architecture. Rather, it represents the maximum size of a potential instruction that the architecture plugin can handle. So for example, the value for x86 is 16 despite the largest valid instruction being only 15 bytes long, and the value for mips32 is currently 8 because multiple instructions are decoded looking for delay slots so they can be reordered.
"""
name = None
endianness = Endianness.LittleEndian
address_size = 8
default_int_size = 4
instr_alignment = 1
max_instr_length = 16
opcode_display_length = 8
regs: Dict[RegisterName, RegisterInfo] = {}
stack_pointer = None
link_reg = None
global_regs = []
system_regs = []
flags: List[FlagName] = []
flag_write_types: List[FlagWriteTypeName] = []
semantic_flag_classes: List[SemanticClassName] = []
semantic_flag_groups: List[SemanticGroupName] = []
flag_roles: Dict[FlagName, FlagRole] = {}
flags_required_for_flag_condition: Dict['lowlevelil.LowLevelILFlagCondition', List[FlagName]] = {}
flags_required_for_semantic_flag_group: Dict[SemanticGroupName, List[FlagName]] = {}
flag_conditions_for_semantic_flag_group: Dict[SemanticGroupName, Dict[Optional[SemanticClassName], 'lowlevelil.LowLevelILFlagCondition']] = {}
flags_written_by_flag_write_type: Dict[FlagWriteTypeName, List[FlagName]] = {}
semantic_class_for_flag_write_type: Dict[FlagWriteTypeName, SemanticClassName] = {}
reg_stacks: Dict[RegisterStackName, RegisterStackInfo] = {}
intrinsics = {}
next_address = 0
function_arch_contexts: Dict[int, Any] = {}
def __init__(self):
binaryninja._init_plugins()
if self.__class__.opcode_display_length > self.__class__.max_instr_length:
self.__class__.opcode_display_length = self.__class__.max_instr_length
self._cb = core.BNCustomArchitecture()
self._cb.context = 0
self._cb.init = self._cb.init.__class__(self._init)
self._cb.getEndianness = self._cb.getEndianness.__class__(self._get_endianness)
self._cb.getAddressSize = self._cb.getAddressSize.__class__(self._get_address_size)
self._cb.getDefaultIntegerSize = self._cb.getDefaultIntegerSize.__class__(self._get_default_integer_size)
self._cb.getInstructionAlignment = self._cb.getInstructionAlignment.__class__(self._get_instruction_alignment)
self._cb.getMaxInstructionLength = self._cb.getMaxInstructionLength.__class__(self._get_max_instruction_length)
self._cb.getOpcodeDisplayLength = self._cb.getOpcodeDisplayLength.__class__(self._get_opcode_display_length)
self._cb.getAssociatedArchitectureByAddress = self._cb.getAssociatedArchitectureByAddress.__class__(
self._get_associated_arch_by_address
)
self._cb.getInstructionInfo = self._cb.getInstructionInfo.__class__(self._get_instruction_info)
self._cb.getInstructionText = self._cb.getInstructionText.__class__(self._get_instruction_text)
self._cb.getInstructionTextWithContext = self._cb.getInstructionTextWithContext.__class__(
self._get_instruction_text_with_context
)
self._cb.freeInstructionText = self._cb.freeInstructionText.__class__(self._free_instruction_text)
self._cb.getInstructionLowLevelIL = self._cb.getInstructionLowLevelIL.__class__(
self._get_instruction_low_level_il
)
self._cb.analyzeBasicBlocks = self._cb.analyzeBasicBlocks.__class__(self._analyze_basic_blocks)
self._cb.liftFunction = self._cb.liftFunction.__class__(self._lift_function)
self._cb.freeFunctionArchContext = self._cb.freeFunctionArchContext.__class__(self._free_function_arch_context)
self._cb.getRegisterName = self._cb.getRegisterName.__class__(self._get_register_name)
self._cb.getFlagName = self._cb.getFlagName.__class__(self._get_flag_name)
self._cb.getFlagWriteTypeName = self._cb.getFlagWriteTypeName.__class__(self._get_flag_write_type_name)
self._cb.getSemanticFlagClassName = self._cb.getSemanticFlagClassName.__class__(
self._get_semantic_flag_class_name
)
self._cb.getSemanticFlagGroupName = self._cb.getSemanticFlagGroupName.__class__(
self._get_semantic_flag_group_name
)
self._cb.getFullWidthRegisters = self._cb.getFullWidthRegisters.__class__(self._get_full_width_registers)
self._cb.getAllRegisters = self._cb.getAllRegisters.__class__(self._get_all_registers)
self._cb.getAllFlags = self._cb.getAllRegisters.__class__(self._get_all_flags)
self._cb.getAllFlagWriteTypes = self._cb.getAllRegisters.__class__(self._get_all_flag_write_types)
self._cb.getAllSemanticFlagClasses = self._cb.getAllSemanticFlagClasses.__class__(
self._get_all_semantic_flag_classes
)
self._cb.getAllSemanticFlagGroups = self._cb.getAllSemanticFlagGroups.__class__(
self._get_all_semantic_flag_groups
)
self._cb.getFlagRole = self._cb.getFlagRole.__class__(self._get_flag_role)
self._cb.getFlagsRequiredForFlagCondition = self._cb.getFlagsRequiredForFlagCondition.__class__(
self._get_flags_required_for_flag_condition
)
self._cb.getFlagsRequiredForSemanticFlagGroup = self._cb.getFlagsRequiredForSemanticFlagGroup.__class__(
self._get_flags_required_for_semantic_flag_group
)
self._cb.getFlagConditionsForSemanticFlagGroup = self._cb.getFlagConditionsForSemanticFlagGroup.__class__(
self._get_flag_conditions_for_semantic_flag_group
)
self._cb.freeFlagConditionsForSemanticFlagGroup = self._cb.freeFlagConditionsForSemanticFlagGroup.__class__(
self._free_flag_conditions_for_semantic_flag_group
)
self._cb.getFlagsWrittenByFlagWriteType = self._cb.getFlagsWrittenByFlagWriteType.__class__(
self._get_flags_written_by_flag_write_type
)
self._cb.getSemanticClassForFlagWriteType = self._cb.getSemanticClassForFlagWriteType.__class__(
self._get_semantic_class_for_flag_write_type
)
self._cb.getFlagWriteLowLevelIL = self._cb.getFlagWriteLowLevelIL.__class__(self._get_flag_write_low_level_il)
self._cb.getFlagConditionLowLevelIL = self._cb.getFlagConditionLowLevelIL.__class__(
self._get_flag_condition_low_level_il
)
self._cb.getSemanticFlagGroupLowLevelIL = self._cb.getSemanticFlagGroupLowLevelIL.__class__(
self._get_semantic_flag_group_low_level_il
)
self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(self._free_register_list)
self._cb.getRegisterInfo = self._cb.getRegisterInfo.__class__(self._get_register_info)
self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__(self._get_stack_pointer_register)
self._cb.getLinkRegister = self._cb.getLinkRegister.__class__(self._get_link_register)
self._cb.getGlobalRegisters = self._cb.getGlobalRegisters.__class__(self._get_global_registers)
self._cb.getSystemRegisters = self._cb.getSystemRegisters.__class__(self._get_system_registers)
self._cb.getRegisterStackName = self._cb.getRegisterStackName.__class__(self._get_register_stack_name)
self._cb.getAllRegisterStacks = self._cb.getAllRegisterStacks.__class__(self._get_all_register_stacks)
self._cb.getRegisterStackInfo = self._cb.getRegisterStackInfo.__class__(self._get_register_stack_info)
self._cb.getIntrinsicClass = self._cb.getIntrinsicClass.__class__(self._get_intrinsic_class)
self._cb.getIntrinsicName = self._cb.getIntrinsicName.__class__(self._get_intrinsic_name)
self._cb.getAllIntrinsics = self._cb.getAllIntrinsics.__class__(self._get_all_intrinsics)
self._cb.getIntrinsicInputs = self._cb.getIntrinsicInputs.__class__(self._get_intrinsic_inputs)
self._cb.freeNameAndTypeList = self._cb.freeNameAndTypeList.__class__(self._free_name_and_type_list)
self._cb.getIntrinsicOutputs = self._cb.getIntrinsicOutputs.__class__(self._get_intrinsic_outputs)
self._cb.freeTypeList = self._cb.freeTypeList.__class__(self._free_type_list)
self._cb.canAssemble = self._cb.canAssemble.__class__(self._can_assemble)
self._cb.assemble = self._cb.assemble.__class__(self._assemble)
self._cb.isNeverBranchPatchAvailable = self._cb.isNeverBranchPatchAvailable.__class__(
self._is_never_branch_patch_available
)
self._cb.isAlwaysBranchPatchAvailable = self._cb.isAlwaysBranchPatchAvailable.__class__(
self._is_always_branch_patch_available
)
self._cb.isInvertBranchPatchAvailable = self._cb.isInvertBranchPatchAvailable.__class__(
self._is_invert_branch_patch_available
)
self._cb.isSkipAndReturnZeroPatchAvailable = self._cb.isSkipAndReturnZeroPatchAvailable.__class__(
self._is_skip_and_return_zero_patch_available
)
self._cb.isSkipAndReturnValuePatchAvailable = self._cb.isSkipAndReturnValuePatchAvailable.__class__(
self._is_skip_and_return_value_patch_available
)
self._cb.convertToNop = self._cb.convertToNop.__class__(self._convert_to_nop)
self._cb.alwaysBranch = self._cb.alwaysBranch.__class__(self._always_branch)
self._cb.invertBranch = self._cb.invertBranch.__class__(self._invert_branch)
self._cb.skipAndReturnValue = self._cb.skipAndReturnValue.__class__(self._skip_and_return_value)
self.__dict__['endianness'] = self.__class__.endianness
self.__dict__['address_size'] = self.__class__.address_size
self.__dict__['default_int_size'] = self.__class__.default_int_size
self.__dict__['instr_alignment'] = self.__class__.instr_alignment
self.__dict__['max_instr_length'] = self.__class__.max_instr_length
self.__dict__['opcode_display_length'] = self.__class__.opcode_display_length
self.__dict__['stack_pointer'] = self.__class__.stack_pointer
self.__dict__['link_reg'] = self.__class__.link_reg
self._all_regs: Dict[RegisterName, RegisterIndex] = {}
self._full_width_regs: Dict[RegisterName, RegisterIndex] = {}
self._regs_by_index: Dict[RegisterIndex, RegisterName] = {}
self.regs = self.__class__.regs
assert self.regs is not None, "Custom Architecture doesn't specify a register map"
reg_index = RegisterIndex(0)
# Registers used for storage in register stacks must be sequential, so allocate these in order first
self._all_reg_stacks: Dict[RegisterStackName, RegisterStackIndex] = {}
self._reg_stacks_by_index: Dict[RegisterStackIndex, RegisterStackName] = {}
self.reg_stacks = self.__class__.reg_stacks
assert self.regs is not None, "Custom Architecture doesn't specify a reg_stacks map"
reg_stack_index = RegisterStackIndex(0)
for reg_stack, info in self.reg_stacks.items():
for reg in info.storage_regs:
self._all_regs[reg] = reg_index
self._regs_by_index[reg_index] = reg
r = self.regs[reg]
self.regs[reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
reg_index = RegisterIndex(reg_index + 1)
for reg in info.top_relative_regs:
self._all_regs[reg] = reg_index
self._regs_by_index[reg_index] = reg
r = self.regs[reg]
self.regs[reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
reg_index = RegisterIndex(reg_index + 1)
if reg_stack not in self._all_reg_stacks:
self._all_reg_stacks[reg_stack] = reg_stack_index
self._reg_stacks_by_index[reg_stack_index] = reg_stack
rs = self.reg_stacks[reg_stack]
self.reg_stacks[reg_stack] = RegisterStackInfo(
rs.storage_regs, rs.top_relative_regs, rs.stack_top_reg, reg_stack_index
)
reg_stack_index = RegisterStackIndex(reg_stack_index + 1)
for reg, info in self.regs.items():
if reg not in self._all_regs:
self._all_regs[reg] = reg_index
self._regs_by_index[reg_index] = reg
r = self.regs[reg]
self.regs[reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
reg_index = RegisterIndex(reg_index + 1)
if info.full_width_reg not in self._all_regs:
self._all_regs[info.full_width_reg] = reg_index
self._regs_by_index[reg_index] = info.full_width_reg
r = self.regs[reg]
self.regs[info.full_width_reg] = RegisterInfo(r.full_width_reg, r.size, r.offset, r.extend, reg_index)
reg_index = RegisterIndex(reg_index + 1)
if info.full_width_reg not in self._full_width_regs:
self._full_width_regs[info.full_width_reg] = self._all_regs[info.full_width_reg]
self._flags: Dict[FlagName, FlagIndex] = {}
self._flags_by_index: Dict[FlagIndex, FlagName] = {}
self.flags: List[FlagName] = self.__class__.flags
flag_index = FlagIndex(0)
for flag in self.__class__.flags:
if flag not in self._flags:
self._flags[flag] = flag_index
self._flags_by_index[flag_index] = flag
flag_index = FlagIndex(flag_index + 1)
self._flag_write_types: Dict[FlagWriteTypeName, FlagWriteTypeIndex] = {}
self._flag_write_types_by_index: Dict[FlagWriteTypeIndex, FlagWriteTypeName] = {}
self.flag_write_types: List[FlagWriteTypeName] = self.__class__.flag_write_types
write_type_index = FlagWriteTypeIndex(1)
for write_type in self.__class__.flag_write_types:
if write_type not in self._flag_write_types:
self._flag_write_types[write_type] = write_type_index
self._flag_write_types_by_index[write_type_index] = write_type
write_type_index = FlagWriteTypeIndex(write_type_index + 1)
self._semantic_flag_classes: Dict[SemanticClassName, SemanticClassIndex] = {}
self._semantic_flag_classes_by_index: Dict[SemanticClassIndex, SemanticClassName] = {}
self.semantic_flag_classes: List[SemanticClassName] = self.__class__.semantic_flag_classes
semantic_class_index = SemanticClassIndex(1)
for sem_class in self.__class__.semantic_flag_classes:
if sem_class not in self._semantic_flag_classes:
self._semantic_flag_classes[sem_class] = semantic_class_index
self._semantic_flag_classes_by_index[semantic_class_index] = sem_class
semantic_class_index = SemanticClassIndex(semantic_class_index + 1)
self._semantic_flag_groups: Dict[SemanticGroupName, SemanticGroupIndex] = {}
self._semantic_flag_groups_by_index: Dict[SemanticGroupIndex, SemanticGroupName] = {}
self.semantic_flag_groups: List[SemanticGroupName] = self.__class__.semantic_flag_groups
semantic_group_index = SemanticGroupIndex(0)
for sem_group in self.__class__.semantic_flag_groups:
if sem_group not in self._semantic_flag_groups:
self._semantic_flag_groups[sem_group] = semantic_group_index
self._semantic_flag_groups_by_index[semantic_group_index] = sem_group
semantic_group_index = SemanticGroupIndex(semantic_group_index + 1)
self._flag_roles: Dict[FlagIndex, FlagRole] = {}
self.flag_roles: Dict[FlagName, FlagRole] = self.__class__.flag_roles
for flag in self.__class__.flag_roles:
role = self.__class__.flag_roles[flag]
if isinstance(role, str):
role = FlagRole[role]
self._flag_roles[self._flags[flag]] = role
self.flags_required_for_flag_condition: Dict['lowlevelil.LowLevelILFlagCondition',
List[FlagName]] = self.__class__.flags_required_for_flag_condition
self._flags_required_by_semantic_flag_group: Dict[SemanticGroupIndex, List[FlagIndex]] = {}
self.flags_required_for_semantic_flag_group: Dict[
SemanticGroupName, List[FlagName]] = self.__class__.flags_required_for_semantic_flag_group
for group in self.__class__.flags_required_for_semantic_flag_group:
flags: List[FlagIndex] = []
for flag in self.__class__.flags_required_for_semantic_flag_group[group]:
flags.append(self._flags[flag])
self._flags_required_by_semantic_flag_group[self._semantic_flag_groups[group]] = flags
self._flag_conditions_for_semantic_flag_group = {}
self.flag_conditions_for_semantic_flag_group = self.__class__.flag_conditions_for_semantic_flag_group
for group in self.__class__.flag_conditions_for_semantic_flag_group:
class_cond = {}
for sem_class in self.__class__.flag_conditions_for_semantic_flag_group[group]:
if sem_class is None:
class_cond[0] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
else:
class_cond[self._semantic_flag_classes[sem_class]
] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class]
self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_cond
self._flags_written_by_flag_write_type = {}
self.flags_written_by_flag_write_type = self.__class__.flags_written_by_flag_write_type
for write_type in self.__class__.flags_written_by_flag_write_type:
flags = []
for flag in self.__class__.flags_written_by_flag_write_type[write_type]:
flags.append(self._flags[flag])
self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flags
self._semantic_class_for_flag_write_type = {}
self.semantic_class_for_flag_write_type = self.__class__.semantic_class_for_flag_write_type
for write_type in self.__class__.semantic_class_for_flag_write_type:
sem_class = self.__class__.semantic_class_for_flag_write_type[write_type]
if sem_class in self._semantic_flag_classes:
sem_class_index = self._semantic_flag_classes[sem_class]
else:
sem_class_index = 0
self._semantic_class_for_flag_write_type[self._flag_write_types[write_type]] = sem_class_index
self.global_regs = self.__class__.global_regs
self.system_regs = self.__class__.system_regs
self._intrinsics: Dict[IntrinsicName, IntrinsicIndex] = {}
self._intrinsic_class_by_index: Dict[IntrinsicIndex, IntrinsicClass] = {}
self._intrinsics_by_index: Dict[IntrinsicIndex, Tuple[IntrinsicName, IntrinsicInfo]] = {}
intrinsic_index = IntrinsicIndex(0)
for intrinsic in self.__class__.intrinsics.keys():
if intrinsic not in self._intrinsics:
info = self.__class__.intrinsics[intrinsic]
for i in range(0, len(info.inputs)):
if isinstance(info.inputs[i], types.Type):
info.inputs[i] = IntrinsicInput(info.inputs[i])
elif isinstance(info.inputs[i], tuple):
info.inputs[i] = IntrinsicInput(info.inputs[i][0], info.inputs[i][1])
info = IntrinsicInfo(info.inputs, info.outputs, intrinsic_index)
self._intrinsics[intrinsic] = intrinsic_index
self._intrinsics_by_index[intrinsic_index] = (intrinsic, info)
intrinsic_index = IntrinsicIndex(intrinsic_index + 1)
self.intrinsics[intrinsic] = info
self._pending_reg_lists = {}
self._pending_token_lists = {}
self._pending_condition_lists = {}
self._pending_name_and_type_lists = {}