# coding=utf-8# Copyright (c) 2015-2025 Vector 35 Inc## Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to# deal in the Software without restriction, including without limitation the# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or# sell copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:## The above copyright notice and this permission notice shall be included in# all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS# IN THE SOFTWARE.importctypesimportinspectfromtypingimportGenerator,Optional,List,Tuple,Union,Mapping,Any,Dict,overloadfromdataclassesimportdataclass# Binary Ninja componentsfrom.import_binaryninjacoreascorefrom.enumsimport(AnalysisSkipReason,FunctionGraphType,SymbolType,SymbolBinding,InstructionTextTokenType,HighlightStandardColor,HighlightColorStyle,DisassemblyOption,IntegerDisplayType,FunctionAnalysisSkipOverride,FunctionUpdateType,BuiltinType,ExprFolding,EarlyReturn,SwitchRecovery)from.importassociateddatastore# Required in the main scope due to being an argument for _FunctionAssociatedDataStorefrom.importtypesfrom.importarchitecturefrom.importlowlevelilfrom.importmediumlevelilfrom.importhighlevelilfrom.importbinaryviewfrom.importbasicblockfrom.importdatabufferfrom.importvariablefrom.importflowgraphfrom.importcallingconventionfrom.importworkflowfrom.importlanguagerepresentationfrom.importdeprecationfrom.importmetadatafrom.import__version__from.commonilimportLocalcall# we define the following as such so the linter doesn't confuse 'highlight' the module with the# property of the same name. There is probably some other work around but it eludes me.from.importhighlightas_highlightfrom.importplatformas_platform# The following imports are for backward compatibility with API version < 3.0# so old plugins which do 'from binaryninja.function import RegisterInfo' will still workfrom.architectureimport(RegisterInfo,RegisterStackInfo,IntrinsicInput,IntrinsicInfo,InstructionBranch,InstructionInfo,InstructionTextToken)from.variableimport(Variable,LookupTableEntry,RegisterValue,ValueRange,PossibleValueSet,StackVariableReference,ConstantReference,IndirectBranchInfo,ParameterVariables,AddressRange)from.importdecoratorsfrom.enumsimportRegisterValueTypefrom.importcomponentExpressionIndex=intInstructionIndex=intAnyFunctionType=Union['Function','lowlevelil.LowLevelILFunction','mediumlevelil.MediumLevelILFunction','highlevelil.HighLevelILFunction']ILFunctionType=Union['lowlevelil.LowLevelILFunction','mediumlevelil.MediumLevelILFunction','highlevelil.HighLevelILFunction']ILInstructionType=Union['lowlevelil.LowLevelILInstruction','mediumlevelil.MediumLevelILInstruction','highlevelil.HighLevelILInstruction']StringOrType=Union[str,'types.Type','types.TypeBuilder']FunctionViewTypeOrName=Union['FunctionViewType',FunctionGraphType,str]def_function_name_():returninspect.stack()[1][0].f_code.co_name[docs]@dataclass(frozen=True)classArchAndAddr:arch:'architecture.Architecture'addr:intdef__repr__(self):returnf"<archandaddr{self.arch} @{self.addr:#x}>" class_FunctionAssociatedDataStore(associateddatastore._AssociatedDataStore):_defaults={}[docs]classDisassemblySettings:[docs]def__init__(self,handle:Optional[core.BNDisassemblySettingsHandle]=None):ifhandleisNone:self.handle=core.BNCreateDisassemblySettings()else:self.handle=handle def__del__(self):ifcoreisnotNone:core.BNFreeDisassemblySettings(self.handle)@propertydefwidth(self)->int:returncore.BNGetDisassemblyWidth(self.handle)@width.setterdefwidth(self,value:int)->None:core.BNSetDisassemblyWidth(self.handle,value)@propertydefmax_symbol_width(self)->int:returncore.BNGetDisassemblyMaximumSymbolWidth(self.handle)@max_symbol_width.setterdefmax_symbol_width(self,value:int)->None:core.BNSetDisassemblyMaximumSymbolWidth(self.handle,value)[docs]defis_option_set(self,option:DisassemblyOption)->bool:ifisinstance(option,str):option=DisassemblyOption[option]returncore.BNIsDisassemblySettingsOptionSet(self.handle,option) [docs]defset_option(self,option:DisassemblyOption,state:bool=True)->None:ifisinstance(option,str):option=DisassemblyOption[option]core.BNSetDisassemblySettingsOption(self.handle,option,state) [docs]@staticmethoddefdefault_settings()->'DisassemblySettings':returnDisassemblySettings(core.BNDefaultDisassemblySettings()) [docs]@staticmethoddefdefault_graph_settings()->'DisassemblySettings':returnDisassemblySettings(core.BNDefaultGraphDisassemblySettings()) [docs]@staticmethoddefdefault_linear_settings()->'DisassemblySettings':returnDisassemblySettings(core.BNDefaultLinearDisassemblySettings()) [docs]@dataclassclassILReferenceSource:func:Optional['Function']arch:Optional['architecture.Architecture']address:intil_type:FunctionGraphTypeexpr_id:ExpressionIndex[docs]@staticmethoddefget_il_name(il_type:FunctionGraphType)->str:ifil_type==FunctionGraphType.NormalFunctionGraph:return'disassembly'ifil_type==FunctionGraphType.LowLevelILFunctionGraph:return'llil'ifil_type==FunctionGraphType.LiftedILFunctionGraph:return'lifted_llil'ifil_type==FunctionGraphType.LowLevelILSSAFormFunctionGraph:return'llil_ssa'ifil_type==FunctionGraphType.MediumLevelILFunctionGraph:return'mlil'ifil_type==FunctionGraphType.MediumLevelILSSAFormFunctionGraph:return'mlil_ssa'ifil_type==FunctionGraphType.MappedMediumLevelILFunctionGraph:return'mapped_mlil'ifil_type==FunctionGraphType.MappedMediumLevelILSSAFormFunctionGraph:return'mapped_mlil_ssa'ifil_type==FunctionGraphType.HighLevelILFunctionGraph:return'hlil'ifil_type==FunctionGraphType.HighLevelILSSAFormFunctionGraph:return'hlil_ssa'return"" def__repr__(self):ifself.arch:returnf"<ref:{self.arch}@{self.address:#x},{self.get_il_name(self.il_type)}@{self.expr_id}>"else:returnf"<ref:{self.address:#x},{self.get_il_name(self.il_type)}@{self.expr_id}>" [docs]@dataclassclassVariableReferenceSource:var:'variable.Variable'src:ILReferenceSourcedef__repr__(self):returnf"<var:{repr(self.var)}, src:{repr(self.src)}>" [docs]@dataclassclassFunctionViewType:view_type:FunctionGraphTypename:Optional[str][docs]def__init__(self,view_type:FunctionViewTypeOrName):ifisinstance(view_type,FunctionViewType):self.view_type=view_type.view_typeself.name=view_type.nameelifisinstance(view_type,FunctionGraphType):self.view_type=view_typeself.name=Noneelse:self.view_type=FunctionGraphType.HighLevelLanguageRepresentationFunctionGraphself.name=str(view_type) def__hash__(self):returnhash((self.view_type,self.name))@staticmethoddef_from_core_struct(view_type:core.BNFunctionViewType)->'FunctionViewType':ifview_type.type==FunctionGraphType.HighLevelLanguageRepresentationFunctionGraph:ifview_type.nameisNone:returnFunctionViewType("Pseudo C")else:returnFunctionViewType(view_type.name)else:returnFunctionViewType(view_type.type)def_to_core_struct(self)->core.BNFunctionViewType:result=core.BNFunctionViewType()result.type=self.view_typeresult.name=self.namereturnresult [docs]classBasicBlockList:[docs]def__init__(self,function:Union['Function','lowlevelil.LowLevelILFunction','mediumlevelil.MediumLevelILFunction','highlevelil.HighLevelILFunction']):self._count,self._blocks=function._basic_block_list()self._function=functionself._n=0 def__repr__(self):returnf"<BasicBlockList{len(self)} BasicBlocks:{list(self)}>"def__del__(self):ifcoreisnotNone:core.BNFreeBasicBlockList(self._blocks,len(self))def__len__(self):returnself._count.valuedef__iter__(self):returnBasicBlockList(self._function)def__next__(self)->'basicblock.BasicBlock':ifself._n>=len(self):raiseStopIterationblock=core.BNNewBasicBlockReference(self._blocks[self._n])assertblockisnotNone,"core.BNNewBasicBlockReference returned None"self._n+=1returnself._function._instantiate_block(block)@overloaddef__getitem__(self,i:int)->'basicblock.BasicBlock':...@overloaddef__getitem__(self,i:slice)->List['basicblock.BasicBlock']:...def__getitem__(self,i:Union[int,slice])->Union['basicblock.BasicBlock',List['basicblock.BasicBlock']]:ifisinstance(i,int):ifi<0:i=len(self)+iifi>=len(self):raiseIndexError(f"Index{i} out of bounds for BasicBlockList of size{len(self)}")block=core.BNNewBasicBlockReference(self._blocks[i])assertblockisnotNone,"core.BNNewBasicBlockReference returned None"returnself._function._instantiate_block(block)elifisinstance(i,slice):result=[]ifi.start<0ori.start>=len(self)ori.stop<0ori.stop>=len(self):raiseIndexError(f"Slice{i} out of bounds for FunctionList of size{len(self)}")forjinrange(i.start,i.stop,i.stepifi.stepisnotNoneelse1):block=core.BNNewBasicBlockReference(self._blocks[j])assertblockisnotNone,"core.BNNewBasicBlockReference returned None"result.append(self._function._instantiate_block(block))returnresultraiseValueError("BasicBlockList.__getitem__ supports argument of type integer or slice only") [docs]classLowLevelILBasicBlockList(BasicBlockList):def__repr__(self):returnf"<LowLevelILBasicBlockList{len(self)} BasicBlocks:{list(self)}>"@overloaddef__getitem__(self,i:int)->'lowlevelil.LowLevelILBasicBlock':...@overloaddef__getitem__(self,i:slice)->List['lowlevelil.LowLevelILBasicBlock']:...def__getitem__(self,i:Union[int,slice])->Union['lowlevelil.LowLevelILBasicBlock',List['lowlevelil.LowLevelILBasicBlock']]:returnBasicBlockList.__getitem__(self,i)# type: ignoredef__next__(self)->'lowlevelil.LowLevelILBasicBlock':returnBasicBlockList.__next__(self)# type: ignore [docs]classMediumLevelILBasicBlockList(BasicBlockList):def__repr__(self):returnf"<MediumLevelILBasicBlockList{len(self)} BasicBlocks:{list(self)}>"@overloaddef__getitem__(self,i:int)->'mediumlevelil.MediumLevelILBasicBlock':...@overloaddef__getitem__(self,i:slice)->List['mediumlevelil.MediumLevelILBasicBlock']:...def__getitem__(self,i:Union[int,slice])->Union['mediumlevelil.MediumLevelILBasicBlock',List['mediumlevelil.MediumLevelILBasicBlock']]:returnBasicBlockList.__getitem__(self,i)# type: ignoredef__next__(self)->'mediumlevelil.MediumLevelILBasicBlock':returnBasicBlockList.__next__(self)# type: ignore [docs]classHighLevelILBasicBlockList(BasicBlockList):def__repr__(self):returnf"<HighLevelILBasicBlockList{len(self)} BasicBlocks:{list(self)}>"@overloaddef__getitem__(self,i:int)->'highlevelil.HighLevelILBasicBlock':...@overloaddef__getitem__(self,i:slice)->List['highlevelil.HighLevelILBasicBlock']:...def__getitem__(self,i:Union[int,slice])->Union['highlevelil.HighLevelILBasicBlock',List['highlevelil.HighLevelILBasicBlock']]:returnBasicBlockList.__getitem__(self,i)# type: ignoredef__next__(self)->'highlevelil.HighLevelILBasicBlock':returnBasicBlockList.__next__(self)# type: ignore [docs]classTagList:[docs]def__init__(self,function:'Function'):self._count=ctypes.c_ulonglong()tags=core.BNGetAddressTagReferences(function.handle,self._count)asserttagsisnotNone,"core.BNGetAddressTagReferences returned None"self._tags=tagsself._function=functionself._n=0 def__repr__(self):returnf"<TagList{len(self)} Tags:{list(self)}>"def__del__(self):ifcoreisnotNone:core.BNFreeTagReferences(self._tags,len(self))def__len__(self):returnself._count.valuedef__iter__(self):returnselfdef__next__(self)->Tuple['architecture.Architecture',int,'binaryview.Tag']:ifself._n>=len(self):raiseStopIterationcore_tag=core.BNNewTagReference(self._tags[self._n].tag)arch=architecture.CoreArchitecture._from_cache(self._tags[self._n].arch)address=self._tags[self._n].addrassertcore_tagisnotNone,"core.BNNewTagReference returned None"self._n+=1returnarch,address,binaryview.Tag(core_tag)@overloaddef__getitem__(self,i:int)->Tuple['architecture.Architecture',int,'binaryview.Tag']:...@overloaddef__getitem__(self,i:slice)->List[Tuple['architecture.Architecture',int,'binaryview.Tag']]:...def__getitem__(self,i:Union[int,slice])->Union[Tuple['architecture.Architecture',int,'binaryview.Tag'],List[Tuple['architecture.Architecture',int,'binaryview.Tag']]]:ifisinstance(i,int):ifi<0:i=len(self)+iifi>=len(self):raiseIndexError(f"Index{i} out of bounds for TagList of size{len(self)}")core_tag=core.BNNewTagReference(self._tags[i].tag)arch=architecture.CoreArchitecture._from_cache(self._tags[i].arch)assertcore_tagisnotNone,"core.BNNewTagReference returned None"returnarch,self._tags[i].addr,binaryview.Tag(core_tag)elifisinstance(i,slice):result=[]ifi.start<0ori.start>=len(self)ori.stop<0ori.stop>=len(self):raiseIndexError(f"Slice{i} out of bounds for FunctionList of size{len(self)}")forjinrange(i.start,i.stop,i.stepifi.stepisnotNoneelse1):core_tag=core.BNNewTagReference(self._tags[j].tag)assertcore_tagisnotNone,"core.BNNewTagReference returned None"arch=architecture.CoreArchitecture._from_cache(self._tags[j].arch)result.append((arch,self._tags[j].addr,binaryview.Tag(core_tag)))returnresultraiseValueError("TagList.__getitem__ supports argument of type integer or slice only") [docs]classFunction:_associated_data={}"""The examples in the following code will use the following variables>>> from binaryninja import *>>> bv = load("/bin/ls")>>> current_function = bv.functions[0]>>> here = current_function.start"""[docs]def__init__(self,view:Optional['binaryview.BinaryView']=None,handle:Optional[core.BNFunctionHandle]=None):self._advanced_analysis_requests=0asserthandleisnotNone,"creation of standalone 'Function' objects is not implemented"FunctionHandle=ctypes.POINTER(core.BNFunction)self.handle=ctypes.cast(handle,FunctionHandle)ifviewisNone:self._view=binaryview.BinaryView(handle=core.BNGetFunctionData(self.handle))else:self._view=viewself._arch=Noneself._platform=None def__del__(self):ifcoreisnotNoneandself.handleisnotNone:ifself._advanced_analysis_requests>0:core.BNReleaseAdvancedFunctionAnalysisDataMultiple(self.handle,self._advanced_analysis_requests)core.BNFreeFunction(self.handle)def__repr__(self):arch=self.archifarch:returnf"<func:{arch.name}@{self.start:#x}>"else:returnf"<func:{self.start:#x}>"def__eq__(self,other:'Function')->bool:ifnotisinstance(other,self.__class__):returnNotImplementedreturnctypes.addressof(self.handle.contents)==ctypes.addressof(other.handle.contents)def__ne__(self,other:'Function')->bool:ifnotisinstance(other,self.__class__):returnNotImplementedreturnnot(self==other)def__lt__(self,other:'Function')->bool:ifnotisinstance(other,self.__class__):returnNotImplementedreturnself.start<other.startdef__gt__(self,other:'Function')->bool:ifnotisinstance(other,self.__class__):returnNotImplementedreturnself.start>other.startdef__le__(self,other:'Function')->bool:ifnotisinstance(other,self.__class__):returnNotImplementedreturnself.start<=other.startdef__ge__(self,other:'Function')->bool:ifnotisinstance(other,self.__class__):returnNotImplementedreturnself.start>=other.startdef__hash__(self):returnhash((self.start,self.arch,self.platform))@overloaddef__getitem__(self,i:int)->'basicblock.BasicBlock':...@overloaddef__getitem__(self,i:slice)->List['basicblock.BasicBlock']:...def__getitem__(self,i:Union[int,slice])->Union['basicblock.BasicBlock',List['basicblock.BasicBlock']]:returnself.basic_blocks[i]def__iter__(self)->Generator['basicblock.BasicBlock',None,None]:yield fromself.basic_blocksdef__str__(self):result=""fortokeninself.type_tokens:result+=token.textreturnresultdef__contains__(self,value:Union[basicblock.BasicBlock,int]):ifisinstance(value,basicblock.BasicBlock):returnvalue.function==selfreturnselfin[block.functionforblockinself.view.get_basic_blocks_at(int(value))]@classmethoddef_unregister(cls,func:'core.BNFunction')->None:handle=ctypes.cast(func,ctypes.c_void_p)ifhandle.valueincls._associated_data:delcls._associated_data[handle.value][docs]@staticmethoddefset_default_session_data(name:str,value)->None:_FunctionAssociatedDataStore.set_default(name,value) @propertydefname(self)->str:"""Symbol name for the function"""returnself.symbol.name@name.setterdefname(self,value:Union[str,'types.CoreSymbol'])->None:# type: ignoreifvalueisNone:ifself.symbolisnotNone:self.view.undefine_user_symbol(self.symbol)elifisinstance(value,str):symbol=types.Symbol(SymbolType.FunctionSymbol,self.start,value)self.view.define_user_symbol(symbol)elifisinstance(value,types.Symbol):self.view.define_user_symbol(value)@propertydefview(self)->'binaryview.BinaryView':"""Function view (read-only)"""returnself._view@propertydefarch(self)->'architecture.Architecture':"""Function architecture (read-only)"""ifself._arch:returnself._archelse:arch=core.BNGetFunctionArchitecture(self.handle)assertarchisnotNone,"core.BNGetFunctionArchitecture returned None"self._arch=architecture.CoreArchitecture._from_cache(arch)returnself._arch@propertydefplatform(self)->Optional['_platform.Platform']:"""Function platform (read-only)"""ifself._platform:returnself._platformelse:plat=core.BNGetFunctionPlatform(self.handle)ifplatisNone:returnNoneself._platform=_platform.CorePlatform._from_cache(handle=plat)returnself._platform@propertydefstart(self)->int:"""Function start address (read-only)"""returncore.BNGetFunctionStart(self.handle)@propertydeftotal_bytes(self)->int:"""Total bytes of a function calculated by summing each basic_block. Because basic blocks can overlap andhave gaps between them this may or may not be equivalent to a .size property."""returnsum(map(len,self))@propertydefhighest_address(self)->int:"""The highest (largest) virtual address contained in a function."""returncore.BNGetFunctionHighestAddress(self.handle)@propertydeflowest_address(self)->int:"""The lowest (smallest) virtual address contained in a function."""returncore.BNGetFunctionLowestAddress(self.handle)@propertydefaddress_ranges(self)->List['variable.AddressRange']:"""All of the address ranges covered by a function"""count=ctypes.c_ulonglong(0)range_list=core.BNGetFunctionAddressRanges(self.handle,count)assertrange_listisnotNone,"core.BNGetFunctionAddressRanges returned None"result=[]foriinrange(0,count.value):result.append(variable.AddressRange(range_list[i].start,range_list[i].end))core.BNFreeAddressRanges(range_list)returnresult@propertydefsymbol(self)->'types.CoreSymbol':"""Function symbol(read-only)"""sym=core.BNGetFunctionSymbol(self.handle)assertsymisnotNone,"core.BNGetFunctionSymbol returned None"returntypes.CoreSymbol(sym)@propertydefis_exported(self)->bool:"""Whether the function is exported (read-only).A function is considered exported when its symbol binding is global or weak."""binding=self.symbol.bindingreturnbindingin(SymbolBinding.GlobalBinding,SymbolBinding.WeakBinding)@propertydefauto(self)->bool:"""Whether function was automatically discovered (read-only) as a result of some creation of a 'user' function.'user' functions may or may not have been created by a user through the or API. For instance the entry pointinto a function is always created a 'user' function. 'user' functions should be considered the root of autoanalysis."""returncore.BNWasFunctionAutomaticallyDiscovered(self.handle)@propertydefhas_user_annotations(self)->bool:"""Whether the function has ever been 'user' modified"""returncore.BNFunctionHasUserAnnotations(self.handle)@propertydefcan_return(self)->'types.BoolWithConfidence':"""Whether function can return"""result=core.BNCanFunctionReturn(self.handle)returntypes.BoolWithConfidence(result.value,confidence=result.confidence)@can_return.setterdefcan_return(self,value:'types.BoolWithConfidence')->None:bc=core.BNBoolWithConfidence()bc.value=bool(value)ifhasattr(value,'confidence'):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetUserFunctionCanReturn(self.handle,bc)@propertydefis_pure(self)->'types.BoolWithConfidence':"""Whether function is pure"""result=core.BNIsFunctionPure(self.handle)returntypes.BoolWithConfidence(result.value,confidence=result.confidence)@is_pure.setterdefis_pure(self,value:'types.BoolWithConfidence')->None:bc=core.BNBoolWithConfidence()bc.value=bool(value)ifhasattr(value,'confidence'):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetUserFunctionPure(self.handle,bc)@propertydefhas_explicitly_defined_type(self)->bool:"""Whether function has explicitly defined types (read-only)"""returncore.BNFunctionHasExplicitlyDefinedType(self.handle)@propertydefneeds_update(self)->bool:"""Whether the function has analysis that needs to be updated (read-only)"""returncore.BNIsFunctionUpdateNeeded(self.handle)def_basic_block_list(self):count=ctypes.c_ulonglong()blocks=core.BNGetFunctionBasicBlockList(self.handle,count)assertblocksisnotNone,"core.BNGetFunctionBasicBlockList returned None"returncount,blocksdef_instantiate_block(self,handle):returnbasicblock.BasicBlock(handle,self.view)@propertydefbasic_blocks(self)->BasicBlockList:"""function.BasicBlockList of BasicBlocks in the current function (read-only)"""returnBasicBlockList(self)@propertydefis_thunk(self)->bool:"""Returns True if the function starts with a Tailcall (read-only)"""ifself.llil_if_availableisnotNone:returnself.llil_if_available.is_thunkelse:returnFalse@propertydefcomments(self)->Dict[int,str]:"""Dict of comments (read-only)"""count=ctypes.c_ulonglong()addrs=core.BNGetCommentedAddresses(self.handle,count)assertaddrsisnotNone,"core.BNGetCommentedAddresses returned None"try:result={}foriinrange(0,count.value):result[addrs[i]]=self.get_comment_at(addrs[i])returnresultfinally:core.BNFreeAddressList(addrs)@propertydeftags(self)->TagList:"""``tags`` gets a TagList of all Tags in the function (but not "function tags").Tags are returned as an iterable indexable object TagList of (arch, address, Tag) tuples.:rtype: TagList((Architecture, int, Tag))"""returnTagList(self)[docs]defget_tags_at(self,addr:int,arch:Optional['architecture.Architecture']=None,auto:Optional[bool]=None)->List['binaryview.Tag']:"""``get_tags`` gets a list of Tags (but not function tags).:param int addr: Address to get tags from.:param bool auto: If None, gets all tags, if True, gets auto tags, if False, gets user tags:rtype: list((Architecture, int, Tag))"""ifarchisNone:assertself.archisnotNone,"Can't call get_tags_at for function with no architecture specified"arch=self.archcount=ctypes.c_ulonglong()ifautoisNone:tags=core.BNGetAddressTags(self.handle,arch.handle,addr,count)asserttagsisnotNone,"core.BNGetAddressTags returned None"elifauto:tags=core.BNGetAutoAddressTags(self.handle,arch.handle,addr,count)asserttagsisnotNone,"core.BNGetAutoAddressTags returned None"else:tags=core.BNGetUserAddressTags(self.handle,arch.handle,addr,count)asserttagsisnotNone,"core.BNGetUserAddressTags returned None"result=[]try:foriinrange(0,count.value):core_tag=core.BNNewTagReference(tags[i])assertcore_tagisnotNone,"core.BNNewTagReference returned None"result.append(binaryview.Tag(core_tag))returnresultfinally:core.BNFreeTagList(tags,count.value) [docs]defget_tags_in_range(self,address_range:'variable.AddressRange',arch:Optional['architecture.Architecture']=None,auto:Optional[bool]=None)->List[Tuple['architecture.Architecture',int,'binaryview.Tag']]:"""``get_address_tags_in_range`` gets a list of all Tags in the function at a given address.Range is inclusive at the start, exclusive at the end.:param AddressRange address_range: Address range from which to get tags:param Architecture arch: Architecture for the block in which the Tag is located (optional):param bool auto: If None, gets all tags, if True, gets auto tags, if False, gets user tags:return: A list of (arch, address, Tag) tuples:rtype: list((Architecture, int, Tag))"""ifarchisNone:assertself.archisnotNone,"Can't call get_address_tags_in_range for function with no architecture specified"arch=self.archcount=ctypes.c_ulonglong()ifautoisNone:refs=core.BNGetAddressTagsInRange(self.handle,arch.handle,address_range.start,address_range.end,count)assertrefsisnotNone,"core.BNGetAddressTagsInRange returned None"elifauto:refs=core.BNGetAutoAddressTagsInRange(self.handle,arch.handle,address_range.start,address_range.end,count)assertrefsisnotNone,"core.BNGetAutoAddressTagsInRange returned None"else:refs=core.BNGetUserAddressTagsInRange(self.handle,arch.handle,address_range.start,address_range.end,count)assertrefsisnotNone,"core.BNGetUserAddressTagsInRange returned None"try:result=[]foriinrange(0,count.value):tag_ref=core.BNNewTagReference(refs[i].tag)asserttag_refisnotNone,"core.BNNewTagReference returned None"tag=binaryview.Tag(tag_ref)result.append((arch,refs[i].addr,tag))returnresultfinally:core.BNFreeTagReferences(refs,count.value) [docs]defget_function_tags(self,auto:Optional[bool]=None,tag_type:Optional[str]=None)->List['binaryview.Tag']:"""``get_function_tags`` gets a list of function Tags for the function.:param bool auto: If None, gets all tags, if True, gets auto tags, if False, gets user tags:param str tag_type: If None, gets all tags, otherwise only gets tags of the given type:rtype: list(Tag)"""count=ctypes.c_ulonglong()tags=[]iftag_typeisnotNone:tag_type=self.view.get_tag_type(tag_type)iftag_typeisNone:return[]ifautoisNone:tags=core.BNGetFunctionTagsOfType(self.handle,tag_type.handle,count)asserttagsisnotNone,"core.BNGetFunctionTagsOfType returned None"elifauto:tags=core.BNGetAutoFunctionTagsOfType(self.handle,tag_type.handle,count)asserttagsisnotNone,"core.BNGetAutoFunctionTagsOfType returned None"else:tags=core.BNGetUserFunctionTagsOfType(self.handle,tag_type.handle,count)asserttagsisnotNone,"core.BNGetUserFunctionTagsOfType returned None"else:ifautoisNone:tags=core.BNGetFunctionTags(self.handle,count)asserttagsisnotNone,"core.BNGetFunctionTags returned None"elifauto:tags=core.BNGetAutoFunctionTags(self.handle,count)asserttagsisnotNone,"core.BNGetAutoFunctionTags returned None"else:tags=core.BNGetUserFunctionTags(self.handle,count)asserttagsisnotNone,"core.BNGetUserFunctionTags returned None"try:result=[]foriinrange(count.value):core_tag=core.BNNewTagReference(tags[i])assertcore_tagisnotNone,"core.BNNewTagReference returned None"result.append(binaryview.Tag(core_tag))returnresultfinally:core.BNFreeTagList(tags,count.value) [docs]defadd_tag(self,tag_type:str,data:str,addr:Optional[int]=None,auto:bool=False,arch:Optional['architecture.Architecture']=None):"""``add_tag`` creates and adds a :py:class:`Tag` object on either a function, or onan address inside of a function."Function tags" appear at the top of a function and are a good way to label anentire function with some information. If you include an address when you callFunction.add_tag, you'll create an "address tag". These are good for labelingspecific instructions.For tagging arbitrary data, consider :py:func:`~binaryninja.binaryview.BinaryView.add_tag`.:param str tag_type: The name of the tag type for this Tag:param str data: additional data for the Tag:param int addr: address at which to add the tag:param bool auto: Whether or not an auto tag:param Architecture arch: Architecture for the block in which the Tag is added (optional):Example:>>> current_function.add_tag("Important", "I think this is the main function")>>> current_function.add_tag("Crashes", "Nullpointer dereference", here)Warning: For performance reasons, this function does not ensure the address youhave supplied is within the function's bounds."""tag_type=self.view.get_tag_type(tag_type)iftag_typeisNone:returnifarchisNone:arch=self.arch# Create tagtag_handle=core.BNCreateTag(tag_type.handle,data)asserttag_handleisnotNone,"core.BNCreateTag returned None"tag=binaryview.Tag(tag_handle)core.BNAddTag(self.view.handle,tag.handle,auto)ifauto:ifaddrisNone:core.BNAddAutoFunctionTag(self.handle,tag.handle)else:core.BNAddAutoAddressTag(self.handle,arch.handle,addr,tag.handle)else:ifaddrisNone:core.BNAddUserFunctionTag(self.handle,tag.handle)else:core.BNAddUserAddressTag(self.handle,arch.handle,addr,tag.handle) [docs]defremove_user_address_tag(self,addr:int,tag:'binaryview.Tag',arch:Optional['architecture.Architecture']=None)->None:"""``remove_user_address_tag`` removes a Tag object at a given address.Since this removes a user tag, it will be added to the current undo buffer.:param int addr: Address at which to remove the tag:param Tag tag: Tag object to be added:param Architecture arch: Architecture for the block in which the Tag is added (optional):rtype: None"""ifarchisNone:arch=self.archcore.BNRemoveUserAddressTag(self.handle,arch.handle,addr,tag.handle) [docs]defremove_user_function_tag(self,tag:'binaryview.Tag')->None:"""``remove_user_function_tag`` removes a Tag object as a function tag.Since this removes a user tag, it will be added to the current undo buffer.:param Tag tag: Tag object to be added:rtype: None"""core.BNRemoveUserFunctionTag(self.handle,tag.handle) [docs]defremove_user_address_tags_of_type(self,addr:int,tag_type:str,arch=None):"""``remove_user_address_tags_of_type`` removes all tags at the given address of the given type.Since this removes user tags, it will be added to the current undo buffer.:param int addr: Address at which to remove the tag:param Tag tag_type: TagType object to match for removing:param Architecture arch: Architecture for the block in which the Tags is located (optional):rtype: None"""ifarchisNone:arch=self.archtag_type=self.view.get_tag_type(tag_type)iftag_typeisnotNone:core.BNRemoveUserAddressTagsOfType(self.handle,arch.handle,addr,tag_type.handle) [docs]defremove_auto_address_tag(self,addr:int,tag:'binaryview.Tag',arch:Optional['architecture.Architecture']=None)->None:"""``remove_auto_address_tag`` removes a Tag object at a given address.:param int addr: Address at which to add the tag:param Tag tag: Tag object to be added:param Architecture arch: Architecture for the block in which the Tag is added (optional):rtype: None"""ifarchisNone:arch=self.archcore.BNRemoveAutoAddressTag(self.handle,arch.handle,addr,tag.handle) [docs]defremove_auto_address_tags_of_type(self,addr:int,tag_type:str,arch=None):"""``remove_auto_address_tags_of_type`` removes all tags at the given address of the given type.:param int addr: Address at which to remove the tags:param Tag tag_type: TagType object to match for removing:param Architecture arch: Architecture for the block in which the Tags is located (optional):rtype: None"""ifarchisNone:arch=self.archtag_type=self.view.get_tag_type(tag_type)iftag_typeisnotNone:core.BNRemoveAutoAddressTagsOfType(self.handle,arch.handle,addr,tag_type.handle) [docs]defremove_user_function_tags_of_type(self,tag_type:str):"""``remove_user_function_tags_of_type`` removes all function Tag objects on a function of a given typeSince this removes user tags, it will be added to the current undo buffer.:param TagType tag_type: TagType object to match for removing:rtype: None"""tag_type=self.view.get_tag_type(tag_type)iftag_typeisnotNone:core.BNRemoveUserFunctionTagsOfType(self.handle,tag_type.handle) [docs]defremove_auto_function_tag(self,tag:'binaryview.Tag')->None:"""``remove_user_function_tag`` removes a Tag object as a function tag.:param Tag tag: Tag object to be added:rtype: None"""core.BNRemoveAutoFunctionTag(self.handle,tag.handle) [docs]defremove_auto_function_tags_of_type(self,tag_type:str):"""``remove_user_function_tags_of_type`` removes all function Tag objects on a function of a given type:param TagType tag_type: TagType object to match for removing:rtype: None"""tag_type=self.view.get_tag_type(tag_type)iftag_typeisnotNone:core.BNRemoveAutoFunctionTagsOfType(self.handle,tag_type.handle) @propertydeflow_level_il(self)->Optional['lowlevelil.LowLevelILFunction']:"""returns LowLevelILFunction used to represent low level IL, or None if an error occurs while loading the IL(read-only).. note::This function causes low level IL to be generated if it has not been already. It is recommended to generateIL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""returnself.llil@propertydefllil(self)->Optional['lowlevelil.LowLevelILFunction']:"""returns LowLevelILFunction used to represent low level IL, or None if an error occurs while loading the IL(read-only).. note::This function causes low level IL to be generated if it has not been already. It is recommended to generateIL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""result=core.BNGetFunctionLowLevelIL(self.handle)ifnotresult:returnNonereturnlowlevelil.LowLevelILFunction(self.arch,result,self)@propertydefllil_if_available(self)->Optional['lowlevelil.LowLevelILFunction']:"""returns LowLevelILFunction used to represent low level IL, or None if not loaded or it cannot be generated(read-only).. note:: This function can be used to check if low level IL is available without generating it."""result=core.BNGetFunctionLowLevelILIfAvailable(self.handle)ifnotresult:returnNonereturnlowlevelil.LowLevelILFunction(self.arch,result,self)@propertydeflifted_il(self)->Optional['lowlevelil.LowLevelILFunction']:"""returns LowLevelILFunction used to represent lifted IL, or None if an error occurs while loading the IL(read-only).. note::This function causes lifted IL to be generated if it has not been already. It is recommended to generate ILon-demand to avoid excessive memory usage instead of generating IL for all functions at once."""result=core.BNGetFunctionLiftedIL(self.handle)ifnotresult:returnNonereturnlowlevelil.LowLevelILFunction(self.arch,result,self)@propertydeflifted_il_if_available(self)->Optional['lowlevelil.LowLevelILFunction']:"""returns LowLevelILFunction used to represent lifted IL, or None if not loaded or it cannot be generated(read-only).. note:: This function can be used to check if lifted IL is available without generating it."""result=core.BNGetFunctionLiftedILIfAvailable(self.handle)ifnotresult:returnNonereturnlowlevelil.LowLevelILFunction(self.arch,result,self)@propertydefmedium_level_il(self)->Optional['mediumlevelil.MediumLevelILFunction']:"""returns MediumLevelILFunction used to represent medium level IL, or None if an error occurs while loading the IL(read-only).. note::This function causes medium level IL to be generated if it has not been already. It is recommended togenerate IL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""returnself.mlil@propertydefmlil(self)->Optional['mediumlevelil.MediumLevelILFunction']:"""returns MediumLevelILFunction used to represent medium level IL, or None if an error occurs while loading the IL(read-only).. note::This function causes medium level IL to be generated if it has not been already. It is recommended togenerate IL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""result=core.BNGetFunctionMediumLevelIL(self.handle)ifnotresult:returnNonereturnmediumlevelil.MediumLevelILFunction(self.arch,result,self)@propertydefmlil_if_available(self)->Optional['mediumlevelil.MediumLevelILFunction']:"""returns MediumLevelILFunction used to represent medium level IL, or None if not loaded or it cannot be generated(read-only).. note:: This function can be used to check if medium level IL is available without generating it."""result=core.BNGetFunctionMediumLevelILIfAvailable(self.handle)ifnotresult:returnNonereturnmediumlevelil.MediumLevelILFunction(self.arch,result,self)@propertydefmmlil(self)->Optional['mediumlevelil.MediumLevelILFunction']:"""returns MediumLevelILFunction used to represent mapped medium level IL, or None if an error occurs while loadingthe IL (read-only).. note::This function causes mapped medium level IL to be generated if it has not been already. It is recommended togenerate IL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""result=core.BNGetFunctionMappedMediumLevelIL(self.handle)ifnotresult:returnNonereturnmediumlevelil.MediumLevelILFunction(self.arch,result,self)@propertydefmapped_medium_level_il(self)->Optional['mediumlevelil.MediumLevelILFunction']:"""returns MediumLevelILFunction used to represent mapped medium level IL, or None if an error occurs while loadingthe IL (read-only).. note::This function causes mapped medium level IL to be generated if it has not been already. It is recommended togenerate IL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""returnself.mmlil@propertydefmmlil_if_available(self)->Optional['mediumlevelil.MediumLevelILFunction']:"""returns MediumLevelILFunction used to represent mapped medium level IL, or None if not loaded or it cannot begenerated (read-only).. note:: This function can be used to check if mapped medium level IL is available without generating it."""result=core.BNGetFunctionMappedMediumLevelILIfAvailable(self.handle)ifnotresult:returnNonereturnmediumlevelil.MediumLevelILFunction(self.arch,result,self)@propertydefhigh_level_il(self)->Optional['highlevelil.HighLevelILFunction']:"""returns HighLevelILFunction used to represent high level IL, or None if an error occurs while loading the IL(read-only).. note::This function causes high level IL to be generated if it has not been already. It is recommended togenerate IL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""returnself.hlil@propertydefhlil(self)->Optional['highlevelil.HighLevelILFunction']:"""returns HighLevelILFunction used to represent high level IL, or None if an error occurs while loading the IL(read-only).. note::This function causes high level IL to be generated if it has not been already. It is recommended to generateIL on-demand to avoid excessive memory usage instead of generating IL for all functions at once."""result=core.BNGetFunctionHighLevelIL(self.handle)ifnotresult:returnNonereturnhighlevelil.HighLevelILFunction(self.arch,result,self)@propertydefhlil_if_available(self)->Optional['highlevelil.HighLevelILFunction']:"""returns HighLevelILFunction used to represent high level IL, or None if not loaded or it cannot be generated(read-only).. note:: This function can be used to check if high level IL is available without generating it."""result=core.BNGetFunctionHighLevelILIfAvailable(self.handle)ifnotresult:returnNonereturnhighlevelil.HighLevelILFunction(self.arch,result,self)@propertydefpseudo_c(self)->Optional['languagerepresentation.LanguageRepresentationFunction']:returnself.language_representation("Pseudo C")@propertydefpseudo_c_if_available(self)->Optional['languagerepresentation.LanguageRepresentationFunction']:returnself.language_representation_if_available("Pseudo C")[docs]deflanguage_representation(self,language:str)->Optional['languagerepresentation.LanguageRepresentationFunction']:result=core.BNGetFunctionLanguageRepresentation(self.handle,language)ifresultisNone:returnNonereturnlanguagerepresentation.LanguageRepresentationFunction(handle=result) [docs]deflanguage_representation_if_available(self,language:str)->Optional['languagerepresentation.LanguageRepresentationFunction']:result=core.BNGetFunctionLanguageRepresentationIfAvailable(self.handle,language)ifresultisNone:returnNonereturnlanguagerepresentation.LanguageRepresentationFunction(handle=result) @propertydeftype(self)->'types.FunctionType':"""Function type object, can be set with either a string representing the function prototype(`str(function)` shows examples) or a :py:class:`Type` object"""returntypes.FunctionType(core.BNGetFunctionType(self.handle),platform=self.platform)@type.setterdeftype(self,value:Union['types.FunctionType',str])->None:ifisinstance(value,str):(parsed_value,new_name)=self.view.parse_type_string(value)self.name=str(new_name)self.set_user_type(parsed_value)else:self.set_user_type(value)@propertydefstack_layout(self)->List['variable.Variable']:"""List of function stack variables (read-only)"""count=ctypes.c_ulonglong()v=core.BNGetStackLayout(self.handle,count)assertvisnotNone,"core.BNGetStackLayout returned None"try:return[variable.Variable.from_BNVariable(self,v[i].var)foriinrange(count.value)]finally:core.BNFreeVariableNameAndTypeList(v,count.value)@propertydefcore_var_stack_layout(self)->List['variable.CoreVariable']:"""List of function stack variables (read-only)"""count=ctypes.c_ulonglong()v=core.BNGetStackLayout(self.handle,count)assertvisnotNone,"core.BNGetStackLayout returned None"try:return[variable.CoreVariable.from_BNVariable(v[i].var)foriinrange(count.value)]finally:core.BNFreeVariableNameAndTypeList(v,count.value)@propertydefvars(self)->List['variable.Variable']:"""List of function variables (read-only)"""count=ctypes.c_ulonglong()v=core.BNGetFunctionVariables(self.handle,count)assertvisnotNone,"core.BNGetFunctionVariables returned None"try:return[variable.Variable.from_BNVariable(self,v[i].var)foriinrange(count.value)]finally:core.BNFreeVariableNameAndTypeList(v,count.value)@propertydefcore_vars(self)->List['variable.CoreVariable']:"""List of CoreVariable objects"""count=ctypes.c_ulonglong()v=core.BNGetFunctionVariables(self.handle,count)assertvisnotNone,"core.BNGetFunctionVariables returned None"try:return[variable.CoreVariable.from_BNVariable(v[i].var)foriinrange(count.value)]finally:core.BNFreeVariableNameAndTypeList(v,count.value)[docs]defget_variable_by_name(self,name:str)->Optional['variable.Variable']:"""Get a specific variable or None if it doesn't exist"""forvinself.vars:ifv.name==name:returnvreturnNone @propertydefindirect_branches(self)->List['variable.IndirectBranchInfo']:"""List of indirect branches (read-only)"""count=ctypes.c_ulonglong()branches=core.BNGetIndirectBranches(self.handle,count)assertbranchesisnotNone,"core.BNGetIndirectBranches returned None"result=[]foriinrange(0,count.value):result.append(variable.IndirectBranchInfo(architecture.CoreArchitecture._from_cache(branches[i].sourceArch),branches[i].sourceAddr,architecture.CoreArchitecture._from_cache(branches[i].destArch),branches[i].destAddr,branches[i].autoDefined))core.BNFreeIndirectBranchList(branches)returnresult@propertydefunresolved_indirect_branches(self)->List[Tuple['architecture.Architecture',int]]:"""List of unresolved indirect branches (read-only)"""count=ctypes.c_ulonglong()addresses=core.BNGetUnresolvedIndirectBranches(self.handle,count)try:assertaddressesisnotNone,"core.BNGetUnresolvedIndirectBranches returned None"result=[]foriinrange(count.value):result.append((architecture.CoreArchitecture._from_cache(addresses[i].arch),addresses[i].address))returnresultfinally:ifaddressesisnotNone:core.BNFreeArchitectureAndAddressList(addresses)@propertydefhas_unresolved_indirect_branches(self)->bool:"""Has unresolved indirect branches (read-only)"""returncore.BNHasUnresolvedIndirectBranches(self.handle)@propertydefsession_data(self)->Any:"""Dictionary object where plugins can store arbitrary data associated with the function"""handle=ctypes.cast(self.handle,ctypes.c_void_p)# type: ignoreifhandle.valuenotinFunction._associated_data:obj=_FunctionAssociatedDataStore()Function._associated_data[handle.value]=objreturnobjelse:returnFunction._associated_data[handle.value]@propertydefanalysis_performance_info(self)->Dict[str,int]:count=ctypes.c_ulonglong()info=core.BNGetFunctionAnalysisPerformanceInfo(self.handle,count)assertinfoisnotNone,"core.BNGetFunctionAnalysisPerformanceInfo returned None"try:result={}foriinrange(0,count.value):result[info[i].name]=info[i].secondsreturnresultfinally:core.BNFreeAnalysisPerformanceInfo(info,count.value)@propertydeftype_tokens(self)->List['InstructionTextToken']:"""Text tokens for this function's prototype"""returnself.get_type_tokens()[0].tokens@propertydefreturn_type(self)->Optional['types.Type']:"""Return type of the function"""result=core.BNGetFunctionReturnType(self.handle)ifnotresult.type:returnNonereturntypes.Type.create(result.type,platform=self.platform,confidence=result.confidence)@return_type.setterdefreturn_type(self,value:Optional[StringOrType])->None:# type: ignoretype_conf=core.BNTypeWithConfidence()ifvalueisNone:type_conf.type=Nonetype_conf.confidence=0elifisinstance(value,str):(value,_)=self.view.parse_type_string(value)type_conf.type=value.handletype_conf.confidence=core.max_confidenceelse:type_conf.type=value.handletype_conf.confidence=value.confidencecore.BNSetUserFunctionReturnType(self.handle,type_conf)@propertydefreturn_regs(self)->'types.RegisterSet':"""Registers that are used for the return value"""result=core.BNGetFunctionReturnRegisters(self.handle)assertresultisnotNone,"core.BNGetFunctionReturnRegisters returned None"try:reg_set=[]foriinrange(result.count):reg_set.append(self.arch.get_reg_name(result.regs[i]))returntypes.RegisterSet(reg_set,confidence=result.confidence)finally:core.BNFreeRegisterSet(result)@return_regs.setterdefreturn_regs(self,value:Union['types.RegisterSet',List['architecture.RegisterType']])->None:# type: ignoreregs=core.BNRegisterSetWithConfidence()regs.regs=(ctypes.c_uint*len(value))()regs.count=len(value)foriinrange(0,len(value)):regs.regs[i]=self.arch.get_reg_index(value[i])ifisinstance(value,types.RegisterSet):regs.confidence=value.confidenceelse:regs.confidence=core.max_confidencecore.BNSetUserFunctionReturnRegisters(self.handle,regs)@propertydefcalling_convention(self)->Optional['callingconvention.CallingConvention']:"""Calling convention used by the function"""result=core.BNGetFunctionCallingConvention(self.handle)ifnotresult.convention:returnNonereturncallingconvention.CallingConvention(None,handle=result.convention,confidence=result.confidence)@calling_convention.setterdefcalling_convention(self,value:Optional['callingconvention.CallingConvention'])->None:conv_conf=core.BNCallingConventionWithConfidence()ifvalueisNone:conv_conf.convention=Noneconv_conf.confidence=0else:conv_conf.convention=value.handleconv_conf.confidence=value.confidencecore.BNSetUserFunctionCallingConvention(self.handle,conv_conf)@propertydefparameter_vars(self)->'variable.ParameterVariables':"""List of variables for the incoming function parameters"""result=core.BNGetFunctionParameterVariables(self.handle)var_list=[]foriinrange(0,result.count):var_list.append(variable.Variable.from_BNVariable(self,result.vars[i]))confidence=result.confidencecore.BNFreeParameterVariables(result)returnvariable.ParameterVariables(var_list,confidence,self)@parameter_vars.setterdefparameter_vars(self,value:Optional[Union['variable.ParameterVariables',List['variable.Variable']]])->None:# type: ignoreifvalueisNone:var_list=[]else:var_list=list(value)var_conf=core.BNParameterVariablesWithConfidence()var_conf.vars=(core.BNVariable*len(var_list))()var_conf.count=len(var_list)foriinrange(0,len(var_list)):var_conf.vars[i].type=var_list[i].source_typevar_conf.vars[i].index=var_list[i].indexvar_conf.vars[i].storage=var_list[i].storageifvalueisNone:var_conf.confidence=0elifisinstance(value,types.RegisterSet):var_conf.confidence=value.confidenceelse:var_conf.confidence=core.max_confidencecore.BNSetUserFunctionParameterVariables(self.handle,var_conf)@propertydefhas_variable_arguments(self)->'types.BoolWithConfidence':"""Whether the function takes a variable number of arguments"""result=core.BNFunctionHasVariableArguments(self.handle)returntypes.BoolWithConfidence(result.value,confidence=result.confidence)@has_variable_arguments.setterdefhas_variable_arguments(self,value:Union[bool,'types.BoolWithConfidence'])->None:# type: ignorebc=core.BNBoolWithConfidence()bc.value=bool(value)ifisinstance(value,types.BoolWithConfidence):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetUserFunctionHasVariableArguments(self.handle,bc)@propertydefstack_adjustment(self)->'types.OffsetWithConfidence':"""Number of bytes removed from the stack after return"""result=core.BNGetFunctionStackAdjustment(self.handle)returntypes.OffsetWithConfidence(result.value,confidence=result.confidence)@stack_adjustment.setterdefstack_adjustment(self,value:'types.OffsetWithConfidence')->None:oc=core.BNOffsetWithConfidence()oc.value=int(value)ifhasattr(value,'confidence'):oc.confidence=value.confidenceelse:oc.confidence=core.max_confidencecore.BNSetUserFunctionStackAdjustment(self.handle,oc)@propertydefreg_stack_adjustments(self)->Dict['architecture.RegisterStackName','types.RegisterStackAdjustmentWithConfidence']:"""Number of entries removed from each register stack after return"""count=ctypes.c_ulonglong()adjust=core.BNGetFunctionRegisterStackAdjustments(self.handle,count)assertadjustisnotNone,"core.BNGetFunctionRegisterStackAdjustments returned None"try:result={}foriinrange(0,count.value):name=self.arch.get_reg_stack_name(adjust[i].regStack)value=types.RegisterStackAdjustmentWithConfidence(adjust[i].adjustment,confidence=adjust[i].confidence)result[name]=valuereturnresultfinally:core.BNFreeRegisterStackAdjustments(adjust)@reg_stack_adjustments.setterdefreg_stack_adjustments(self,value:Mapping['architecture.RegisterStackName',Union[int,'types.RegisterStackAdjustmentWithConfidence']])->None:# type: ignoreadjust=(core.BNRegisterStackAdjustment*len(value))()fori,reg_stackinenumerate(value.keys()):adjust[i].regStack=self.arch.get_reg_stack_index(reg_stack)entry=value[reg_stack]ifisinstance(entry,types.RegisterStackAdjustmentWithConfidence):adjust[i].adjustment=entry.valueadjust[i].confidence=entry.confidenceelse:adjust[i].adjustment=int(entry)adjust[i].confidence=core.max_confidencecore.BNSetUserFunctionRegisterStackAdjustments(self.handle,adjust,len(value))@propertydefclobbered_regs(self)->'types.RegisterSet':"""Registers that are modified by this function"""result=core.BNGetFunctionClobberedRegisters(self.handle)reg_set=[]foriinrange(0,result.count):reg_set.append(self.arch.get_reg_name(result.regs[i]))regs=types.RegisterSet(reg_set,confidence=result.confidence)core.BNFreeRegisterSet(result)returnregs@clobbered_regs.setterdefclobbered_regs(self,value:Union['types.RegisterSet',List['architecture.RegisterType']])->None:# type: ignoreregs=core.BNRegisterSetWithConfidence()regs.regs=(ctypes.c_uint*len(value))()regs.count=len(value)foriinrange(0,len(value)):regs.regs[i]=self.arch.get_reg_index(value[i])ifisinstance(value,types.RegisterSet):regs.confidence=value.confidenceelse:regs.confidence=core.max_confidencecore.BNSetUserFunctionClobberedRegisters(self.handle,regs)@propertydefglobal_pointer_value(self)->variable.RegisterValue:"""Discovered value of the global pointer register, if the function uses one (read-only)"""result=core.BNGetFunctionGlobalPointerValue(self.handle)returnvariable.RegisterValue.from_BNRegisterValue(result,self.arch)@propertydefuses_incoming_global_pointer(self)->bool:"""Whether the function uses the incoming global pointer value"""returncore.BNFunctionUsesIncomingGlobalPointer(self.handle)@propertydefcomment(self)->str:"""Gets the comment for the current function"""returncore.BNGetFunctionComment(self.handle)@comment.setterdefcomment(self,comment:str)->None:"""Sets a comment for the current function"""core.BNSetFunctionComment(self.handle,comment)@propertydefllil_basic_blocks(self)->Generator['lowlevelil.LowLevelILBasicBlock',None,None]:"""A generator of all LowLevelILBasicBlock objects in the current function"""llil=self.llilifllilisNone:returnforblockinllil:yieldblock@propertydefmlil_basic_blocks(self)->Generator['mediumlevelil.MediumLevelILBasicBlock',None,None]:"""A generator of all MediumLevelILBasicBlock objects in the current function"""mlil=self.mlilifmlilisNone:returnforblockinmlil:yieldblock@propertydefinstructions(self)->Generator[Tuple[List['InstructionTextToken'],int],None,None]:"""A generator of instruction tokens and their start addresses for the current function"""forblockinself.basic_blocks:start=block.startforiinblock:yieldi[0],startstart+=i[1]@propertydeftoo_large(self)->bool:"""Whether the function is too large to automatically perform analysis (read-only)"""returncore.BNIsFunctionTooLarge(self.handle)@propertydefanalysis_skipped(self)->bool:"""Whether automatic analysis was skipped for this function. Can be set to false to re-enable analysis."""returncore.BNIsFunctionAnalysisSkipped(self.handle)@analysis_skipped.setterdefanalysis_skipped(self,skip:bool)->None:ifskip:core.BNSetFunctionAnalysisSkipOverride(self.handle,FunctionAnalysisSkipOverride.AlwaysSkipFunctionAnalysis)else:core.BNSetFunctionAnalysisSkipOverride(self.handle,FunctionAnalysisSkipOverride.NeverSkipFunctionAnalysis)@propertydefanalysis_skip_reason(self)->AnalysisSkipReason:"""Function analysis skip reason"""returnAnalysisSkipReason(core.BNGetAnalysisSkipReason(self.handle))@propertydefanalysis_skip_override(self)->FunctionAnalysisSkipOverride:"""Override for skipping of automatic analysis"""returnFunctionAnalysisSkipOverride(core.BNGetFunctionAnalysisSkipOverride(self.handle))@analysis_skip_override.setterdefanalysis_skip_override(self,override:FunctionAnalysisSkipOverride)->None:core.BNSetFunctionAnalysisSkipOverride(self.handle,override)@propertydefunresolved_stack_adjustment_graph(self)->Optional['flowgraph.CoreFlowGraph']:"""Flow graph of unresolved stack adjustments (read-only)"""graph=core.BNGetUnresolvedStackAdjustmentGraph(self.handle)ifnotgraph:returnNonereturnflowgraph.CoreFlowGraph(graph)@propertydefmerged_vars(self)->Dict['variable.Variable',List['variable.Variable']]:"""Map of merged variables, organized by target variable (read-only). Use ``merge_vars`` and``unmerge_vars`` to update merged variables."""count=ctypes.c_ulonglong()data=core.BNGetMergedVariables(self.handle,count)result={}foriinrange(count.value):target=Variable.from_BNVariable(self,data[i].target)sources=[]forjinrange(data[i].sourceCount):sources.append(Variable.from_BNVariable(self,data[i].sources[j]))result[target]=sourcescore.BNFreeMergedVariableList(data,count.value)returnresult@propertydefsplit_vars(self)->List['variable.Variable']:"""Set of variables that have been split with ``split_var``. These variables correspondto those unique to each definition site and are obtained by using``MediumLevelILInstruction.get_split_var_for_definition`` at the definitions."""count=ctypes.c_ulonglong()data=core.BNGetSplitVariables(self.handle,count)result=[]foriinrange(count.value):result.append(Variable.from_BNVariable(self,data[i]))core.BNFreeVariableList(data)returnresult@propertydefcomponents(self):returnself.view.get_function_parent_components(self)@propertydefinline_during_analysis(self)->'types.BoolWithConfidence':"""Whether the function's IL should be inlined into all callers' IL"""result=core.BNIsFunctionInlinedDuringAnalysis(self.handle)returntypes.BoolWithConfidence(result.value,confidence=result.confidence)@inline_during_analysis.setterdefinline_during_analysis(self,value:Union[bool,'types.BoolWithConfidence']):self.set_user_inline_during_analysis(value)[docs]defmark_recent_use(self)->None:core.BNMarkFunctionAsRecentlyUsed(self.handle) [docs]defget_comment_at(self,addr:int)->str:returncore.BNGetCommentForAddress(self.handle,addr) [docs]defset_comment_at(self,addr:int,comment:str)->None:"""``set_comment_at`` sets a comment for the current function at the address specified:param int addr: virtual address within the current function to apply the comment to:param str comment: string comment to apply:rtype: None:Example:>>> current_function.set_comment_at(here, "hi")"""core.BNSetCommentForAddress(self.handle,addr,comment) [docs]defadd_user_code_ref(self,from_addr:int,to_addr:int,arch:Optional['architecture.Architecture']=None)->None:"""``add_user_code_ref`` places a user-defined cross-reference from the instruction atthe given address and architecture to the specified target address. If the specifiedsource instruction is not contained within this function, no action is performed.To remove the reference, use :func:`remove_user_code_ref`.:param int from_addr: virtual address of the source instruction:param int to_addr: virtual address of the xref's destination.:param Architecture arch: (optional) architecture of the source instruction:rtype: None:Example:>>> current_function.add_user_code_ref(here, 0x400000)"""ifarchisNone:arch=self.archcore.BNAddUserCodeReference(self.handle,arch.handle,from_addr,to_addr) [docs]defremove_user_code_ref(self,from_addr:int,to_addr:int,from_arch:Optional['architecture.Architecture']=None)->None:"""``remove_user_code_ref`` removes a user-defined cross-reference.If the given address is not contained within this function, or if there is nosuch user-defined cross-reference, no action is performed.:param int from_addr: virtual address of the source instruction:param int to_addr: virtual address of the xref's destination.:param Architecture from_arch: (optional) architecture of the source instruction:rtype: None:Example:>>> current_function.remove_user_code_ref(here, 0x400000)"""iffrom_archisNone:from_arch=self.archcore.BNRemoveUserCodeReference(self.handle,from_arch.handle,from_addr,to_addr) [docs]defadd_user_type_ref(self,from_addr:int,name:'types.QualifiedNameType',from_arch:Optional['architecture.Architecture']=None)->None:"""``add_user_type_ref`` places a user-defined type cross-reference from the instruction atthe given address and architecture to the specified type. If the specifiedsource instruction is not contained within this function, no action is performed.To remove the reference, use :func:`remove_user_type_ref`.:param int from_addr: virtual address of the source instruction:param QualifiedName name: name of the referenced type:param Architecture from_arch: (optional) architecture of the source instruction:rtype: None:Example:>>> current_function.add_user_code_ref(here, 'A')"""iffrom_archisNone:from_arch=self.arch_name=types.QualifiedName(name)._to_core_struct()core.BNAddUserTypeReference(self.handle,from_arch.handle,from_addr,_name) [docs]defremove_user_type_ref(self,from_addr:int,name:'types.QualifiedNameType',from_arch:Optional['architecture.Architecture']=None)->None:"""``remove_user_type_ref`` removes a user-defined type cross-reference.If the given address is not contained within this function, or if there is nosuch user-defined cross-reference, no action is performed.:param int from_addr: virtual address of the source instruction:param QualifiedName name: name of the referenced type:param Architecture from_arch: (optional) architecture of the source instruction:rtype: None:Example:>>> current_function.remove_user_type_ref(here, 'A')"""iffrom_archisNone:from_arch=self.arch_name=types.QualifiedName(name)._to_core_struct()core.BNRemoveUserTypeReference(self.handle,from_arch.handle,from_addr,_name) [docs]defadd_user_type_field_ref(self,from_addr:int,name:'types.QualifiedNameType',offset:int,from_arch:Optional['architecture.Architecture']=None,size:int=0)->None:"""``add_user_type_field_ref`` places a user-defined type field cross-reference from theinstruction at the given address and architecture to the specified type. If the specifiedsource instruction is not contained within this function, no action is performed.To remove the reference, use :func:`remove_user_type_field_ref`.:param int from_addr: virtual address of the source instruction:param QualifiedName name: name of the referenced type:param int offset: offset of the field, relative to the type:param Architecture from_arch: (optional) architecture of the source instruction:param int size: (optional) the size of the access:rtype: None:Example:>>> current_function.add_user_type_field_ref(here, 'A', 0x8)"""iffrom_archisNone:from_arch=self.arch_name=types.QualifiedName(name)._to_core_struct()core.BNAddUserTypeFieldReference(self.handle,from_arch.handle,from_addr,_name,offset,size) [docs]defremove_user_type_field_ref(self,from_addr:int,name:'types.QualifiedNameType',offset:int,from_arch:Optional['architecture.Architecture']=None,size:int=0)->None:"""``remove_user_type_field_ref`` removes a user-defined type field cross-reference.If the given address is not contained within this function, or if there is nosuch user-defined cross-reference, no action is performed.:param int from_addr: virtual address of the source instruction:param QualifiedName name: name of the referenced type:param int offset: offset of the field, relative to the type:param Architecture from_arch: (optional) architecture of the source instruction:param int size: (optional) the size of the access:rtype: None:Example:>>> current_function.remove_user_type_field_ref(here, 'A', 0x8)"""iffrom_archisNone:from_arch=self.arch_name=types.QualifiedName(name)._to_core_struct()core.BNRemoveUserTypeFieldReference(self.handle,from_arch.handle,from_addr,_name,offset,size) [docs]defget_low_level_il_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['lowlevelil.LowLevelILInstruction']:"""``get_low_level_il_at`` gets the LowLevelILInstruction corresponding to the given virtual address:param int addr: virtual address of the function to be queried:param Architecture arch: (optional) Architecture for the given function:rtype: LowLevelILInstruction:Example:>>> func = next(bv.functions)>>> func.get_low_level_il_at(func.start)<il: push(rbp)>"""llil=self.llilifllilisNone:returnNoneidx=llil.get_instruction_start(addr,arch)ifidxisNone:returnNonereturnllil[idx] [docs]defget_low_level_ils_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['lowlevelil.LowLevelILInstruction']:"""``get_low_level_ils_at`` gets the LowLevelILInstruction(s) corresponding to the given virtual addressSee the `developer docs <https://dev-docs.binary.ninja/dev/concepts.html#mapping-between-ils>`_ for more information.:param int addr: virtual address of the instruction to be queried:param Architecture arch: (optional) Architecture for the given function:rtype: list(LowLevelILInstruction):Example:>>> func = next(bv.functions)>>> func.get_low_level_ils_at(func.start)[<il: push(rbp)>]"""llil=self.llilifllilisNone:return[]return[llil[i]foriinllil.get_instructions_at(addr,arch)] [docs]defget_llil_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['lowlevelil.LowLevelILInstruction']:"""``get_llil_at`` gets the LowLevelILInstruction corresponding to the given virtual address:param int addr: virtual address of the instruction to be queried:param Architecture arch: (optional) Architecture for the given function:rtype: LowLevelILInstruction:Example:>>> func = next(bv.functions)>>> func.get_llil_at(func.start)<il: push(rbp)>"""returnself.get_low_level_il_at(addr,arch) [docs]defget_llils_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['lowlevelil.LowLevelILInstruction']:"""``get_llils_at`` gets the LowLevelILInstruction(s) corresponding to the given virtual addressSee the `developer docs <https://dev-docs.binary.ninja/dev/concepts.html#mapping-between-ils>`_ for more information.:param int addr: virtual address of the instruction to be queried:param Architecture arch: (optional) Architecture for the given function:rtype: list(LowLevelILInstruction):Example:>>> func = next(bv.functions)>>> func.get_llils_at(func.start)[<il: push(rbp)>]"""llil=self.llilifllilisNone:return[]return[llil[i]foriinllil.get_instructions_at(addr,arch)] [docs]defget_low_level_il_exits_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->List[int]:llil=self.llilifllilisNone:return[]idx=llil.get_instruction_start(addr,arch)ifidxisNone:return[]returnllil.get_exits_for_instr(idx) [docs]defget_constant_data(self,state:RegisterValueType,value:int,size:int=0)->databuffer.DataBuffer:returndatabuffer.DataBuffer(handle=core.BNGetConstantData(self.handle,state,value,size,None)) [docs]defget_constant_data_and_builtin(self,state:RegisterValueType,value:int,size:int=0)->Tuple[databuffer.DataBuffer,BuiltinType]:builtin=ctypes.c_int()db=databuffer.DataBuffer(handle=core.BNGetConstantData(self.handle,state,value,size,ctypes.byref(builtin)))returndb,BuiltinType(builtin.value) [docs]defget_reg_value_at(self,addr:int,reg:'architecture.RegisterType',arch:Optional['architecture.Architecture']=None)->'variable.RegisterValue':"""``get_reg_value_at`` gets the value the provided string register address corresponding to the given virtual address:param int addr: virtual address of the instruction to query:param str reg: string value of native register to query:param Architecture arch: (optional) Architecture for the given function:rtype: variable.RegisterValue:Example:>>> current_function.get_reg_value_at(0x400dbe, 'rdi')<const 0x2>"""ifarchisNone:arch=self.archreg=arch.get_reg_index(reg)value=core.BNGetRegisterValueAtInstruction(self.handle,arch.handle,addr,reg)result=variable.RegisterValue.from_BNRegisterValue(value,arch)returnresult [docs]defget_reg_value_after(self,addr:int,reg:'architecture.RegisterType',arch:Optional['architecture.Architecture']=None)->'variable.RegisterValue':"""``get_reg_value_after`` gets the value instruction address corresponding to the given virtual address:param int addr: virtual address of the instruction to query:param str reg: string value of native register to query:param Architecture arch: (optional) Architecture for the given function:rtype: variable.RegisterValue:Example:>>> current_function.get_reg_value_after(0x400dbe, 'rdi')<undetermined>"""ifarchisNone:arch=self.archreg=arch.get_reg_index(reg)value=core.BNGetRegisterValueAfterInstruction(self.handle,arch.handle,addr,reg)result=variable.RegisterValue.from_BNRegisterValue(value,arch)returnresult [docs]defget_stack_contents_at(self,addr:int,offset:int,size:int,arch:Optional['architecture.Architecture']=None)->'variable.RegisterValue':"""``get_stack_contents_at`` returns the RegisterValue for the item on the stack in the current function at thegiven virtual address ``addr``, stack offset ``offset`` and size of ``size``. Optionally specifying the architecture.:param int addr: virtual address of the instruction to query:param int offset: stack offset base of stack:param int size: size of memory to query:param Architecture arch: (optional) Architecture for the given function:rtype: variable.RegisterValue.. note:: Stack base is zero on entry into the function unless the architecture places the return address on the \stack as in (x86/x86_64) where the stack base will start at address_size:Example:>>> current_function.get_stack_contents_at(0x400fad, -16, 4)<range: 0x8 to 0xffffffff>"""ifarchisNone:arch=self.archvalue=core.BNGetStackContentsAtInstruction(self.handle,arch.handle,addr,offset,size)result=variable.RegisterValue.from_BNRegisterValue(value,arch)returnresult [docs]defget_stack_contents_after(self,addr:int,offset:int,size:int,arch:Optional['architecture.Architecture']=None)->'variable.RegisterValue':ifarchisNone:arch=self.archvalue=core.BNGetStackContentsAfterInstruction(self.handle,arch.handle,addr,offset,size)result=variable.RegisterValue.from_BNRegisterValue(value,arch)returnresult [docs]defget_parameter_at(self,addr:int,func_type:Optional['types.Type'],i:int,arch:Optional['architecture.Architecture']=None)->'variable.RegisterValue':ifarchisNone:arch=self.arch_func_type=Noneiffunc_typeisnotNone:_func_type=func_type.handlevalue=core.BNGetParameterValueAtInstruction(self.handle,arch.handle,addr,_func_type,i)result=variable.RegisterValue.from_BNRegisterValue(value,arch)returnresult [docs]defget_parameter_at_low_level_il_instruction(self,instr:'lowlevelil.InstructionIndex',func_type:'types.Type',i:int)->'variable.RegisterValue':_func_type=Noneiffunc_typeisnotNone:_func_type=func_type.handlevalue=core.BNGetParameterValueAtLowLevelILInstruction(self.handle,instr,_func_type,i)result=variable.RegisterValue.from_BNRegisterValue(value,self.arch)returnresult [docs]defget_regs_read_by(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['architecture.RegisterName']:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()regs=core.BNGetRegistersReadByInstruction(self.handle,arch.handle,addr,count)assertregsisnotNone,"core.BNGetRegistersReadByInstruction returned None"result=[]foriinrange(0,count.value):result.append(arch.get_reg_name(regs[i]))core.BNFreeRegisterList(regs)returnresult [docs]defget_regs_written_by(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['architecture.RegisterName']:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()regs=core.BNGetRegistersWrittenByInstruction(self.handle,arch.handle,addr,count)assertregsisnotNone,"core.BNGetRegistersWrittenByInstruction returned None"result=[]foriinrange(0,count.value):result.append(arch.get_reg_name(regs[i]))core.BNFreeRegisterList(regs)returnresult [docs]defget_stack_vars_referenced_by(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['variable.StackVariableReference']:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()refs=core.BNGetStackVariablesReferencedByInstruction(self.handle,arch.handle,addr,count)assertrefsisnotNone,"core.BNGetStackVariablesReferencedByInstruction returned None"result=[]foriinrange(0,count.value):var_type=types.Type.create(core.BNNewTypeReference(refs[i].type),platform=self.platform,confidence=refs[i].typeConfidence)var=variable.Variable.from_identifier(self,refs[i].varIdentifier)result.append(variable.StackVariableReference(refs[i].sourceOperand,var_type,refs[i].name,var,refs[i].referencedOffset,refs[i].size))core.BNFreeStackVariableReferenceList(refs,count.value)returnresult [docs]defget_stack_vars_referenced_by_address_if_available(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['variable.StackVariableReference']:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()refs=core.BNGetStackVariablesReferencedByInstructionIfAvailable(self.handle,arch.handle,addr,count)assertrefsisnotNone,"core.BNGetStackVariablesReferencedByInstructionIfAvailable returned None"result=[]foriinrange(0,count.value):var_type=types.Type.create(core.BNNewTypeReference(refs[i].type),platform=self.platform,confidence=refs[i].typeConfidence)var=variable.Variable.from_identifier(self,refs[i].varIdentifier)result.append(variable.StackVariableReference(refs[i].sourceOperand,var_type,refs[i].name,var,refs[i].referencedOffset,refs[i].size))core.BNFreeStackVariableReferenceList(refs,count.value)returnresult [docs]defget_lifted_il_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['lowlevelil.LowLevelILInstruction']:lifted_il=self.lifted_iliflifted_ilisNone:returnNoneidx=lifted_il.get_instruction_start(addr,arch)ifidxisNone:returnNonereturnlifted_il[idx] [docs]defget_lifted_ils_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['lowlevelil.LowLevelILInstruction']:"""``get_lifted_ils_at`` gets the Lifted IL Instruction(s) corresponding to the given virtual address:param int addr: virtual address of the function to be queried:param Architecture arch: (optional) Architecture for the given function:rtype: list(LowLevelILInstruction):Example:>>> func = next(bv.functions)>>> func.get_lifted_ils_at(func.start)[<il: push(rbp)>]"""lifted_il=self.lifted_iliflifted_ilisNone:return[]return[lifted_il[i]foriinlifted_il.get_instructions_at(addr,arch)] [docs]defget_constants_referenced_by(self,addr:int,arch:Optional['architecture.Architecture']=None)->List[variable.ConstantReference]:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()refs=core.BNGetConstantsReferencedByInstruction(self.handle,arch.handle,addr,count)assertrefsisnotNone,"core.BNGetConstantsReferencedByInstruction returned None"result=[]foriinrange(0,count.value):result.append(variable.ConstantReference(refs[i].value,refs[i].size,refs[i].pointer,refs[i].intermediate))core.BNFreeConstantReferenceList(refs)returnresult [docs]defget_constants_referenced_by_address_if_available(self,addr:int,arch:Optional['architecture.Architecture']=None)->List[variable.ConstantReference]:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()refs=core.BNGetConstantsReferencedByInstructionIfAvailable(self.handle,arch.handle,addr,count)assertrefsisnotNone,"core.BNGetConstantsReferencedByInstructionIfAvailable returned None"result=[]foriinrange(0,count.value):result.append(variable.ConstantReference(refs[i].value,refs[i].size,refs[i].pointer,refs[i].intermediate))core.BNFreeConstantReferenceList(refs)returnresult [docs]defget_lifted_il_flag_uses_for_definition(self,i:'lowlevelil.InstructionIndex',flag:'architecture.FlagType')->List['lowlevelil.LowLevelILInstruction']:flag=self.arch.get_flag_index(flag)count=ctypes.c_ulonglong()instrs=core.BNGetLiftedILFlagUsesForDefinition(self.handle,i,flag,count)assertinstrsisnotNone,"core.BNGetLiftedILFlagUsesForDefinition returned None"result=[]forjinrange(0,count.value):result.append(instrs[lowlevelil.InstructionIndex(j)])core.BNFreeILInstructionList(instrs)returnresult [docs]defget_lifted_il_flag_definitions_for_use(self,i:'lowlevelil.InstructionIndex',flag:'architecture.FlagType')->List['lowlevelil.InstructionIndex']:flag=self.arch.get_flag_index(flag)count=ctypes.c_ulonglong()instrs=core.BNGetLiftedILFlagDefinitionsForUse(self.handle,i,flag,count)assertinstrsisnotNone,"core.BNGetLiftedILFlagDefinitionsForUse returned None"result=[]forjinrange(0,count.value):result.append(instrs[lowlevelil.InstructionIndex(j)])core.BNFreeILInstructionList(instrs)returnresult [docs]defget_flags_read_by_lifted_il_instruction(self,i:'lowlevelil.InstructionIndex')->List['architecture.FlagName']:count=ctypes.c_ulonglong()flags=core.BNGetFlagsReadByLiftedILInstruction(self.handle,i,count)assertflagsisnotNone,"core.BNGetFlagsReadByLiftedILInstruction returned None"result=[]forjinrange(0,count.value):result.append(self.arch._flags_by_index[flags[j]])core.BNFreeRegisterList(flags)returnresult [docs]defget_flags_written_by_lifted_il_instruction(self,i:'lowlevelil.InstructionIndex')->List['architecture.FlagName']:count=ctypes.c_ulonglong()flags=core.BNGetFlagsWrittenByLiftedILInstruction(self.handle,i,count)assertflagsisnotNone,"core.BNGetFlagsWrittenByLiftedILInstruction returned None"result=[]forjinrange(0,count.value):result.append(self.arch._flags_by_index[flags[j]])core.BNFreeRegisterList(flags)returnresult [docs]defcreate_graph(self,graph_type:FunctionViewTypeOrName=FunctionGraphType.NormalFunctionGraph,settings:Optional['DisassemblySettings']=None)->flowgraph.CoreFlowGraph:"""Create a flow graph with the disassembly of this function... note:: This graph waits for function analysis, so Workflow Activities should instead use :py:func:`create_graph_immediate` to create graphs with the function contents as-is.:param graph_type: IL form of the disassembly in the graph:param settings: Optional settings for the disassembly text renderer:return: Flow graph object"""ifsettingsisnotNone:settings_obj=settings.handleelse:settings_obj=Nonegraph_type=FunctionViewType(graph_type)._to_core_struct()returnflowgraph.CoreFlowGraph(core.BNCreateFunctionGraph(self.handle,graph_type,settings_obj)) [docs]defcreate_graph_immediate(self,graph_type:FunctionViewTypeOrName=FunctionGraphType.NormalFunctionGraph,settings:Optional['DisassemblySettings']=None)->flowgraph.CoreFlowGraph:"""Create a flow graph with the disassembly of this function, specifically using theinstructions as they are in the function when this is called. You probably want to usethis if you are creating a Debug Report in a Workflow Activity.:param graph_type: IL form of the disassembly in the graph:param settings: Optional settings for the disassembly text renderer:return: Flow graph object"""ifsettingsisnotNone:settings_obj=settings.handleelse:settings_obj=Nonegraph_type=FunctionViewType(graph_type)._to_core_struct()returnflowgraph.CoreFlowGraph(core.BNCreateImmediateFunctionGraph(self.handle,graph_type,settings_obj)) [docs]defapply_imported_types(self,sym:'types.CoreSymbol',type:Optional[StringOrType]=None)->None:ifisinstance(type,str):(type,_)=self.view.parse_type_string(type)core.BNApplyImportedTypes(self.handle,sym.handle,NoneiftypeisNoneelsetype.handle) [docs]defapply_auto_discovered_type(self,func_type:StringOrType)->None:ifisinstance(func_type,str):(func_type,_)=self.view.parse_type_string(func_type)core.BNApplyAutoDiscoveredFunctionType(self.handle,func_type.handle) [docs]defset_auto_indirect_branches(self,source:int,branches:List[Tuple['architecture.Architecture',int]],source_arch:Optional['architecture.Architecture']=None)->None:ifsource_archisNone:source_arch=self.archbranch_list=(core.BNArchitectureAndAddress*len(branches))()foriinrange(len(branches)):branch_list[i].arch=branches[i][0].handlebranch_list[i].address=branches[i][1]core.BNSetAutoIndirectBranches(self.handle,source_arch.handle,source,branch_list,len(branches)) [docs]defset_user_indirect_branches(self,source:int,branches:List[Tuple['architecture.Architecture',int]],source_arch:Optional['architecture.Architecture']=None)->None:ifsource_archisNone:source_arch=self.archbranch_list=(core.BNArchitectureAndAddress*len(branches))()foriinrange(len(branches)):branch_list[i].arch=branches[i][0].handlebranch_list[i].address=branches[i][1]core.BNSetUserIndirectBranches(self.handle,source_arch.handle,source,branch_list,len(branches)) [docs]defset_guided_source_blocks(self,addresses:List[Tuple['architecture.Architecture',int]])->None:"""``set_guided_source_blocks`` sets the complete list of guided source blocks for this function.Only blocks in this set will have their direct outgoing branch targets analyzed. This replacesany existing guided source blocks and automatically enables or disables the ``analysis.guided.enable``setting based on whether addresses are provided.:param List[Tuple[architecture.Architecture, int]] addresses: List of (architecture, address) tuples:rtype: None"""address_list=(core.BNArchitectureAndAddress*len(addresses))()foriinrange(len(addresses)):address_list[i].arch=addresses[i][0].handleaddress_list[i].address=addresses[i][1]core.BNSetGuidedSourceBlocks(self.handle,address_list,len(addresses)) [docs]defadd_guided_source_blocks(self,addresses:List[Tuple['architecture.Architecture',int]])->None:"""``add_guided_source_blocks`` adds blocks to the guided source block list for this function.The specified blocks will have their direct outgoing branch targets analyzed. This automaticallyenables the ``analysis.guided.enable`` setting if it is not already enabled.:param List[Tuple[architecture.Architecture, int]] addresses: List of (architecture, address) tuples to add:rtype: None"""address_list=(core.BNArchitectureAndAddress*len(addresses))()foriinrange(len(addresses)):address_list[i].arch=addresses[i][0].handleaddress_list[i].address=addresses[i][1]core.BNAddGuidedSourceBlocks(self.handle,address_list,len(addresses)) [docs]defremove_guided_source_blocks(self,addresses:List[Tuple['architecture.Architecture',int]])->None:"""``remove_guided_source_blocks`` removes blocks from the guided source block list for this function.The specified blocks will no longer have their direct outgoing branch targets analyzed.This automatically enables the ``analysis.guided.enable`` setting if it is not already enabled.:param List[Tuple[architecture.Architecture, int]] addresses: List of (architecture, address) tuples to remove:rtype: None"""address_list=(core.BNArchitectureAndAddress*len(addresses))()foriinrange(len(addresses)):address_list[i].arch=addresses[i][0].handleaddress_list[i].address=addresses[i][1]core.BNRemoveGuidedSourceBlocks(self.handle,address_list,len(addresses)) [docs]defis_guided_source_block(self,arch:'architecture.Architecture',addr:int)->bool:"""``is_guided_source_block`` checks if the given address is a guided source block.:param architecture.Architecture arch: Architecture of the address to check:param int addr: Address to check:rtype: bool"""returncore.BNIsGuidedSourceBlock(self.handle,arch.handle,addr) [docs]defget_guided_source_blocks(self)->List[Tuple['architecture.Architecture',int]]:"""``get_guided_source_blocks`` returns the current list of guided source blocks for this function.These blocks have their direct outgoing branch targets analyzed.:rtype: List[Tuple[architecture.Architecture, int]]:return: List of (architecture, address) tuples representing current guided source blocks"""count=ctypes.c_ulonglong()addresses=core.BNGetGuidedSourceBlocks(self.handle,count)try:assertaddressesisnotNone,"core.BNGetGuidedSourceBlocks returned None"result=[]foriinrange(count.value):result.append((architecture.CoreArchitecture._from_cache(addresses[i].arch),addresses[i].address))returnresultfinally:ifaddressesisnotNone:core.BNFreeArchitectureAndAddressList(addresses) [docs]defhas_guided_source_blocks(self)->bool:"""``has_guided_source_blocks`` checks if this function has any guided source blocks configured.This indicates whether guided analysis is active for this function.:rtype: bool:return: True if the function has guided source blocks, False otherwise"""returncore.BNHasGuidedSourceBlocks(self.handle) [docs]defget_indirect_branches_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->List['variable.IndirectBranchInfo']:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()branches=core.BNGetIndirectBranchesAt(self.handle,arch.handle,addr,count)try:assertbranchesisnotNone,"core.BNGetIndirectBranchesAt returned None"result=[]foriinrange(count.value):result.append(variable.IndirectBranchInfo(architecture.CoreArchitecture._from_cache(branches[i].sourceArch),branches[i].sourceAddr,architecture.CoreArchitecture._from_cache(branches[i].destArch),branches[i].destAddr,branches[i].autoDefined))returnresultfinally:core.BNFreeIndirectBranchList(branches) [docs]defget_block_annotations(self,addr:int,arch:Optional['architecture.Architecture']=None)->List[List['InstructionTextToken']]:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong(0)lines=core.BNGetFunctionBlockAnnotations(self.handle,arch.handle,addr,count)try:assertlinesisnotNone,"core.BNGetFunctionBlockAnnotations returned None"result=[]foriinrange(count.value):result.append(InstructionTextToken._from_core_struct(lines[i].tokens,lines[i].count))returnresultfinally:core.BNFreeInstructionTextLines(lines,count.value) [docs]defset_auto_type(self,value:StringOrType)->None:ifisinstance(value,str):(value,_)=self.view.parse_type_string(value)core.BNSetFunctionAutoType(self.handle,value.handle) [docs]defset_user_type(self,value:StringOrType)->None:ifisinstance(value,str):(value,_)=self.view.parse_type_string(value)core.BNSetFunctionUserType(self.handle,value.handle) @propertydefhas_user_type(self)->bool:"""True if the function has a user-defined type"""returncore.BNFunctionHasUserType(self.handle)[docs]defset_auto_return_type(self,value:StringOrType)->None:type_conf=core.BNTypeWithConfidence()ifvalueisNone:type_conf.type=Nonetype_conf.confidence=0elifisinstance(value,str):(value,_)=self.view.parse_type_string(value)type_conf.type=valuetype_conf.confidence=core.max_confidenceelse:type_conf.type=value.handletype_conf.confidence=value.confidencecore.BNSetAutoFunctionReturnType(self.handle,type_conf) [docs]defset_auto_return_regs(self,value:Union['types.RegisterSet',List['architecture.RegisterType']])->None:regs=core.BNRegisterSetWithConfidence()regs.regs=(ctypes.c_uint*len(value))()regs.count=len(value)foriinrange(0,len(value)):regs.regs[i]=self.arch.get_reg_index(value[i])ifisinstance(value,types.RegisterSet):regs.confidence=value.confidenceelse:regs.confidence=core.max_confidencecore.BNSetAutoFunctionReturnRegisters(self.handle,regs) [docs]defset_auto_calling_convention(self,value:'callingconvention.CallingConvention')->None:conv_conf=core.BNCallingConventionWithConfidence()ifvalueisNone:conv_conf.convention=Noneconv_conf.confidence=0else:conv_conf.convention=value.handleconv_conf.confidence=value.confidencecore.BNSetAutoFunctionCallingConvention(self.handle,conv_conf) [docs]defset_auto_parameter_vars(self,value:Optional[Union[List['variable.Variable'],'variable.Variable','variable.ParameterVariables']])->None:ifvalueisNone:var_list=[]elifisinstance(value,variable.Variable):var_list=[value]elifisinstance(value,variable.ParameterVariables):var_list=value.varselse:var_list=list(value)var_conf=core.BNParameterVariablesWithConfidence()var_conf.vars=(core.BNVariable*len(var_list))()var_conf.count=len(var_list)foriinrange(0,len(var_list)):var_conf.vars[i].type=var_list[i].source_typevar_conf.vars[i].index=var_list[i].indexvar_conf.vars[i].storage=var_list[i].storageifvalueisNone:var_conf.confidence=0elifisinstance(value,variable.ParameterVariables):var_conf.confidence=value.confidenceelse:var_conf.confidence=core.max_confidencecore.BNSetAutoFunctionParameterVariables(self.handle,var_conf) [docs]defset_auto_has_variable_arguments(self,value:Union[bool,'types.BoolWithConfidence'])->None:bc=core.BNBoolWithConfidence()bc.value=bool(value)ifisinstance(value,types.BoolWithConfidence):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetAutoFunctionHasVariableArguments(self.handle,bc) [docs]defset_auto_can_return(self,value:Union[bool,'types.BoolWithConfidence'])->None:bc=core.BNBoolWithConfidence()bc.value=bool(value)ifisinstance(value,types.BoolWithConfidence):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetAutoFunctionCanReturn(self.handle,bc) [docs]defset_auto_pure(self,value:Union[bool,'types.BoolWithConfidence'])->None:bc=core.BNBoolWithConfidence()bc.value=bool(value)ifisinstance(value,types.BoolWithConfidence):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetAutoFunctionPure(self.handle,bc) [docs]defset_auto_stack_adjustment(self,value:Union[int,'types.OffsetWithConfidence'])->None:oc=core.BNOffsetWithConfidence()oc.value=int(value)ifisinstance(value,types.OffsetWithConfidence):oc.confidence=value.confidenceelse:oc.confidence=core.max_confidencecore.BNSetAutoFunctionStackAdjustment(self.handle,oc) [docs]defset_auto_reg_stack_adjustments(self,value:Mapping['architecture.RegisterStackName','types.RegisterStackAdjustmentWithConfidence']):adjust=(core.BNRegisterStackAdjustment*len(value))()fori,reg_stackinenumerate(value.keys()):adjust[i].regStack=self.arch.get_reg_stack_index(reg_stack)ifisinstance(value[reg_stack],types.RegisterStackAdjustmentWithConfidence):adjust[i].adjustment=value[reg_stack].valueadjust[i].confidence=value[reg_stack].confidenceelse:adjust[i].adjustment=value[reg_stack]adjust[i].confidence=core.max_confidencecore.BNSetAutoFunctionRegisterStackAdjustments(self.handle,adjust,len(value)) [docs]defset_auto_clobbered_regs(self,value:List['architecture.RegisterType'])->None:regs=core.BNRegisterSetWithConfidence()regs.regs=(ctypes.c_uint*len(value))()regs.count=len(value)foriinrange(0,len(value)):regs.regs[i]=self.arch.get_reg_index(value[i])ifisinstance(value,types.RegisterSet):regs.confidence=value.confidenceelse:regs.confidence=core.max_confidencecore.BNSetAutoFunctionClobberedRegisters(self.handle,regs) [docs]defget_int_display_type(self,instr_addr:int,value:int,operand:int,arch:Optional['architecture.Architecture']=None)->IntegerDisplayType:"""Get the current text display type for an integer token in the disassembly or IL viewsSee also see :py:func:`get_int_display_type_and_typeid`:param int instr_addr: Address of the instruction or IL line containing the token:param int value: ``value`` field of the InstructionTextToken object for the token, usually the constant displayed:param int operand: Operand index of the token, defined as the number of OperandSeparatorTokens in the disassembly line before the token:param Architecture arch: (optional) Architecture of the instruction or IL line containing the token"""ifarchisNone:arch=self.archreturnIntegerDisplayType(core.BNGetIntegerConstantDisplayType(self.handle,arch.handle,instr_addr,value,operand)) [docs]defget_int_enum_display_typeid(self,instr_addr:int,value:int,operand:int,arch:Optional['architecture.Architecture']=None)->str:"""Get the current text display enum type for an integer token in the disassembly or IL views.See also see :py:func:`get_int_display_type_and_typeid`:param int instr_addr: Address of the instruction or IL line containing the token:param int value: ``value`` field of the InstructionTextToken object for the token, usually the constant displayed:param int operand: Operand index of the token, defined as the number of OperandSeparatorTokens in the disassembly line before the token:param Architecture arch: (optional) Architecture of the instruction or IL line containing the token:return: TypeID for the integer token"""ifarchisNone:arch=self.archtype_id=core.BNGetIntegerConstantDisplayTypeEnumerationType(self.handle,arch.handle,instr_addr,value,operand)returntype_id [docs]defset_int_display_type(self,instr_addr:int,value:int,operand:int,display_type:IntegerDisplayType,arch:Optional['architecture.Architecture']=None,enum_display_typeid=None)->None:"""Change the text display type for an integer token in the disassembly or IL views:param int instr_addr: Address of the instruction or IL line containing the token:param int value: ``value`` field of the InstructionTextToken object for the token, usually the constant displayed:param int operand: Operand index of the token, defined as the number of OperandSeparatorTokens in the disassembly line before the token:param enums.IntegerDisplayType display_type: Desired display type:param Architecture arch: (optional) Architecture of the instruction or IL line containing the token:param str enum_display_typeid: (optional) Whenever passing EnumDisplayType to ``display_type``, passing a type ID here will specify the Enumeration display type. Must be a valid type ID and resolve to an enumeration type."""ifarchisNone:arch=self.archifisinstance(display_type,str):display_type=IntegerDisplayType[display_type]core.BNSetIntegerConstantDisplayType(self.handle,arch.handle,instr_addr,value,operand,display_type,enum_display_typeid) [docs]defget_int_display_type_and_typeid(self,instr_addr:int,value:int,operand:int,arch:Optional['architecture.Architecture']=None)->(IntegerDisplayType,str):"""Get the current text display type for an integer token in the disassembly or IL views:param int instr_addr: Address of the instruction or IL line containing the token:param int value: ``value`` field of the InstructionTextToken object for the token, usually the constant displayed:param int operand: Operand index of the token, defined as the number of OperandSeparatorTokens in the disassembly line before the token:param Architecture arch: (optional) Architecture of the instruction or IL line containing the token"""ifarchisNone:arch=self.archdisplay_type=core.BNGetIntegerConstantDisplayType(self.handle,arch.handle,instr_addr,value,operand)type_id=core.BNGetIntegerConstantDisplayTypeEnumerationType(self.handle,arch.handle,instr_addr,value,operand)returndisplay_type,type_id [docs]defanalyze(self)->None:"""``analyze`` causes this function to be analyzed if it's out of date. This function does not wait for the analysis to finish.:rtype: None"""core.BNAnalyzeFunction(self.handle) [docs]defreanalyze(self,update_type:FunctionUpdateType=FunctionUpdateType.UserFunctionUpdate)->None:"""``reanalyze`` causes this function to be reanalyzed. This function does not wait for the analysis to finish.:param enums.FunctionUpdateType update_type: (optional) Desired update type.. warning:: If analysis_skipped is True, using this API will not trigger re-analysis. Instead, set `analysis_skipped` to `False`.:rtype: None"""core.BNReanalyzeFunction(self.handle,update_type) [docs]defmark_updates_required(self,update_type:FunctionUpdateType=FunctionUpdateType.UserFunctionUpdate)->None:"""``mark_updates_required`` indicates that this function needs to be reanalyzed during the next update cycle:param enums.FunctionUpdateType update_type: (optional) Desired update type:rtype: None"""core.BNMarkUpdatesRequired(self.handle,update_type) [docs]defmark_caller_updates_required(self,update_type:FunctionUpdateType=FunctionUpdateType.UserFunctionUpdate)->None:"""``mark_caller_updates_required`` indicates that callers of this function need to be reanalyzed during the next update cycle:param enums.FunctionUpdateType update_type: (optional) Desired update type:rtype: None"""core.BNMarkCallerUpdatesRequired(self.handle,update_type) [docs]defrequest_advanced_analysis_data(self)->None:core.BNRequestAdvancedFunctionAnalysisData(self.handle)self._advanced_analysis_requests+=1 [docs]defrelease_advanced_analysis_data(self)->None:core.BNReleaseAdvancedFunctionAnalysisData(self.handle)self._advanced_analysis_requests-=1 [docs]defget_basic_block_at(self,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['basicblock.BasicBlock']:"""``get_basic_block_at`` returns the BasicBlock of the optionally specified Architecture ``arch`` at the givenaddress ``addr``.:param int addr: Address of the BasicBlock to retrieve.:param Architecture arch: (optional) Architecture of the basic block if different from the Function's self.arch:Example:>>> current_function.get_basic_block_at(current_function.start)<block: x86_64@0x100000f30-0x100000f50>"""ifarchisNone:arch=self.archblock=core.BNGetFunctionBasicBlockAtAddress(self.handle,arch.handle,addr)ifnotblock:returnNonereturnbasicblock.BasicBlock(block,self._view) [docs]defget_callee_for_analysis(self,platform:'_platform.Platform',addr:int,exact:bool=False)->Optional['Function']:"""``get_callee_for_analysis`` retrieves the callee function for the specified address and platform... note:: This method is intended for use by architecture plugins only.:param platform.Platform platform: Platform of the callee function:param int addr: Address of the callee function:param bool exact: If True, only return a function if it exactly matches the address and platform:return: The callee function or None if not found:rtype: Optional[Function]"""func=core.BNGetCalleeForAnalysis(self.handle,platform.handle,addr,exact)iffuncisNone:returnNonereturnFunction(func,self._view) [docs]defget_instr_highlight(self,addr:int,arch:Optional['architecture.Architecture']=None)->'_highlight.HighlightColor':""":Example:>>> current_function.set_user_instr_highlight(here, highlight.HighlightColor(red=0xff, blue=0xff, green=0))>>> current_function.get_instr_highlight(here)<color: #ff00ff>"""ifarchisNone:arch=self.archcolor=core.BNGetInstructionHighlight(self.handle,arch.handle,addr)ifcolor.style==HighlightColorStyle.StandardHighlightColor:return_highlight.HighlightColor(color=color.color,alpha=color.alpha)elifcolor.style==HighlightColorStyle.MixedHighlightColor:return_highlight.HighlightColor(color=color.color,mix_color=color.mixColor,mix=color.mix,alpha=color.alpha)elifcolor.style==HighlightColorStyle.CustomHighlightColor:return_highlight.HighlightColor(red=color.r,green=color.g,blue=color.b,alpha=color.alpha)return_highlight.HighlightColor(color=HighlightStandardColor.NoHighlightColor) [docs]defset_auto_instr_highlight(self,addr:int,color:Union['_highlight.HighlightColor',HighlightStandardColor],arch:Optional['architecture.Architecture']=None):"""``set_auto_instr_highlight`` highlights the instruction at the specified address with the supplied color.. warning:: Use only in analysis plugins. Do not use in regular plugins, as colors won't be saved to the database.:param int addr: virtual address of the instruction to be highlighted:param HighlightStandardColor|highlight.HighlightColor color: Color value to use for highlighting:param Architecture arch: (optional) Architecture of the instruction if different from self.arch"""ifarchisNone:arch=self.archifnotisinstance(color,HighlightStandardColor)andnotisinstance(color,_highlight.HighlightColor):raiseValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")ifisinstance(color,HighlightStandardColor):color=_highlight.HighlightColor(color=color)core.BNSetAutoInstructionHighlight(self.handle,arch.handle,addr,color._to_core_struct()) [docs]defset_user_instr_highlight(self,addr:int,color:Union['_highlight.HighlightColor',HighlightStandardColor],arch:Optional['architecture.Architecture']=None):"""``set_user_instr_highlight`` highlights the instruction at the specified address with the supplied color:param int addr: virtual address of the instruction to be highlighted:param HighlightStandardColor|highlight.HighlightColor color: Color value to use for highlighting:param Architecture arch: (optional) Architecture of the instruction if different from self.arch:Example:>>> current_function.set_user_instr_highlight(here, HighlightStandardColor.BlueHighlightColor)>>> current_function.set_user_instr_highlight(here, highlight.HighlightColor(red=0xff, blue=0xff, green=0))Warning: For performance reasons, this function does not ensure the address you have supplied is within thefunction's bounds."""ifarchisNone:arch=self.archifnotisinstance(color,HighlightStandardColor)andnotisinstance(color,_highlight.HighlightColor):raiseValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor")ifisinstance(color,HighlightStandardColor):color=_highlight.HighlightColor(color)core.BNSetUserInstructionHighlight(self.handle,arch.handle,addr,color._to_core_struct()) [docs]defcreate_auto_stack_var(self,offset:int,var_type:StringOrType,name:str)->None:ifisinstance(var_type,str):(var_type,_)=self.view.parse_type_string(var_type)tc=var_type._to_core_struct()core.BNCreateAutoStackVariable(self.handle,offset,tc,name) [docs]defcreate_user_stack_var(self,offset:int,var_type:StringOrType,name:str)->None:ifisinstance(var_type,str):(var_type,_)=self.view.parse_type_string(var_type)tc=var_type._to_core_struct()core.BNCreateUserStackVariable(self.handle,offset,tc,name) [docs]defdelete_auto_stack_var(self,offset:int)->None:core.BNDeleteAutoStackVariable(self.handle,offset) [docs]defdelete_user_stack_var(self,offset:int)->None:core.BNDeleteUserStackVariable(self.handle,offset) [docs]defcreate_auto_var(self,var:'variable.Variable',var_type:StringOrType,name:str,ignore_disjoint_uses:bool=False)->None:ifisinstance(var_type,str):(var_type,_)=self.view.parse_type_string(var_type)tc=var_type._to_core_struct()core.BNCreateAutoVariable(self.handle,var.to_BNVariable(),tc,name,ignore_disjoint_uses) [docs]defcreate_user_var(self,var:'variable.Variable',var_type:StringOrType,name:str,ignore_disjoint_uses:bool=False)->None:ifisinstance(var_type,str):(var_type,_)=self.view.parse_type_string(var_type)tc=var_type._to_core_struct()core.BNCreateUserVariable(self.handle,var.to_BNVariable(),tc,name,ignore_disjoint_uses) [docs]defdelete_user_var(self,var:'variable.Variable')->None:core.BNDeleteUserVariable(self.handle,var.to_BNVariable()) [docs]defis_var_user_defined(self,var:'variable.Variable')->bool:returncore.BNIsVariableUserDefined(self.handle,var.to_BNVariable()) [docs]defget_stack_var_at_frame_offset(self,offset:int,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['variable.Variable']:ifarchisNone:arch=self.archfound_var=core.BNVariableNameAndType()ifnotcore.BNGetStackVariableAtFrameOffset(self.handle,arch.handle,addr,offset,found_var):returnNoneresult=variable.Variable.from_BNVariable(self,found_var.var)core.BNFreeVariableNameAndType(found_var)returnresult [docs]defget_stack_var_at_frame_offset_after_instruction(self,offset:int,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['variable.Variable']:ifarchisNone:arch=self.archfound_var=core.BNVariableNameAndType()ifnotcore.BNGetStackVariableAtFrameOffsetAfterInstruction(self.handle,arch.handle,addr,offset,found_var):returnNoneresult=variable.Variable.from_BNVariable(self,found_var.var)core.BNFreeVariableNameAndType(found_var)returnresult [docs]defget_type_tokens(self,settings:Optional['DisassemblySettings']=None)->List['DisassemblyTextLine']:_settings=NoneifsettingsisnotNone:_settings=settings.handlecount=ctypes.c_ulonglong()lines=core.BNGetFunctionTypeTokens(self.handle,settings,count)assertlinesisnotNone,"core.BNGetFunctionTypeTokens returned None"result=[]foriinrange(0,count.value):addr=lines[i].addrcolor=_highlight.HighlightColor._from_core_struct(lines[i].highlight)tokens=InstructionTextToken._from_core_struct(lines[i].tokens,lines[i].count)result.append(DisassemblyTextLine(tokens,addr,color=color))core.BNFreeDisassemblyTextLines(lines,count.value)returnresult [docs]defget_reg_value_at_exit(self,reg:'architecture.RegisterType')->'variable.RegisterValue':result=core.BNGetFunctionRegisterValueAtExit(self.handle,self.arch.get_reg_index(reg))returnvariable.RegisterValue.from_BNRegisterValue(result,self.arch) [docs]defset_auto_call_stack_adjustment(self,addr:int,adjust:Union[int,'types.OffsetWithConfidence'],arch:Optional['architecture.Architecture']=None)->None:ifarchisNone:arch=self.archifnotisinstance(adjust,types.OffsetWithConfidence):adjust=types.OffsetWithConfidence(adjust)core.BNSetAutoCallStackAdjustment(self.handle,arch.handle,addr,adjust.value,adjust.confidence) [docs]defset_auto_call_reg_stack_adjustment(self,addr:int,adjust:Mapping['architecture.RegisterStackName',int],arch:Optional['architecture.Architecture']=None)->None:ifarchisNone:arch=self.archadjust_buf=(core.BNRegisterStackAdjustment*len(adjust))()fori,reg_stackinenumerate(adjust.keys()):adjust_buf[i].regStack=arch.get_reg_stack_index(reg_stack)value=adjust[reg_stack]ifnotisinstance(value,types.RegisterStackAdjustmentWithConfidence):value=types.RegisterStackAdjustmentWithConfidence(value)adjust_buf[i].adjustment=value.valueadjust_buf[i].confidence=value.confidencecore.BNSetAutoCallRegisterStackAdjustment(self.handle,arch.handle,addr,adjust_buf,len(adjust)) [docs]defset_auto_call_reg_stack_adjustment_for_reg_stack(self,addr:int,reg_stack:'architecture.RegisterStackType',adjust,arch:Optional['architecture.Architecture']=None)->None:ifarchisNone:arch=self.archreg_stack=arch.get_reg_stack_index(reg_stack)ifnotisinstance(adjust,types.RegisterStackAdjustmentWithConfidence):adjust=types.RegisterStackAdjustmentWithConfidence(adjust)core.BNSetAutoCallRegisterStackAdjustmentForRegisterStack(self.handle,arch.handle,addr,reg_stack,adjust.value,adjust.confidence) [docs]defset_call_type_adjustment(self,addr:int,adjust_type:Optional[StringOrType]=None,arch:Optional['architecture.Architecture']=None)->None:"""``set_call_type_adjustment`` sets or removes the call type override at a call site to the given type.:param int addr: virtual address of the call instruction to adjust:param str|types.Type|types.TypeBuilder adjust_type: (optional) overridden call type, or `None` to remove an existing adjustment:param Architecture arch: (optional) Architecture of the instruction if different from self.arch:Example:>>> # Change the current call site to no-return>>> target = bv.get_function_at(list(filter(lambda ref: ref.address == here, current_function.call_sites))[0].mlil.dest.value.value)>>> ft = target.type.mutable_copy()>>> ft.can_return = False>>> current_function.set_call_type_adjustment(here, ft)"""ifarchisNone:arch=self.archifadjust_typeisnotNone:ifisinstance(adjust_type,str):(adjust_type,_)=self.view.parse_type_string(adjust_type)confidence=core.max_confidenceelse:confidence=adjust_type.confidencetype_conf=core.BNTypeWithConfidence()type_conf.type=adjust_type.handletype_conf.confidence=confidenceelse:type_conf=Nonecore.BNSetUserCallTypeAdjustment(self.handle,arch.handle,addr,type_conf) [docs]defset_call_stack_adjustment(self,addr:int,adjust:Union[int,'types.OffsetWithConfidence'],arch:Optional['architecture.Architecture']=None):ifarchisNone:arch=self.archifnotisinstance(adjust,types.OffsetWithConfidence):adjust=types.OffsetWithConfidence(adjust)core.BNSetUserCallStackAdjustment(self.handle,arch.handle,addr,adjust.value,adjust.confidence) [docs]defset_call_reg_stack_adjustment(self,addr:int,adjust:Mapping['architecture.RegisterStackName',Union[int,'types.RegisterStackAdjustmentWithConfidence']],arch:Optional['architecture.Architecture']=None)->None:ifarchisNone:arch=self.archadjust_buf=(core.BNRegisterStackAdjustment*len(adjust))()fori,reg_stackinenumerate(adjust.keys()):adjust_buf[i].regStack=arch.get_reg_stack_index(reg_stack)value=adjust[reg_stack]ifnotisinstance(value,types.RegisterStackAdjustmentWithConfidence):value=types.RegisterStackAdjustmentWithConfidence(int(value))adjust_buf[i].adjustment=value.valueadjust_buf[i].confidence=value.confidencecore.BNSetUserCallRegisterStackAdjustment(self.handle,arch.handle,addr,adjust_buf,len(adjust)) [docs]defset_call_reg_stack_adjustment_for_reg_stack(self,addr:int,reg_stack:'architecture.RegisterStackType',adjust:Union[int,'types.RegisterStackAdjustmentWithConfidence'],arch:Optional['architecture.Architecture']=None)->None:ifarchisNone:arch=self.archreg_stack=arch.get_reg_stack_index(reg_stack)ifnotisinstance(adjust,types.RegisterStackAdjustmentWithConfidence):adjust=types.RegisterStackAdjustmentWithConfidence(adjust)core.BNSetUserCallRegisterStackAdjustmentForRegisterStack(self.handle,arch.handle,addr,reg_stack,adjust.value,adjust.confidence) [docs]defget_call_type_adjustment(self,addr:int,arch:Optional['architecture.Architecture']=None)->Optional['types.Type']:ifarchisNone:arch=self.archresult=core.BNGetCallTypeAdjustment(self.handle,arch.handle,addr)ifnotresult.type:returnNoneplatform=self.platformreturntypes.Type.create(result.type,platform=platform,confidence=result.confidence) [docs]defget_call_stack_adjustment(self,addr:int,arch:Optional['architecture.Architecture']=None)->'types.OffsetWithConfidence':ifarchisNone:arch=self.archresult=core.BNGetCallStackAdjustment(self.handle,arch.handle,addr)returntypes.OffsetWithConfidence(result.value,confidence=result.confidence) [docs]defget_call_reg_stack_adjustment(self,addr:int,arch:Optional['architecture.Architecture']=None)->Dict['architecture.RegisterStackName','types.RegisterStackAdjustmentWithConfidence']:ifarchisNone:arch=self.archcount=ctypes.c_ulonglong()adjust=core.BNGetCallRegisterStackAdjustment(self.handle,arch.handle,addr,count)assertadjustisnotNone,"core.BNGetCallRegisterStackAdjustment returned None"result={}foriinrange(0,count.value):result[arch.get_reg_stack_name(adjust[i].regStack)]=types.RegisterStackAdjustmentWithConfidence(adjust[i].adjustment,confidence=adjust[i].confidence)core.BNFreeRegisterStackAdjustments(adjust)returnresult [docs]defget_call_reg_stack_adjustment_for_reg_stack(self,addr:int,reg_stack:'architecture.RegisterStackType',arch:Optional['architecture.Architecture']=None)->'types.RegisterStackAdjustmentWithConfidence':ifarchisNone:arch=self.archreg_stack=arch.get_reg_stack_index(reg_stack)adjust=core.BNGetCallRegisterStackAdjustmentForRegisterStack(self.handle,arch.handle,addr,reg_stack)result=types.RegisterStackAdjustmentWithConfidence(adjust.adjustment,confidence=adjust.confidence)returnresult [docs]defis_call_instruction(self,addr:int,arch:Optional['architecture.Architecture']=None)->bool:ifarchisNone:arch=self.archreturncore.BNIsCallInstruction(self.handle,arch.handle,addr) [docs]defcreate_forced_var_version(self,var:'variable.Variable',def_addr:int)->None:def_site=core.BNArchitectureAndAddress()def_site.arch=self.arch.handledef_site.address=def_addrcore.BNCreateForcedVariableVersion(self.handle,var.to_BNVariable(),def_site) [docs]defclear_forced_var_version(self,var:'variable.Variable',def_addr:int)->None:def_site=core.BNArchitectureAndAddress()def_site.arch=self.arch.handledef_site.address=def_addrcore.BNClearForcedVariableVersion(self.handle,var.to_BNVariable(),def_site) [docs]defset_user_var_value(self,var:'variable.Variable',def_addr:int,value:'variable.PossibleValueSet',after:bool=True)->None:"""`set_user_var_value` allows the user to specify a PossibleValueSet value for an MLIL variable at its \definition site... warning:: Setting the variable value, triggers a reanalysis of the function and allows the dataflow \to compute and propagate values which depend on the current variable. This implies that branch conditions \whose values can be determined statically will be computed, leading to potential branch elimination at \the HLIL layer.:param Variable var: Variable for which the value is to be set:param int def_addr: Address where the variable is set:param PossibleValueSet value: Informed value of the variable:param bool after: Whether the value happens before or after the instruction:rtype: None:Example:>>> mlil_var = current_mlil[0].operands[0]>>> def_address = 0x40108d>>> var_value = PossibleValueSet.constant(5)>>> current_function.set_user_var_value(mlil_var, def_address, var_value)"""#if var.index == 0:## Special case: function parameters have index 0 and are defined at the start of the function#def_addr = self.start#else:#var_defs = self.mlil.get_var_definitions(var)#if var_defs is None:#raise ValueError("Could not get definition for Variable")#found = False#for site in var_defs:#if site.address == def_addr:#found = True#break#if not found:#raise ValueError("No definition for Variable found at given address")def_site=core.BNArchitectureAndAddress()def_site.arch=self.arch.handledef_site.address=def_addrcore.BNSetUserVariableValue(self.handle,var.to_BNVariable(),def_site,after,value._to_core_struct()) [docs]defclear_user_var_value(self,var:'variable.Variable',def_addr:int,after:bool=True)->None:"""Clears a previously defined user variable value.:param Variable var: Variable for which the value was informed:param int def_addr: Address of the definition site of the variable:rtype: None"""ifvar.index==0:# Special case: function parameters have index 0 and are defined at the start of the functiondef_addr=self.startelse:func_mlil=self.mliliffunc_mlilisNone:raiseValueError("Could not get definition for Variable")var_defs=func_mlil.get_var_definitions(var)ifvar_defsisNone:raiseValueError("Could not get definition for Variable")found=Falseforsiteinvar_defs:ifsite.address==def_addr:found=Truebreakifnotfound:raiseValueError("No definition for Variable found at given address")def_site=core.BNArchitectureAndAddress()def_site.arch=self.arch.handledef_site.address=def_addrcore.BNClearUserVariableValue(self.handle,var.to_BNVariable(),def_site,after) [docs]defget_all_user_var_values(self)->Dict['variable.Variable',Dict['ArchAndAddr','variable.PossibleValueSet']]:"""Returns a map of current defined user variable values.:returns: Map of user current defined user variable values and their definition sites.:type: dict of (Variable, dict of (ArchAndAddr, PossibleValueSet))"""count=ctypes.c_ulonglong(0)var_values=core.BNGetAllUserVariableValues(self.handle,count)assertvar_valuesisnotNone,"core.BNGetAllUserVariableValues returned None"try:result={}foriinrange(count.value):var_val=var_values[i]var=variable.Variable.from_BNVariable(self,var_val.var)ifvarnotinresult:result[var]={}def_site=ArchAndAddr(architecture.CoreArchitecture._from_cache(var_val.defSite.arch),var_val.defSite.address)result[var][def_site]=variable.PossibleValueSet(def_site.arch,var_val.value)returnresultfinally:core.BNFreeUserVariableValues(var_values) [docs]defclear_all_user_var_values(self)->None:"""Clear all user defined variable values.:rtype: None"""all_values=self.get_all_user_var_values()forvarinall_values:fordef_siteinall_values[var]:self.clear_user_var_value(var,def_site.addr) [docs]defrequest_debug_report(self,name:str)->None:"""``request_debug_report`` can generate internal debug reports for a variety of analysis.Current list of possible values include:- mlil_translator- stack_adjust_graph- high_level_il:param str name: Name of the debug report:rtype: None"""debug_report_alias={"stack":"stack_adjust_graph","mlil":"mlil_translator","hlil":"high_level_il"}ifnameindebug_report_alias:name=debug_report_alias[name]core.BNRequestFunctionDebugReport(self.handle,name)self.view.update_analysis() [docs]defcheck_for_debug_report(self,name:str)->bool:"""``check_for_debug_report`` checks if a function has had a debug report requestedwith the given name, and then, if one has been requested, clears the request internallyso that future calls to this function for that report will return False.If a function has had a debug report requested, it is the caller of this function'sresponsibility to actually generate and show the debug report.You can use :py:func:`binaryninja.interaction.show_report_collection`for showing a debug report from a workflow activity.:param name: Name of the debug report:return: True if the report has been requested (and not checked for yet)"""returncore.BNFunctionCheckForDebugReport(self.handle,name) @propertydefcall_sites(self)->List['binaryview.ReferenceSource']:"""``call_sites`` returns a list of possible call sites contained in this function.This includes ordinary calls, tail calls, and indirect jumps. Not all of the returned call sitesare necessarily true call sites; some may simply be unresolved indirect jumps, for example.:return: List of References that represent the sources of possible calls in this function:rtype: list(ReferenceSource)"""count=ctypes.c_ulonglong(0)refs=core.BNGetFunctionCallSites(self.handle,count)assertrefsisnotNone,"core.BNGetFunctionCallSites returned None"result=[]foriinrange(0,count.value):ifrefs[i].func:func=Function(self.view,core.BNNewFunctionReference(refs[i].func))else:func=Noneifrefs[i].arch:arch=architecture.CoreArchitecture._from_cache(refs[i].arch)else:arch=Noneaddr=refs[i].addrresult.append(binaryview.ReferenceSource(func,arch,addr))core.BNFreeCodeReferences(refs,count.value)returnresult@propertydefcallees(self)->List['Function']:"""``callees`` returns a list of functions that this function callsThis does not include the address of those calls, rather just the function objects themselves. Use :py:meth:`call_sites` to identify the location of these calls.This does not include calls to imported functions, as they do not have a function object, use :py:meth:`callee_addresses` for that.:return: List of Functions that this function calls:rtype: list(Function)"""called=[]forcallee_addrinself.callee_addresses:# a second argument to get_function_at() can filter callees whose platform matchers caller# good when two functions with different arch's start at same address (rare polyglot code)# bad for ARM/Thumb (common)func=self.view.get_function_at(callee_addr)iffuncisnotNone:called.append(func)returncalled@propertydefcallee_addresses(self)->List[int]:"""``callee_addresses`` returns a list of start addresses for functions that this function calls.Does not point to the actual address where the call occurs, just the start of the function that contains the reference.:return: List of start address for functions that this function calls:rtype: list(int)"""result=[]forrefinself.call_sites:result.extend(self.view.get_callees(ref.address,ref.function,ref.arch))returnresult@propertydefcallers(self)->List['Function']:"""``callers`` returns a list of functions that call this functionDoes not point to the actual address where the call occurs, just the start of the function that contains the call.:return: List of Functions that call this function:rtype: list(Function)"""functions=[]forrefinself.caller_sites:ifref.functionisnotNone:functions.append(ref.function)returnfunctions@propertydefcaller_sites(self)->Generator['binaryview.ReferenceSource',None,None]:"""``caller_sites`` returns a list of ReferenceSource objects corresponding to the addressesin functions which call this function:return: List of ReferenceSource objects of the call sites to this function:rtype: list(ReferenceSource)"""returnself.view.get_callers(self.start)@propertydefworkflow(self):handle=core.BNGetWorkflowForFunction(self.handle)ifhandleisNone:returnNonereturnworkflow.Workflow(handle=handle,object_handle=self.handle)@propertydefprovenance(self):"""``provenance`` returns a string representing the provenance. This portion of the API is under development.Currently the provenance information is undocumented, not persistent, and not saved to a database.:return: string representation of the provenance:rtype: str"""returncore.BNGetProvenanceString(self.handle)[docs]defget_mlil_var_refs(self,var:'variable.Variable')->List[ILReferenceSource]:"""``get_mlil_var_refs`` returns a list of ILReferenceSource objects (IL xrefs or cross-references)that reference the given variable. The variable is a local variable that can be either on the stack,in a register, or in a flag.This function is related to get_hlil_var_refs(), which returns variable references collectedfrom HLIL. The two can be different in several cases, e.g., multiple variables in MLIL can be mergedinto a single variable in HLIL.:param Variable var: Variable for which to query the xref:return: List of IL References for the given variable:rtype: list(ILReferenceSource):Example:>>> mlil_var = current_mlil[0].operands[0]>>> current_function.get_mlil_var_refs(mlil_var)"""count=ctypes.c_ulonglong(0)refs=core.BNGetMediumLevelILVariableReferences(self.handle,var.to_BNVariable(),count)assertrefsisnotNone,"core.BNGetMediumLevelILVariableReferences returned None"result=[]foriinrange(0,count.value):ifrefs[i].func:func=Function(self.view,core.BNNewFunctionReference(refs[i].func))else:func=Noneifrefs[i].arch:arch=architecture.CoreArchitecture._from_cache(refs[i].arch)else:arch=Noneresult.append(ILReferenceSource(func,arch,refs[i].addr,refs[i].type,refs[i].exprId))core.BNFreeILReferences(refs,count.value)returnresult [docs]defget_mlil_var_refs_from(self,addr:int,length:Optional[int]=None,arch:Optional['architecture.Architecture']=None)->List[VariableReferenceSource]:"""``get_mlil_var_refs_from`` returns a list of variables referenced by code in the function ``func``,of the architecture ``arch``, and at the address ``addr``. If no function is specified, references fromall functions and containing the address will be returned. If no architecture is specified, thearchitecture of the function will be used.This function is related to get_hlil_var_refs_from(), which returns variable references collectedfrom HLIL. The two can be different in several cases, e.g., multiple variables in MLIL can be mergedinto a single variable in HLIL.:param int addr: virtual address to query for variable references:param int length: optional length of query:param Architecture arch: optional architecture of query:return: list of variable reference sources:rtype: list(VariableReferenceSource)"""result=[]count=ctypes.c_ulonglong(0)ifarchisNone:arch=self.archiflengthisNone:refs=core.BNGetMediumLevelILVariableReferencesFrom(self.handle,arch.handle,addr,count)assertrefsisnotNone,"core.BNGetMediumLevelILVariableReferencesFrom returned None"else:refs=core.BNGetMediumLevelILVariableReferencesInRange(self.handle,arch.handle,addr,length,count)assertrefsisnotNone,"core.BNGetMediumLevelILVariableReferencesInRange returned None"foriinrange(0,count.value):var=variable.Variable.from_BNVariable(self,refs[i].var)ifrefs[i].source.func:func=Function(self.view,core.BNNewFunctionReference(refs[i].source.func))else:func=Noneifrefs[i].source.arch:_arch=architecture.CoreArchitecture._from_cache(refs[i].source.arch)else:_arch=archsrc=ILReferenceSource(func,_arch,refs[i].source.addr,refs[i].source.type,refs[i].source.exprId)result.append(VariableReferenceSource(var,src))core.BNFreeVariableReferenceSourceList(refs,count.value)returnresult [docs]defget_hlil_var_refs(self,var:'variable.Variable')->List[ILReferenceSource]:"""``get_hlil_var_refs`` returns a list of ILReferenceSource objects (IL xrefs or cross-references)that reference the given variable. The variable is a local variable that can be either on the stack,in a register, or in a flag.:param Variable var: Variable for which to query the xref:return: List of IL References for the given variable:rtype: list(ILReferenceSource):Example:>>> mlil_var = current_hlil[0].operands[0]>>> current_function.get_hlil_var_refs(mlil_var)"""count=ctypes.c_ulonglong(0)refs=core.BNGetHighLevelILVariableReferences(self.handle,var.to_BNVariable(),count)assertrefsisnotNone,"core.BNGetHighLevelILVariableReferences returned None"result=[]foriinrange(0,count.value):ifrefs[i].func:func=Function(self.view,core.BNNewFunctionReference(refs[i].func))else:func=Noneifrefs[i].arch:arch=architecture.CoreArchitecture._from_cache(refs[i].arch)else:arch=Noneresult.append(ILReferenceSource(func,arch,refs[i].addr,refs[i].type,refs[i].exprId))core.BNFreeILReferences(refs,count.value)returnresult [docs]defget_hlil_var_refs_from(self,addr:int,length:Optional[int]=None,arch:Optional['architecture.Architecture']=None)->List[VariableReferenceSource]:"""``get_hlil_var_refs_from`` returns a list of variables referenced by code in the function ``func``,of the architecture ``arch``, and at the address ``addr``. If no function is specified, references fromall functions and containing the address will be returned. If no architecture is specified, thearchitecture of the function will be used.:param int addr: virtual address to query for variable references:param int length: optional length of query:param Architecture arch: optional architecture of query:return: list of variables reference sources:rtype: list(VariableReferenceSource)"""result=[]count=ctypes.c_ulonglong(0)ifarchisNone:arch=self.archiflengthisNone:refs=core.BNGetHighLevelILVariableReferencesFrom(self.handle,arch.handle,addr,count)assertrefsisnotNone,"core.BNGetHighLevelILVariableReferencesFrom returned None"else:refs=core.BNGetHighLevelILVariableReferencesInRange(self.handle,arch.handle,addr,length,count)assertrefsisnotNone,"core.BNGetHighLevelILVariableReferencesInRange returned None"foriinrange(0,count.value):var=variable.Variable.from_BNVariable(self,refs[i].var)ifrefs[i].source.func:func=Function(self.view,core.BNNewFunctionReference(refs[i].source.func))else:func=Noneifrefs[i].source.arch:_arch=architecture.CoreArchitecture._from_cache(refs[i].source.arch)else:_arch=archsrc=ILReferenceSource(func,_arch,refs[i].source.addr,refs[i].source.type,refs[i].source.exprId)result.append(VariableReferenceSource(var,src))core.BNFreeVariableReferenceSourceList(refs,count.value)returnresult [docs]defget_instruction_containing_address(self,addr:int,arch:Optional['architecture.Architecture']=None)->Optional[int]:ifarchisNone:arch=self.archstart=ctypes.c_ulonglong()ifcore.BNGetInstructionContainingAddress(self.handle,arch.handle,addr,start):returnstart.valuereturnNone [docs]defmerge_vars(self,target:'variable.Variable',sources:Union[List['variable.Variable'],'variable.Variable'])->None:"""``merge_vars`` merges one or more variables in ``sources`` into the ``target`` variable. Allvariable accesses to the variables in ``sources`` will be rewritten to use ``target``.:param Variable target: target variable:param list(Variable) sources: list of source variables"""ifisinstance(sources,variable.Variable):sources=[sources]source_list=(core.BNVariable*len(sources))()foriinrange(0,len(sources)):source_list[i].type=sources[i].source_typesource_list[i].index=sources[i].indexsource_list[i].storage=sources[i].storagecore.BNMergeVariables(self.handle,target.to_BNVariable(),source_list,len(sources)) [docs]defunmerge_vars(self,target:'variable.Variable',sources:Union[List['variable.Variable'],'variable.Variable'])->None:"""``unmerge_vars`` undoes variable merging performed with ``merge_vars``. The variables in``sources`` will no longer be merged into the ``target`` variable.:param Variable target: target variable:param list(Variable) sources: list of source variables"""ifisinstance(sources,variable.Variable):sources=[sources]source_list=(core.BNVariable*len(sources))()foriinrange(0,len(sources)):source_list[i].type=sources[i].source_typesource_list[i].index=sources[i].indexsource_list[i].storage=sources[i].storagecore.BNUnmergeVariables(self.handle,target.to_BNVariable(),source_list,len(sources)) [docs]defsplit_var(self,var:'variable.Variable')->None:"""``split_var`` splits a variable at the definition site. The given ``var`` must be thevariable unique to the definition and should be obtained by using``MediumLevelILInstruction.get_split_var_for_definition`` at the definition site.This function is not meant to split variables that have been previously merged. Use``unmerge_vars`` to split previously merged variables... warning:: Binary Ninja automatically splits all variables that the analysis determines \to be safely splittable. Splitting a variable manually with ``split_var`` can cause \IL and decompilation to be incorrect. There are some patterns where variables can be safely \split semantically but analysis cannot determine that it is safe. This function is provided \to allow variable splitting to be performed in these cases by plugins or by the user.:param Variable var: variable to split"""core.BNSplitVariable(self.handle,var.to_BNVariable()) [docs]defunsplit_var(self,var:'variable.Variable')->None:"""``unsplit_var`` undoes variable splitting performed with ``split_var``. The given ``var``must be the variable unique to the definition and should be obtained by using``MediumLevelILInstruction.get_split_var_for_definition`` at the definition site.:param Variable var: variable to unsplit"""core.BNUnsplitVariable(self.handle,var.to_BNVariable()) [docs]defset_auto_inline_during_analysis(self,value:Union[bool,'types.BoolWithConfidence']):bc=core.BNBoolWithConfidence()bc.value=bool(value)ifisinstance(value,types.BoolWithConfidence):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetAutoFunctionInlinedDuringAnalysis(self.handle,bc) [docs]defset_user_inline_during_analysis(self,value:Union[bool,'types.BoolWithConfidence']):bc=core.BNBoolWithConfidence()bc.value=bool(value)ifisinstance(value,types.BoolWithConfidence):bc.confidence=value.confidenceelse:bc.confidence=core.max_confidencecore.BNSetUserFunctionInlinedDuringAnalysis(self.handle,bc) [docs]deftoggle_region(self,hash):"""Toggle the collapsed state of a region during rendering, by hash value:param hash: Hash value of region"""core.BNFunctionToggleRegion(self.handle,hash) [docs]defcollapse_region(self,hash):"""Collapse a region during rendering:param hash: Hash value of region"""core.BNFunctionCollapseRegion(self.handle,hash) [docs]defexpand_region(self,hash):"""Un-collapse a region during rendering:param hash: Hash value of region"""core.BNFunctionExpandRegion(self.handle,hash) [docs]defexpand_all(self):"""Expand all regions in the function"""core.BNFunctionExpandAll(self.handle) @propertydefis_collapsed(self):"""If the entire function is collapsed during rendering."""returnself.is_region_collapsed(self.start)[docs]defis_instruction_collapsed(self,instr:'highlevelil.HighLevelILInstruction',discriminator:int=0)->bool:"""Determine if a given HLIL instruction (with discriminator) is collapsed during rendering.:param instr: Instruction which might be collapsed:param discriminator: Unique discriminator id for the region:return: True if the instruction should be rendered as collapsed"""returnself.is_region_collapsed(instr.get_instruction_hash(discriminator)) [docs]defis_region_collapsed(self,hash)->bool:"""Determine if a given region is collapsed during rendering.:param hash: Hash value of region:return: True if the region should be rendered as collapsed"""returncore.BNFunctionIsRegionCollapsed(self.handle,hash) [docs]defstore_metadata(self,key:str,md:metadata.MetadataValueType,isAuto:bool=False)->None:"""`store_metadata` stores an object for the given key in the current Function. Objects stored using`store_metadata` can be retrieved when the database is reopened unless isAuto is set to True.:param str key: key value to associate the Metadata object with:param Varies md: object to store:param bool isAuto: whether the metadata is an auto metadata:rtype: None """_md=mdifnotisinstance(_md,metadata.Metadata):_md=metadata.Metadata(_md)core.BNFunctionStoreMetadata(self.handle,key,_md.handle,isAuto) [docs]defquery_metadata(self,key:str)->'metadata.MetadataValueType':"""`query_metadata` retrieves metadata associated with the given key stored in the current function.:param str key: key to query:rtype: metadata associated with the key"""md_handle=core.BNFunctionQueryMetadata(self.handle,key)ifmd_handleisNone:raiseKeyError(key)returnmetadata.Metadata(handle=md_handle).value [docs]defremove_metadata(self,key:str)->None:"""`remove_metadata` removes the metadata associated with key from the current function.:param str key: key associated with metadata to remove from the function:rtype: None"""core.BNFunctionRemoveMetadata(self.handle,key) @propertydefmetadata(self)->Dict[str,'metadata.MetadataValueType']:"""`metadata` retrieves the metadata associated with the current function.:rtype: metadata associated with the function"""md_handle=core.BNFunctionGetMetadata(self.handle)assertmd_handleisnotNone,"core.BNFunctionGetMetadata returned None"value=metadata.Metadata(handle=md_handle).valueassertisinstance(value,dict),"core.BNFunctionGetMetadata did not return a dict"returnvalue@propertydefauto_metadata(self)->Dict[str,'metadata.MetadataValueType']:"""`metadata` retrieves the metadata associated with the current function.:rtype: metadata associated with the function"""md_handle=core.BNFunctionGetAutoMetadata(self.handle)assertmd_handleisnotNone,"core.BNFunctionGetAutoMetadata returned None"value=metadata.Metadata(handle=md_handle).valueassertisinstance(value,dict),"core.BNFunctionGetAutoMetadata did not return a dict"returnvalue[docs]defget_expr_folding(self,addr:Union[int,highlevelil.HighLevelILInstruction])->ExprFolding:ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addressreturnExprFolding(core.BNGetExprFolding(self.handle,addr)) [docs]defset_expr_folding(self,addr:Union[int,highlevelil.HighLevelILInstruction],value:ExprFolding):ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addresscore.BNSetExprFolding(self.handle,addr,value) [docs]defis_condition_inverted(self,addr:Union[int,highlevelil.HighLevelILInstruction])->bool:ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addressreturncore.BNIsConditionInverted(self.handle,addr) [docs]defset_condition_inverted(self,addr:Union[int,highlevelil.HighLevelILInstruction],invert:bool):ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addresscore.BNSetConditionInverted(self.handle,addr,invert) [docs]defget_early_return(self,addr:Union[int,highlevelil.HighLevelILInstruction])->EarlyReturn:ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addressreturnEarlyReturn(core.BNGetEarlyReturn(self.handle,addr)) [docs]defset_early_return(self,addr:Union[int,highlevelil.HighLevelILInstruction],value:EarlyReturn):ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addresscore.BNSetEarlyReturn(self.handle,addr,value) [docs]defget_switch_recovery(self,addr:Union[int,highlevelil.HighLevelILInstruction])->SwitchRecovery:ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addressreturnSwitchRecovery(core.BNGetSwitchRecovery(self.handle,addr)) [docs]defset_switch_recovery(self,addr:Union[int,highlevelil.HighLevelILInstruction],value:SwitchRecovery):ifisinstance(addr,highlevelil.HighLevelILInstruction):addr=addr.addresscore.BNSetSwitchRecovery(self.handle,addr,value) [docs]classAdvancedFunctionAnalysisDataRequestor:[docs]def__init__(self,func:Optional['Function']=None):self._function=funcifself._functionisnotNone:self._function.request_advanced_analysis_data() def__del__(self):ifself._functionisnotNone:self._function.release_advanced_analysis_data()@propertydeffunction(self)->Optional['Function']:returnself._function@function.setterdeffunction(self,func:'Function')->None:ifself._functionisnotNone:self._function.release_advanced_analysis_data()self._function=funcifself._functionisnotNone:self._function.request_advanced_analysis_data()[docs]defclose(self)->None:ifself._functionisnotNone:self._function.release_advanced_analysis_data()self._function=None [docs]@dataclassclassDisassemblyTextLineTypeInfo:parent_type:Optional['types.Type']field_index:intoffset:int [docs]@dataclassclassDisassemblyTextLine:tokens:List['InstructionTextToken']highlight:'_highlight.HighlightColor'address:Optional[int]il_instruction:Optional[ILInstructionType]tags:List['binaryview.Tag']type_info:Optional[DisassemblyTextLineTypeInfo][docs]def__init__(self,tokens:List['InstructionTextToken'],address:Optional[int]=None,il_instr:Optional[ILInstructionType]=None,color:Optional[Union['_highlight.HighlightColor',HighlightStandardColor]]=None,tags:Optional[List['binaryview.Tag']]=None,type_info:Optional[DisassemblyTextLineTypeInfo]=None,):self.address=addressself.tokens=tokensself.il_instruction=il_instrself.address=addressifcolorisNone:self.highlight=_highlight.HighlightColor()else:ifnotisinstance(color,HighlightStandardColor)andnotisinstance(color,_highlight.HighlightColor):raiseValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")ifisinstance(color,HighlightStandardColor):self.highlight=_highlight.HighlightColor(color)else:self.highlight=coloriftagsisNone:tags=[]self.tags=tagsself.type_info=type_info def__str__(self):return"".join(map(str,self.tokens))def__repr__(self):ifself.addressisNone:returnf"<disassemblyTextLine{self}>"returnf"<disassemblyTextLine{self.address:#x}:{self}>"@propertydeftotal_width(self):returnsum(token.widthfortokeninself.tokens)def_find_address_and_indentation_tokens(self,callback):start_token=0foriinrange(len(self.tokens)):ifself.tokens[i].type==InstructionTextTokenType.AddressSeparatorToken:start_token=i+1breakfortokeninself.tokens[:start_token]:callback(token)fortokeninself.tokens[start_token:]:iftoken.typein[InstructionTextTokenType.AddressDisplayToken,InstructionTextTokenType.AddressSeparatorToken,InstructionTextTokenType.CollapseStateIndicatorToken]:callback(token)continueiflen(token.text)!=0andnottoken.text.isspace():breakcallback(token)@propertydefaddress_and_indentation_width(self):result=0defsum_width(token):nonlocalresultresult+=token.widthself._find_address_and_indentation_tokens(sum_width)returnresult@propertydefaddress_and_indentation_tokens(self):result=[]defcollect_tokens(token):nonlocalresultresult.append(token)self._find_address_and_indentation_tokens(collect_tokens)returnresult@classmethoddef_from_core_struct(cls,struct:core.BNDisassemblyTextLine,il_func:Optional['ILFunctionType']=None):il_instr=Noneifil_funcisnotNoneandstruct.instrIndex<len(il_func):try:il_instr=il_func[struct.instrIndex]except:il_instr=Nonetokens=InstructionTextToken._from_core_struct(struct.tokens,struct.count)tags=[]foriinrange(struct.tagCount):tags.append(binaryview.Tag(handle=core.BNNewTagReference(struct.tags[i])))type_info=Noneifstruct.typeInfo.hasTypeInfo:parent_type=Noneifstruct.typeInfo.parentType:parent_type=types.Type.create(core.BNNewTypeReference(struct.typeInfo.parentType))type_info=DisassemblyTextLineTypeInfo(parent_type=parent_type,field_index=struct.typeInfo.fieldIndex,offset=struct.typeInfo.offset)returnDisassemblyTextLine(tokens,struct.addr,il_instr,_highlight.HighlightColor._from_core_struct(struct.highlight),tags,type_info)def_to_core_struct(self)->core.BNDisassemblyTextLine:result=core.BNDisassemblyTextLine()result.addr=self.addressifself.il_instructionisnotNone:result.instrIndex=self.il_instruction.instr_indexelse:result.instrIndex=0xffffffffffffffffresult.tokens=InstructionTextToken._get_core_struct(self.tokens)result.count=len(self.tokens)result.highlight=self.highlight._to_core_struct()result.tagCount=len(self.tags)result.tags=(ctypes.POINTER(core.BNTag)*len(self.tags))()fori,taginenumerate(self.tags):result.tags[i]=tag.handleifself.type_infoisNone:result.typeInfo.hasTypeInfo=Falseelse:result.typeInfo.hasTypeInfo=Trueifself.type_info.parent_typeisnotNone:result.typeInfo.parentType=self.type_info.parent_type.handleresult.typeInfo.fieldIndex=self.type_info.field_indexresult.typeInfo.offset=self.type_info.offsetreturnresult [docs]classDisassemblyTextRenderer:[docs]def__init__(self,func:Optional[AnyFunctionType]=None,settings:Optional['DisassemblySettings']=None,handle:Optional[core.BNDisassemblySettings]=None):ifhandleisNone:iffuncisNone:raiseValueError("function required for disassembly")settings_obj=NoneifsettingsisnotNone:settings_obj=settings.handleifisinstance(func,Function):self.handle=core.BNCreateDisassemblyTextRenderer(func.handle,settings_obj)elifisinstance(func,lowlevelil.LowLevelILFunction):self.handle=core.BNCreateLowLevelILDisassemblyTextRenderer(func.handle,settings_obj)elifisinstance(func,mediumlevelil.MediumLevelILFunction):self.handle=core.BNCreateMediumLevelILDisassemblyTextRenderer(func.handle,settings_obj)elifisinstance(func,highlevelil.HighLevelILFunction):self.handle=core.BNCreateHighLevelILDisassemblyTextRenderer(func.handle,settings_obj)else:raiseTypeError("invalid function object")else:self.handle=handle def__del__(self):ifcoreisnotNone:core.BNFreeDisassemblyTextRenderer(self.handle)@propertydeffunction(self)->'Function':returnFunction(handle=core.BNGetDisassemblyTextRendererFunction(self.handle))@propertydefil_function(self)->Optional[ILFunctionType]:llil=core.BNGetDisassemblyTextRendererLowLevelILFunction(self.handle)ifllil:returnlowlevelil.LowLevelILFunction(handle=llil)mlil=core.BNGetDisassemblyTextRendererMediumLevelILFunction(self.handle)ifmlil:returnmediumlevelil.MediumLevelILFunction(handle=mlil)hlil=core.BNGetDisassemblyTextRendererHighLevelILFunction(self.handle)ifhlil:returnhighlevelil.HighLevelILFunction(handle=hlil)returnNone@propertydefbasic_block(self)->Optional['basicblock.BasicBlock']:result=core.BNGetDisassemblyTextRendererBasicBlock(self.handle)ifresult:returnbasicblock.BasicBlock._from_core_block(handle=result)returnNone@basic_block.setterdefbasic_block(self,block:Optional['basicblock.BasicBlock'])->None:ifblockisnotNone:core.BNSetDisassemblyTextRendererBasicBlock(self.handle,block.handle)else:core.BNSetDisassemblyTextRendererBasicBlock(self.handle,None)@propertydefarch(self)->'architecture.Architecture':returnarchitecture.CoreArchitecture._from_cache(handle=core.BNGetDisassemblyTextRendererArchitecture(self.handle))@arch.setterdefarch(self,arch:'architecture.Architecture')->None:core.BNSetDisassemblyTextRendererArchitecture(self.handle,arch.handle)@propertydefsettings(self)->'DisassemblySettings':returnDisassemblySettings(handle=core.BNGetDisassemblyTextRendererSettings(self.handle))@settings.setterdefsettings(self,settings:Optional['DisassemblySettings'])->None:ifsettingsisnotNone:core.BNSetDisassemblyTextRendererSettings(self.handle,settings.handle)else:core.BNSetDisassemblyTextRendererSettings(self.handle,None)@propertydefil(self)->bool:returncore.BNIsILDisassemblyTextRenderer(self.handle)@propertydefhas_data_flow(self)->bool:returncore.BNDisassemblyTextRendererHasDataFlow(self.handle)[docs]defget_instruction_annotations(self,addr:int)->List['InstructionTextToken']:count=ctypes.c_ulonglong()tokens=core.BNGetDisassemblyTextRendererInstructionAnnotations(self.handle,addr,count)asserttokensisnotNone,"core.BNGetDisassemblyTextRendererInstructionAnnotations returned None"result=InstructionTextToken._from_core_struct(tokens,count.value)core.BNFreeInstructionText(tokens,count.value)returnresult [docs]defget_instruction_text(self,addr:int)->Generator[Tuple[Optional['DisassemblyTextLine'],int],None,None]:count=ctypes.c_ulonglong()length=ctypes.c_ulonglong()lines=ctypes.POINTER(core.BNDisassemblyTextLine)()ifnotcore.BNGetDisassemblyTextRendererInstructionText(self.handle,addr,length,lines,count):yieldNone,0returnil_function=self.il_functiontry:foriinrange(0,count.value):addr=lines[i].addrif(lines[i].instrIndex!=0xffffffffffffffff)and(il_functionisnotNone):il_instr=il_function[lines[i].instrIndex]else:il_instr=Nonecolor=_highlight.HighlightColor._from_core_struct(lines[i].highlight)tokens=InstructionTextToken._from_core_struct(lines[i].tokens,lines[i].count)yieldDisassemblyTextLine(tokens,addr,il_instr,color),length.valuefinally:core.BNFreeDisassemblyTextLines(lines,count.value) [docs]defget_disassembly_text(self,addr:int)->Generator[Tuple[Optional['DisassemblyTextLine'],int],None,None]:count=ctypes.c_ulonglong()length=ctypes.c_ulonglong()length.value=0lines=ctypes.POINTER(core.BNDisassemblyTextLine)()ok=core.BNGetDisassemblyTextRendererLines(self.handle,addr,length,lines,count)ifnotok:yieldNone,0returnil_function=self.il_functiontry:foriinrange(0,count.value):addr=lines[i].addrif(lines[i].instrIndex!=0xffffffffffffffff)and(il_functionisnotNone):il_instr=il_function[lines[i].instrIndex]else:il_instr=Nonecolor=_highlight.HighlightColor._from_core_struct(lines[i].highlight)tokens=InstructionTextToken._from_core_struct(lines[i].tokens,lines[i].count)yieldDisassemblyTextLine(tokens,addr,il_instr,color),length.valuefinally:core.BNFreeDisassemblyTextLines(lines,count.value) [docs]defpost_process_lines(self,addr:int,length:int,in_lines:Union[str,List[str],List['DisassemblyTextLine']],indent_spaces:str=''):ifisinstance(in_lines,str):in_lines=in_lines.split('\n')line_buf=(core.BNDisassemblyTextLine*len(in_lines))()fori,lineinenumerate(in_lines):ifisinstance(line,str):line=DisassemblyTextLine([InstructionTextToken(InstructionTextTokenType.TextToken,line)])ifnotisinstance(line,DisassemblyTextLine):line=DisassemblyTextLine(line)ifline.addressisNone:iflen(line.tokens)>0:line_buf[i].addr=line.tokens[0].addresselse:line_buf[i].addr=0else:line_buf[i].addr=line.addressifline.il_instructionisnotNone:line_buf[i].instrIndex=line.il_instruction.instr_indexelse:line_buf[i].instrIndex=0xffffffffffffffffcolor=line.highlightifnotisinstance(color,HighlightStandardColor)andnotisinstance(color,_highlight.HighlightColor):raiseValueError("Specified color is not one of HighlightStandardColor, _highlight.HighlightColor")ifisinstance(color,HighlightStandardColor):color=_highlight.HighlightColor(color)line_buf[i].highlight=color._to_core_struct()line_buf[i].count=len(line.tokens)line_buf[i].tokens=InstructionTextToken._get_core_struct(line.tokens)count=ctypes.c_ulonglong()lines=core.BNPostProcessDisassemblyTextRendererLines(self.handle,addr,length,line_buf,len(in_lines),count,indent_spaces)assertlinesisnotNone,"core.BNPostProcessDisassemblyTextRendererLines returned None"il_function=self.il_functiontry:foriinrange(count.value):addr=lines[i].addrif(lines[i].instrIndex!=0xffffffffffffffff)and(il_functionisnotNone):il_instr=il_function[lines[i].instrIndex]else:il_instr=Nonecolor=_highlight.HighlightColor._from_core_struct(lines[i].highlight)tokens=InstructionTextToken._from_core_struct(lines[i].tokens,lines[i].count)yieldDisassemblyTextLine(tokens,addr,il_instr,color)finally:core.BNFreeDisassemblyTextLines(lines,count.value) [docs]defreset_deduplicated_comments(self)->None:core.BNResetDisassemblyTextRendererDeduplicatedComments(self.handle) [docs]defadd_symbol_token(self,tokens:List['InstructionTextToken'],addr:int,size:int,operand:Optional[int]=None)->bool:ifoperandisNone:operand=0xffffffffcount=ctypes.c_ulonglong()new_tokens=ctypes.POINTER(core.BNInstructionTextToken)()ifnotcore.BNGetDisassemblyTextRendererSymbolTokens(self.handle,addr,size,operand,new_tokens,count):returnFalseassertnew_tokensisnotNoneresult=InstructionTextToken._from_core_struct(new_tokens,count.value)tokens+=resultcore.BNFreeInstructionText(new_tokens,count.value)returnTrue [docs]defadd_stack_var_reference_tokens(self,tokens:List['InstructionTextToken'],ref:'variable.StackVariableReference')->None:stack_ref=core.BNStackVariableReference()ifref.source_operandisNone:stack_ref.sourceOperand=0xffffffffelse:stack_ref.sourceOperand=ref.source_operandifref.typeisNone:stack_ref.type=Nonestack_ref.typeConfidence=0else:stack_ref.type=ref.type.handlestack_ref.typeConfidence=ref.type.confidencestack_ref.name=ref.namestack_ref.varIdentifier=ref.var.identifierstack_ref.referencedOffset=ref.referenced_offsetstack_ref.size=ref.sizecount=ctypes.c_ulonglong()new_tokens=core.BNGetDisassemblyTextRendererStackVariableReferenceTokens(self.handle,stack_ref,count)assertnew_tokensisnotNoneresult=InstructionTextToken._from_core_struct(new_tokens,count.value)tokens+=resultcore.BNFreeInstructionText(new_tokens,count.value) [docs]@staticmethoddefis_integer_token(token:'InstructionTextToken')->bool:returncore.BNIsIntegerToken(token.type) [docs]defadd_integer_token(self,tokens:List['InstructionTextToken'],int_token:'InstructionTextToken',addr:int,arch:Optional['architecture.Architecture']=None)->None:ifarchisnotNone:arch=arch.handlein_token_obj=InstructionTextToken._get_core_struct([int_token])count=ctypes.c_ulonglong()new_tokens=core.BNGetDisassemblyTextRendererIntegerTokens(self.handle,in_token_obj,arch,addr,count)assertnew_tokensisnotNoneresult=InstructionTextToken._from_core_struct(new_tokens,count.value)tokens+=resultcore.BNFreeInstructionText(new_tokens,count.value) [docs]defwrap_comment(self,lines:List['DisassemblyTextLine'],cur_line:'DisassemblyTextLine',comment:str,has_auto_annotations:bool,leading_spaces:str=" ",indent_spaces:str="")->None:cur_line_obj=core.BNDisassemblyTextLine()cur_line_obj.addr=cur_line.addressifcur_line.il_instructionisNone:cur_line_obj.instrIndex=0xffffffffffffffffelse:cur_line_obj.instrIndex=cur_line.il_instruction.instr_indexcur_line_obj.highlight=cur_line.highlight._to_core_struct()cur_line_obj.tokens=InstructionTextToken._get_core_struct(cur_line.tokens)cur_line_obj.count=len(cur_line.tokens)count=ctypes.c_ulonglong()new_lines=core.BNDisassemblyTextRendererWrapComment(self.handle,cur_line_obj,count,comment,has_auto_annotations,leading_spaces,indent_spaces)assertnew_linesisnotNone,"core.BNDisassemblyTextRendererWrapComment returned None"il_function=self.il_functionforiinrange(0,count.value):addr=new_lines[i].addrif(new_lines[i].instrIndex!=0xffffffffffffffff)and(il_functionisnotNone):il_instr=il_function[new_lines[i].instrIndex]else:il_instr=Nonecolor=_highlight.HighlightColor._from_core_struct(new_lines[i].highlight)tokens=InstructionTextToken._from_core_struct(new_lines[i].tokens,new_lines[i].count)lines.append(DisassemblyTextLine(tokens,addr,il_instr,color))core.BNFreeDisassemblyTextLines(new_lines,count.value)