Source code for binaryninja.types

# 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.importctypesimporttypingfromtypingimportGenerator,List,Union,Tuple,Optional,Iterable,Dict,Generic,TypeVar,Callablefromdataclassesimportdataclassimportuuid# Binary Ninja componentsfrom.import_binaryninjacoreascorefrom.enumsimport(StructureVariant,SymbolType,SymbolBinding,TypeClass,NamedTypeReferenceClass,ReferenceType,VariableSourceType,TypeReferenceType,MemberAccess,MemberScope,TypeDefinitionLineType,TokenEscapingType,NameType,PointerSuffix,PointerBaseType)from.importcallingconventionfrom.importfunctionas_functionfrom.importvariablefrom.importarchitecturefrom.importbinaryviewfrom.importplatformas_platformfrom.importtypecontainerfrom.importtypelibraryfrom.importtypeparserQualifiedNameType=Union[Iterable[Union[str,bytes]],str,'QualifiedName']BoolWithConfidenceType=Union[bool,'BoolWithConfidence']OffsetWithConfidenceType=Union[int,'OffsetWithConfidence']ParamsType=Union[List['Type'],List['FunctionParameter'],List[Tuple[str,'Type']]]MembersType=Union[List['StructureMember'],List['Type'],List[Tuple['Type',str]]]EnumMembersType=Union[List[Tuple[str,int]],List[str],List['EnumerationMember']]SomeType=Union['TypeBuilder','Type']TypeContainerType=Union['binaryview.BinaryView','typelibrary.TypeLibrary']NameSpaceType=Optional[Union[str,List[str],'NameSpace']]TypeParserResult=typeparser.TypeParserResultBasicTypeParserResult=typeparser.BasicTypeParserResultResolveMemberCallback=Callable[['NamedTypeReferenceType','StructureType',int,int,int,'StructureMember'],None]# The following are needed to prevent the type checker from getting# confused as we have member functions in `Type` named the same thing_int=int_bool=boolMemberName=strMemberIndex=intMemberOffset=intTB=TypeVar('TB',bound='TypeBuilder')
[docs]defconvert_integer(value:ctypes.c_uint64,signed:bool,width:int)->int:ifwidthnotin[1,2,4,8]:raiseValueError("Width must be 1, 2, 4, or 8 bytes")func={True:{1:ctypes.c_int8,2:ctypes.c_int16,4:ctypes.c_int32,8:ctypes.c_int64},False:{1:ctypes.c_uint8,2:ctypes.c_uint16,4:ctypes.c_uint32,8:ctypes.c_uint64}}returnfunc[bool(signed)][width](value).value
[docs]classQualifiedName:
[docs]def__init__(self,name:Optional[QualifiedNameType]=None):self._name:List[str]=[]ifisinstance(name,str):self._name=[name]elifisinstance(name,bytes):self._name=[name.decode("utf-8")]elifisinstance(name,self.__class__):self._name=name._nameelifisinstance(name,(list,tuple)):foriinname:ifisinstance(i,bytes):self._name.append(i.decode("utf-8"))else:self._name.append(str(i))
def__str__(self):return"::".join(self.name)def__repr__(self):returnrepr(str(self))def__len__(self):returnlen(self.name)def__eq__(self,other):ifisinstance(other,str):returnstr(self)==otherelifisinstance(other,list):returnself.name==otherelifisinstance(other,self.__class__):returnself.name==other.namereturnNotImplementeddef__ne__(self,other):ifisinstance(other,str):returnstr(self)!=otherelifisinstance(other,list):returnself.name!=otherelifisinstance(other,self.__class__):returnself.name!=other.namereturnNotImplementeddef__lt__(self,other):ifisinstance(other,self.__class__):returnself.name<other.namereturnNotImplementeddef__le__(self,other):ifisinstance(other,self.__class__):returnself.name<=other.namereturnNotImplementeddef__gt__(self,other):ifisinstance(other,self.__class__):returnself.name>other.namereturnNotImplementeddef__ge__(self,other):ifisinstance(other,self.__class__):returnself.name>=other.namereturnNotImplementeddef__hash__(self):returnhash(str(self))def__getitem__(self,key):returnself.name[key]def__iter__(self):returniter(self.name)def_to_core_struct(self)->core.BNQualifiedName:result=core.BNQualifiedName()name_list=(ctypes.c_char_p*len(self.name))()foriinrange(0,len(self.name)):name_list[i]=self.name[i].encode("utf-8")result.name=name_listresult.nameCount=len(self.name)result.join="::".encode("utf-8")returnresult@staticmethoddef_from_core_struct(name):result=[]foriinrange(0,name.nameCount):result.append(name.name[i].decode("utf-8"))returnQualifiedName(result)@propertydefname(self)->List[str]:returnself._name@name.setterdefname(self,value:List[str])->None:self._name=value
[docs]@staticmethoddefescape(name:QualifiedNameType,escaping:TokenEscapingType)->str:returncore.BNEscapeTypeName(str(QualifiedName(name)),escaping)
[docs]@staticmethoddefunescape(name:QualifiedNameType,escaping:TokenEscapingType)->str:returncore.BNUnescapeTypeName(str(QualifiedName(name)),escaping)
[docs]@dataclass(frozen=True)classTypeReferenceSource:name:QualifiedNameoffset:intref_type:TypeReferenceTypedef__repr__(self):ifself.ref_type==TypeReferenceType.DirectTypeReferenceType:s='direct'elifself.ref_type==TypeReferenceType.IndirectTypeReferenceType:s='indirect'else:s='unknown'return'<type%s, offset 0x%x,%s>'%(self.name,self.offset,s)
[docs]classNameSpace(QualifiedName):def__str__(self):return":".join(self.name)def_to_core_struct(self)->core.BNNameSpace:result=core.BNNameSpace()name_list=(ctypes.c_char_p*len(self.name))()foriinrange(0,len(self.name)):name_list[i]=self.name[i].encode('charmap')result.name=name_listresult.nameCount=len(self.name)returnresult@staticmethoddef_from_core_struct(name:core.BNNameSpace)->'NameSpace':result=[]foriinrange(0,name.nameCount):result.append(name.name[i].decode("utf-8"))returnNameSpace(result)
[docs]@staticmethoddefget_core_struct(name:Optional[Union[str,List[str],'NameSpace']])->Optional[core.BNNameSpace]:ifnameisNone:returnNoneifisinstance(name,NameSpace):returnname._to_core_struct()else:returnNameSpace(name)._to_core_struct()
[docs]@dataclass(frozen=True)classTypeDefinitionLine:line_type:TypeDefinitionLineTypetokens:List['_function.InstructionTextToken']type:'Type'parent_type:'Type'root_type:'Type'root_type_name:strbase_type:Optional['NamedTypeReferenceType']base_offset:intoffset:intfield_index:intdef__str__(self):return"".join(map(str,self.tokens))def__repr__(self):returnf"<typeDefinitionLine{self.type}:{self}>"@staticmethoddef_from_core_struct(struct:core.BNTypeDefinitionLine,platform:Optional[_platform.Platform]=None):tokens=_function.InstructionTextToken._from_core_struct(struct.tokens,struct.count)type_=Type.create(handle=core.BNNewTypeReference(struct.type),platform=platform)parent_type=Type.create(handle=core.BNNewTypeReference(struct.parentType),platform=platform)root_type=Type.create(handle=core.BNNewTypeReference(struct.rootType),platform=platform)root_type_name=core.pyNativeStr(struct.rootTypeName)ifstruct.baseType:const_conf=BoolWithConfidence.get_core_struct(False,0)volatile_conf=BoolWithConfidence.get_core_struct(False,0)handle=core.BNCreateNamedTypeReference(struct.baseType,0,1,const_conf,volatile_conf)base_type=NamedTypeReferenceType(handle,platform)else:base_type=NonereturnTypeDefinitionLine(struct.lineType,tokens,type_,parent_type,root_type,root_type_name,base_type,struct.baseOffset,struct.offset,struct.fieldIndex)def_to_core_struct(self):struct=core.BNTypeDefinitionLine()struct.lineType=self.line_typestruct.tokens=_function.InstructionTextToken._get_core_struct(self.tokens)struct.count=len(self.tokens)struct.type=core.BNNewTypeReference(self.type.handle)struct.parentType=core.BNNewTypeReference(self.parent_type.handle)struct.rootType=core.BNNewTypeReference(self.root_type.handle)struct.rootTypeName=self.root_type_nameifself.base_typeisNone:struct.baseType=Noneelse:struct.baseType=core.BNNewNamedTypeReference(self.base_type.ntr_handle)struct.baseOffset=self.base_offsetstruct.offset=self.offsetstruct.fieldIndex=self.field_indexreturnstruct
[docs]classCoreSymbol:
[docs]def__init__(self,handle:core.BNSymbolHandle):self._handle=handle
def__del__(self):ifcoreisnotNone:core.BNFreeSymbol(self._handle)def__repr__(self):try:returnf"<{self.type.name}:\"{self.full_name}\" @{self.address:#x}>"exceptUnicodeDecodeError:returnf"<{self.type.name}:\"{self.raw_bytes}\" @{self.address:#x}>"def__eq__(self,other):ifnotisinstance(other,self.__class__):returnNotImplementedreturnctypes.addressof(self._handle.contents)==ctypes.addressof(other._handle.contents)def__ne__(self,other):ifnotisinstance(other,self.__class__):returnNotImplementedreturnnot(self==other)def__hash__(self):returnhash(ctypes.addressof(self._handle.contents))@propertydeftype(self)->SymbolType:"""Symbol type (read-only)"""returnSymbolType(core.BNGetSymbolType(self._handle))@propertydefbinding(self)->SymbolBinding:"""Symbol binding (read-only)"""returnSymbolBinding(core.BNGetSymbolBinding(self._handle))@propertydefnamespace(self)->'NameSpace':"""Symbol namespace (read-only)"""ns=core.BNGetSymbolNameSpace(self._handle)result=NameSpace._from_core_struct(ns)core.BNFreeNameSpace(ns)returnresult@propertydefname(self)->str:"""Symbol name (read-only)"""returncore.BNGetSymbolRawName(self._handle)@propertydefshort_name(self)->str:"""Symbol short name (read-only)"""returncore.BNGetSymbolShortName(self._handle)@propertydeffull_name(self)->str:"""Symbol full name (read-only)"""returncore.BNGetSymbolFullName(self._handle)@propertydefraw_name(self)->str:"""Symbol raw name (read-only)"""returncore.BNGetSymbolRawName(self._handle)@propertydefraw_bytes(self)->bytes:"""Bytes of the raw symbol (read-only)"""count=ctypes.c_ulonglong()result=core.BNGetSymbolRawBytes(self._handle,count)assertresultisnotNone,"core.BNGetSymbolRawBytes returned None"buf=ctypes.create_string_buffer(count.value)ctypes.memmove(buf,result,count.value)core.BNFreeSymbolRawBytes(result)returnbuf.raw@propertydefaddress(self)->int:"""Symbol address (read-only)"""returncore.BNGetSymbolAddress(self._handle)@propertydefordinal(self)->int:"""Symbol ordinal (read-only)"""returncore.BNGetSymbolOrdinal(self._handle)@propertydefauto(self)->bool:"""Whether the symbol was auto-defined"""returncore.BNIsSymbolAutoDefined(self._handle)@propertydefhandle(self):returnself._handle
[docs]defimported_function_from_import_address_symbol(self,addr:int)->Optional['CoreSymbol']:sym=core.BNImportedFunctionFromImportAddressSymbol(self._handle,addr)ifsymisNone:returnNonereturnCoreSymbol(sym)
[docs]classSymbol(CoreSymbol):"""Symbols are defined as one of the following types:=========================== =================================================================SymbolType Description=========================== =================================================================FunctionSymbol Symbol for function that exists in the current binaryImportAddressSymbol Symbol defined in the Import Address TableImportedFunctionSymbol Symbol for a function that is not defined in the current binaryDataSymbol Symbol for data in the current binaryImportedDataSymbol Symbol for data that is not defined in the current binaryExternalSymbol Symbols for data and code that reside outside the BinaryViewLibraryFunctionSymbol Symbols for functions identified as belonging to a shared librarySymbolicFunctionSymbol Symbols for functions without a concrete implementation or which have been abstractly representedLocalLabelSymbol Symbol for a local label in the current binary=========================== ================================================================="""
[docs]def__init__(self,sym_type,addr,short_name,full_name=None,raw_name=None,binding=None,namespace=None,ordinal=0):ifisinstance(sym_type,str):sym_type=SymbolType[sym_type]iffull_nameisNone:full_name=short_nameifraw_nameisNone:raw_name=full_nameifbindingisNone:binding=SymbolBinding.NoBinding_namespace=NameSpace.get_core_struct(namespace)_handle=core.BNCreateSymbol(sym_type,short_name,full_name,raw_name,addr,binding,_namespace,ordinal)assert_handleisnotNone,"core.BNCreateSymbol return None"super(Symbol,self).__init__(_handle)
[docs]@dataclassclassFunctionParameter:type:SomeTypename:str=""location:Optional['variable.VariableNameAndType']=Nonedef__repr__(self):if(self.locationisnotNone)and(self.location.name!=self.name):returnf"{self.type.immutable_copy().get_string_before_name()}{self.name}{self.type.immutable_copy().get_string_after_name()} @{self.location.name}"returnf"{self.type.immutable_copy().get_string_before_name()}{self.name}{self.type.immutable_copy().get_string_after_name()}"
[docs]defimmutable_copy(self)->'FunctionParameter':returnFunctionParameter(self.type.immutable_copy(),self.name,self.location)
[docs]defmutable_copy(self)->'FunctionParameter':returnFunctionParameter(self.type.mutable_copy(),self.name,self.location)
[docs]@dataclass(frozen=True)classOffsetWithConfidence:value:intconfidence:int=core.max_confidencedef__int__(self):returnself.valuedef__eq__(self,other):ifnotisinstance(other,self.__class__):returnself.value==int(other)else:return(self.value,self.confidence)==(other.value,other.confidence)def__ne__(self,other):returnnot(self==other)def__gt__(self,other):returnself.value>int(other)def__le__(self,other):returnself.value<=int(other)def__ge__(self,other):returnself.value>=int(other)def__lt__(self,other):returnself.value<int(other)def_to_core_struct(self)->core.BNOffsetWithConfidence:result=core.BNOffsetWithConfidence()result.value=self.valueresult.confidence=self.confidencereturnresult
[docs]@classmethoddeffrom_core_struct(cls,core_struct:core.BNOffsetWithConfidence)->'OffsetWithConfidence':returncls(core_struct.value,core_struct.confidence)
[docs]@staticmethoddefget_core_struct(value:OffsetWithConfidenceType,confidence:int=core.max_confidence)->core.BNOffsetWithConfidence:ifisinstance(value,OffsetWithConfidence):returnvalue._to_core_struct()else:returnOffsetWithConfidence(value,confidence)._to_core_struct()
[docs]@dataclass(frozen=True)classBoolWithConfidence:value:boolconfidence:int=core.max_confidencedef__eq__(self,other):ifnotisinstance(other,self.__class__):returnself.value==bool(other)else:return(self.value,self.confidence)==(other.value,other.confidence)def__ne__(self,other):returnnot(self==other)def__bool__(self):returnself.valuedef_to_core_struct(self)->core.BNBoolWithConfidence:result=core.BNBoolWithConfidence()result.value=self.valueresult.confidence=self.confidencereturnresult
[docs]@classmethoddeffrom_core_struct(cls,core_struct:core.BNBoolWithConfidence)->'BoolWithConfidence':returncls(core_struct.value,core_struct.confidence)
[docs]@staticmethoddefget_core_struct(value:Union[BoolWithConfidenceType,bool],confidence:int=core.max_confidence)->core.BNBoolWithConfidence:ifisinstance(value,BoolWithConfidence):returnvalue._to_core_struct()else:returnBoolWithConfidence(value,confidence)._to_core_struct()
[docs]@dataclassclassMutableTypeBuilder(Generic[TB]):type:TBcontainer:TypeContainerTypename:QualifiedNameplatform:Optional['_platform.Platform']confidence:intuser:bool=Truedef__enter__(self)->TB:returnself.typedef__exit__(self,type,value,traceback):ifisinstance(self.container,binaryview.BinaryView):ifself.user:self.container.define_user_type(self.name,self.type.immutable_copy())else:type_id=Type.generate_auto_type_id(str(uuid.uuid4()),str(self.name))self.container.define_type(type_id,self.name,self.type.immutable_copy())else:self.container.add_named_type(self.name,self.type.immutable_copy())
[docs]classTypeBuilderAttributes(dict):
[docs]def__init__(self,builder,*args):super(TypeBuilderAttributes,self).__init__(*args)self._builder=builder
def__setitem__(self,key:str,value:str):ifnotisinstance(key,str):raiseTypeError("Type attribute key must be a string")ifnotisinstance(value,str):raiseTypeError("Type attribute value must be a string")core.BNSetTypeBuilderAttribute(self._builder._handle,key,value)super(TypeBuilderAttributes,self).__setitem__(key,value)def__delitem__(self,key:str):ifnotisinstance(key,str):raiseTypeError("Type attribute key must be a string")core.BNRemoveTypeBuilderAttribute(self._builder._handle,key)super(TypeBuilderAttributes,self).__delitem__(key)
[docs]classTypeBuilder:"""All TypeBuilder objects should not be instantiated directly but created via ``.create`` APIs."""
[docs]def__init__(self,handle:core.BNTypeBuilderHandle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):assertisinstance(handle,core.BNTypeBuilderHandle),"handle isn't an instance of BNTypeBuilderHandle"self._handle=handleself.platform=platformself.confidence=confidence
def__del__(self):ifcoreisnotNone:core.BNFreeTypeBuilder(self._handle)def__eq__(self,other:'TypeBuilder')->bool:ifnotisinstance(other,TypeBuilder):raiseValueError(f"Unable compare equality of TypeBuilder and{type(other)}")returnself.immutable_copy()==other.immutable_copy()def__ne__(self,other:'TypeBuilder')->bool:returnnotself.__eq__(other)def__repr__(self):returnf"<type: mutable:{self.type_class.name} '{self}'>"def__str__(self):returnstr(self.immutable_copy())@propertydefhandle(self)->core.BNTypeHandle:returnself.immutable_copy().handledef__hash__(self):returnhash(ctypes.addressof(self.handle.contents))def_to_core_struct(self)->core.BNTypeWithConfidence:type_conf=core.BNTypeWithConfidence()type_conf.type=self.handletype_conf.confidence=self.confidencereturntype_conf
[docs]defimmutable_copy(self):Types={TypeClass.VoidTypeClass:VoidType,TypeClass.BoolTypeClass:BoolType,TypeClass.IntegerTypeClass:IntegerType,TypeClass.FloatTypeClass:FloatType,TypeClass.PointerTypeClass:PointerType,TypeClass.ArrayTypeClass:ArrayType,TypeClass.FunctionTypeClass:FunctionType,TypeClass.WideCharTypeClass:WideCharType,TypeClass.StructureTypeClass:StructureType,TypeClass.EnumerationTypeClass:EnumerationType,TypeClass.NamedTypeReferenceClass:NamedTypeReferenceType,}returnTypes[self.type_class](self._finalized,self.platform,self.confidence)
[docs]defmutable_copy(self)->'TypeBuilder':returnself
[docs]@classmethoddefcreate(cls):_=clsreturnNotImplemented
[docs]@classmethoddefbuilder(cls:typing.Type[TB],container:TypeContainerType,name:'QualifiedName',user:bool=True,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'MutableTypeBuilder[TB]':returnMutableTypeBuilder(cls.create(),container,name,platform,confidence,user)
[docs]@staticmethoddefvoid()->'VoidBuilder':returnVoidBuilder.create()
[docs]@staticmethoddefbool()->'BoolBuilder':returnBoolBuilder.create()
[docs]@staticmethoddefchar(alternate_name:str="")->'CharBuilder':returnCharBuilder.create(alternate_name)
[docs]@staticmethoddefint(width:_int,sign:BoolWithConfidenceType=BoolWithConfidence(True),altname:str="")->'IntegerBuilder':"""``int`` class method for creating an int Type.:param int width: width of the integer in bytes:param bool sign: optional variable representing signedness:param str altname: alternate name for type"""returnIntegerBuilder.create(width,sign,altname)
[docs]@staticmethoddeffloat(width:_int,altname:str="")->'FloatBuilder':"""``float`` class method for creating floating point Types.:param int width: width of the floating point number in bytes:param str altname: alternate name for type"""returnFloatBuilder.create(width,altname)
[docs]@staticmethoddefwide_char(width:_int,altname:str="")->'WideCharBuilder':"""``wide_char`` class method for creating wide char Types.:param int width: width of the wide character in bytes:param str altname: alternate name for type"""returnWideCharBuilder.create(width,altname)
[docs]@staticmethoddefnamed_type_from_type(name:QualifiedNameType,type_class:Optional[NamedTypeReferenceClass]=None)->'NamedTypeReferenceBuilder':returnNamedTypeReferenceBuilder.named_type_from_type(name,type_class)
[docs]@staticmethoddefnamed_type_from_type_and_id(type_id:str,name:QualifiedNameType,type:Optional['Type']=None)->'NamedTypeReferenceBuilder':returnNamedTypeReferenceBuilder.named_type_from_type_and_id(type_id,name,type)
[docs]@staticmethoddefnamed_type_from_registered_type(view:'binaryview.BinaryView',name:QualifiedName)->'NamedTypeReferenceBuilder':returnNamedTypeReferenceBuilder.named_type_from_registered_type(view,name)
[docs]@staticmethoddefpointer(arch:'architecture.Architecture',type:'Type',const:BoolWithConfidenceType=BoolWithConfidence(False),volatile:BoolWithConfidenceType=BoolWithConfidence(False),ref_type:ReferenceType=ReferenceType.PointerReferenceType)->'PointerBuilder':returnPointerBuilder.create(type,arch.address_size,arch,const,volatile,ref_type)
[docs]@staticmethoddefpointer_of_width(width:_int,type:'Type',const:BoolWithConfidenceType=BoolWithConfidence(False),volatile:BoolWithConfidenceType=BoolWithConfidence(False),ref_type:ReferenceType=ReferenceType.PointerReferenceType)->'PointerBuilder':returnPointerBuilder.create(type,width,None,const,volatile,ref_type)
[docs]@staticmethoddefarray(type:'Type',count:_int)->'ArrayBuilder':returnArrayBuilder.create(type,count)
[docs]@staticmethoddeffunction(ret:Optional['Type']=None,params:Optional[ParamsType]=None,calling_convention:Optional['callingconvention.CallingConvention']=None,variable_arguments:Optional[BoolWithConfidenceType]=None,stack_adjust:Optional[OffsetWithConfidenceType]=None)->'FunctionBuilder':"""``function`` class method for creating a function Type.:param Type ret: return Type of the function:param params: list of parameter Types:type params: list(Type):param CallingConvention calling_convention: optional argument for the function calling convention:param bool variable_arguments: optional boolean, true if the function has a variable number of arguments"""returnFunctionBuilder.create(ret,calling_convention,params,variable_arguments,stack_adjust)
[docs]@staticmethoddefstructure(members:Optional[MembersType]=None,packed:_bool=False,type:StructureVariant=StructureVariant.StructStructureType)->'StructureBuilder':returnStructureBuilder.create(members,type=type,packed=packed)
[docs]@staticmethoddefunion(members:Optional[MembersType]=None,packed:_bool=False)->'StructureBuilder':returnStructureBuilder.create(members,type=StructureVariant.UnionStructureType,packed=packed)
[docs]@staticmethoddefclass_type(members:Optional[MembersType]=None,packed:_bool=False)->'StructureBuilder':returnStructureBuilder.create(members,type=StructureVariant.ClassStructureType,packed=packed)
[docs]@staticmethoddefenumeration(arch:Optional['architecture.Architecture']=None,members:Optional[EnumMembersType]=None,width:Optional[_int]=None,sign:BoolWithConfidenceType=BoolWithConfidence(False))->'EnumerationBuilder':returnEnumerationBuilder.create(members,width,arch,sign)
[docs]@staticmethoddefnamed_type_reference(type_class:NamedTypeReferenceClass,name:QualifiedName,type_id:Optional[str]=None,alignment:_int=1,width:_int=0,const:BoolWithConfidenceType=BoolWithConfidence(False),volatile:BoolWithConfidenceType=BoolWithConfidence(False))->'NamedTypeReferenceBuilder':returnNamedTypeReferenceBuilder.create(type_class,type_id,name,width,alignment,None,core.max_confidence,const,volatile)
@propertydefwidth(self)->_int:returncore.BNGetTypeBuilderWidth(self._handle)@width.setterdefwidth(self,value:_int):core.BNTypeBuilderSetWidth(self._handle,value)def__len__(self):returnself.width@propertydef_finalized(self):type_handle=core.BNFinalizeTypeBuilder(self._handle)asserttype_handleisnotNone,"core.BNFinalizeTypeBuilder returned None"returntype_handle@propertydefconst(self)->BoolWithConfidence:"""Whether type is const (read/write)"""result=core.BNIsTypeBuilderConst(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@const.setterdefconst(self,value:BoolWithConfidenceType)->None:# We explicitly allow 'set' type to be different than 'get' typecore.BNTypeBuilderSetConst(self._handle,BoolWithConfidence.get_core_struct(value))@propertydefvolatile(self)->BoolWithConfidence:"""Whether type is volatile (read/write)"""result=core.BNIsTypeBuilderVolatile(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@volatile.setterdefvolatile(self,value:BoolWithConfidenceType)->None:# We explicitly allow 'set' type to be different than 'get' typecore.BNTypeBuilderSetVolatile(self._handle,BoolWithConfidence.get_core_struct(value))@propertydefalignment(self)->_int:returncore.BNGetTypeBuilderAlignment(self._handle)@alignment.setterdefalignment(self,alignment:_int):core.BNTypeBuilderSetAlignment(self._handle,alignment)@propertydefchild(self)->'Type':type_conf=core.BNGetTypeBuilderChildType(self._handle)asserttype_confisnotNone,"core.BNGetTypeBuilderChildType returned None"returnType.create(type_conf.type,self.platform,type_conf.confidence)@child.setterdefchild(self,value:SomeType)->None:core.BNTypeBuilderSetChildType(self._handle,value.immutable_copy()._to_core_struct())@propertydefalternate_name(self)->Optional[str]:returncore.BNGetTypeBuilderAlternateName(self._handle)@alternate_name.setterdefalternate_name(self,name:str)->None:core.BNTypeBuilderSetAlternateName(self._handle,name)@propertydefsystem_call_number(self)->Optional[_int]:"""Gets/Sets the system call number for a FunctionType object if one exists otherwise None"""ifnotcore.BNTypeBuilderIsSystemCall(self._handle):returnNonereturncore.BNTypeBuilderGetSystemCallNumber(self._handle)@system_call_number.setterdefsystem_call_number(self,value:_int)->None:core.BNTypeBuilderSetSystemCallNumber(self._handle,True,value)
[docs]defclear_system_call(self)->None:core.BNTypeBuilderSetSystemCallNumber(self._handle,False,0)
@propertydeftype_class(self)->TypeClass:returnTypeClass(core.BNGetTypeBuilderClass(self._handle))@propertydefsigned(self)->BoolWithConfidence:returnBoolWithConfidence.from_core_struct(core.BNIsTypeBuilderSigned(self._handle))@signed.setterdefsigned(self,value:BoolWithConfidenceType)->None:_value=BoolWithConfidence.get_core_struct(value)core.BNTypeBuilderSetSigned(self._handle,_value)@propertydefchildren(self)->List['TypeBuilder']:return[]@propertydefattributes(self)->Dict[str,str]:"""Attribute names and their values"""count=ctypes.c_ulonglong()attributes=core.BNGetTypeBuilderAttributes(self._handle,count)result=dict()foriinrange(count.value):result[attributes[i].name]=attributes[i].valuecore.BNFreeTypeAttributeList(attributes,count.value)returnTypeBuilderAttributes(self,result)@attributes.setterdefattributes(self,values:Dict[str,str])->None:ifnotisinstance(values,dict):raiseTypeError("Attributes must be a dictionary")attributes=(core.BNTypeAttribute*len(values))()i=0forname,valueinvalues.items():ifnotisinstance(name,str):raiseTypeError("Attribute names must be strings")ifnotisinstance(value,str):raiseTypeError("Attribute values must be strings")attributes[i].name=nameattributes[i].value=valuei+=1core.BNSetTypeBuilderAttributeList(self._handle,attributes,len(values))
[docs]classVoidBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'VoidBuilder':handle=core.BNCreateVoidTypeBuilder()asserthandleisnotNone,"core.BNCreateVoidTypeBuilder returned None"returncls(handle,platform,confidence)
[docs]classBoolBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'BoolBuilder':handle=core.BNCreateBoolTypeBuilder()asserthandleisnotNone,"core.BNCreateBoolTypeBuilder returned None"returncls(handle,platform,confidence)
[docs]classIntegerBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,width:int,sign:BoolWithConfidenceType=True,alternate_name:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'IntegerBuilder':_sign=BoolWithConfidence.get_core_struct(sign)handle=core.BNCreateIntegerTypeBuilder(width,_sign,alternate_name)asserthandleisnotNone,"core.BNCreateIntegerTypeBuilder returned None"returncls(handle,platform,confidence)
[docs]classCharBuilder(IntegerBuilder):
[docs]@classmethoddefcreate(cls,alternate_name:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'CharBuilder':handle=core.BNCreateIntegerTypeBuilder(1,BoolWithConfidence.get_core_struct(False),alternate_name)asserthandleisnotNone,"BNCreateIntegerTypeBuilder returned None"returncls(handle,platform,confidence)
[docs]classFloatBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,width:int,alternate_name:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'FloatBuilder':handle=core.BNCreateFloatTypeBuilder(width,alternate_name)asserthandleisnotNone,"core.BNCreateFloatTypeBuilder returned None"returncls(handle,platform,confidence)
[docs]classWideCharBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,width:int,alternate_name:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'WideCharBuilder':handle=core.BNCreateWideCharTypeBuilder(width,alternate_name)asserthandleisnotNone,"core.BNCreateWideCharTypeBuilder returned None"returncls(handle,platform,confidence)
[docs]classPointerBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,type:'Type',width:int=4,arch:Optional['architecture.Architecture']=None,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False,ref_type:ReferenceType=ReferenceType.PointerReferenceType,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'PointerBuilder':ifwidthisnotNone:_width=widthelifarchisnotNone:_width=arch.address_sizeelse:raiseValueError("Must specify either a width or architecture when creating a pointer")_const=BoolWithConfidence.get_core_struct(const)_volatile=BoolWithConfidence.get_core_struct(volatile)handle=core.BNCreatePointerTypeBuilderOfWidth(_width,type._to_core_struct(),_const,_volatile,ref_type)asserthandleisnotNone,"BNCreatePointerTypeBuilderOfWidth returned None"returncls(handle,platform,confidence)
@propertydeftarget(self)->'TypeBuilder':returnself.immutable_target.mutable_copy()@propertydefimmutable_target(self)->'Type':returnself.child@propertydefchildren(self)->List[TypeBuilder]:return[self.target]@propertydefoffset(self)->int:""" Currently not used and has no effect (Leaving this in for compatibility)"""returncore.BNGetTypeBuilderOffset(self._handle)@offset.setterdefoffset(self,offset:int)->None:core.BNSetTypeBuilderOffset(self._handle,offset)@propertydeforigin(self)->Optional[Tuple['QualifiedName',int]]:ntr_handle=core.BNGetTypeBuilderNamedTypeReference(self._handle)ifntr_handleisNone:returnNonename=core.BNGetTypeReferenceName(ntr_handle)core.BNFreeNamedTypeReference(ntr_handle)ifnameisNone:returnNoneqn=QualifiedName._from_core_struct(name)core.BNFreeQualifiedName(name)return(qn,self.offset)@origin.setterdeforigin(self,origin:'NamedTypeReferenceType'):core.BNSetTypeBuilderNamedTypeReference(self._handle,origin.ntr_handle)@propertydefpointer_suffix(self)->List[PointerSuffix]:"""Pointer suffix, e.g. __unaligned is [UnalignedSuffix] (read-only)"""count=ctypes.c_size_t(0)suffix=core.BNGetTypeBuilderPointerSuffix(self._handle,count)assertsuffixisnotNone,"core.BNGetTypeBuilderPointerSuffix returned None"try:result=[]foriinrange(count.value):result.append(PointerSuffix(suffix[i]))returnresultfinally:core.BNFreePointerSuffixList(suffix,count)@pointer_suffix.setterdefpointer_suffix(self,value:List[PointerSuffix]):suffix=(core.PointerSuffixEnum*len(value))()fori,sinenumerate(value):suffix[i]=core.PointerSuffixEnum(s)core.BNSetTypeBuilderPointerSuffix(self._handle,suffix,len(value))
[docs]defadd_pointer_suffix(self,suffix:PointerSuffix):"""Append a suffix to the pointer, must be one defined in :py:class:`PointerSuffix`.:param suffix: New suffix"""core.BNAddTypeBuilderPointerSuffix(self._handle,suffix)
@propertydefpointer_suffix_string(self)->str:"""Pointer suffix, but as a string, e.g. "__unaligned" (read-only)"""returncore.BNGetTypeBuilderPointerSuffixString(self._handle)
[docs]defget_pointer_suffix_tokens(self,base_confidence:int=core.max_confidence)->List['_function.InstructionTextToken']:"""Get the pointer suffix, as a list of tokens:param base_confidence: (optional) Confidence value to combine with the pointer's confidence:return: Token list"""count=ctypes.c_ulonglong()tokens=core.BNGetTypeBuilderPointerSuffixTokens(self._handle,base_confidence,count)asserttokensisnotNone,"core.BNGetTypeBuilderPointerSuffixTokens returned None"result=_function.InstructionTextToken._from_core_struct(tokens,count.value)core.BNFreeInstructionText(tokens,count.value)returnresult
[docs]defset_pointer_base(self,base_type:PointerBaseType,base_offset:int):"""Set the pointer base type and offset:param base_type: Base type, e.g. __based(start) is RelativeToBinaryStartPointerBaseType:param base_offset: Base offset, e.g. __based(start, 0x1000) is 0x1000"""core.BNSetTypeBuilderPointerBase(self._handle,base_type,base_offset)
@propertydefpointer_base_type(self)->PointerBaseType:"""Pointer base type, e.g. __based(start) is RelativeToBinaryStartPointerBaseType"""returnPointerBaseType(core.BNTypeBuilderGetPointerBaseType(self._handle))@pointer_base_type.setterdefpointer_base_type(self,value:PointerBaseType):self.set_pointer_base(value,self.pointer_base_offset)@propertydefpointer_base_offset(self)->int:"""Pointer base offset, e.g. __based(start, 0x1000) is 0x1000"""returncore.BNTypeBuilderGetPointerBaseOffset(self._handle)@pointer_base_offset.setterdefpointer_base_offset(self,value:int):self.set_pointer_base(self.pointer_base_type,value)
[docs]classArrayBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,type:SomeType,element_count:int,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'ArrayBuilder':handle=core.BNCreateArrayTypeBuilder(type._to_core_struct(),element_count)asserthandleisnotNone,"BNCreateArrayTypeBuilder returned None"returncls(handle,platform,confidence)
@propertydefcount(self)->int:returncore.BNGetTypeBuilderElementCount(self._handle)@propertydefelement_type(self)->TypeBuilder:returnself.child.mutable_copy()@propertydefchildren(self)->List[TypeBuilder]:return[self.element_type]
[docs]classFunctionBuilder(TypeBuilder):
[docs]@classmethoddefcreate(cls,return_type:Optional[SomeType]=None,calling_convention:Optional['callingconvention.CallingConvention']=None,params:Optional[ParamsType]=None,var_args:Optional[BoolWithConfidenceType]=None,stack_adjust:Optional[OffsetWithConfidenceType]=None,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,can_return:Optional[BoolWithConfidence]=None,reg_stack_adjust:Optional[Dict['architecture.RegisterName',OffsetWithConfidenceType]]=None,return_regs:Optional[Union['RegisterSet',List['architecture.RegisterType']]]=None,name_type:'NameType'=NameType.NoNameType,pure:Optional[BoolWithConfidence]=None)->'FunctionBuilder':param_buf=FunctionBuilder._to_core_struct(params)ifreturn_typeisNone:ret_conf=Type.void()._to_core_struct()else:ret_conf=return_type._to_core_struct()conv_conf=core.BNCallingConventionWithConfidence()ifcalling_conventionisNone:conv_conf.convention=Noneconv_conf.confidence=0else:conv_conf.convention=calling_convention.handleconv_conf.confidence=calling_convention.confidenceifreg_stack_adjustisNone:reg_stack_adjust={}reg_stack_adjust_regs=(ctypes.c_uint32*len(reg_stack_adjust))()reg_stack_adjust_values=(core.BNOffsetWithConfidence*len(reg_stack_adjust))()fori,(reg,adjust)inenumerate(reg_stack_adjust.items()):reg_stack_adjust_regs[i]=regreg_stack_adjust_values[i].value=adjust.valuereg_stack_adjust_values[i].confidence=adjust.confidencereturn_regs_set=core.BNRegisterSetWithConfidence()ifreturn_regsisNoneorplatformisNone:return_regs_set.count=0return_regs_set.confidence=0else:return_regs_set.count=len(return_regs)return_regs_set.confidence=255return_regs_set.regs=(ctypes.c_uint32*len(return_regs))()fori,reginenumerate(return_regs):return_regs_set[i]=platform.arch.get_reg_index(reg)ifvar_argsisNone:vararg_conf=BoolWithConfidence.get_core_struct(False,0)else:vararg_conf=BoolWithConfidence.get_core_struct(var_args,core.max_confidence)ifcan_returnisNone:can_return_conf=BoolWithConfidence.get_core_struct(True,0)else:can_return_conf=BoolWithConfidence.get_core_struct(can_return,core.max_confidence)ifpureisNone:pure_conf=BoolWithConfidence.get_core_struct(False,0)else:pure_conf=BoolWithConfidence.get_core_struct(pure,core.max_confidence)ifstack_adjustisNone:stack_adjust_conf=OffsetWithConfidence.get_core_struct(0,0)else:stack_adjust_conf=OffsetWithConfidence.get_core_struct(stack_adjust,core.max_confidence)ifparamsisNone:params=[]handle=core.BNCreateFunctionTypeBuilder(ret_conf,conv_conf,param_buf,len(params),vararg_conf,can_return_conf,stack_adjust_conf,reg_stack_adjust_regs,reg_stack_adjust_values,len(reg_stack_adjust),return_regs_set,name_type,pure_conf)asserthandleisnotNone,"BNCreateFunctionTypeBuilder returned None"returncls(handle,platform,confidence)
@propertydefimmutable_return_value(self)->'Type':returnself.child@propertydefreturn_value(self)->TypeBuilder:returnself.child.mutable_copy()@return_value.setterdefreturn_value(self,value:SomeType)->None:self.child=value
[docs]defappend(self,type:Union[SomeType,FunctionParameter],name:str=""):ifisinstance(type,FunctionParameter):self.parameters=[*self.parameters,type]else:self.parameters=[*self.parameters,FunctionParameter(type,name)]
@propertydefcalling_convention(self)->'callingconvention.CallingConvention':cc=core.BNGetTypeBuilderCallingConvention(self._handle)returncallingconvention.CallingConvention(handle=core.BNNewCallingConventionReference(cc.convention))@propertydefcan_return(self)->BoolWithConfidence:returnBoolWithConfidence.from_core_struct(core.BNFunctionTypeBuilderCanReturn(self._handle))@can_return.setterdefcan_return(self,value:BoolWithConfidenceType)->None:core.BNSetFunctionTypeBuilderCanReturn(self._handle,BoolWithConfidence.get_core_struct(value))@propertydefpure(self)->BoolWithConfidence:returnBoolWithConfidence.from_core_struct(core.BNIsTypeBuilderPure(self._handle))@pure.setterdefpure(self,value:BoolWithConfidenceType)->None:core.BNSetTypeBuilderPure(self._handle,BoolWithConfidence.get_core_struct(value))@propertydefstack_adjust(self)->OffsetWithConfidence:returnOffsetWithConfidence.from_core_struct(core.BNGetTypeBuilderStackAdjustment(self._handle))@propertydefstack_adjustment(self)->OffsetWithConfidence:returnOffsetWithConfidence.from_core_struct(core.BNGetTypeBuilderStackAdjustment(self._handle))@stack_adjustment.setterdefstack_adjustment(self,value:OffsetWithConfidenceType)->None:ifisinstance(value,int):_value=OffsetWithConfidence(value)else:_value=valuecore.BNTypeBuilderSetStackAdjustment(self._handle,_value._to_core_struct())@propertydefparameters(self)->List[FunctionParameter]:"""Type parameters list (read-only)"""count=ctypes.c_ulonglong()params=core.BNGetTypeBuilderParameters(self._handle,count)assertparamsisnotNone,"core.BNGetTypeBuilderParameters returned None"result=[]foriinrange(0,count.value):param_type=Type.create(core.BNNewTypeReference(params[i].type),platform=self.platform,confidence=params[i].typeConfidence)ifparams[i].defaultLocation:param_location=Noneelse:name=params[i].nameif(params[i].location.type==VariableSourceType.RegisterVariableSourceType)and(self.platformisnotNone):name=self.platform.arch.get_reg_name(params[i].location.storage)elifparams[i].location.type==VariableSourceType.StackVariableSourceType:name="arg_%x"%params[i].location.storageparam_location=variable.VariableNameAndType(params[i].location.type,params[i].location.index,params[i].location.storage,name,param_type)result.append(FunctionParameter(param_type,params[i].name,param_location))core.BNFreeTypeParameterList(params,count.value)returnresult@propertydefvariable_arguments(self)->BoolWithConfidence:returnBoolWithConfidence.from_core_struct(core.BNTypeBuilderHasVariableArguments(self._handle))@staticmethoddef_to_core_struct(params:Optional[ParamsType]=None):ifparamsisNone:params=[]param_buf=(core.BNFunctionParameter*len(params))()fori,paraminenumerate(params):core_param=param_buf[i]ifisinstance(param,(Type,TypeBuilder)):assertparam.handleisnotNone,"Attempting to construct function parameter without properly constructed type"core_param.name=""core_param.type=param.handlecore_param.typeConfidence=param.confidencecore_param.defaultLocation=Trueelifisinstance(param,FunctionParameter):assertparam.typeisnotNone,"Attempting to construct function parameter without properly constructed type"core_param.name=param.namecore_param.type=param.type.handlecore_param.typeConfidence=param.type.confidenceifparam.locationisNone:core_param.defaultLocation=Trueelse:core_param.defaultLocation=Falsecore_param.location.type=param.location.source_typecore_param.location.index=param.location.indexcore_param.location.storage=param.location.storageelifisinstance(param,tuple):name,_type=paramifnotisinstance(name,str)ornotisinstance(_type,(Type,TypeBuilder)):raiseValueError(f"Conversion from unsupported function parameter type{type(param)}")core_param.name=namecore_param.type=_type.handlecore_param.typeConfidence=_type.confidencecore_param.defaultLocation=Trueelse:raiseValueError(f"Conversion from unsupported function parameter type{type(param)}")returnparam_buf@parameters.setterdefparameters(self,params:List[FunctionParameter])->None:core.BNSetFunctionTypeBuilderParameters(self._handle,FunctionBuilder._to_core_struct(params),len(params))@propertydefchildren(self)->List[TypeBuilder]:return[self.child.mutable_copy(),*[param.type.mutable_copy()forparaminself.parameters]]
[docs]@dataclassclassStructureMember:type:'Type'name:stroffset:int# Offset (in bytes) from the start of the structure. Use `bit_offset` for bitwise fields.access:MemberAccess=MemberAccess.NoAccessscope:MemberScope=MemberScope.NoScopebit_position:int=0# Relative to the starting byte at `offset`, must be in range 0 to 7.bit_width:int=0@propertydefbit_offset(self)->int:"""Total bit offset from the start of the structure.Computed as: offset * 8 + bit_position."""return(self.offset*8)+self.bit_position@bit_offset.setterdefbit_offset(self,value:int)->None:"""Set the total bit offset from the start of the structure.This will automatically set: - offset to value // 8 (byte offset) - bit_position to value % 8 (bit within the byte offset)"""ifvalue<0:raiseValueError("bit_offset must be non-negative")self.offset=value//8self.bit_position=value%8def__repr__(self):iflen(self.name)==0:base=f"<member:{self.type}, offset{self.offset:#x}>"else:base=f"<{self.type.get_string_before_name()}{self.name}{self.type.get_string_after_name()}, offset{self.offset:#x}>"# Append bit position/width only if bit_width is not zero (indicates a bitfield)ifself.bit_width!=0:returnbase[:-1]+f", bit{self.bit_position}:{self.bit_width}>"returnbasedef__len__(self):returnlen(self.type)
[docs]@dataclassclassInheritedStructureMember:base:'NamedTypeReferenceType'base_offset:intmember:StructureMembermember_index:intdef__repr__(self):ifself.baseisNone:returnf"<member index{self.member_index}:{repr(self.member)}>"returnf"<inherited from{self.base.name} @{self.base_offset:#x} index{self.member_index}:{repr(self.member)}>"def__len__(self):returnlen(self.member.type)
[docs]@dataclassclassBaseStructure:type:'NamedTypeReferenceType'offset:intwidth:int
[docs]def__init__(self,type:Union['NamedTypeReferenceType','StructureType'],offset:int,width:int=0):ifisinstance(type,StructureType):iftype.registered_nameisNone:raiseValueError("StructureType must be registered to be used as a base structure")self.type=type.registered_nameself.offset=offsetself.width=type.widthelse:self.type=typeself.offset=offsetself.width=width
def__repr__(self):returnf"<base:{repr(self.type)}, offset{self.offset:#x}, width:{self.width:#x}>"def_to_core_struct(self):result=core.BNBaseStructure()result.type=self.type.ntr_handleresult.offset=self.offsetresult.width=self.widthreturnresult@staticmethoddef_from_core_struct(core_obj:core.BNBaseStructure,platform:Optional['_platform.Platform']=None):const_conf=BoolWithConfidence.get_core_struct(False,0)volatile_conf=BoolWithConfidence.get_core_struct(False,0)handle=core.BNCreateNamedTypeReference(core_obj.type,0,1,const_conf,volatile_conf)returnBaseStructure(NamedTypeReferenceType(handle,platform),core_obj.offset,core_obj.width)
[docs]classStructureBuilder(TypeBuilder):
[docs]def__init__(self,handle:core.BNTypeBuilderHandle,builder_handle:core.BNStructureBuilderHandle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):super(StructureBuilder,self).__init__(handle,platform,confidence)assertbuilder_handleisnotNone,"Can't instantiate Structure with builder_handle set to None"self.builder_handle=builder_handle
@staticmethoddef_add_members_to_builder(structure_builder_handle,members:Optional[MembersType])->None:ifmembersisNone:members=[]formemberinmembers:ifisinstance(member,Tuple):_type,_name=membercore.BNAddStructureBuilderMember(structure_builder_handle,_type._to_core_struct(),_name,MemberAccess.NoAccess,MemberScope.NoScope)elifisinstance(member,StructureMember):core.BNAddStructureBuilderMemberAtOffset(structure_builder_handle,member.type._to_core_struct(),member.name,member.offset,False,member.access,member.scope,member.bit_position,member.bit_width)elifisinstance(member,(TypeBuilder,Type)):core.BNAddStructureBuilderMember(structure_builder_handle,member._to_core_struct(),"",MemberAccess.NoAccess,MemberScope.NoScope)else:raiseValueError(f"Structure member type{member} not supported")def_add_members(self,members):StructureBuilder._add_members_to_builder(self.builder_handle,members)
[docs]@classmethoddefcreate(cls,members:Optional[MembersType]=None,type:StructureVariant=StructureVariant.StructStructureType,packed:bool=False,width:Optional[int]=None,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'StructureBuilder':structure_builder_handle=core.BNCreateStructureBuilderWithOptions(type,packed)assertstructure_builder_handleisnotNone,"core.BNCreateStructureBuilderWithOptions returned None"ifwidthisnotNone:core.BNSetStructureBuilderWidth(structure_builder_handle,width)StructureBuilder._add_members_to_builder(structure_builder_handle,members)type_builder_handle=core.BNCreateStructureTypeBuilderWithBuilder(structure_builder_handle)asserttype_builder_handleisnotNone,"core.BNCreateStructureTypeBuilderWithBuilder returned None"returncls(type_builder_handle,structure_builder_handle,platform,confidence)
@propertydefmembers(self)->List[StructureMember]:"""Structure member list (read-only)"""count=ctypes.c_ulonglong()members=core.BNGetStructureBuilderMembers(self.builder_handle,count)assertmembersisnotNone,"core.BNGetStructureBuilderMembers returned None"try:result=[]foriinrange(0,count.value):t=Type.create(core.BNNewTypeReference(members[i].type),confidence=members[i].typeConfidence)result.append(StructureMember(t,members[i].name,members[i].offset,MemberAccess(members[i].access),MemberScope(members[i].scope),members[i].bitPosition,members[i].bitWidth))returnresultfinally:core.BNFreeStructureMemberList(members,count.value)@members.setterdefmembers(self,members:Optional[MembersType]=None)->None:count=len(self.members)# remove members in reverse orderforiinreversed(range(count)):self.remove(i)self._add_members(members)@propertydefbase_structures(self)->List[BaseStructure]:"""Base structure list. Offsets that are not defined by this structure will be filled in by the fields of the base structure(s)."""count=ctypes.c_ulonglong()bases=core.BNGetBaseStructuresForStructureBuilder(self.builder_handle,count)try:result=[]foriinrange(0,count.value):result.append(BaseStructure._from_core_struct(bases[i],self.platform))returnresultfinally:core.BNFreeBaseStructureList(bases,count.value)@base_structures.setterdefbase_structures(self,value:List[BaseStructure])->None:bases=(core.BNBaseStructure*len(value))()foriinrange(0,len(value)):bases[i]=value[i]._to_core_struct()core.BNSetBaseStructuresForStructureBuilder(self.builder_handle,bases,len(value))@propertydefpacked(self)->bool:returncore.BNIsStructureBuilderPacked(self.builder_handle)@packed.setterdefpacked(self,value:bool)->None:core.BNSetStructureBuilderPacked(self.builder_handle,value)@propertydefalignment(self)->int:returncore.BNGetStructureBuilderAlignment(self.builder_handle)@alignment.setterdefalignment(self,value:int)->None:core.BNSetStructureBuilderAlignment(self.builder_handle,value)@propertydefwidth(self)->int:returncore.BNGetStructureBuilderWidth(self.builder_handle)@width.setterdefwidth(self,value:int)->None:core.BNSetStructureBuilderWidth(self.builder_handle,value)@propertydefpointer_offset(self)->int:returncore.BNGetStructureBuilderPointerOffset(self.builder_handle)@pointer_offset.setterdefpointer_offset(self,value:int)->None:core.BNSetStructureBuilderPointerOffset(self.builder_handle,value)@propertydefunion(self)->bool:returncore.BNIsStructureBuilderUnion(self.builder_handle)@propertydefpropagate_data_var_refs(self)->bool:returncore.BNStructureBuilderPropagatesDataVariableReferences(self.builder_handle)@propagate_data_var_refs.setterdefpropagate_data_var_refs(self,value:bool)->None:core.BNSetStructureBuilderPropagatesDataVariableReferences(self.builder_handle,value)@propertydeftype(self)->StructureVariant:returnStructureVariant(core.BNGetStructureBuilderType(self.builder_handle))@type.setterdeftype(self,value:StructureVariant)->None:core.BNSetStructureBuilderType(self.builder_handle,value)def__getitem__(self,name:str)->Optional[StructureMember]:member=core.BNGetStructureBuilderMemberByName(self.builder_handle,name)ifmemberisNone:returnNonetry:returnStructureMember(Type.create(core.BNNewTypeReference(member.contents.type),confidence=member.contents.typeConfidence),member.contents.name,member.contents.offset,MemberAccess(member.contents.access),MemberScope(member.contents.scope),member.contents.bitPosition,member.contents.bitWidth)finally:core.BNFreeStructureMember(member)def__iter__(self)->Generator[StructureMember,None,None]:formemberinself.members:yieldmemberdef__len__(self)->int:returnself.width
[docs]defmember_at_offset(self,offset:int)->Optional[StructureMember]:formemberinself.members:ifmember.offset==offset:returnmemberreturnNone
[docs]defindex_by_name(self,name:MemberName)->Optional[MemberIndex]:fori,memberinenumerate(self.members):ifmember.name==name:returnireturnNone
[docs]defindex_by_offset(self,offset:MemberOffset)->Optional[MemberIndex]:fori,memberinenumerate(self.members):ifmember.offset==offset:returnireturnNone
[docs]defreplace(self,index:int,type:SomeType,name:str="",overwrite_existing:bool=True):core.BNReplaceStructureBuilderMember(self.builder_handle,index,type._to_core_struct(),name,overwrite_existing)
[docs]defremove(self,index:int):core.BNRemoveStructureBuilderMember(self.builder_handle,index)
[docs]definsert(self,offset:int,type:SomeType,name:str="",overwrite_existing:bool=True,access:MemberAccess=MemberAccess.NoAccess,scope:MemberScope=MemberScope.NoScope,bit_position:int=0,bit_width:int=0):core.BNAddStructureBuilderMemberAtOffset(self.builder_handle,type._to_core_struct(),name,offset,overwrite_existing,access,scope,bit_position,bit_width)
[docs]defappend(self,type:SomeType,name:MemberName="",access:MemberAccess=MemberAccess.NoAccess,scope:MemberScope=MemberScope.NoScope)->'StructureBuilder':# appends a member at the end of the structure growing the structurecore.BNAddStructureBuilderMember(self.builder_handle,type._to_core_struct(),name,access,scope)returnself
[docs]defadd_member_at_offset(self,name:MemberName,type:SomeType,offset:MemberOffset,overwrite_existing:bool=True,access:MemberAccess=MemberAccess.NoAccess,scope:MemberScope=MemberScope.NoScope,bit_position:int=0,bit_width:int=0)->'StructureBuilder':# Adds structure member to the given offset optionally clearing any members within the range offset-offset+len(type)core.BNAddStructureBuilderMemberAtOffset(self.builder_handle,type._to_core_struct(),name,offset,overwrite_existing,access,scope,bit_position,bit_width)returnself
@propertydefchildren(self)->List[TypeBuilder]:return[member.type.mutable_copy()formemberinself.members]
[docs]@dataclass(frozen=True)classEnumerationMember:name:strvalue:Optional[int]=Nonedef__repr__(self):value=f"{self.value:#x}"ifself.valueisnotNoneelse"auto()"returnf"<{self.name} ={value}>"def__int__(self)->Optional[int]:returnself.value
[docs]classEnumerationBuilder(TypeBuilder):
[docs]def__init__(self,handle:core.BNTypeBuilderHandle,enum_builder_handle:core.BNEnumerationBuilderHandle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):super(EnumerationBuilder,self).__init__(handle,platform,confidence)assertisinstance(enum_builder_handle,core.BNEnumerationBuilderHandle)self.enum_builder_handle=enum_builder_handle
[docs]@classmethoddefcreate(cls,members:Optional[EnumMembersType]=None,width:Optional[int]=None,arch:Optional['architecture.Architecture']=None,sign:BoolWithConfidenceType=False,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'EnumerationBuilder':ifmembersisNone:members=[]ifwidthisNoneorwidth==0:_width=4ifarchisNoneelsearch.default_int_sizeelse:_width=width_sign=BoolWithConfidence.get_core_struct(sign)enum_builder_handle=core.BNCreateEnumerationBuilder()assertenum_builder_handleisnotNone,"core.BNCreateEnumerationBuilder returned None"EnumerationBuilder._add_members(enum_builder_handle,members)type_builder_handle=core.BNCreateEnumerationTypeBuilderWithBuilder(None,enum_builder_handle,_width,_sign)asserttype_builder_handleisnotNone,"core.BNCreateEnumerationTypeBuilderWithBuilder returned None"returncls(type_builder_handle,enum_builder_handle,platform,confidence)
@propertydefmembers(self)->List[EnumerationMember]:"""Enumeration member list (read-only)"""count=ctypes.c_ulonglong()members=core.BNGetEnumerationBuilderMembers(self.enum_builder_handle,count)assertmembersisnotNone,"core.BNGetEnumerationBuilderMembers returned None"result=[]try:foriinrange(count.value):value=convert_integer(members[i].value,self.signed,self.width)result.append(EnumerationMember(members[i].name,valueifnotmembers[i].isDefaultelseNone))returnresultfinally:core.BNFreeEnumerationMemberList(members,count.value)@members.setterdefmembers(self,members:EnumMembersType)->None:foriinreversed(range(len(self.members))):self.remove(i)EnumerationBuilder._add_members(self.enum_builder_handle,members)@staticmethoddef_add_members(enum_builder_handle,members:EnumMembersType):fori,memberinenumerate(members):value=Noneifisinstance(member,Tuple):name,value=memberelifisinstance(member,EnumerationMember):name=member.namevalue=member.valueelse:ifnotisinstance(member,str):raiseValueError(f"Member type{member} not supported")name=memberifvalueisNone:core.BNAddEnumerationBuilderMember(enum_builder_handle,name)else:core.BNAddEnumerationBuilderMemberWithValue(enum_builder_handle,name,value)
[docs]defappend(self,name:str,value:Optional[int]=None)->'EnumerationBuilder':EnumerationBuilder._add_members(self.enum_builder_handle,[EnumerationMember(name,value)])returnself
[docs]defremove(self,i:int)->'EnumerationBuilder':core.BNRemoveEnumerationBuilderMember(self.enum_builder_handle,i)returnself
[docs]defreplace(self,i:int,name:str,value:int)->'EnumerationBuilder':core.BNReplaceEnumerationBuilderMember(self.enum_builder_handle,i,name,value)returnself
def__iter__(self)->Generator[EnumerationMember,None,None]:formemberinself.members:yieldmemberdef__getitem__(self,value:Union[str,int,slice]):ifisinstance(value,str):formemberinself.members:ifmember.name==value:returnmemberreturnNoneelifisinstance(value,int):returnself.members[value]elifisinstance(value,slice):# not combined with the previous check due to pyright bugreturnself.members[value]else:raiseValueError(f"Incompatible type{type(value)} for __getitem__")def__setitem__(self,item:Union[str,int],value:Union[Optional[int],EnumerationMember]):ifisinstance(item,str):fori,memberinenumerate(self.members):ifmember.name==item:self.replace(i,member.name,value)elifisinstance(item,int)andisinstance(value,EnumerationMember):self.replace(item,value.name,value.value)else:raiseValueError("Invalid type for Enumeration.__setitem__")
[docs]classNamedTypeReferenceBuilder(TypeBuilder):
[docs]def__init__(self,handle:core.BNTypeBuilderHandle,ntr_builder_handle:core.BNNamedTypeReferenceBuilderHandle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):assertntr_builder_handleisnotNone,"Failed to construct NameTypeReference"asserthandleisnotNone,"Failed to construct NameTypeReference"assertisinstance(ntr_builder_handle,core.BNNamedTypeReferenceBuilderHandle),"Failed to construct NameTypeReference"super(NamedTypeReferenceBuilder,self).__init__(handle,platform,confidence)self.ntr_builder_handle=ntr_builder_handle
[docs]@classmethoddefcreate(cls,type_class:NamedTypeReferenceClass=NamedTypeReferenceClass.UnknownNamedTypeClass,type_id:Optional[str]=None,name:QualifiedNameType="",width:int=0,align:int=1,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False)->'NamedTypeReferenceBuilder':ifnotisinstance(type_class,NamedTypeReferenceClass):raiseValueError("named_type_class must be a NamedTypeReferenceClass")ntr_builder_handle=core.BNCreateNamedTypeBuilder(type_class,type_id,QualifiedName(name)._to_core_struct())assertntr_builder_handleisnotNone,"core.BNCreateNamedTypeBuilder returned None"_const=BoolWithConfidence.get_core_struct(const)_volatile=BoolWithConfidence.get_core_struct(volatile)type_builder_handle=core.BNCreateNamedTypeReferenceBuilderWithBuilder(ntr_builder_handle,width,align,_const,_volatile)asserttype_builder_handleisnotNone,"core.BNCreateNamedTypeReferenceBuilderWithBuilder returned None"returncls(type_builder_handle,ntr_builder_handle,platform,confidence)
@propertydefname(self)->QualifiedName:returnQualifiedName._from_core_struct(core.BNGetTypeReferenceBuilderName(self.ntr_builder_handle))@propertydefid(self)->str:returncore.BNGetTypeReferenceBuilderId(self.ntr_builder_handle)@propertydeftype_id(self)->str:returncore.BNGetTypeReferenceBuilderId(self.ntr_builder_handle)@propertydefnamed_type_class(self)->NamedTypeReferenceClass:returnNamedTypeReferenceClass(core.BNGetTypeReferenceBuilderClass(self.ntr_builder_handle))
[docs]@staticmethoddefnamed_type(named_type:'NamedTypeReferenceBuilder',width:int=0,align:int=1,const:BoolWithConfidenceType=BoolWithConfidence(False),volatile:BoolWithConfidenceType=BoolWithConfidence(False))->'NamedTypeReferenceBuilder':returnNamedTypeReferenceBuilder.create(named_type.named_type_class,named_type.id,named_type.name,width,align,None,core.max_confidence,const,volatile)
[docs]@staticmethoddefnamed_type_from_type_and_id(type_id:str,name:QualifiedNameType,type:Optional['Type']=None)->'NamedTypeReferenceBuilder':iftypeisNone:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.UnknownNamedTypeClass,type_id,name)eliftype.type_class==TypeClass.StructureTypeClass:iftype.type==StructureVariant.StructStructureType:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.StructNamedTypeClass,type_id,name)eliftype.type==StructureVariant.UnionStructureType:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.UnionNamedTypeClass,type_id,name)else:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.ClassNamedTypeClass,type_id,name)eliftype.type_class==TypeClass.EnumerationTypeClass:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.EnumNamedTypeClass,type_id,name)else:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.TypedefNamedTypeClass,type_id,name)
[docs]@staticmethoddefnamed_type_from_type(name:QualifiedNameType,type_class:Optional[NamedTypeReferenceClass]=None)->'NamedTypeReferenceBuilder':iftype_classisNone:returnNamedTypeReferenceBuilder.create(NamedTypeReferenceClass.UnknownNamedTypeClass,str(uuid.uuid4()),name)else:returnNamedTypeReferenceBuilder.create(type_class,str(uuid.uuid4()),name)
[docs]@staticmethoddefnamed_type_from_registered_type(view:'binaryview.BinaryView',name:QualifiedNameType)->'NamedTypeReferenceBuilder':type=view.get_type_by_name(name)iftypeisNone:raiseValueError(f"Unable to find type named{name}")returnNamedTypeReferenceBuilder.named_type_from_type_and_id(type_id=str(uuid.uuid4()),name=name,type=type)
def__repr__(self):ifself.named_type_class==NamedTypeReferenceClass.TypedefNamedTypeClass:returnf"<type: mutable:{self.type_class.name} 'typedef{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.StructNamedTypeClass:returnf"<type: mutable:{self.type_class.name} 'struct{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.UnionNamedTypeClass:returnf"<type: mutable:{self.type_class.name} 'union{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.ClassNamedTypeClass:returnf"<type: mutable:{self.type_class.name} 'class{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.EnumNamedTypeClass:returnf"<type: mutable:{self.type_class.name} 'enum{self.name}'>"else:returnf"<type: mutable:{self.type_class.name} 'unknown'>"
[docs]classType:"""``class Type`` allows you to interact with the Binary Ninja type system. Note that the ``repr`` and ``str``handlers respond differently on type objects.Other related functions that may be helpful include::py:meth:`parse_type_string <binaryview.BinaryView.parse_type_string>`:py:meth:`parse_types_from_source <platform.Platform.parse_types_from_source>`:py:meth:`parse_types_from_source_file <platform.Platform.parse_types_from_source_file>`"""
[docs]def__init__(self,handle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):assertisinstance(handle.contents,core.BNType),"Attempting to create mutable Type"ifself.__class__==Type:raiseException("Cannot instantiate Type directly use Type.create instead")self._handle=handleself._confidence=confidenceself._platform=platformself._type_class=Noneself._width=Noneself._alignment=Noneself._offset=None
[docs]@classmethoddefcreate(cls,handle:core.BNTypeHandle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'Type':asserthandleisnotNone,"Passed a handle which is None"assertisinstance(handle,core.BNTypeHandle)type_class=TypeClass(core.BNGetTypeClass(handle))returnTypes[type_class](handle,platform,confidence)
def__del__(self):ifcoreisnotNone:core.BNFreeType(self._handle)def__repr__(self):ifself._confidence<core.max_confidence:returnf"<type: immutable:{self.type_class.name} '{self}',{self._confidence*100//core.max_confidence}% confidence>"returnf"<type: immutable:{self.type_class.name} '{self}'>"def__str__(self):returnself.get_string()def__len__(self):returnself.widthdef__eq__(self,other):ifnotisinstance(other,self.__class__):returnNotImplementedreturncore.BNTypesEqual(self._handle,other._handle)def__ne__(self,other):ifnotisinstance(other,self.__class__):returnNotImplementedreturncore.BNTypesNotEqual(self._handle,other._handle)def__hash__(self):returnhash(ctypes.addressof(self.handle.contents))@propertydefhandle(self):returnself._handle@propertydeftype_class(self)->TypeClass:"""Type class (read-only)"""ifself._type_classisNone:self._type_class=TypeClass(core.BNGetTypeClass(self._handle))returnself._type_class@propertydefwidth(self)->int:"""Type width (read-only)"""ifself._widthisNone:self._width=core.BNGetTypeWidth(self._handle)returnself._width@propertydefalignment(self)->int:"""Type alignment (read-only)"""ifself._alignmentisNone:self._alignment=core.BNGetTypeAlignment(self._handle)returnself._alignment@propertydefoffset(self)->int:"""Offset into structure (read-only)"""ifself._offsetisNone:self._offset=core.BNGetTypeOffset(self._handle)returnself._offset@propertydefaltname(self)->str:"""Alternative name for the type object"""returncore.BNGetTypeAlternateName(self._handle)@propertydefattributes(self)->Dict[str,str]:"""Attribute names and their values"""count=ctypes.c_ulonglong()attributes=core.BNGetTypeAttributes(self._handle,count)result=dict()foriinrange(count.value):result[attributes[i].name]=attributes[i].valuecore.BNFreeTypeAttributeList(attributes,count.value)returnresultdef_to_core_struct(self)->core.BNTypeWithConfidence:type_conf=core.BNTypeWithConfidence()type_conf.type=self._handletype_conf.confidence=self.confidencereturntype_conf
[docs]defget_string(self,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->str:"""Get string representation for this type:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: String for type:rtype: str:Example:>>> Type.array(Type.int(4), 10).get_string()'int32_t[0xa]'"""platform=Noneifself._platformisnotNone:platform=self._platform.handlereturncore.BNGetTypeString(self._handle,platform,escaping)
[docs]defget_string_before_name(self,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->str:"""Get the string to be printed before this type's name in a representation of it:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: String for type representation before the name:rtype: str:Example:>>> Type.array(Type.int(4), 10).get_string()'int32_t[0xa]'>>> Type.array(Type.int(4), 10).get_string_before_name()'int32_t'"""platform=Noneifself._platformisnotNone:platform=self._platform.handlereturncore.BNGetTypeStringBeforeName(self._handle,platform,escaping)
[docs]defget_string_after_name(self,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->str:"""Get the string to be printed after this type's name in a representation:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: String for type representation after the name:rtype: str:Example:>>> Type.array(Type.int(4), 10).get_string()'int32_t[0xa]'>>> Type.array(Type.int(4), 10).get_string_after_name()'[0xa]'"""platform=Noneifself._platformisnotNone:platform=self._platform.handlereturncore.BNGetTypeStringAfterName(self._handle,platform,escaping)
@propertydeftokens(self)->List['_function.InstructionTextToken']:"""Type string as a list of tokens (read-only)"""returnself.get_tokens()
[docs]defget_tokens(self,base_confidence=core.max_confidence,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->List['_function.InstructionTextToken']:"""Get a list of tokens for the definition of a type:param int base_confidence: Confidence of this type:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: List of tokens:rtype: List[_function.InstructionTextToken]:Example:>>> Type.array(Type.int(4), 10).get_string()'int32_t[0xa]'>>> Type.array(Type.int(4), 10).get_tokens()['int32_t', ' ', '[', '0xa', ']']"""count=ctypes.c_ulonglong()platform=Noneifself._platformisnotNone:platform=self._platform.handletokens=core.BNGetTypeTokens(self._handle,platform,base_confidence,escaping,count)asserttokensisnotNone,"core.BNGetTypeTokens returned None"result=_function.InstructionTextToken._from_core_struct(tokens,count.value)core.BNFreeInstructionText(tokens,count.value)returnresult
[docs]defget_tokens_before_name(self,base_confidence=core.max_confidence,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->List['_function.InstructionTextToken']:"""Get a list of tokens for the definition of a type that are placed before the type name:param int base_confidence: Confidence of this type:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: List of tokens:rtype: List[_function.InstructionTextToken]:Example:>>> Type.array(Type.int(4), 10).get_string()'int32_t[0xa]'>>> Type.array(Type.int(4), 10).get_tokens_before_name()['int32_t']"""count=ctypes.c_ulonglong()platform=Noneifself._platformisnotNone:platform=self._platform.handletokens=core.BNGetTypeTokensBeforeName(self._handle,platform,base_confidence,escaping,count)asserttokensisnotNone,"core.BNGetTypeTokensBeforeName returned None"result=_function.InstructionTextToken._from_core_struct(tokens,count.value)core.BNFreeInstructionText(tokens,count.value)returnresult
@propertydefchildren(self)->List['Type']:return[]
[docs]defget_tokens_after_name(self,base_confidence=core.max_confidence,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->List['_function.InstructionTextToken']:"""Get a list of tokens for the definition of a type that are placed after the type name:param int base_confidence: Confidence of this type:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: List of tokens:rtype: List[_function.InstructionTextToken]:Example:>>> Type.array(Type.int(4), 10).get_string()'int32_t[0xa]'>>> Type.array(Type.int(4), 10).get_tokens_after_name()['[', '0xa', ']']"""count=ctypes.c_ulonglong()platform=Noneifself._platformisnotNone:platform=self._platform.handletokens=core.BNGetTypeTokensAfterName(self._handle,platform,base_confidence,escaping,count)asserttokensisnotNone,"core.BNGetTypeTokensAfterName returned None"result=_function.InstructionTextToken._from_core_struct(tokens,count.value)core.BNFreeInstructionText(tokens,count.value)returnresult
[docs]defget_lines(self,bv:Union['binaryview.BinaryView','typecontainer.TypeContainer'],name:Union[str,'QualifiedName'],padding_cols:int=64,collapsed:bool=False,escaping:TokenEscapingType=TokenEscapingType.NoTokenEscapingType)->List['TypeDefinitionLine']:"""Get a list of :py:class:`TypeDefinitionLine` structures for representing a Type in a structured form.This structure uses the same logic as Types View and will expand structures and enumerationsunless `collapsed` is set.:param BinaryView bv: BinaryView object owning this Type:param str name: Displayed name of the Type:param int padding_cols: Maximum number of bytes represented by each padding line:param bool collapsed: If the type should be collapsed, and not show fields/members:param TokenEscapingType escaping: How to escape non-parsable strings in types:return: Returns a list of :py:class:`TypeDefinitionLine` structures:rtype: :py:class:`TypeDefinitionLine`"""count=ctypes.c_ulonglong()ifisinstance(bv,(binaryview.BinaryView,)):container=bv.type_containerelifisinstance(bv,(typecontainer.TypeContainer,)):container=bvelse:assertFalse,"Unexpected type container type"ifisinstance(name,QualifiedName):name=str(name)core_lines=core.BNGetTypeLines(self._handle,container.handle,name,padding_cols,collapsed,escaping,count)assertcore_linesisnotNone,"core.BNGetTypeLines returned None"lines=[]foriinrange(count.value):lines.append(TypeDefinitionLine._from_core_struct(core_lines[i]))core.BNFreeTypeDefinitionLineList(core_lines,count.value)returnlines
[docs]defwith_confidence(self,confidence:int)->'Type':returnType.create(handle=core.BNNewTypeReference(self._handle),platform=self._platform,confidence=confidence)
@propertydefconfidence(self)->_int:returnself._confidence@confidence.setterdefconfidence(self,value:_int)->None:self._confidence=value@propertydefplatform(self)->Optional['_platform.Platform']:returnself._platform@platform.setterdefplatform(self,value:'_platform.Platform')->None:self._platform=value
[docs]defmutable_copy(self)->'TypeBuilder':TypeBuilders:Dict[TypeClass,typing.Type[TypeBuilder]]={TypeClass.VoidTypeClass:VoidBuilder,TypeClass.BoolTypeClass:BoolBuilder,TypeClass.IntegerTypeClass:IntegerBuilder,TypeClass.FloatTypeClass:FloatBuilder,TypeClass.PointerTypeClass:PointerBuilder,TypeClass.ArrayTypeClass:ArrayBuilder,TypeClass.FunctionTypeClass:FunctionBuilder,TypeClass.WideCharTypeClass:WideCharBuilder,# TypeClass.StructureTypeClass:Structure,# TypeClass.EnumerationTypeClass:Enumeration,# TypeClass.NamedTypeReferenceClass:NamedTypeReference,}builder_handle=core.BNCreateTypeBuilderFromType(self._handle)assertbuilder_handleisnotNone,"core.BNCreateTypeBuilderFromType returned None"returnTypeBuilders[self.type_class](builder_handle,self.platform,self.confidence)
[docs]defimmutable_copy(self)->'Type':returnself
[docs]defget_builder(self,bv:'binaryview.BinaryView')->'MutableTypeBuilder':returnMutableTypeBuilder(self.mutable_copy(),bv,self.registered_name,self.platform,self._confidence)
[docs]@staticmethoddefbuilder(bv:'binaryview.BinaryView',name:Optional[QualifiedName]=None,id:Optional[str]=None,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'MutableTypeBuilder':type=NoneifnameisNoneandidisNone:raiseValueError("Must specify either a name or id to create a builder object")ifnameisNoneandidisnotNone:type=bv.get_type_by_id(id)iftypeisNone:raiseValueError("failed to look up type by id")registered_name=type.registered_nameifregistered_nameisNone:raiseValueError("Registered name for type is None")name=registered_name.nameifnameisNone:raiseValueError("Name for registered name is None")elifnameisnotNone:type=bv.get_type_by_name(name)iftypeisNone:raiseValueError("failed to look up type by name")asserttypeisnotNoneassertnameisnotNonereturnMutableTypeBuilder(type.mutable_copy(),bv,name,platform,confidence)
[docs]defwith_replaced_structure(self,from_struct:'StructureType',to_struct:'StructureType'):ifnotisinstance(from_struct,StructureType):raiseValueError("from_struct must be a StructureType")ifnotisinstance(to_struct,StructureType):raiseValueError("to_struct must be a StructureType")handle=core.BNTypeWithReplacedStructure(self._handle,from_struct.ntr_handle,to_struct.ntr_handle)returnType.create(handle)
[docs]defwith_replaced_enumeration(self,from_enum:'EnumerationType',to_enum:'EnumerationType'):ifnotisinstance(from_enum,EnumerationType):raiseValueError("from_enum must be an EnumerationType")ifnotisinstance(to_enum,EnumerationType):raiseValueError("to_enum must be an EnumerationType")handle=core.BNTypeWithReplacedEnumeration(self._handle,from_enum.ntr_handle,to_enum.ntr_handle)returnType.create(handle)
[docs]defwith_replaced_named_type_reference(self,from_ref:'NamedTypeReferenceType',to_ref:'NamedTypeReferenceType'):ifnotisinstance(from_ref,NamedTypeReferenceType):raiseValueError("from_ref must be a NamedTypeReferenceType")ifnotisinstance(to_ref,NamedTypeReferenceType):raiseValueError("to_ref must be a NamedTypeReferenceType")handle=core.BNTypeWithReplacedNamedTypeReference(self._handle,from_ref.ntr_handle,to_ref.ntr_handle)returnType.create(handle)
[docs]defderef_named_type_reference(self,view:'binaryview.BinaryView')->'Type':"""Dereferences any named type references to find the underlying type. This may still return anamed type reference if there are circular references. If the type isn't a named typereference, the input type is returned unchanged.:param BinaryView view: BinaryView object owning this Type:return: Type with named type references resolved:rtype: :py:class:`Type`"""handle=core.BNDerefNamedTypeReference(view.handle,self._handle)returnType.create(handle)
[docs]@staticmethoddefvoid()->'VoidType':returnVoidType.create()
[docs]@staticmethoddefbool()->'BoolType':returnBoolType.create()
[docs]@staticmethoddefchar(alternate_name:str="")->'CharType':returnCharType.create(alternate_name)
[docs]@staticmethoddefint(width:_int,sign:BoolWithConfidenceType=True,alternate_name:str="")->'IntegerType':"""``int`` class method for creating an int Type.:param int width: width of the integer in bytes:param bool sign: optional variable representing signedness:param str alternate_name: alternate name for type"""returnIntegerType.create(width,sign,alternate_name)
[docs]@staticmethoddeffloat(width:_int,alternate_name:str="")->'FloatType':"""``float`` class method for creating floating point Types.:param int width: width of the floating point number in bytes:param str alternate_name: alternate name for type"""returnFloatType.create(width,alternate_name)
[docs]@staticmethoddefwide_char(width:_int,alternate_name:str="")->'WideCharType':"""``wide_char`` class method for creating wide char Types.:param int width: width of the wide character in bytes:param str alternate_name: alternate name for type"""returnWideCharType.create(width=width,alternate_name=alternate_name)
[docs]@staticmethoddefstructure_type(structure:'StructureBuilder')->'StructureType':result=structure.immutable_copy()assertisinstance(result,StructureType)returnresult
[docs]@staticmethoddefnamed_type(named_type:'NamedTypeReferenceBuilder')->'NamedTypeReferenceType':result=named_type.immutable_copy()assertisinstance(result,NamedTypeReferenceType)returnresult
[docs]@staticmethoddefnamed_type_from_type(name:QualifiedNameType,type:'Type')->'NamedTypeReferenceType':returnNamedTypeReferenceType.create_from_type(name,type)
[docs]@staticmethoddefnamed_type_from_type_and_id(type_id:str,name:QualifiedNameType,type:Optional['Type']=None)->'NamedTypeReferenceType':returnNamedTypeReferenceType.create_from_type(name,type,type_id)
[docs]@staticmethoddefgenerate_named_type_reference(guid:str,name:QualifiedNameType)->'NamedTypeReferenceType':returnNamedTypeReferenceType.create(NamedTypeReferenceClass.TypedefNamedTypeClass,guid,name)
[docs]@staticmethoddefnamed_type_from_registered_type(view:'binaryview.BinaryView',name:QualifiedNameType)->'NamedTypeReferenceType':returnNamedTypeReferenceType.create_from_registered_type(view,name)
[docs]@staticmethoddefenumeration_type(arch,enum:'EnumerationBuilder',width:_int=None,sign:_bool=False)->'EnumerationType':returnEnumerationType.create(enum.members,enum.width,arch,enum.signed)
[docs]@staticmethoddefpointer(arch:'architecture.Architecture',type:'Type',const:BoolWithConfidenceType=BoolWithConfidence(False),volatile:BoolWithConfidenceType=BoolWithConfidence(False),ref_type:ReferenceType=ReferenceType.PointerReferenceType,width:_int=None)->'PointerType':ifarchisNoneandwidthisNone:raiseValueError("Must specify either an architecture or a width to create a pointer")_width=widthifwidthisnotNoneelsearch.address_sizereturnPointerType.create_with_width(_width,type,const,volatile,ref_type)
[docs]@staticmethoddefpointer_of_width(width:_int,type:'Type',const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False,ref_type:ReferenceType=ReferenceType.PointerReferenceType)->'PointerType':returnPointerType.create_with_width(width,type,const,volatile,ref_type)
[docs]@staticmethoddefarray(type:'Type',count:_int)->'ArrayType':returnArrayType.create(type,count)
[docs]@staticmethoddeffunction(ret:Optional['Type']=None,params:Optional[ParamsType]=None,calling_convention:Optional['callingconvention.CallingConvention']=None,variable_arguments:BoolWithConfidenceType=False,stack_adjust:OffsetWithConfidence=OffsetWithConfidence(0))->'FunctionType':"""``function`` class method for creating a function Type.:param Type ret: return Type of the function:param params: list of parameter Types:type params: list(Type):param CallingConvention calling_convention: optional argument for the function calling convention:param bool variable_arguments: optional boolean, true if the function has a variable number of arguments"""returnFunctionType.create(ret,params,calling_convention,variable_arguments,stack_adjust)
[docs]@staticmethoddeffrom_core_struct(core_type:core.BNType):returnType.create(core.BNNewTypeReference(core_type))
[docs]@staticmethoddefstructure(members:Optional[MembersType]=None,packed:_bool=False,type:StructureVariant=StructureVariant.StructStructureType)->'StructureType':returnStructureType.create(members,packed,type)
[docs]@staticmethoddefunion(members:Optional[MembersType]=None,packed:_bool=False)->'StructureType':returnStructureType.create(members,type=StructureVariant.UnionStructureType,packed=packed)
[docs]@staticmethoddefclass_type(members:Optional[MembersType]=None,packed:_bool=False)->'StructureType':returnStructureType.create(members,type=StructureVariant.ClassStructureType,packed=packed)
[docs]@staticmethoddefenumeration(arch:Optional['architecture.Architecture']=None,members:Optional[EnumMembersType]=None,width:Optional[_int]=None,sign:BoolWithConfidenceType=False)->'EnumerationType':ifmembersisNone:members=[]returnEnumerationType.create(members,width,arch,sign)
[docs]@staticmethoddefnamed_type_reference(type_class:NamedTypeReferenceClass,name:QualifiedNameType,type_id:Optional[str]=None,alignment:_int=1,width:_int=0,const:BoolWithConfidenceType=BoolWithConfidence(False),volatile:BoolWithConfidenceType=BoolWithConfidence(False)):returnNamedTypeReferenceType.create(type_class,type_id,name,alignment,width,None,core.max_confidence,const,volatile)
@propertydefname(self)->QualifiedName:raiseNotImplementedError("Name not implemented for this type")
[docs]@staticmethoddefgenerate_auto_type_id(source:str,name:QualifiedNameType)->str:_name=QualifiedName(name)._to_core_struct()returncore.BNGenerateAutoTypeId(source,_name)
[docs]@staticmethoddefgenerate_auto_demangled_type_id(name:QualifiedNameType)->str:_name=QualifiedName(name)._to_core_struct()returncore.BNGenerateAutoDemangledTypeId(_name)
[docs]@staticmethoddefget_auto_demangled_type_id_source()->str:returncore.BNGetAutoDemangledTypeIdSource()
@propertydefregistered_name(self)->Optional['NamedTypeReferenceType']:"""Name of type registered to binary view, if any (read-only)"""ntr_handle=core.BNGetRegisteredTypeName(self._handle)ifntr_handleisNone:returnNonereturnNamedTypeReferenceType.create_from_handle(ntr_handle,self.alignment,self.width,self.platform,self.confidence,self.const,self.volatile)@propertydefconst(self):"""Whether type is const (read/write)"""result=core.BNIsTypeConst(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@propertydefvolatile(self):"""Whether type is volatile (read/write)"""result=core.BNIsTypeVolatile(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@propertydefsystem_call_number(self)->Optional[_int]:"""Returns the system call number for a FunctionType object if one exists otherwise None"""ifnotcore.BNTypeIsSystemCall(self._handle):returnNonereturncore.BNTypeGetSystemCallNumber(self._handle)
[docs]@dataclass(frozen=True)classRegisterStackAdjustmentWithConfidence:value:intconfidence:int=core.max_confidencedef__int__(self):returnself.value
[docs]classVoidType(Type):
[docs]@classmethoddefcreate(cls,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'VoidType':core_void=core.BNCreateVoidType()assertcore_voidisnotNone,"core.BNCreateVoidType returned None"returncls(core_void,platform,confidence)
[docs]classBoolType(Type):
[docs]@classmethoddefcreate(cls,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'BoolType':handle=core.BNCreateBoolType()asserthandleisnotNone,"core.BNCreateBoolType returned None"returncls(handle,platform,confidence)
[docs]classIntegerType(Type):
[docs]def__init__(self,handle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):super(IntegerType,self).__init__(handle,platform,confidence)
[docs]@classmethoddefcreate(cls,width:int,sign:BoolWithConfidenceType=True,alternate_name:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'IntegerType':_sign=BoolWithConfidence.get_core_struct(sign)handle=core.BNCreateIntegerType(width,_sign,alternate_name)asserthandleisnotNone,"core.BNCreateIntegerType returned None"returncls(handle,platform,confidence)
@propertydefsigned(self)->BoolWithConfidence:"""Whether type is signed (read-only)"""returnBoolWithConfidence.from_core_struct(core.BNIsTypeSigned(self._handle))
[docs]classCharType(IntegerType):
[docs]@classmethoddefcreate(cls,altname:str="char",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'CharType':result=IntegerType.create(1,True,altname)returncls(core.BNNewTypeReference(result.handle),platform,confidence)
[docs]classFloatType(Type):
[docs]@classmethoddefcreate(cls,width:int,altname:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'FloatType':"""``float`` class method for creating floating point Types.:param int width: width of the floating point number in bytes:param str altname: alternate name for type"""core_float=core.BNCreateFloatType(width,altname)assertcore_floatisnotNone,"core.BNCreateFloatType returned None"returncls(core_float,platform,confidence)
[docs]classStructureType(Type):
[docs]def__init__(self,handle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):asserthandleisnotNone,"Attempted to create EnumerationType with handle which is None"super(StructureType,self).__init__(handle,platform,confidence)struct_handle=core.BNGetTypeStructure(handle)assertstruct_handleisnotNone,"core.BNGetTypeStructure returned None"self.struct_handle=struct_handle
[docs]@classmethoddefcreate(cls,members:Optional[MembersType]=None,packed:bool=False,type:StructureVariant=StructureVariant.StructStructureType,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'StructureType':builder=core.BNCreateStructureBuilderWithOptions(type,packed)assertbuilderisnotNone,"core.BNCreateStructureBuilder returned None"StructureBuilder._add_members_to_builder(builder,members)core_struct=core.BNFinalizeStructureBuilder(builder)assertcore_structisnotNone,"core.BNFinalizeStructureBuilder returned None"core_type=core.BNCreateStructureType(core_struct)assertcore_typeisnotNone,"core.BNCreateStructureType returned None"returncls(core_type,platform,confidence)
[docs]defmutable_copy(self)->'StructureBuilder':type_builder_handle=core.BNCreateTypeBuilderFromType(self._handle)asserttype_builder_handleisnotNone,"core.BNCreateTypeBuilderFromType returned None"structure_handle=core.BNGetTypeStructure(self._handle)assertstructure_handleisnotNone,"core.BNGetTypeStructure returned None"structure_builder_handle=core.BNCreateStructureBuilderFromStructure(structure_handle)assertstructure_builder_handleisnotNone,"core.BNCreateStructureBuilderFromStructure returned None"core.BNSetStructureBuilder(type_builder_handle,structure_builder_handle)returnStructureBuilder(type_builder_handle,structure_builder_handle,self.platform,self.confidence)
[docs]@classmethoddeffrom_core_struct(cls,structure:core.BNStructure)->'StructureType':returncls(core.BNNewTypeReference(core.BNCreateStructureType(structure)))
def__del__(self):ifcoreisnotNone:core.BNFreeStructure(self.struct_handle)super(StructureType,self).__del__()def__hash__(self):returnhash(ctypes.addressof(self.struct_handle.contents))def__getitem__(self,name:str)->StructureMember:member=Nonetry:member=core.BNGetStructureMemberByName(self.struct_handle,name)ifmemberisNone:raiseValueError(f"Member{name} is not part of structure")returnStructureMember(Type.create(core.BNNewTypeReference(member.contents.type),confidence=member.contents.typeConfidence),member.contents.name,member.contents.offset,MemberAccess(member.contents.access),MemberScope(member.contents.scope),member.contents.bitPosition,member.contents.bitWidth)finally:ifmemberisnotNone:core.BNFreeStructureMember(member)
[docs]defmember_at_offset(self,offset:int)->StructureMember:member=Nonetry:member=core.BNGetStructureMemberAtOffset(self.struct_handle,offset,None)ifmemberisNone:raiseValueError(f"No member exists at offset{offset}")returnStructureMember(Type.create(core.BNNewTypeReference(member.contents.type),confidence=member.contents.typeConfidence),member.contents.name,member.contents.offset,MemberAccess(member.contents.access),MemberScope(member.contents.scope),member.contents.bitPosition,member.contents.bitWidth)finally:core.BNFreeStructureMember(member)
@propertydefmembers(self):"""Structure member list (read-only). This list will **not** contain members inherited from base structures.To get members including inherited ones, call `members_including_inherited`."""count=ctypes.c_ulonglong()members=core.BNGetStructureMembers(self.struct_handle,count)assertmembersisnotNone,"core.BNGetStructureMembers returned None"try:result=[]foriinrange(0,count.value):result.append(StructureMember(Type.create(core.BNNewTypeReference(members[i].type),confidence=members[i].typeConfidence),members[i].name,members[i].offset,MemberAccess(members[i].access),MemberScope(members[i].scope),members[i].bitPosition,members[i].bitWidth))finally:core.BNFreeStructureMemberList(members,count.value)returnresult@propertydefbase_structures(self)->List[BaseStructure]:"""Base structure list (read-only). Offsets that are not defined by this structure will be filled in by the fields of the base structure(s)."""count=ctypes.c_ulonglong()bases=core.BNGetBaseStructuresForStructure(self.struct_handle,count)try:result=[]foriinrange(0,count.value):result.append(BaseStructure._from_core_struct(bases[i],self.platform))returnresultfinally:core.BNFreeBaseStructureList(bases,count.value)@propertydefwidth(self):"""Structure width"""returncore.BNGetStructureWidth(self.struct_handle)@propertydefpointer_offset(self):"""Structure pointer offset. Pointers to this structure will implicitlyhave this offset subtracted from the pointer to arrive at the start of the structure.Effectively, the pointer offset becomes the new start of the structure, and fieldsbefore it are accessed using negative offsets from the pointer."""returncore.BNGetStructurePointerOffset(self.struct_handle)@propertydefalignment(self):"""Structure alignment"""returncore.BNGetStructureAlignment(self.struct_handle)@propertydefpacked(self):returncore.BNIsStructurePacked(self.struct_handle)@propertydefpropagate_data_var_refs(self)->bool:"""Whether structure field references propagate the references to data variable field values"""returncore.BNStructurePropagatesDataVariableReferences(self.struct_handle)@propertydeftype(self)->StructureVariant:returnStructureVariant(core.BNGetStructureType(self.struct_handle))
[docs]defmembers_including_inherited(self,view:Union['binaryview.BinaryView','typecontainer.TypeContainer'])->List[InheritedStructureMember]:"""Returns structure member list, including those inherited by base structures"""count=ctypes.c_ulonglong()ifisinstance(view,(binaryview.BinaryView,)):container=view.type_containerelifisinstance(view,(typecontainer.TypeContainer,)):container=viewelse:assertFalse,"Unexpected type container type"members=core.BNGetStructureMembersIncludingInherited(self.struct_handle,container.handle,count)assertmembersisnotNone,"core.BNGetInheritedStructureMembers returned None"try:result=[]foriinrange(0,count.value):ifmembers[i].base:const_conf=BoolWithConfidence.get_core_struct(False,0)volatile_conf=BoolWithConfidence.get_core_struct(False,0)handle=core.BNCreateNamedTypeReference(members[i].base,0,1,const_conf,volatile_conf)base_type=NamedTypeReferenceType(handle,self.platform)else:base_type=Noneresult.append(InheritedStructureMember(base_type,members[i].baseOffset,StructureMember(Type.create(core.BNNewTypeReference(members[i].member.type),confidence=members[i].member.typeConfidence),members[i].member.name,members[i].member.offset,MemberAccess(members[i].member.access),MemberScope(members[i].member.scope),members[i].member.bitPosition,members[i].member.bitWidth),members[i].memberIndex))finally:core.BNFreeInheritedStructureMemberList(members,count.value)returnresult
[docs]defmember_at_offset_including_inherited(self,view:'binaryview.BinaryView',offset:int)->InheritedStructureMember:"""Returns the member (including inherited member at the specified offset"""member=Nonetry:member=core.BNGetMemberIncludingInheritedAtOffset(self.struct_handle,view.handle,offset)ifmemberisNone:raiseValueError(f"No member exists at offset{offset}")ifmember[0].base:const_conf=BoolWithConfidence.get_core_struct(False,0)volatile_conf=BoolWithConfidence.get_core_struct(False,0)handle=core.BNCreateNamedTypeReference(member[0].base,0,1,const_conf,volatile_conf)base_type=NamedTypeReferenceType(handle,self.platform)else:base_type=Noneresult=InheritedStructureMember(base_type,member[0].baseOffset,StructureMember(Type.create(core.BNNewTypeReference(member[0].member.type),confidence=member[0].member.typeConfidence),member[0].member.name,member[0].member.offset,MemberAccess(member[0].member.access),MemberScope(member[0].member.scope),member[0].member.bitPosition,member[0].member.bitWidth),member[0].memberIndex)finally:core.BNFreeInheritedStructureMember(member)returnresult
[docs]defwith_replaced_structure(self,from_struct,to_struct)->'StructureType':returnStructureType.from_core_struct(core.BNStructureWithReplacedStructure(self.struct_handle,from_struct.handle,to_struct.handle))
[docs]defwith_replaced_enumeration(self,from_enum,to_enum)->'StructureType':returnStructureType.from_core_struct(core.BNStructureWithReplacedEnumeration(self.struct_handle,from_enum.handle,to_enum.handle))
[docs]defwith_replaced_named_type_reference(self,from_ref,to_ref)->'StructureType':returnStructureType.from_core_struct(core.BNStructureWithReplacedNamedTypeReference(self.struct_handle,from_ref.ntr_handle,to_ref.ntr_handle))
[docs]defgenerate_named_type_reference(self,guid:str,name:QualifiedNameType):ifself.type==StructureVariant.StructStructureType:ntr_type=NamedTypeReferenceClass.StructNamedTypeClasselifself.type==StructureVariant.UnionStructureType:ntr_type=NamedTypeReferenceClass.UnionNamedTypeClasselse:ntr_type=NamedTypeReferenceClass.ClassNamedTypeClassreturnNamedTypeReferenceType.create(ntr_type,guid,name,self.alignment,self.width,self.platform,self.confidence)
[docs]defresolve_member_or_base_member(self,view:Optional['binaryview.BinaryView'],offset:int,size:int,resolve_func:ResolveMemberCallback,member_index_hint:Optional[int]=None)->bool:ifviewisnotNone:view=view.handledefresolve_member_callback(ctxt,base_name:core.BNNamedTypeReferenceHandle,resolved_struct:core.BNStructureHandle,member_index:int,struct_offset:int,adjusted_offset:int,member:core.BNStructureMember):ifbase_name:base_name=NamedTypeReferenceType.create_from_handle(core.BNNewNamedTypeReference(base_name))ifresolved_struct:resolved_struct=StructureType.from_core_struct(core.BNNewStructureReference(resolved_struct))t=Type.create(core.BNNewTypeReference(member.type),confidence=member.typeConfidence)struct_member=StructureMember(t,member.name,member.offset,MemberAccess(member.access),MemberScope(member.scope))resolve_func(base_name,resolved_struct,member_index,struct_offset,adjusted_offset,struct_member)member_index_hint_value=0ifmember_index_hintisnotNone:member_index_hint_value=member_index_hintreturncore.BNResolveStructureMemberOrBaseMember(self.struct_handle,view,offset,size,None,ctypes.CFUNCTYPE(None,ctypes.c_void_p,core.BNNamedTypeReferenceHandle,core.BNStructureHandle,ctypes.c_size_t,ctypes.c_uint64,ctypes.c_uint64,core.BNStructureMember)(resolve_member_callback),member_index_hintisnotNone,member_index_hint_value)
@propertydefchildren(self)->List[Type]:return[member.typeformemberinself.members]
[docs]classEnumerationType(IntegerType):
[docs]def__init__(self,handle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence):asserthandleisnotNone,"Attempted to create EnumerationType without handle"super(EnumerationType,self).__init__(handle,platform,confidence)enum_handle=core.BNGetTypeEnumeration(handle)assertenum_handleisnotNone,"core.BNGetTypeEnumeration returned None"self.enum_handle=enum_handle
def__del__(self):ifcoreisnotNone:core.BNFreeEnumeration(self.enum_handle)super(EnumerationType,self).__del__()def__hash__(self):returnhash(ctypes.addressof(self.enum_handle.contents))@propertydefmembers(self):"""Enumeration member list (read-only)"""count=ctypes.c_ulonglong()members=core.BNGetEnumerationMembers(self.enum_handle,count)assertmembersisnotNone,"core.BNGetEnumerationMembers returned None"try:result=[]foriinrange(0,count.value):value=convert_integer(members[i].value,self.signed,self.width)result.append(EnumerationMember(members[i].name,valueifnotmembers[i].isDefaultelseNone))returnresultfinally:core.BNFreeEnumerationMemberList(members,count.value)
[docs]@classmethoddefcreate(cls,members:EnumMembersType,width:Optional[int]=None,arch:Optional['architecture.Architecture']=None,sign:BoolWithConfidenceType=False,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'EnumerationType':ifwidthisnotNone:_width=widthelifarchisnotNone:_width=arch.address_sizeelse:raiseValueError("One of the following parameters must not be None: (arch, width)")ifwidth==0:raiseValueError("enumeration width must not be 0")builder=core.BNCreateEnumerationBuilder()assertbuilderisnotNone,"core.BNCreateEnumerationType returned None"EnumerationBuilder._add_members(builder,members)core_enum=core.BNFinalizeEnumerationBuilder(builder)assertcore_enumisnotNone,"core.BNFinalizeEnumerationBuilder returned None"core.BNFreeEnumerationBuilder(builder)core_type=core.BNCreateEnumerationTypeOfWidth(core_enum,_width,BoolWithConfidence.get_core_struct(sign))assertcore_typeisnotNone,"core.BNCreateEnumerationTypeOfWidth returned None"returncls(core_type,platform,confidence)
[docs]defmutable_copy(self)->'EnumerationBuilder':type_builder_handle=core.BNCreateTypeBuilderFromType(self._handle)asserttype_builder_handleisnotNone,"core.BNCreateTypeBuilderFromType returned None"enumeration_handle=core.BNGetTypeEnumeration(self._handle)assertenumeration_handleisnotNone,"core.BNGetTypeEnumeration returned None"enumeration_builder_handle=core.BNCreateEnumerationBuilderFromEnumeration(enumeration_handle)assertenumeration_builder_handleisnotNone,"core.BNCreateEnumerationBuilderFromEnumeration returned None"core.BNSetEnumerationBuilder(type_builder_handle,enumeration_builder_handle)returnEnumerationBuilder(type_builder_handle,enumeration_builder_handle,self.platform,self.confidence)
[docs]defgenerate_named_type_reference(self,guid:str,name:QualifiedNameType):ntr_type=NamedTypeReferenceClass.EnumNamedTypeClassreturnNamedTypeReferenceType.create(ntr_type,guid,name,platform=self.platform,confidence=self.confidence)
[docs]classPointerType(Type):@propertydefref_type(self)->ReferenceType:returnReferenceType(core.BNTypeGetReferenceType(self._handle))
[docs]@classmethoddefcreate(cls,arch:'architecture.Architecture',type:SomeType,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False,ref_type:ReferenceType=ReferenceType.PointerReferenceType,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'PointerType':returncls.create_with_width(arch.address_size,type,const,volatile,ref_type,platform,confidence)
[docs]@staticmethoddeffrom_bools(const:BoolWithConfidenceType,volatile:BoolWithConfidenceType)->Tuple[BoolWithConfidence,BoolWithConfidence]:_const=constifconstisNone:_const=BoolWithConfidence(False,confidence=0)elifisinstance(const,bool):_const=BoolWithConfidence(const)ifnotisinstance(_const,BoolWithConfidence):raiseValueError(f"unhandled type{type(const)} for 'const' argument")_volatile=volatileifvolatileisNone:_volatile=BoolWithConfidence(False,confidence=0)elifisinstance(volatile,bool):_volatile=BoolWithConfidence(volatile)ifnotisinstance(_volatile,BoolWithConfidence):raiseValueError(f"unhandled type{type(volatile)} for 'volatile' argument")return(_const,_volatile)
[docs]@classmethoddefcreate_with_width(cls,width:int,type:SomeType,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False,ref_type:Optional[ReferenceType]=None,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'PointerType':_const,_volatile=PointerType.from_bools(const,volatile)type=type.immutable_copy()ifref_typeisNone:ref_type=ReferenceType.PointerReferenceTypetype_conf=type._to_core_struct()core_type=core.BNCreatePointerTypeOfWidth(width,type_conf,_const._to_core_struct(),_volatile._to_core_struct(),ref_type)assertcore_typeisnotNone,"core.BNCreatePointerTypeOfWidth returned None"returncls(core_type,platform,confidence)
[docs]deforigin(self,bv:Optional['binaryview.BinaryView'])->Optional[Tuple['QualifiedName',int]]:ntr_handle=core.BNGetTypeNamedTypeReference(self._handle)ifntr_handleisNone:returnNonename=core.BNGetTypeReferenceName(ntr_handle)core.BNFreeNamedTypeReference(ntr_handle)ifnameisNone:returnNoneqn=QualifiedName._from_core_struct(name)core.BNFreeQualifiedName(name)return(qn,self.offset)
@propertydeftarget(self)->Type:"""Target (read-only)"""result=core.BNGetChildType(self._handle)assertresultisnotNone,"core.BNGetChildType returned None"returnType.create(result.type,self._platform,result.confidence)@propertydefchildren(self)->List[Type]:return[self.target]@propertydefpointer_suffix(self)->List[PointerSuffix]:"""Pointer suffix, e.g. __unaligned is [UnalignedSuffix] (read-only)"""count=ctypes.c_size_t(0)suffix=core.BNGetTypePointerSuffix(self.handle,count)assertsuffixisnotNone,"core.BNGetTypePointerSuffix returned None"try:result=[]foriinrange(count.value):result.append(suffix[i])returnresultfinally:core.BNFreePointerSuffixList(suffix,count)@propertydefpointer_suffix_string(self)->str:"""Pointer suffix, but as a string, e.g. "__unaligned" (read-only)"""returncore.BNGetTypePointerSuffixString(self.handle)
[docs]defget_pointer_suffix_tokens(self,base_confidence:int=core.max_confidence)->List['_function.InstructionTextToken']:"""Get the pointer suffix, as a list of tokens:param base_confidence: (optional) Confidence value to combine with the pointer's confidence:return: Token list"""count=ctypes.c_ulonglong()platform=Noneifself._platformisnotNone:platform=self._platform.handletokens=core.BNGetTypePointerSuffixTokens(self._handle,base_confidence,count)asserttokensisnotNone,"core.BNGetTypePointerSuffixTokens returned None"result=_function.InstructionTextToken._from_core_struct(tokens,count.value)core.BNFreeInstructionText(tokens,count.value)returnresult
@propertydefpointer_base_type(self)->PointerBaseType:"""Pointer base type, e.g. __based(start) is RelativeToBinaryStartPointerBaseType (read-only)"""returnPointerBaseType(core.BNTypeGetPointerBaseType(self._handle))@propertydefpointer_base_offset(self)->int:"""Pointer base offset, e.g. __based(start, 0x1000) is 0x1000 (read-only)"""returncore.BNTypeGetPointerBaseOffset(self._handle)
[docs]classArrayType(Type):
[docs]@classmethoddefcreate(cls,element_type:Type,count:int,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'ArrayType':type_conf=element_type._to_core_struct()core_array=core.BNCreateArrayType(type_conf,count)assertcore_arrayisnotNone,"core.BNCreateArrayType returned None"returncls(core_array)
@propertydefcount(self):"""Type count (read-only)"""returncore.BNGetTypeElementCount(self._handle)@propertydefelement_type(self)->Type:result=core.BNGetChildType(self._handle)assertresultisnotNone,"core.BNGetChildType returned None"returnType.create(result.type,self._platform,result.confidence)@propertydefchildren(self)->List[Type]:return[self.element_type]
[docs]classFunctionType(Type):
[docs]@classmethoddefcreate(cls,ret:Optional[Type]=None,params:Optional[ParamsType]=None,calling_convention:Optional['callingconvention.CallingConvention']=None,variable_arguments:BoolWithConfidenceType=BoolWithConfidence(False),stack_adjust:OffsetWithConfidence=OffsetWithConfidence(0),platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,can_return:Union[BoolWithConfidence,bool]=True,reg_stack_adjust:Optional[Dict['architecture.RegisterName',OffsetWithConfidenceType]]=None,return_regs:Optional[Union['RegisterSet',List['architecture.RegisterType']]]=None,name_type:'NameType'=NameType.NoNameType,pure:Union[BoolWithConfidence,bool]=False)->'FunctionType':ifretisNone:ret=VoidType.create()ifparamsisNone:params=[]param_buf=FunctionBuilder._to_core_struct(params)ret_conf=ret._to_core_struct()conv_conf=core.BNCallingConventionWithConfidence()ifcalling_conventionisNone:conv_conf.convention=Noneconv_conf.confidence=0else:conv_conf.convention=calling_convention.handleconv_conf.confidence=calling_convention.confidenceifvariable_argumentsisNone:_variable_arguments=BoolWithConfidence.get_core_struct(False,0)else:_variable_arguments=BoolWithConfidence.get_core_struct(variable_arguments,core.max_confidence)ifstack_adjustisNone:_stack_adjust=OffsetWithConfidence.get_core_struct(0,0)else:_stack_adjust=OffsetWithConfidence.get_core_struct(stack_adjust,core.max_confidence)ifreg_stack_adjustisNone:reg_stack_adjust={}reg_stack_adjust_regs=(ctypes.c_uint32*len(reg_stack_adjust))()reg_stack_adjust_values=(core.BNOffsetWithConfidence*len(reg_stack_adjust))()fori,(reg,adjust)inenumerate(reg_stack_adjust.items()):reg_stack_adjust_regs[i]=regreg_stack_adjust_values[i].value=adjust.valuereg_stack_adjust_values[i].confidence=adjust.confidencereturn_regs_set=core.BNRegisterSetWithConfidence()ifreturn_regsisNoneorplatformisNone:return_regs_set.count=0return_regs_set.confidence=0else:return_regs_set.count=len(return_regs)return_regs_set.confidence=255return_regs_set.regs=(ctypes.c_uint32*len(return_regs))()fori,reginenumerate(return_regs):return_regs_set[i]=platform.arch.get_reg_index(reg)_can_return=BoolWithConfidence.get_core_struct(can_return)_pure=BoolWithConfidence.get_core_struct(pure)ifparamsisNone:params=[]func_type=core.BNCreateFunctionType(ret_conf,conv_conf,param_buf,len(params),_variable_arguments,_can_return,_stack_adjust,reg_stack_adjust_regs,reg_stack_adjust_values,len(reg_stack_adjust),return_regs_set,name_type,_pure)assertfunc_typeisnotNone,f"core.BNCreateFunctionType returned None{ret_conf}{conv_conf}{param_buf}{_variable_arguments}{_stack_adjust}"returncls(func_type,platform,confidence)
@propertydefstack_adjustment(self)->OffsetWithConfidence:"""Stack adjustment for function (read-only)"""result=core.BNGetTypeStackAdjustment(self._handle)returnOffsetWithConfidence(result.value,confidence=result.confidence)@propertydefreturn_value(self)->Type:"""Return value (read-only)"""result=core.BNGetChildType(self._handle)ifresultisNone:returnType.void()returnType.create(result.type,platform=self._platform,confidence=result.confidence)@propertydefcalling_convention(self)->Optional[callingconvention.CallingConvention]:"""Calling convention (read-only)"""result=core.BNGetTypeCallingConvention(self._handle)ifnotresult.convention:returnNonereturncallingconvention.CallingConvention(None,handle=result.convention,confidence=result.confidence)@propertydefparameters(self)->List[FunctionParameter]:"""Type parameters list (read-only)"""count=ctypes.c_ulonglong()params=core.BNGetTypeParameters(self._handle,count)assertparamsisnotNone,"core.BNGetTypeParameters returned None"result=[]foriinrange(0,count.value):param_type=Type.create(core.BNNewTypeReference(params[i].type),platform=self._platform,confidence=params[i].typeConfidence)ifparams[i].defaultLocation:param_location=Noneelse:name=params[i].nameif(params[i].location.type==VariableSourceType.RegisterVariableSourceType)and(self._platformisnotNone):name=self._platform.arch.get_reg_name(params[i].location.storage)elifparams[i].location.type==VariableSourceType.StackVariableSourceType:name="arg_%x"%params[i].location.storageparam_location=variable.VariableNameAndType(params[i].location.type,params[i].location.index,params[i].location.storage,name,param_type)result.append(FunctionParameter(param_type,params[i].name,param_location))core.BNFreeTypeParameterList(params,count.value)returnresult@propertydefparameters_with_all_locations(self)->List[FunctionParameter]:"""Type parameters list with default locations filled in with values (read-only)"""count=ctypes.c_ulonglong()params=core.BNGetTypeParameters(self._handle,count)assertparamsisnotNone,"core.BNGetTypeParameters returned None"result=[]foriinrange(0,count.value):param_type=Type.create(core.BNNewTypeReference(params[i].type),platform=self._platform,confidence=params[i].typeConfidence)name=params[i].nameif(params[i].location.type==VariableSourceType.RegisterVariableSourceType)and(self._platformisnotNone):name=self._platform.arch.get_reg_name(params[i].location.storage)elifparams[i].location.type==VariableSourceType.StackVariableSourceType:name="arg_%x"%params[i].location.storageparam_location=variable.VariableNameAndType(params[i].location.type,params[i].location.index,params[i].location.storage,name,param_type)result.append(FunctionParameter(param_type,params[i].name,param_location))core.BNFreeTypeParameterList(params,count.value)returnresult@propertydefhas_variable_arguments(self)->BoolWithConfidence:"""Whether type has variable arguments (read-only)"""result=core.BNTypeHasVariableArguments(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@propertydefcan_return(self)->BoolWithConfidence:"""Whether type can return"""result=core.BNFunctionTypeCanReturn(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@propertydefpure(self)->BoolWithConfidence:"""Whether type is pure"""result=core.BNIsTypePure(self._handle)returnBoolWithConfidence(result.value,confidence=result.confidence)@propertydefchildren(self)->List[Type]:return[self.return_value,*[param.typeforparaminself.parameters]]
[docs]classNamedTypeReferenceType(Type):
[docs]def__init__(self,handle,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,ntr_handle=None):asserthandleisnotNone,"Attempting to create NamedTypeReferenceType handle which is None"super(NamedTypeReferenceType,self).__init__(handle,platform,confidence)ifntr_handleisNone:ntr_handle=core.BNGetTypeNamedTypeReference(handle)assertntr_handleisnotNone,"core.BNGetTypeNamedTypeReference returned None"self.ntr_handle=ntr_handle
[docs]defmutable_copy(self):type_builder_handle=core.BNCreateTypeBuilderFromType(self._handle)asserttype_builder_handleisnotNone,"core.BNCreateTypeBuilderFromType returned None"ntr_builder_handle=core.BNCreateNamedTypeBuilder(self.named_type_class,self.type_id,self.name._to_core_struct())assertntr_builder_handleisnotNone,"core.BNCreateNamedTypeBuilder returned None"core.BNSetNamedTypeReferenceBuilder(type_builder_handle,ntr_builder_handle)returnNamedTypeReferenceBuilder(type_builder_handle,ntr_builder_handle,self.platform,self.confidence)
[docs]@classmethoddefcreate(cls,named_type_class:NamedTypeReferenceClass,guid:Optional[str],name:QualifiedNameType,alignment:int=0,width:int=0,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False)->'NamedTypeReferenceType':ifnotisinstance(named_type_class,NamedTypeReferenceClass):raiseValueError("named_type_class must be a NamedTypeReferenceClass")_guid=guidifguidisNone:_guid=str(uuid.uuid4())_name=QualifiedName(name)._to_core_struct()core_ntr=core.BNCreateNamedType(named_type_class,_guid,_name)assertcore_ntrisnotNone,"core.BNCreateNamedType returned None"_const=BoolWithConfidence.get_core_struct(const)_volatile=BoolWithConfidence.get_core_struct(volatile)core_type=core.BNCreateNamedTypeReference(core_ntr,width,alignment,_const,_volatile)assertcore_typeisnotNone,"core.BNCreateNamedTypeReference returned None"returncls(core_type,platform,confidence)
[docs]@classmethoddefcreate_from_handle(cls,ntr_handle,alignment:int=0,width:int=0,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False):"""Create a NamedTypeReferenceType from a BNNamedTypeReference handle"""assertntr_handleisnotNone,"Attempting to create NamedTypeReferenceType from None handle"_const=BoolWithConfidence.get_core_struct(const)_volatile=BoolWithConfidence.get_core_struct(volatile)core_type=core.BNCreateNamedTypeReference(ntr_handle,width,alignment,_const,_volatile)assertcore_typeisnotNone,"core.BNCreateNamedTypeReference returned None"returncls(core_type,platform,confidence)
[docs]@classmethoddefcreate_from_type(cls,name:QualifiedNameType,type:Optional[Type],guid:Optional[str]=None,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence,const:BoolWithConfidenceType=False,volatile:BoolWithConfidenceType=False)->'NamedTypeReferenceType':_guid=guidif_guidisNone:_guid=str(uuid.uuid4())iftypeisNone:returncls.create(NamedTypeReferenceClass.UnknownNamedTypeClass,_guid,name,0,0,platform,confidence)else:returnNamedTypeReferenceType.create(NamedTypeReferenceClass.TypedefNamedTypeClass,_guid,name,type.alignment,type.width,platform,confidence,const,volatile)
[docs]@classmethoddefcreate_from_registered_type(cls,view:'binaryview.BinaryView',name:QualifiedNameType,platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'NamedTypeReferenceType':_name=QualifiedName(name)._to_core_struct()core_type=core.BNCreateNamedTypeReferenceFromType(view.handle,_name)assertcore_typeisnotNone,"core.BNCreateNamedTypeReferenceFromType returned None"returncls(core_type,platform,confidence)
def__del__(self):ifcoreisnotNone:core.BNFreeNamedTypeReference(self.ntr_handle)super(NamedTypeReferenceType,self).__del__()def__repr__(self):ifself.named_type_class==NamedTypeReferenceClass.TypedefNamedTypeClass:returnf"<type: immutable:NamedTypeReferenceClass 'typedef{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.StructNamedTypeClass:returnf"<type: immutable:NamedTypeReferenceClass 'struct{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.UnionNamedTypeClass:returnf"<type: immutable:NamedTypeReferenceClass 'union{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.ClassNamedTypeClass:returnf"<type: immutable:NamedTypeReferenceClass 'class{self.name}'>"elifself.named_type_class==NamedTypeReferenceClass.EnumNamedTypeClass:returnf"<type: immutable:NamedTypeReferenceClass 'enum{self.name}'>"else:returnf"<type: immutable:NamedTypeReferenceClass 'unknown'>"def__str__(self):name=self.registered_nameifnameisNone:name=""else:name=" "+str(name.name)returnf"{self.get_string_before_name()}{name}{self.get_string_after_name()}"def__hash__(self):returnhash(ctypes.addressof(self.ntr_handle.contents))@propertydefnamed_type_class(self)->NamedTypeReferenceClass:returnNamedTypeReferenceClass(core.BNGetTypeReferenceClass(self.ntr_handle))@propertydeftype_id(self)->str:returncore.BNGetTypeReferenceId(self.ntr_handle)@propertydefname(self)->QualifiedName:name=core.BNGetTypeReferenceName(self.ntr_handle)result=QualifiedName._from_core_struct(name)core.BNFreeQualifiedName(name)returnresult
[docs]@staticmethoddefgenerate_auto_type_ref(type_class:NamedTypeReferenceClass,source:str,name:QualifiedNameType):type_id=Type.generate_auto_type_id(source,name)returnNamedTypeReferenceType.create(type_class,type_id,name)
[docs]@staticmethoddefgenerate_auto_demangled_type_ref(type_class:NamedTypeReferenceClass,name:QualifiedNameType):type_id=Type.generate_auto_demangled_type_id(name)returnNamedTypeReferenceType.create(type_class,type_id,name)
def_target_helper(self,bv:'binaryview.BinaryView',type_ids=None)->Optional[Type]:t=bv.get_type_by_id(self.type_id)iftisNone:returnNoneiftype_idsisNone:type_ids=set()ifisinstance(t,NamedTypeReferenceType):ift.type_idintype_ids:raiseTypeError("Can't get target for recursively defined type")type_ids.add(t)returnt._target_helper(bv,type_ids)else:returnt
[docs]deftarget(self,bv:'binaryview.BinaryView')->Optional[Type]:"""Returns the type pointed to by the current type:param bv: The BinaryView in which this type is defined.:type bv: binaryview.BinaryView:return: The type this NamedTypeReference is referencing:rtype: Optional[Type]"""returnself._target_helper(bv)
[docs]classWideCharType(Type):
[docs]@classmethoddefcreate(cls,width:int,alternate_name:str="",platform:Optional['_platform.Platform']=None,confidence:int=core.max_confidence)->'WideCharType':"""``wide_char`` class method for creating wide char Types.:param int width: width of the wide character in bytes:param str alternate_name: alternate name for type"""core_type=core.BNCreateWideCharType(width,alternate_name)assertcore_typeisnotNone,"core.BNCreateWideCharType returned None"returncls(core_type,platform,confidence)
Types={TypeClass.VoidTypeClass:VoidType,TypeClass.BoolTypeClass:BoolType,TypeClass.IntegerTypeClass:IntegerType,TypeClass.FloatTypeClass:FloatType,TypeClass.StructureTypeClass:StructureType,TypeClass.EnumerationTypeClass:EnumerationType,TypeClass.PointerTypeClass:PointerType,TypeClass.ArrayTypeClass:ArrayType,TypeClass.FunctionTypeClass:FunctionType,TypeClass.NamedTypeReferenceClass:NamedTypeReferenceType,TypeClass.WideCharTypeClass:WideCharType,}
[docs]@dataclass(frozen=True)classRegisterSet:regs:List['architecture.RegisterName']confidence:int=core.max_confidencedef__iter__(self)->Generator['architecture.RegisterName',None,None]:forreginself.regs:yieldregdef__getitem__(self,idx):returnself.regs[idx]def__len__(self):returnlen(self.regs)
[docs]defwith_confidence(self,confidence):returnRegisterSet(list(self.regs),confidence=confidence)
[docs]@dataclass(frozen=True)classTypeFieldReference:func:Optional['_function.Function']arch:Optional['architecture.Architecture']address:intsize:intincomingType:Optional[Type]def__repr__(self):ifself.arch:returnf"<ref:{self.arch.name}@{self.address:#x}, size:{self.size:#x}, type:{self.incomingType}>"else:returnf"<ref:{self.address:#x}, size:{self.size:#x}, type:{self.incomingType}>"