From 1c6f11277096534479c958b6d9fc5265d318ca2a Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Mon, 18 Sep 2017 23:25:08 -0400 Subject: Add basic floating point instructions --- python/mediumlevelil.py | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) (limited to 'python/mediumlevelil.py') diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py index 07759a47..05b558d2 100644 --- a/python/mediumlevelil.py +++ b/python/mediumlevelil.py @@ -85,6 +85,7 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_STORE_STRUCT: [("dest", "expr"), ("offset", "int"), ("src", "expr")], MediumLevelILOperation.MLIL_VAR: [("src", "var")], MediumLevelILOperation.MLIL_VAR_FIELD: [("src", "var"), ("offset", "int")], + MediumLevelILOperation.MLIL_VAR_SPLIT: [("high", "var"), ("low", "var")], MediumLevelILOperation.MLIL_ADDRESS_OF: [("src", "var")], MediumLevelILOperation.MLIL_ADDRESS_OF_FIELD: [("src", "var"), ("offset", "int")], MediumLevelILOperation.MLIL_CONST: [("constant", "int")], @@ -108,13 +109,13 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_MULU_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_MULS_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_DIVU: [("left", "expr"), ("right", "expr")], - MediumLevelILOperation.MLIL_DIVU_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_DIVU_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_DIVS: [("left", "expr"), ("right", "expr")], - MediumLevelILOperation.MLIL_DIVS_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_DIVS_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_MODU: [("left", "expr"), ("right", "expr")], - MediumLevelILOperation.MLIL_MODU_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_MODU_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_MODS: [("left", "expr"), ("right", "expr")], - MediumLevelILOperation.MLIL_MODS_DP: [("hi", "expr"), ("lo", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_MODS_DP: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_NEG: [("src", "expr")], MediumLevelILOperation.MLIL_NOT: [("src", "expr")], MediumLevelILOperation.MLIL_SX: [("src", "expr")], @@ -150,6 +151,23 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_UNDEF: [], MediumLevelILOperation.MLIL_UNIMPL: [], MediumLevelILOperation.MLIL_UNIMPL_MEM: [("src", "expr")], + MediumLevelILOperation.MLIL_FADD: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FSUB: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FMUL: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FDIV: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FSQRT: [("src", "expr")], + MediumLevelILOperation.MLIL_FNEG: [("src", "expr")], + MediumLevelILOperation.MLIL_FABS: [("src", "expr")], + MediumLevelILOperation.MLIL_FLOAT_TO_INT: [("src", "expr")], + MediumLevelILOperation.MLIL_INT_TO_FLOAT: [("src", "expr")], + MediumLevelILOperation.MLIL_FLOAT_CONV: [("src", "expr")], + MediumLevelILOperation.MLIL_FCMP_E: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_NE: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_LT: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_LE: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_GE: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_GT: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_UO: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_SET_VAR_SSA: [("dest", "var_ssa"), ("src", "expr")], MediumLevelILOperation.MLIL_SET_VAR_SSA_FIELD: [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")], MediumLevelILOperation.MLIL_SET_VAR_SPLIT_SSA: [("high", "var_ssa"), ("low", "var_ssa"), ("src", "expr")], @@ -159,6 +177,7 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_VAR_SSA_FIELD: [("src", "var_ssa"), ("offset", "int")], MediumLevelILOperation.MLIL_VAR_ALIASED: [("src", "var_ssa")], MediumLevelILOperation.MLIL_VAR_ALIASED_FIELD: [("src", "var_ssa"), ("offset", "int")], + MediumLevelILOperation.MLIL_VAR_SPLIT_SSA: [("high", "var_ssa"), ("low", "var_ssa")], MediumLevelILOperation.MLIL_CALL_SSA: [("output", "expr"), ("dest", "expr"), ("params", "expr_list"), ("src_memory", "int")], MediumLevelILOperation.MLIL_CALL_UNTYPED_SSA: [("output", "expr"), ("dest", "expr"), ("params", "expr"), ("stack", "expr")], MediumLevelILOperation.MLIL_SYSCALL_SSA: [("output", "expr"), ("params", "expr_list"), ("src_memory", "int")], -- cgit v1.3.1 From 95a7be141a07a20b8465981b01116fcafb6b5f41 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Tue, 3 Oct 2017 23:07:48 -0400 Subject: Adding support for register stacks in IL (for x87) --- architecture.cpp | 90 ++++++++++ binaryninjaapi.h | 38 +++++ binaryninjacore.h | 28 +++ callingconvention.cpp | 12 +- lowlevelil.cpp | 14 ++ lowlevelilinstruction.cpp | 394 ++++++++++++++++++++++++++++++++++++++++++- lowlevelilinstruction.h | 149 ++++++++++++++++ mediumlevelilinstruction.cpp | 33 ++++ mediumlevelilinstruction.h | 1 + python/architecture.py | 101 +++++++++++ python/callingconvention.py | 4 + python/function.py | 59 ++++++- python/lowlevelil.py | 165 +++++++++++++++++- python/mediumlevelil.py | 9 + 14 files changed, 1092 insertions(+), 5 deletions(-) (limited to 'python/mediumlevelil.py') diff --git a/architecture.cpp b/architecture.cpp index eb588394..56af3f80 100644 --- a/architecture.cpp +++ b/architecture.cpp @@ -359,6 +359,34 @@ uint32_t* Architecture::GetGlobalRegistersCallback(void* ctxt, size_t* count) } +char* Architecture::GetRegisterStackNameCallback(void* ctxt, uint32_t regStack) +{ + Architecture* arch = (Architecture*)ctxt; + string result = arch->GetRegisterStackName(regStack); + return BNAllocString(result.c_str()); +} + + +uint32_t* Architecture::GetAllRegisterStacksCallback(void* ctxt, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector regs = arch->GetAllRegisterStacks(); + *count = regs.size(); + + uint32_t* result = new uint32_t[regs.size()]; + for (size_t i = 0; i < regs.size(); i++) + result[i] = regs[i]; + return result; +} + + +void Architecture::GetRegisterStackInfoCallback(void* ctxt, uint32_t regStack, BNRegisterStackInfo* result) +{ + Architecture* arch = (Architecture*)ctxt; + *result = arch->GetRegisterStackInfo(regStack); +} + + bool Architecture::AssembleCallback(void* ctxt, const char* code, uint64_t addr, BNDataBuffer* result, char** errors) { Architecture* arch = (Architecture*)ctxt; @@ -467,6 +495,9 @@ void Architecture::Register(Architecture* arch) callbacks.getStackPointerRegister = GetStackPointerRegisterCallback; callbacks.getLinkRegister = GetLinkRegisterCallback; callbacks.getGlobalRegisters = GetGlobalRegistersCallback; + callbacks.getRegisterStackName = GetRegisterStackNameCallback; + callbacks.getAllRegisterStacks = GetAllRegisterStacksCallback; + callbacks.getRegisterStackInfo = GetRegisterStackInfoCallback; callbacks.assemble = AssembleCallback; callbacks.isNeverBranchPatchAvailable = IsNeverBranchPatchAvailableCallback; callbacks.isAlwaysBranchPatchAvailable = IsAlwaysBranchPatchAvailableCallback; @@ -682,6 +713,36 @@ bool Architecture::IsGlobalRegister(uint32_t reg) } +string Architecture::GetRegisterStackName(uint32_t regStack) +{ + char regStr[32]; + sprintf(regStr, "reg_stack_%" PRIu32, regStack); + return regStr; +} + + +vector Architecture::GetAllRegisterStacks() +{ + return vector(); +} + + +BNRegisterStackInfo Architecture::GetRegisterStackInfo(uint32_t) +{ + BNRegisterStackInfo result; + result.firstStorageReg = BN_INVALID_REGISTER; + result.count = 0; + result.stackTopReg = BN_INVALID_REGISTER; + return result; +} + + +uint32_t Architecture::GetRegisterStackForRegister(uint32_t reg) +{ + return BNGetArchitectureRegisterStackForRegister(m_object, reg); +} + + vector Architecture::GetModifiedRegistersOnWrite(uint32_t reg) { size_t count; @@ -1116,6 +1177,35 @@ vector CoreArchitecture::GetGlobalRegisters() } +string CoreArchitecture::GetRegisterStackName(uint32_t regStack) +{ + char* name = BNGetArchitectureRegisterStackName(m_object, regStack); + string result = name; + BNFreeString(name); + return result; +} + + +vector CoreArchitecture::GetAllRegisterStacks() +{ + size_t count; + uint32_t* regs = BNGetAllArchitectureRegisterStacks(m_object, &count); + + vector result; + for (size_t i = 0; i < count; i++) + result.push_back(regs[i]); + + BNFreeRegisterList(regs); + return result; +} + + +BNRegisterStackInfo CoreArchitecture::GetRegisterStackInfo(uint32_t regStack) +{ + return BNGetArchitectureRegisterStackInfo(m_object, regStack); +} + + bool CoreArchitecture::Assemble(const string& code, uint64_t addr, DataBuffer& result, string& errors) { char* errorStr = nullptr; diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 7d686142..5c122966 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -1610,6 +1610,10 @@ namespace BinaryNinja static uint32_t GetLinkRegisterCallback(void* ctxt); static uint32_t* GetGlobalRegistersCallback(void* ctxt, size_t* count); + static char* GetRegisterStackNameCallback(void* ctxt, uint32_t regStack); + static uint32_t* GetAllRegisterStacksCallback(void* ctxt, size_t* count); + static void GetRegisterStackInfoCallback(void* ctxt, uint32_t regStack, BNRegisterStackInfo* result); + static bool AssembleCallback(void* ctxt, const char* code, uint64_t addr, BNDataBuffer* result, char** errors); static bool IsNeverBranchPatchAvailableCallback(void* ctxt, const uint8_t* data, uint64_t addr, size_t len); static bool IsAlwaysBranchPatchAvailableCallback(void* ctxt, const uint8_t* data, uint64_t addr, size_t len); @@ -1676,6 +1680,11 @@ namespace BinaryNinja std::vector GetModifiedRegistersOnWrite(uint32_t reg); uint32_t GetRegisterByName(const std::string& name); + virtual std::string GetRegisterStackName(uint32_t regStack); + virtual std::vector GetAllRegisterStacks(); + virtual BNRegisterStackInfo GetRegisterStackInfo(uint32_t regStack); + uint32_t GetRegisterStackForRegister(uint32_t reg); + virtual bool Assemble(const std::string& code, uint64_t addr, DataBuffer& result, std::string& errors); /*! IsNeverBranchPatchAvailable returns true if the instruction at addr can be patched to never branch. @@ -1800,6 +1809,10 @@ namespace BinaryNinja virtual uint32_t GetLinkRegister() override; virtual std::vector GetGlobalRegisters() override; + virtual std::string GetRegisterStackName(uint32_t regStack) override; + virtual std::vector GetAllRegisterStacks() override; + virtual BNRegisterStackInfo GetRegisterStackInfo(uint32_t regStack) override; + virtual bool Assemble(const std::string& code, uint64_t addr, DataBuffer& result, std::string& errors) override; virtual bool IsNeverBranchPatchAvailable(const uint8_t* data, uint64_t addr, size_t len) override; @@ -2394,6 +2407,7 @@ namespace BinaryNinja struct LowLevelILInstruction; struct SSARegister; + struct SSARegisterStack; struct SSAFlag; class LowLevelILFunction: public CoreRefCountObject& sources, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RegisterStackPhi(const SSARegisterStack& dest, const std::vector& sources, + const ILSourceLocation& loc = ILSourceLocation()); ExprId FlagPhi(const SSAFlag& dest, const std::vector& sources, const ILSourceLocation& loc = ILSourceLocation()); ExprId MemoryPhi(size_t dest, const std::vector& sources, @@ -2602,6 +2636,7 @@ namespace BinaryNinja ExprId AddOperandList(const std::vector operands); ExprId AddIndexList(const std::vector operands); ExprId AddSSARegisterList(const std::vector& regs); + ExprId AddSSARegisterStackList(const std::vector& regStacks); ExprId AddSSAFlagList(const std::vector& flags); ExprId GetExprForRegisterOrConstant(const BNRegisterOrConstant& operand, size_t size); @@ -2765,6 +2800,9 @@ namespace BinaryNinja const ILSourceLocation& loc = ILSourceLocation()); ExprId Const(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); ExprId ConstPointer(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatConstRaw(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatConstSingle(float val, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatConstDouble(double val, const ILSourceLocation& loc = ILSourceLocation()); ExprId ImportedAddress(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); ExprId Add(size_t size, ExprId left, ExprId right, const ILSourceLocation& loc = ILSourceLocation()); ExprId AddWithCarry(size_t size, ExprId left, ExprId right, ExprId carry, diff --git a/binaryninjacore.h b/binaryninjacore.h index 9bbea512..f50c28c8 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -281,14 +281,19 @@ extern "C" LLIL_SET_REG, // Not valid in SSA form (see LLIL_SET_REG_SSA) LLIL_SET_REG_SPLIT, // Not valid in SSA form (see LLIL_SET_REG_SPLIT_SSA) LLIL_SET_FLAG, // Not valid in SSA form (see LLIL_SET_FLAG_SSA) + LLIL_SET_REG_STACK_REL, // Not valid in SSA form (see LLIL_SET_REG_STACK_REL_SSA) + LLIL_REG_STACK_PUSH, // Not valid in SSA form (expanded) LLIL_LOAD, // Not valid in SSA form (see LLIL_LOAD_SSA) LLIL_STORE, // Not valid in SSA form (see LLIL_STORE_SSA) LLIL_PUSH, // Not valid in SSA form (expanded) LLIL_POP, // Not valid in SSA form (expanded) LLIL_REG, // Not valid in SSA form (see LLIL_REG_SSA) LLIL_REG_SPLIT, // Not valid in SSA form (see LLIL_REG_SPLIT_SSA) + LLIL_REG_STACK_REL, // Not valid in SSA form (see LLIL_REG_STACK_REL_SSA) + LLIL_REG_STACK_POP, // Not valid in SSA form (expanded) LLIL_CONST, LLIL_CONST_PTR, + LLIL_FLOAT_CONST, LLIL_FLAG, // Not valid in SSA form (see LLIL_FLAG_SSA) LLIL_FLAG_BIT, // Not valid in SSA form (see LLIL_FLAG_BIT_SSA) LLIL_ADD, @@ -373,10 +378,15 @@ extern "C" LLIL_SET_REG_SSA, LLIL_SET_REG_SSA_PARTIAL, LLIL_SET_REG_SPLIT_SSA, + LLIL_SET_REG_STACK_REL_SSA, + LLIL_SET_REG_STACK_ABS_SSA, LLIL_REG_SPLIT_DEST_SSA, // Only valid within an LLIL_SET_REG_SPLIT_SSA instruction + LLIL_REG_STACK_DEST_SSA, // Only valid within LLIL_SET_REG_STACK_REL_SSA or LLIL_SET_REG_STACK_ABS_SSA LLIL_REG_SSA, LLIL_REG_SSA_PARTIAL, LLIL_REG_SPLIT_SSA, + LLIL_REG_STACK_REL_SSA, + LLIL_REG_STACK_ABS_SSA, LLIL_SET_FLAG_SSA, LLIL_FLAG_SSA, LLIL_FLAG_BIT_SSA, @@ -388,6 +398,7 @@ extern "C" LLIL_LOAD_SSA, LLIL_STORE_SSA, LLIL_REG_PHI, + LLIL_REG_STACK_PHI, LLIL_FLAG_PHI, LLIL_MEM_PHI }; @@ -666,6 +677,13 @@ extern "C" BNImplicitRegisterExtend extend; }; + struct BNRegisterStackInfo + { + uint32_t firstStorageReg; + uint32_t count; + uint32_t stackTopReg; + }; + enum BNRegisterValueType { UndeterminedValue, @@ -771,6 +789,7 @@ extern "C" MLIL_ADDRESS_OF_FIELD, MLIL_CONST, MLIL_CONST_PTR, + MLIL_FLOAT_CONST, MLIL_IMPORT, MLIL_ADD, MLIL_ADC, @@ -1071,6 +1090,10 @@ extern "C" uint32_t (*getLinkRegister)(void* ctxt); uint32_t* (*getGlobalRegisters)(void* ctxt, size_t* count); + char* (*getRegisterStackName)(void* ctxt, uint32_t regStack); + uint32_t* (*getAllRegisterStacks)(void* ctxt, size_t* count); + void (*getRegisterStackInfo)(void* ctxt, uint32_t regStack, BNRegisterStackInfo* result); + bool (*assemble)(void* ctxt, const char* code, uint64_t addr, BNDataBuffer* result, char** errors); bool (*isNeverBranchPatchAvailable)(void* ctxt, const uint8_t* data, uint64_t addr, size_t len); @@ -2022,6 +2045,11 @@ extern "C" BINARYNINJACOREAPI bool BNIsArchitectureGlobalRegister(BNArchitecture* arch, uint32_t reg); BINARYNINJACOREAPI uint32_t BNGetArchitectureRegisterByName(BNArchitecture* arch, const char* name); + BINARYNINJACOREAPI char* BNGetArchitectureRegisterStackName(BNArchitecture* arch, uint32_t regStack); + BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureRegisterStacks(BNArchitecture* arch, size_t* count); + BINARYNINJACOREAPI BNRegisterStackInfo BNGetArchitectureRegisterStackInfo(BNArchitecture* arch, uint32_t regStack); + BINARYNINJACOREAPI uint32_t BNGetArchitectureRegisterStackForRegister(BNArchitecture* arch, uint32_t reg); + BINARYNINJACOREAPI bool BNAssemble(BNArchitecture* arch, const char* code, uint64_t addr, BNDataBuffer* result, char** errors); BINARYNINJACOREAPI bool BNIsArchitectureNeverBranchPatchAvailable(BNArchitecture* arch, const uint8_t* data, diff --git a/callingconvention.cpp b/callingconvention.cpp index 945ba25f..b29d51e2 100644 --- a/callingconvention.cpp +++ b/callingconvention.cpp @@ -264,8 +264,16 @@ vector CallingConvention::GetImplicitlyDefinedRegisters() } -RegisterValue CallingConvention::GetIncomingRegisterValue(uint32_t, Function*) -{ +RegisterValue CallingConvention::GetIncomingRegisterValue(uint32_t reg, Function*) +{ + uint32_t regStack = GetArchitecture()->GetRegisterStackForRegister(reg); + if ((regStack != BN_INVALID_REGISTER) && (reg == GetArchitecture()->GetRegisterStackInfo(regStack).stackTopReg)) + { + RegisterValue value; + value.state = ConstantValue; + value.value = 0; + return value; + } return RegisterValue(); } diff --git a/lowlevelil.cpp b/lowlevelil.cpp index 690f0b41..c72d4b68 100644 --- a/lowlevelil.cpp +++ b/lowlevelil.cpp @@ -230,6 +230,20 @@ ExprId LowLevelILFunction::AddSSARegisterList(const vector& regs) } +ExprId LowLevelILFunction::AddSSARegisterStackList(const vector& regStacks) +{ + uint64_t* operandList = new uint64_t[regStacks.size() * 2]; + for (size_t i = 0; i < regStacks.size(); i++) + { + operandList[i * 2] = regStacks[i].regStack; + operandList[(i * 2) + 1] = regStacks[i].version; + } + ExprId result = (ExprId)BNLowLevelILAddOperandList(m_object, operandList, regStacks.size() * 2); + delete[] operandList; + return result; +} + + ExprId LowLevelILFunction::AddSSAFlagList(const vector& flags) { uint64_t* operandList = new uint64_t[flags.size() * 2]; diff --git a/lowlevelilinstruction.cpp b/lowlevelilinstruction.cpp index 501b7b72..4130dd2a 100644 --- a/lowlevelilinstruction.cpp +++ b/lowlevelilinstruction.cpp @@ -37,17 +37,23 @@ unordered_map LowLevelILInstructionBase::operandTypeForUsage = { {SourceExprLowLevelOperandUsage, ExprLowLevelOperand}, {SourceRegisterLowLevelOperandUsage, RegisterLowLevelOperand}, + {SourceRegisterStackLowLevelOperandUsage, RegisterStackLowLevelOperand}, {SourceFlagLowLevelOperandUsage, FlagLowLevelOperand}, {SourceSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, + {SourceSSARegisterStackLowLevelOperandUsage, SSARegisterStackLowLevelOperand}, {SourceSSAFlagLowLevelOperandUsage, SSAFlagLowLevelOperand}, {DestExprLowLevelOperandUsage, ExprLowLevelOperand}, {DestRegisterLowLevelOperandUsage, RegisterLowLevelOperand}, + {DestRegisterStackLowLevelOperandUsage, RegisterStackLowLevelOperand}, {DestFlagLowLevelOperandUsage, FlagLowLevelOperand}, {DestSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, + {DestSSARegisterStackLowLevelOperandUsage, SSARegisterStackLowLevelOperand}, {DestSSAFlagLowLevelOperandUsage, SSAFlagLowLevelOperand}, {PartialRegisterLowLevelOperandUsage, RegisterLowLevelOperand}, + {PartialSSARegisterStackSourceLowLevelOperandUsage, SSARegisterStackLowLevelOperand}, {StackSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, {StackMemoryVersionLowLevelOperandUsage, IndexLowLevelOperand}, + {TopSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, {LeftExprLowLevelOperandUsage, ExprLowLevelOperand}, {RightExprLowLevelOperandUsage, ExprLowLevelOperand}, {CarryExprLowLevelOperandUsage, ExprLowLevelOperand}, @@ -70,6 +76,7 @@ unordered_map {OutputMemoryVersionLowLevelOperandUsage, IndexLowLevelOperand}, {ParameterSSARegistersLowLevelOperandUsage, SSARegisterListLowLevelOperand}, {SourceSSARegistersLowLevelOperandUsage, SSARegisterListLowLevelOperand}, + {SourceSSARegisterStacksLowLevelOperandUsage, SSARegisterStackListLowLevelOperand}, {SourceSSAFlagsLowLevelOperandUsage, SSAFlagListLowLevelOperand}, {SourceMemoryVersionsLowLevelOperandUsage, IndexListLowLevelOperand}, {TargetListLowLevelOperandUsage, IndexListLowLevelOperand} @@ -93,6 +100,15 @@ unordered_map> SourceExprLowLevelOperandUsage}}, {LLIL_SET_REG_SPLIT_SSA, {HighSSARegisterLowLevelOperandUsage, LowSSARegisterLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, + {LLIL_SET_REG_STACK_REL, {DestRegisterStackLowLevelOperandUsage, DestExprLowLevelOperandUsage, + SourceExprLowLevelOperandUsage}}, + {LLIL_REG_STACK_PUSH, {DestRegisterStackLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, + {LLIL_SET_REG_STACK_REL_SSA, {DestSSARegisterStackLowLevelOperandUsage, + PartialSSARegisterStackSourceLowLevelOperandUsage, DestExprLowLevelOperandUsage, + TopSSARegisterLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, + {LLIL_SET_REG_STACK_ABS_SSA, {DestSSARegisterStackLowLevelOperandUsage, + PartialSSARegisterStackSourceLowLevelOperandUsage, DestRegisterLowLevelOperandUsage, + SourceExprLowLevelOperandUsage}}, {LLIL_SET_FLAG, {DestFlagLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, {LLIL_SET_FLAG_SSA, {DestSSAFlagLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, {LLIL_LOAD, {SourceExprLowLevelOperandUsage}}, @@ -105,6 +121,11 @@ unordered_map> {LLIL_REG_SSA_PARTIAL, {SourceSSARegisterLowLevelOperandUsage, PartialRegisterLowLevelOperandUsage}}, {LLIL_REG_SPLIT, {HighRegisterLowLevelOperandUsage, LowRegisterLowLevelOperandUsage}}, {LLIL_REG_SPLIT_SSA, {HighSSARegisterLowLevelOperandUsage, LowSSARegisterLowLevelOperandUsage}}, + {LLIL_REG_STACK_REL, {SourceRegisterStackLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, + {LLIL_REG_STACK_POP, {SourceRegisterStackLowLevelOperandUsage}}, + {LLIL_REG_STACK_REL_SSA, {SourceSSARegisterStackLowLevelOperandUsage, TopSSARegisterLowLevelOperandUsage, + SourceExprLowLevelOperandUsage}}, + {LLIL_REG_STACK_ABS_SSA, {SourceSSARegisterStackLowLevelOperandUsage, SourceRegisterLowLevelOperandUsage}}, {LLIL_FLAG, {SourceFlagLowLevelOperandUsage}}, {LLIL_FLAG_BIT, {SourceFlagLowLevelOperandUsage, BitIndexLowLevelOperandUsage}}, {LLIL_FLAG_SSA, {SourceSSAFlagLowLevelOperandUsage}}, @@ -126,10 +147,12 @@ unordered_map> StackSSARegisterLowLevelOperandUsage, StackMemoryVersionLowLevelOperandUsage, ParameterSSARegistersLowLevelOperandUsage}}, {LLIL_REG_PHI, {DestSSARegisterLowLevelOperandUsage, SourceSSARegistersLowLevelOperandUsage}}, + {LLIL_REG_STACK_PHI, {DestSSARegisterStackLowLevelOperandUsage, SourceSSARegisterStacksLowLevelOperandUsage}}, {LLIL_FLAG_PHI, {DestSSAFlagLowLevelOperandUsage, SourceSSAFlagsLowLevelOperandUsage}}, {LLIL_MEM_PHI, {DestMemoryVersionLowLevelOperandUsage, SourceMemoryVersionsLowLevelOperandUsage}}, {LLIL_CONST, {ConstantLowLevelOperandUsage}}, {LLIL_CONST_PTR, {ConstantLowLevelOperandUsage}}, + {LLIL_FLOAT_CONST, {ConstantLowLevelOperandUsage}}, {LLIL_ADD, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, {LLIL_SUB, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, {LLIL_AND, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, @@ -211,6 +234,8 @@ static unordered_map() const } +const SSARegisterStack LowLevelILSSARegisterStackList::ListIterator::operator*() +{ + LowLevelILIntegerList::const_iterator cur = pos; + uint32_t regStack = (uint32_t)*cur; + ++cur; + size_t version = (size_t)*cur; + return SSARegisterStack(regStack, version); +} + + +LowLevelILSSARegisterStackList::LowLevelILSSARegisterStackList(LowLevelILFunction* func, + const BNLowLevelILInstruction& instr, size_t count): m_list(func, instr, count & (~1)) +{ +} + + +LowLevelILSSARegisterStackList::const_iterator LowLevelILSSARegisterStackList::begin() const +{ + const_iterator result; + result.pos = m_list.begin(); + return result; +} + + +LowLevelILSSARegisterStackList::const_iterator LowLevelILSSARegisterStackList::end() const +{ + const_iterator result; + result.pos = m_list.end(); + return result; +} + + +size_t LowLevelILSSARegisterStackList::size() const +{ + return m_list.size() / 2; +} + + +const SSARegisterStack LowLevelILSSARegisterStackList::operator[](size_t i) const +{ + if (i >= size()) + throw LowLevelILInstructionAccessException(); + auto iter = begin(); + for (size_t j = 0; j < i; j++) + ++iter; + return *iter; +} + + +LowLevelILSSARegisterStackList::operator vector() const +{ + vector result; + for (auto& i : *this) + result.push_back(i); + return result; +} + + const SSAFlag LowLevelILSSAFlagList::ListIterator::operator*() { LowLevelILIntegerList::const_iterator cur = pos; @@ -666,6 +801,14 @@ uint32_t LowLevelILOperand::GetRegister() const } +uint32_t LowLevelILOperand::GetRegisterStack() const +{ + if (m_type != RegisterStackLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsRegister(m_operandIndex); +} + + uint32_t LowLevelILOperand::GetFlag() const { if (m_type != FlagLowLevelOperand) @@ -687,12 +830,24 @@ SSARegister LowLevelILOperand::GetSSARegister() const if (m_type != SSARegisterLowLevelOperand) throw LowLevelILInstructionAccessException(); if ((m_usage == HighSSARegisterLowLevelOperandUsage) || (m_usage == LowSSARegisterLowLevelOperandUsage) || - (m_usage == StackSSARegisterLowLevelOperandUsage)) + (m_usage == StackSSARegisterLowLevelOperandUsage) || (m_usage == TopSSARegisterLowLevelOperandUsage)) return m_instr.GetRawOperandAsExpr(m_operandIndex).GetRawOperandAsSSARegister(0); return m_instr.GetRawOperandAsSSARegister(m_operandIndex); } +SSARegisterStack LowLevelILOperand::GetSSARegisterStack() const +{ + if (m_type != SSARegisterStackLowLevelOperand) + throw LowLevelILInstructionAccessException(); + if (m_usage == DestSSARegisterStackLowLevelOperandUsage) + return m_instr.GetRawOperandAsExpr(m_operandIndex).GetRawOperandAsSSARegisterStack(0); + if (m_usage == PartialSSARegisterStackSourceLowLevelOperandUsage) + return m_instr.GetRawOperandAsExpr(m_operandIndex).GetRawOperandAsPartialSSARegisterStackSource(0); + return m_instr.GetRawOperandAsSSARegisterStack(m_operandIndex); +} + + SSAFlag LowLevelILOperand::GetSSAFlag() const { if (m_type != SSAFlagLowLevelOperand) @@ -721,6 +876,14 @@ LowLevelILSSARegisterList LowLevelILOperand::GetSSARegisterList() const } +LowLevelILSSARegisterStackList LowLevelILOperand::GetSSARegisterStackList() const +{ + if (m_type != SSARegisterStackListLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsSSARegisterStackList(m_operandIndex); +} + + LowLevelILSSAFlagList LowLevelILOperand::GetSSAFlagList() const { if (m_type != SSAFlagListLowLevelOperand) @@ -886,6 +1049,18 @@ SSARegister LowLevelILInstructionBase::GetRawOperandAsSSARegister(size_t operand } +SSARegisterStack LowLevelILInstructionBase::GetRawOperandAsSSARegisterStack(size_t operand) const +{ + return SSARegisterStack((uint32_t)operands[operand], (size_t)operands[operand + 1]); +} + + +SSARegisterStack LowLevelILInstructionBase::GetRawOperandAsPartialSSARegisterStackSource(size_t operand) const +{ + return SSARegisterStack((uint32_t)operands[operand], (size_t)operands[operand + 2]); +} + + SSAFlag LowLevelILInstructionBase::GetRawOperandAsSSAFlag(size_t operand) const { return SSAFlag((uint32_t)operands[operand], (size_t)operands[operand + 1]); @@ -904,6 +1079,12 @@ LowLevelILSSARegisterList LowLevelILInstructionBase::GetRawOperandAsSSARegisterL } +LowLevelILSSARegisterStackList LowLevelILInstructionBase::GetRawOperandAsSSARegisterStackList(size_t operand) const +{ + return LowLevelILSSARegisterStackList(function, function->GetRawExpr(operands[operand + 1]), operands[operand]); +} + + LowLevelILSSAFlagList LowLevelILInstructionBase::GetRawOperandAsSSAFlagList(size_t operand) const { return LowLevelILSSAFlagList(function, function->GetRawExpr(operands[operand + 1]), operands[operand]); @@ -1147,12 +1328,32 @@ void LowLevelILInstruction::VisitExprs(const std::function().VisitExprs(func); break; + case LLIL_SET_REG_STACK_REL: + GetDestExpr().VisitExprs(func); + GetSourceExpr().VisitExprs(func); + break; + case LLIL_REG_STACK_PUSH: + GetSourceExpr().VisitExprs(func); + break; + case LLIL_SET_REG_STACK_REL_SSA: + GetDestExpr().VisitExprs(func); + GetSourceExpr().VisitExprs(func); + break; + case LLIL_SET_REG_STACK_ABS_SSA: + GetSourceExpr().VisitExprs(func); + break; case LLIL_SET_FLAG: GetSourceExpr().VisitExprs(func); break; case LLIL_SET_FLAG_SSA: GetSourceExpr().VisitExprs(func); break; + case LLIL_REG_STACK_REL: + GetSourceExpr().VisitExprs(func); + break; + case LLIL_REG_STACK_REL_SSA: + GetSourceExpr().VisitExprs(func); + break; case LLIL_LOAD: GetSourceExpr().VisitExprs(func); break; @@ -1300,6 +1501,25 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, return dest->SetRegisterSplitSSA(size, GetHighSSARegister(), GetLowSSARegister(), subExprHandler(GetSourceExpr()), *this); + case LLIL_SET_REG_STACK_REL: + return dest->SetRegisterStackTopRelative(size, GetDestRegisterStack(), + subExprHandler(GetDestExpr()), + subExprHandler(GetSourceExpr()), flags, *this); + case LLIL_REG_STACK_PUSH: + return dest->RegisterStackPush(size, GetDestRegisterStack(), + subExprHandler(GetSourceExpr()), flags, *this); + case LLIL_SET_REG_STACK_REL_SSA: + return dest->SetRegisterStackTopRelativeSSA(size, GetDestSSARegisterStack().regStack, + GetDestSSARegisterStack().version, + GetSourceSSARegisterStack().version, + subExprHandler(GetDestExpr()), GetTopSSARegister(), + subExprHandler(GetSourceExpr()), *this); + case LLIL_SET_REG_STACK_ABS_SSA: + return dest->SetRegisterStackAbsoluteSSA(size, GetDestSSARegisterStack().regStack, + GetDestSSARegisterStack().version, + GetSourceSSARegisterStack().version, + GetDestRegister(), + subExprHandler(GetSourceExpr()), *this); case LLIL_SET_FLAG: return dest->SetFlag(GetDestFlag(), subExprHandler(GetSourceExpr()), *this); case LLIL_SET_FLAG_SSA: @@ -1330,6 +1550,18 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, case LLIL_REG_SPLIT_SSA: return dest->RegisterSplitSSA(size, GetHighSSARegister(), GetLowSSARegister(), *this); + case LLIL_REG_STACK_REL: + return dest->RegisterStackTopRelative(size, GetSourceRegisterStack(), + subExprHandler(GetSourceExpr()), *this); + case LLIL_REG_STACK_POP: + return dest->RegisterStackPop(size, GetSourceRegisterStack(), *this); + case LLIL_REG_STACK_REL_SSA: + return dest->RegisterStackTopRelativeSSA(size, GetSourceSSARegisterStack(), + subExprHandler(GetSourceExpr()), + GetTopSSARegister(), *this); + case LLIL_REG_STACK_ABS_SSA: + return dest->RegisterStackAbsoluteSSA(size, GetSourceSSARegisterStack(), + GetSourceRegister(), *this); case LLIL_FLAG: return dest->Flag(GetSourceFlag(), *this); case LLIL_FLAG_SSA: @@ -1384,6 +1616,9 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, GetDestMemoryVersion(), GetSourceMemoryVersion(), *this); case LLIL_REG_PHI: return dest->RegisterPhi(GetDestSSARegister(), GetSourceSSARegisters(), *this); + case LLIL_REG_STACK_PHI: + return dest->RegisterStackPhi(GetDestSSARegisterStack(), + GetSourceSSARegisterStacks(), *this); case LLIL_FLAG_PHI: return dest->FlagPhi(GetDestSSAFlag(), GetSourceSSAFlags(), *this); case LLIL_MEM_PHI: @@ -1392,6 +1627,8 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, return dest->Const(size, GetConstant(), *this); case LLIL_CONST_PTR: return dest->ConstPointer(size, GetConstant(), *this); + case LLIL_FLOAT_CONST: + return dest->FloatConstRaw(size, GetConstant(), *this); case LLIL_POP: case LLIL_NORET: case LLIL_SYSCALL: @@ -1506,6 +1743,15 @@ uint32_t LowLevelILInstruction::GetSourceRegister() const } +uint32_t LowLevelILInstruction::GetSourceRegisterStack() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(SourceRegisterStackLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsRegister(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + uint32_t LowLevelILInstruction::GetSourceFlag() const { size_t operandIndex; @@ -1524,6 +1770,17 @@ SSARegister LowLevelILInstruction::GetSourceSSARegister() const } +SSARegisterStack LowLevelILInstruction::GetSourceSSARegisterStack() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(PartialSSARegisterStackSourceLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsExpr(operandIndex).GetRawOperandAsPartialSSARegisterStackSource(0); + if (GetOperandIndexForUsage(SourceSSARegisterStackLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsSSARegisterStack(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + SSAFlag LowLevelILInstruction::GetSourceSSAFlag() const { size_t operandIndex; @@ -1551,6 +1808,15 @@ uint32_t LowLevelILInstruction::GetDestRegister() const } +uint32_t LowLevelILInstruction::GetDestRegisterStack() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(DestRegisterStackLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsRegister(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + uint32_t LowLevelILInstruction::GetDestFlag() const { size_t operandIndex; @@ -1569,6 +1835,15 @@ SSARegister LowLevelILInstruction::GetDestSSARegister() const } +SSARegisterStack LowLevelILInstruction::GetDestSSARegisterStack() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(DestSSARegisterStackLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsExpr(operandIndex).GetRawOperandAsSSARegisterStack(0); + throw LowLevelILInstructionAccessException(); +} + + SSAFlag LowLevelILInstruction::GetDestSSAFlag() const { size_t operandIndex; @@ -1596,6 +1871,15 @@ SSARegister LowLevelILInstruction::GetStackSSARegister() const } +SSARegister LowLevelILInstruction::GetTopSSARegister() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(TopSSARegisterLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsExpr(operandIndex).GetRawOperandAsSSARegister(0); + throw LowLevelILInstructionAccessException(); +} + + LowLevelILInstruction LowLevelILInstruction::GetLeftExpr() const { size_t operandIndex; @@ -1789,6 +2073,15 @@ LowLevelILSSARegisterList LowLevelILInstruction::GetSourceSSARegisters() const } +LowLevelILSSARegisterStackList LowLevelILInstruction::GetSourceSSARegisterStacks() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(SourceSSARegisterStacksLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsSSARegisterStackList(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + LowLevelILSSAFlagList LowLevelILInstruction::GetSourceSSAFlags() const { size_t operandIndex; @@ -1859,6 +2152,39 @@ ExprId LowLevelILFunction::SetRegisterSplitSSA(size_t size, const SSARegister& h } +ExprId LowLevelILFunction::SetRegisterStackTopRelative(size_t size, uint32_t regStack, ExprId entry, + ExprId val, uint32_t flags, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_SET_REG_STACK_REL, loc, size, flags, regStack, entry, val); +} + + +ExprId LowLevelILFunction::RegisterStackPush(size_t size, uint32_t regStack, ExprId val, + uint32_t flags, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_PUSH, loc, size, flags, regStack, val); +} + + +ExprId LowLevelILFunction::SetRegisterStackTopRelativeSSA(size_t size, uint32_t regStack, + size_t destVersion, size_t srcVersion, ExprId entry, const SSARegister& top, + ExprId val, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_SET_REG_STACK_REL_SSA, loc, size, 0, + AddExprWithLocation(LLIL_REG_STACK_DEST_SSA, loc, size, 0, regStack, destVersion, srcVersion), + entry, AddExprWithLocation(LLIL_REG_SSA, loc, 0, 0, top.reg, top.version), val); +} + + +ExprId LowLevelILFunction::SetRegisterStackAbsoluteSSA(size_t size, uint32_t regStack, + size_t destVersion, size_t srcVersion, uint32_t reg, ExprId val, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_SET_REG_STACK_REL_SSA, loc, size, 0, + AddExprWithLocation(LLIL_REG_STACK_DEST_SSA, loc, size, 0, regStack, destVersion, srcVersion), + reg, val); +} + + ExprId LowLevelILFunction::SetFlag(uint32_t flag, ExprId val, const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_SET_FLAG, loc, 0, 0, flag, val); @@ -1943,6 +2269,34 @@ ExprId LowLevelILFunction::RegisterSplitSSA(size_t size, const SSARegister& high } +ExprId LowLevelILFunction::RegisterStackTopRelative(size_t size, uint32_t regStack, ExprId entry, + const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_REL, loc, size, 0, regStack, entry); +} + + +ExprId LowLevelILFunction::RegisterStackPop(size_t size, uint32_t regStack, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_POP, loc, size, 0, regStack); +} + + +ExprId LowLevelILFunction::RegisterStackTopRelativeSSA(size_t size, const SSARegisterStack& regStack, ExprId entry, + const SSARegister& top, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_REL_SSA, loc, size, 0, regStack.regStack, regStack.version, entry, + AddExprWithLocation(LLIL_REG_SSA, loc, 0, 0, top.reg, top.version)); +} + + +ExprId LowLevelILFunction::RegisterStackAbsoluteSSA(size_t size, const SSARegisterStack& regStack, uint32_t reg, + const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_ABS_SSA, loc, size, 0, regStack.regStack, regStack.version, reg); +} + + ExprId LowLevelILFunction::Const(size_t size, uint64_t val, const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_CONST, loc, size, 0, val); @@ -1955,6 +2309,36 @@ ExprId LowLevelILFunction::ConstPointer(size_t size, uint64_t val, const ILSourc } +ExprId LowLevelILFunction::FloatConstRaw(size_t size, uint64_t val, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_FLOAT_CONST, loc, size, 0, val); +} + + +ExprId LowLevelILFunction::FloatConstSingle(float val, const ILSourceLocation& loc) +{ + union + { + float f; + uint32_t i; + } bits; + bits.f = val; + return AddExprWithLocation(LLIL_FLOAT_CONST, loc, 4, 0, bits.i); +} + + +ExprId LowLevelILFunction::FloatConstDouble(double val, const ILSourceLocation& loc) +{ + union + { + double f; + uint64_t i; + } bits; + bits.f = val; + return AddExprWithLocation(LLIL_FLOAT_CONST, loc, 8, 0, bits.i); +} + + ExprId LowLevelILFunction::Flag(uint32_t flag, const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_FLAG, loc, 0, 0, flag); @@ -2358,6 +2742,14 @@ ExprId LowLevelILFunction::RegisterPhi(const SSARegister& dest, const vector& sources, + const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_PHI, loc, 0, 0, dest.regStack, dest.version, + sources.size() * 2, AddSSARegisterStackList(sources)); +} + + ExprId LowLevelILFunction::FlagPhi(const SSAFlag& dest, const vector& sources, const ILSourceLocation& loc) { diff --git a/lowlevelilinstruction.h b/lowlevelilinstruction.h index 8c8fe55f..4e02632e 100644 --- a/lowlevelilinstruction.h +++ b/lowlevelilinstruction.h @@ -69,6 +69,21 @@ namespace BinaryNinja bool operator<(const SSARegister& v) const; }; + struct SSARegisterStack + { + uint32_t regStack; + size_t version; + + SSARegisterStack(); + SSARegisterStack(uint32_t r, size_t i); + SSARegisterStack(const SSARegisterStack& v); + + SSARegisterStack& operator=(const SSARegisterStack& v); + bool operator==(const SSARegisterStack& v) const; + bool operator!=(const SSARegisterStack& v) const; + bool operator<(const SSARegisterStack& v) const; + }; + struct SSAFlag { uint32_t flag; @@ -90,12 +105,15 @@ namespace BinaryNinja IndexLowLevelOperand, ExprLowLevelOperand, RegisterLowLevelOperand, + RegisterStackLowLevelOperand, FlagLowLevelOperand, FlagConditionLowLevelOperand, SSARegisterLowLevelOperand, + SSARegisterStackLowLevelOperand, SSAFlagLowLevelOperand, IndexListLowLevelOperand, SSARegisterListLowLevelOperand, + SSARegisterStackListLowLevelOperand, SSAFlagListLowLevelOperand }; @@ -103,17 +121,23 @@ namespace BinaryNinja { SourceExprLowLevelOperandUsage, SourceRegisterLowLevelOperandUsage, + SourceRegisterStackLowLevelOperandUsage, SourceFlagLowLevelOperandUsage, SourceSSARegisterLowLevelOperandUsage, + SourceSSARegisterStackLowLevelOperandUsage, SourceSSAFlagLowLevelOperandUsage, DestExprLowLevelOperandUsage, DestRegisterLowLevelOperandUsage, + DestRegisterStackLowLevelOperandUsage, DestFlagLowLevelOperandUsage, DestSSARegisterLowLevelOperandUsage, + DestSSARegisterStackLowLevelOperandUsage, DestSSAFlagLowLevelOperandUsage, PartialRegisterLowLevelOperandUsage, + PartialSSARegisterStackSourceLowLevelOperandUsage, StackSSARegisterLowLevelOperandUsage, StackMemoryVersionLowLevelOperandUsage, + TopSSARegisterLowLevelOperandUsage, LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage, CarryExprLowLevelOperandUsage, @@ -136,6 +160,7 @@ namespace BinaryNinja OutputMemoryVersionLowLevelOperandUsage, ParameterSSARegistersLowLevelOperandUsage, SourceSSARegistersLowLevelOperandUsage, + SourceSSARegisterStacksLowLevelOperandUsage, SourceSSAFlagsLowLevelOperandUsage, SourceMemoryVersionsLowLevelOperandUsage, TargetListLowLevelOperandUsage @@ -162,6 +187,24 @@ namespace std } }; +#ifdef BINARYNINJACORE_LIBRARY + template<> struct hash +#else + template<> struct hash +#endif + { +#ifdef BINARYNINJACORE_LIBRARY + typedef BinaryNinjaCore::SSARegisterStack argument_type; +#else + typedef BinaryNinja::SSARegisterStack argument_type; +#endif + typedef uint64_t result_type; + result_type operator()(argument_type const& value) const + { + return ((result_type)value.regStack) ^ ((result_type)value.version << 32); + } + }; + #ifdef BINARYNINJACORE_LIBRARY template<> struct hash #else @@ -312,6 +355,33 @@ namespace BinaryNinja operator std::vector() const; }; + class LowLevelILSSARegisterStackList + { + struct ListIterator + { + LowLevelILIntegerList::const_iterator pos; + bool operator==(const ListIterator& a) const { return pos == a.pos; } + bool operator!=(const ListIterator& a) const { return pos != a.pos; } + bool operator<(const ListIterator& a) const { return pos < a.pos; } + ListIterator& operator++() { ++pos; ++pos; return *this; } + const SSARegisterStack operator*(); + }; + + LowLevelILIntegerList m_list; + + public: + typedef ListIterator const_iterator; + + LowLevelILSSARegisterStackList(LowLevelILFunction* func, const BNLowLevelILInstruction& instr, size_t count); + + const_iterator begin() const; + const_iterator end() const; + size_t size() const; + const SSARegisterStack operator[](size_t i) const; + + operator std::vector() const; + }; + class LowLevelILSSAFlagList { struct ListIterator @@ -362,9 +432,12 @@ namespace BinaryNinja BNLowLevelILFlagCondition GetRawOperandAsFlagCondition(size_t operand) const; LowLevelILInstruction GetRawOperandAsExpr(size_t operand) const; SSARegister GetRawOperandAsSSARegister(size_t operand) const; + SSARegisterStack GetRawOperandAsSSARegisterStack(size_t operand) const; + SSARegisterStack GetRawOperandAsPartialSSARegisterStackSource(size_t operand) const; SSAFlag GetRawOperandAsSSAFlag(size_t operand) const; LowLevelILIndexList GetRawOperandAsIndexList(size_t operand) const; LowLevelILSSARegisterList GetRawOperandAsSSARegisterList(size_t operand) const; + LowLevelILSSARegisterStackList GetRawOperandAsSSARegisterStackList(size_t operand) const; LowLevelILSSAFlagList GetRawOperandAsSSAFlagList(size_t operand) const; void UpdateRawOperand(size_t operandIndex, ExprId value); @@ -467,16 +540,21 @@ namespace BinaryNinja // Templated accessors for instruction operands, use these for efficient access to a known instruction template LowLevelILInstruction GetSourceExpr() const { return As().GetSourceExpr(); } template uint32_t GetSourceRegister() const { return As().GetSourceRegister(); } + template uint32_t GetSourceRegisterStack() const { return As().GetSourceRegisterStack(); } template uint32_t GetSourceFlag() const { return As().GetSourceFlag(); } template SSARegister GetSourceSSARegister() const { return As().GetSourceSSARegister(); } + template SSARegisterStack GetSourceSSARegisterStack() const { return As().GetSourceSSARegisterStack(); } template SSAFlag GetSourceSSAFlag() const { return As().GetSourceSSAFlag(); } template LowLevelILInstruction GetDestExpr() const { return As().GetDestExpr(); } template uint32_t GetDestRegister() const { return As().GetDestRegister(); } + template uint32_t GetDestRegisterStack() const { return As().GetDestRegisterStack(); } template uint32_t GetDestFlag() const { return As().GetDestFlag(); } template SSARegister GetDestSSARegister() const { return As().GetDestSSARegister(); } + template SSARegisterStack GetDestSSARegisterStack() const { return As().GetDestSSARegisterStack(); } template SSAFlag GetDestSSAFlag() const { return As().GetDestSSAFlag(); } template uint32_t GetPartialRegister() const { return As().GetPartialRegister(); } template SSARegister GetStackSSARegister() const { return As().GetStackSSARegister(); } + template SSARegister GetTopSSARegister() const { return As().GetTopSSARegister(); } template LowLevelILInstruction GetLeftExpr() const { return As().GetLeftExpr(); } template LowLevelILInstruction GetRightExpr() const { return As().GetRightExpr(); } template LowLevelILInstruction GetCarryExpr() const { return As().GetCarryExpr(); } @@ -498,6 +576,7 @@ namespace BinaryNinja template LowLevelILSSARegisterList GetOutputSSARegisters() const { return As().GetOutputSSARegisters(); } template LowLevelILSSARegisterList GetParameterSSARegisters() const { return As().GetParameterSSARegisters(); } template LowLevelILSSARegisterList GetSourceSSARegisters() const { return As().GetSourceSSARegisters(); } + template LowLevelILSSARegisterStackList GetSourceSSARegisterStacks() const { return As().GetSourceSSARegisterStacks(); } template LowLevelILSSAFlagList GetSourceSSAFlags() const { return As().GetSourceSSAFlags(); } template LowLevelILIndexList GetSourceMemoryVersions() const { return As().GetSourceMemoryVersions(); } template LowLevelILIndexList GetTargetList() const { return As().GetTargetList(); } @@ -507,6 +586,7 @@ namespace BinaryNinja template void SetHighSSAVersion(size_t version) { As().SetHighSSAVersion(version); } template void SetLowSSAVersion(size_t version) { As().SetLowSSAVersion(version); } template void SetStackSSAVersion(size_t version) { As().SetStackSSAVersion(version); } + template void SetTopSSAVersion(size_t version) { As().SetTopSSAVersion(version); } template void SetDestMemoryVersion(size_t version) { As().SetDestMemoryVersion(version); } template void SetSourceMemoryVersion(size_t version) { As().SetSourceMemoryVersion(version); } template void SetOutputSSARegisters(const std::vector& regs) { As().SetOutputSSARegisters(regs); } @@ -518,16 +598,21 @@ namespace BinaryNinja // on type mismatch. These are slower than the templated versions above. LowLevelILInstruction GetSourceExpr() const; uint32_t GetSourceRegister() const; + uint32_t GetSourceRegisterStack() const; uint32_t GetSourceFlag() const; SSARegister GetSourceSSARegister() const; + SSARegisterStack GetSourceSSARegisterStack() const; SSAFlag GetSourceSSAFlag() const; LowLevelILInstruction GetDestExpr() const; uint32_t GetDestRegister() const; + uint32_t GetDestRegisterStack() const; uint32_t GetDestFlag() const; SSARegister GetDestSSARegister() const; + SSARegisterStack GetDestSSARegisterStack() const; SSAFlag GetDestSSAFlag() const; uint32_t GetPartialRegister() const; SSARegister GetStackSSARegister() const; + SSARegister GetTopSSARegister() const; LowLevelILInstruction GetLeftExpr() const; LowLevelILInstruction GetRightExpr() const; LowLevelILInstruction GetCarryExpr() const; @@ -549,6 +634,7 @@ namespace BinaryNinja LowLevelILSSARegisterList GetOutputSSARegisters() const; LowLevelILSSARegisterList GetParameterSSARegisters() const; LowLevelILSSARegisterList GetSourceSSARegisters() const; + LowLevelILSSARegisterStackList GetSourceSSARegisterStacks() const; LowLevelILSSAFlagList GetSourceSSAFlags() const; LowLevelILIndexList GetSourceMemoryVersions() const; LowLevelILIndexList GetTargetList() const; @@ -572,12 +658,15 @@ namespace BinaryNinja size_t GetIndex() const; LowLevelILInstruction GetExpr() const; uint32_t GetRegister() const; + uint32_t GetRegisterStack() const; uint32_t GetFlag() const; BNLowLevelILFlagCondition GetFlagCondition() const; SSARegister GetSSARegister() const; + SSARegisterStack GetSSARegisterStack() const; SSAFlag GetSSAFlag() const; LowLevelILIndexList GetIndexList() const; LowLevelILSSARegisterList GetSSARegisterList() const; + LowLevelILSSARegisterStackList GetSSARegisterStackList() const; LowLevelILSSAFlagList GetSSAFlagList() const; }; @@ -671,6 +760,37 @@ namespace BinaryNinja void SetHighSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(1, version); } void SetLowSSAVersion(size_t version) { GetRawOperandAsExpr(1).UpdateRawOperand(1, version); } }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetDestRegisterStack() const { return GetRawOperandAsRegister(0); } + LowLevelILInstruction GetDestExpr() const { return GetRawOperandAsExpr(1); } + LowLevelILInstruction GetSourceExpr() const { return GetRawOperandAsExpr(2); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetDestRegisterStack() const { return GetRawOperandAsRegister(0); } + LowLevelILInstruction GetSourceExpr() const { return GetRawOperandAsExpr(1); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetDestSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsSSARegisterStack(0); } + SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsPartialSSARegisterStackSource(0); } + LowLevelILInstruction GetDestExpr() const { return GetRawOperandAsExpr(1); } + SSARegister GetTopSSARegister() const { return GetRawOperandAsExpr(2).GetRawOperandAsSSARegister(0); } + LowLevelILInstruction GetSourceExpr() const { return GetRawOperandAsExpr(3); } + void SetDestSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(1, version); } + void SetSourceSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(2, version); } + void SetTopSSAVersion(size_t version) { GetRawOperandAsExpr(2).UpdateRawOperand(1, version); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetDestSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsSSARegisterStack(0); } + SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsPartialSSARegisterStackSource(0); } + uint32_t GetDestRegister() const { return GetRawOperandAsRegister(1); } + LowLevelILInstruction GetSourceExpr() const { return GetRawOperandAsExpr(2); } + void SetDestSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(1, version); } + void SetSourceSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(2, version); } + }; template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { uint32_t GetDestFlag() const { return GetRawOperandAsRegister(0); } @@ -721,6 +841,29 @@ namespace BinaryNinja uint32_t GetPartialRegister() const { return GetRawOperandAsRegister(2); } void SetSourceSSAVersion(size_t version) { UpdateRawOperand(1, version); } }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetSourceRegisterStack() const { return GetRawOperandAsRegister(0); } + LowLevelILInstruction GetSourceExpr() const { return GetRawOperandAsExpr(1); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetSourceRegisterStack() const { return GetRawOperandAsRegister(0); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsSSARegisterStack(0); } + LowLevelILInstruction GetSourceExpr() const { return GetRawOperandAsExpr(2); } + SSARegister GetTopSSARegister() const { return GetRawOperandAsExpr(3).GetRawOperandAsSSARegister(0); } + void SetSourceSSAVersion(size_t version) { UpdateRawOperand(1, version); } + void SetTopSSAVersion(size_t version) { GetRawOperandAsExpr(3).UpdateRawOperand(1, version); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsSSARegisterStack(0); } + uint32_t GetSourceRegister() const { return GetRawOperandAsRegister(2); } + void SetSourceSSAVersion(size_t version) { UpdateRawOperand(1, version); } + }; template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { uint32_t GetSourceFlag() const { return GetRawOperandAsRegister(0); } @@ -832,6 +975,11 @@ namespace BinaryNinja SSARegister GetDestSSARegister() const { return GetRawOperandAsSSARegister(0); } LowLevelILSSARegisterList GetSourceSSARegisters() const { return GetRawOperandAsSSARegisterList(2); } }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetDestSSARegisterStack() const { return GetRawOperandAsSSARegisterStack(0); } + LowLevelILSSARegisterStackList GetSourceSSARegisterStacks() const { return GetRawOperandAsSSARegisterStackList(2); } + }; template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { SSAFlag GetDestSSAFlag() const { return GetRawOperandAsSSAFlag(0); } @@ -853,6 +1001,7 @@ namespace BinaryNinja template <> struct LowLevelILInstructionAccessor: public LowLevelILConstantInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILConstantInstruction {}; + template <> struct LowLevelILInstructionAccessor: public LowLevelILConstantInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; diff --git a/mediumlevelilinstruction.cpp b/mediumlevelilinstruction.cpp index b0e607b2..c3b4014f 100644 --- a/mediumlevelilinstruction.cpp +++ b/mediumlevelilinstruction.cpp @@ -149,6 +149,7 @@ unordered_map> {MLIL_MEM_PHI, {DestMemoryVersionMediumLevelOperandUsage, SourceMemoryVersionsMediumLevelOperandUsage}}, {MLIL_CONST, {ConstantMediumLevelOperandUsage}}, {MLIL_CONST_PTR, {ConstantMediumLevelOperandUsage}}, + {MLIL_FLOAT_CONST, {ConstantMediumLevelOperandUsage}}, {MLIL_IMPORT, {ConstantMediumLevelOperandUsage}}, {MLIL_ADD, {LeftExprMediumLevelOperandUsage, RightExprMediumLevelOperandUsage}}, {MLIL_SUB, {LeftExprMediumLevelOperandUsage, RightExprMediumLevelOperandUsage}}, @@ -1598,6 +1599,8 @@ ExprId MediumLevelILInstruction::CopyTo(MediumLevelILFunction* dest, return dest->Const(size, GetConstant(), *this); case MLIL_CONST_PTR: return dest->ConstPointer(size, GetConstant(), *this); + case MLIL_FLOAT_CONST: + return dest->FloatConstRaw(size, GetConstant(), *this); case MLIL_IMPORT: return dest->ImportedAddress(size, GetConstant(), *this); case MLIL_BP: @@ -2131,6 +2134,36 @@ ExprId MediumLevelILFunction::ConstPointer(size_t size, uint64_t val, const ILSo } +ExprId MediumLevelILFunction::FloatConstRaw(size_t size, uint64_t val, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_FLOAT_CONST, loc, size, val); +} + + +ExprId MediumLevelILFunction::FloatConstSingle(float val, const ILSourceLocation& loc) +{ + union + { + float f; + uint32_t i; + } bits; + bits.f = val; + return AddExprWithLocation(MLIL_FLOAT_CONST, loc, 4, bits.i); +} + + +ExprId MediumLevelILFunction::FloatConstDouble(double val, const ILSourceLocation& loc) +{ + union + { + double f; + uint64_t i; + } bits; + bits.f = val; + return AddExprWithLocation(MLIL_FLOAT_CONST, loc, 8, bits.i); +} + + ExprId MediumLevelILFunction::ImportedAddress(size_t size, uint64_t val, const ILSourceLocation& loc) { return AddExprWithLocation(MLIL_IMPORT, loc, size, val); diff --git a/mediumlevelilinstruction.h b/mediumlevelilinstruction.h index aa4600df..85630843 100644 --- a/mediumlevelilinstruction.h +++ b/mediumlevelilinstruction.h @@ -925,6 +925,7 @@ namespace BinaryNinja template <> struct MediumLevelILInstructionAccessor: public MediumLevelILConstantInstruction {}; template <> struct MediumLevelILInstructionAccessor: public MediumLevelILConstantInstruction {}; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILConstantInstruction {}; template <> struct MediumLevelILInstructionAccessor: public MediumLevelILConstantInstruction {}; template <> struct MediumLevelILInstructionAccessor: public MediumLevelILTwoOperandInstruction {}; diff --git a/python/architecture.py b/python/architecture.py index 72403fec..289b0abd 100644 --- a/python/architecture.py +++ b/python/architecture.py @@ -122,6 +122,7 @@ class Architecture(object): flag_roles = {} flags_required_for_flag_condition = {} flags_written_by_flag_write_type = {} + reg_stacks = {} __metaclass__ = _ArchitectureMetaClass next_address = 0 @@ -216,6 +217,19 @@ class Architecture(object): for i in xrange(0, count.value): self.global_regs.append(core.BNGetArchitectureRegisterName(self.handle, regs[i])) core.BNFreeRegisterList(regs) + + count = ctypes.c_ulonglong() + regs = core.BNGetAllArchitectureRegisterStacks(self.handle, count) + self.__dict__["reg_stacks"] = {} + for i in xrange(0, count.value): + name = core.BNGetArchitectureRegisterStackName(self.handle, regs[i]) + info = core.BNGetArchitectureRegisterStackInfo(self.handle, regs[i]) + storage = [] + for j in xrange(0, info.count): + storage.append(core.BNGetArchitectureRegisterName(self.handle, info.firstStorageReg + j)) + top = core.BNGetArchitectureRegisterName(self.handle, info.stackTopReg) + self.reg_stacks[name] = function.RegisterStackInfo(storage, top) + core.BNFreeRegisterList(regs) else: startup._init_plugins() @@ -259,6 +273,9 @@ class Architecture(object): self._get_stack_pointer_register) self._cb.getLinkRegister = self._cb.getLinkRegister.__class__(self._get_link_register) self._cb.getGlobalRegisters = self._cb.getGlobalRegisters.__class__(self._get_global_registers) + self._cb.getRegisterStackName = self._cb.getRegisterStackName.__class__(self._get_register_stack_name) + self._cb.getAllRegisterStacks = self._cb.getAllRegisterStacks.__class__(self._get_all_register_stacks) + self._cb.getRegisterStackInfo = self._cb.getRegisterStackInfo.__class__(self._get_register_stack_info) self._cb.assemble = self._cb.assemble.__class__(self._assemble) self._cb.isNeverBranchPatchAvailable = self._cb.isNeverBranchPatchAvailable.__class__( self._is_never_branch_patch_available) @@ -280,6 +297,25 @@ class Architecture(object): self._regs_by_index = {} self.__dict__["regs"] = self.__class__.regs reg_index = 0 + + # Registers used for storage in register stacks must be sequential, so allocate these in order first + self._all_reg_stacks = {} + self._reg_stacks_by_index = {} + self.__dict__["reg_stacks"] = self.__class__.reg_stacks + reg_stack_index = 0 + for reg_stack in self.reg_stacks: + info = self.reg_stacks[reg_stack] + for reg in info.storage_regs: + self._all_regs[reg] = reg_index + self._regs_by_index[reg_index] = reg + self.regs[reg].index = reg_index + reg_index += 1 + if reg_stack not in self._all_reg_stacks: + self._all_reg_stacks[reg_stack] = reg_stack_index + self._reg_stacks_by_index[reg_stack_index] = reg_stack + self.reg_stacks[reg_stack].index = reg_stack_index + reg_stack_index += 1 + for reg in self.regs: info = self.regs[reg] if reg not in self._all_regs: @@ -744,6 +780,47 @@ class Architecture(object): count[0] = 0 return None + def _get_register_stack_name(self, ctxt, reg_stack): + try: + if reg_stack in self._reg_stacks_by_index: + return core.BNAllocString(self._reg_stacks_by_index[reg_stack]) + return core.BNAllocString("") + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + return core.BNAllocString("") + + def _get_all_register_stacks(self, ctxt, count): + try: + regs = self._reg_stacks_by_index.keys() + count[0] = len(regs) + reg_buf = (ctypes.c_uint * len(regs))() + for i in xrange(0, len(regs)): + reg_buf[i] = regs[i] + result = ctypes.cast(reg_buf, ctypes.c_void_p) + self._pending_reg_lists[result.value] = (result, reg_buf) + return result.value + except KeyError: + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _get_register_stack_info(self, ctxt, reg_stack, result): + try: + if reg_stack not in self._reg_stacks_by_index: + result[0].firstStorageReg = 0 + result[0].count = 0 + result[0].stackTopReg = 0 + return + info = self.__class__.regs[self._reg_stacks_by_index[reg_stack]] + result[0].firstStorageReg = self._all_regs[info.storage_regs[0]] + result[0].count = len(info.storage_regs) + result[0].stackTopReg = self._all_regs[info.stack_top_reg] + except KeyError: + log.log_error(traceback.format_exc()) + result[0].firstStorageReg = 0 + result[0].count = 0 + result[0].stackTopReg = 0 + def _assemble(self, ctxt, code, addr, result, errors): try: data, error_str = self.perform_assemble(code, addr) @@ -1251,6 +1328,23 @@ class Architecture(object): """ return core.BNGetArchitectureRegisterName(self.handle, reg) + def get_reg_stack_name(self, reg_stack): + """ + ``get_reg_stack_name`` gets a register stack name from a register stack number. + + :param int reg_stack: register stack number + :return: the corresponding register string + :rtype: str + """ + return core.BNGetArchitectureRegisterStackName(self.handle, reg_stack) + + def get_reg_stack_for_reg(self, reg): + reg = self.get_reg_index(reg) + result = core.BNGetArchitectureRegisterStackForRegister(self.handle, reg) + if result == 0xffffffff: + return None + return self.get_reg_stack_name(result) + def get_flag_name(self, flag): """ ``get_flag_name`` gets a flag name from a flag number. @@ -1268,6 +1362,13 @@ class Architecture(object): return reg.index return reg + def get_reg_stack_index(self, reg_stack): + if isinstance(reg_stack, str): + return self.reg_stacks[reg_stack].index + elif isinstance(reg_stack, lowlevelil.ILRegisterStack): + return reg_stack.index + return reg_stack + def get_flag_index(self, flag): if isinstance(flag, str): return self._flags[flag] diff --git a/python/callingconvention.py b/python/callingconvention.py index e72475c9..18662fc5 100644 --- a/python/callingconvention.py +++ b/python/callingconvention.py @@ -308,6 +308,10 @@ class CallingConvention(object): return self.name def perform_get_incoming_reg_value(self, reg, func): + reg_stack = self.arch.get_reg_stack_for_reg(reg) + if reg_stack is not None: + if reg == self.arch.reg_stacks[reg_stack].stack_top_reg: + return function.RegisterValue.constant(0) return function.RegisterValue() def perform_get_incoming_flag_value(self, reg, func): diff --git a/python/function.py b/python/function.py index 5daa7b2a..eb8796f1 100644 --- a/python/function.py +++ b/python/function.py @@ -51,11 +51,11 @@ class LookupTableEntry(object): class RegisterValue(object): def __init__(self, arch = None, value = None, confidence = types.max_confidence): + self.is_constant = False if value is None: self.type = RegisterValueType.UndeterminedValue else: self.type = RegisterValueType(value.state) - self.is_constant = False if value.state == RegisterValueType.EntryValue: self.arch = arch if arch is not None: @@ -103,6 +103,54 @@ class RegisterValue(object): result.value = self.value return result + @classmethod + def undetermined(self): + return RegisterValue() + + @classmethod + def entry_value(self, arch, reg): + result = RegisterValue() + result.type = RegisterValueType.EntryValue + result.arch = arch + result.reg = reg + return result + + @classmethod + def constant(self, value): + result = RegisterValue() + result.type = RegisterValueType.ConstantValue + result.value = value + result.is_constant = True + return result + + @classmethod + def constant_ptr(self, value): + result = RegisterValue() + result.type = RegisterValueType.ConstantPointerValue + result.value = value + result.is_constant = True + return result + + @classmethod + def stack_frame_offset(self, offset): + result = RegisterValue() + result.type = RegisterValueType.StackFrameOffset + result.offset = offset + return result + + @classmethod + def imported_address(self, value): + result = RegisterValue() + result.type = RegisterValueType.ImportedAddressValue + result.value = value + return result + + @classmethod + def return_address(self): + result = RegisterValue() + result.type = RegisterValueType.ReturnAddressValue + return result + class ValueRange(object): def __init__(self, start, end, step): @@ -1678,6 +1726,15 @@ class RegisterInfo(object): return "" % (self.size, self.offset, self.full_width_reg, extend) +class RegisterStackInfo(object): + def __init__(self, storage_regs, stack_top_reg): + self.storage_regs = storage_regs + self.stack_top_reg = stack_top_reg + + def __repr__(self): + return "" % (len(self.storage_regs), self.stack_top_reg) + + class InstructionBranch(object): def __init__(self, branch_type, target = 0, arch = None): self.type = branch_type diff --git a/python/lowlevelil.py b/python/lowlevelil.py index a3b1fcb6..f5a39b7e 100644 --- a/python/lowlevelil.py +++ b/python/lowlevelil.py @@ -26,6 +26,7 @@ from .enums import LowLevelILOperation, LowLevelILFlagCondition, InstructionText import function import basicblock import mediumlevelil +import struct class LowLevelILLabel(object): @@ -61,6 +62,26 @@ class ILRegister(object): return self.info == other.info +class ILRegisterStack(object): + def __init__(self, arch, reg_stack): + self.arch = arch + self.index = reg_stack + self.name = self.arch.get_reg_stack_name(self.index) + + @property + def info(self): + return self.arch.reg_stacks[self.name] + + def __str__(self): + return self.name + + def __repr__(self): + return self.name + + def __eq__(self, other): + return self.info == other.info + + class ILFlag(object): def __init__(self, arch, flag): self.arch = arch @@ -87,6 +108,15 @@ class SSARegister(object): return "" % (repr(self.reg), self.version) +class SSARegisterStack(object): + def __init__(self, reg_stack, version): + self.reg_stack = reg_stack + self.version = version + + def __repr__(self): + return "" % (repr(self.reg_stack), self.version) + + class SSAFlag(object): def __init__(self, flag, version): self.flag = flag @@ -118,15 +148,20 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_NOP: [], LowLevelILOperation.LLIL_SET_REG: [("dest", "reg"), ("src", "expr")], LowLevelILOperation.LLIL_SET_REG_SPLIT: [("hi", "reg"), ("lo", "reg"), ("src", "expr")], + LowLevelILOperation.LLIL_SET_REG_STACK_REL: [("stack", "reg_stack"), ("dest", "expr"), ("src", "expr")], + LowLevelILOperation.LLIL_REG_STACK_PUSH: [("stack", "reg_stack"), ("src", "expr")], LowLevelILOperation.LLIL_SET_FLAG: [("dest", "flag"), ("src", "expr")], LowLevelILOperation.LLIL_LOAD: [("src", "expr")], LowLevelILOperation.LLIL_STORE: [("dest", "expr"), ("src", "expr")], LowLevelILOperation.LLIL_PUSH: [("src", "expr")], LowLevelILOperation.LLIL_POP: [], LowLevelILOperation.LLIL_REG: [("src", "reg")], - LowLevelILOperation.LLIL_REG_SPLIT: [("hi", "reg", "lo", "reg")], + LowLevelILOperation.LLIL_REG_SPLIT: [("hi", "reg"), ("lo", "reg")], + LowLevelILOperation.LLIL_REG_STACK_REL: [("stack", "reg_stack"), ("src", "expr")], + LowLevelILOperation.LLIL_REG_STACK_POP: [("stack", "reg_stack")], LowLevelILOperation.LLIL_CONST: [("constant", "int")], LowLevelILOperation.LLIL_CONST_PTR: [("constant", "int")], + LowLevelILOperation.LLIL_FLOAT_CONST: [("constant", "float")], LowLevelILOperation.LLIL_FLAG: [("src", "flag")], LowLevelILOperation.LLIL_FLAG_BIT: [("src", "flag"), ("bit", "int")], LowLevelILOperation.LLIL_ADD: [("left", "expr"), ("right", "expr")], @@ -207,10 +242,15 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_SET_REG_SSA: [("dest", "reg_ssa"), ("src", "expr")], LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")], LowLevelILOperation.LLIL_SET_REG_SPLIT_SSA: [("hi", "expr"), ("lo", "expr"), ("src", "expr")], + LowLevelILOperation.LLIL_SET_REG_STACK_REL_SSA: [("stack", "expr"), ("dest", "expr"), ("top", "expr"), ("src", "expr")], + LowLevelILOperation.LLIL_SET_REG_STACK_ABS_SSA: [("stack", "expr"), ("dest", "reg"), ("src", "expr")], LowLevelILOperation.LLIL_REG_SPLIT_DEST_SSA: [("dest", "reg_ssa")], + LowLevelILOperation.LLIL_REG_STACK_DEST_SSA: [("src", "reg_stack_ssa_dest_and_src")], LowLevelILOperation.LLIL_REG_SSA: [("src", "reg_ssa")], LowLevelILOperation.LLIL_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("src", "reg")], LowLevelILOperation.LLIL_REG_SPLIT_SSA: [("hi", "reg_ssa"), ("lo", "reg_ssa")], + LowLevelILOperation.LLIL_REG_STACK_REL_SSA: [("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")], + LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: [("stack", "reg_stack_ssa"), ("src", "reg")], LowLevelILOperation.LLIL_SET_FLAG_SSA: [("dest", "flag_ssa"), ("src", "expr")], LowLevelILOperation.LLIL_FLAG_SSA: [("src", "flag_ssa")], LowLevelILOperation.LLIL_FLAG_BIT_SSA: [("src", "flag_ssa"), ("bit", "int")], @@ -222,6 +262,7 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_LOAD_SSA: [("src", "expr"), ("src_memory", "int")], LowLevelILOperation.LLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")], LowLevelILOperation.LLIL_REG_PHI: [("dest", "reg_ssa"), ("src", "reg_ssa_list")], + LowLevelILOperation.LLIL_REG_STACK_PHI: [("dest", "reg_stack_ssa"), ("src", "reg_stack_ssa_list")], LowLevelILOperation.LLIL_FLAG_PHI: [("dest", "flag_ssa"), ("src", "flag_ssa_list")], LowLevelILOperation.LLIL_MEM_PHI: [("dest_memory", "int"), ("src_memory", "int_list")] } @@ -248,14 +289,35 @@ class LowLevelILInstruction(object): name, operand_type = operand if operand_type == "int": value = instr.operands[i] + elif operand_type == "float": + if instr.size == 4: + value = struct.unpack("f", struct.pack("I", instr.operands[i] & 0xffffffff))[0] + elif instr.size == 8: + value = struct.unpack("d", struct.pack("Q", instr.operands[i]))[0] + else: + value = instr.operands[i] elif operand_type == "expr": value = LowLevelILInstruction(func, instr.operands[i]) elif operand_type == "reg": value = ILRegister(func.arch, instr.operands[i]) + elif operand_type == "reg_stack": + value = ILRegisterStack(func.arch, instr.operands[i]) elif operand_type == "reg_ssa": reg = ILRegister(func.arch, instr.operands[i]) i += 1 value = SSARegister(reg, instr.operands[i]) + elif operand_type == "reg_stack_ssa": + reg_stack = ILRegisterStack(func.arch, instr.operands[i]) + i += 1 + value = SSARegisterStack(reg_stack, instr.operands[i]) + elif operand_type == "reg_stack_ssa_dest_and_src": + reg_stack = ILRegisterStack(func.arch, instr.operands[i]) + i += 1 + value = SSARegisterStack(reg_stack, instr.operands[i]) + i += 1 + self.operands.append(value) + self.dest = value + value = SSARegisterStack(reg_stack, instr.operands[i]) elif operand_type == "flag": value = ILFlag(func.arch, instr.operands[i]) elif operand_type == "flag_ssa": @@ -282,6 +344,16 @@ class LowLevelILInstruction(object): reg_version = operand_list[(i * 2) + 1] value.append(SSARegister(ILRegister(func.arch, reg), reg_version)) core.BNLowLevelILFreeOperandList(operand_list) + elif operand_type == "reg_stack_ssa_list": + count = ctypes.c_ulonglong() + operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) + i += 1 + value = [] + for i in xrange(count.value / 2): + reg_stack = operand_list[i * 2] + reg_version = operand_list[(i * 2) + 1] + value.append(SSARegisterStack(ILRegisterStack(func.arch, reg_stack), reg_version)) + core.BNLowLevelILFreeOperandList(operand_list) elif operand_type == "flag_ssa_list": count = ctypes.c_ulonglong() operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) @@ -729,6 +801,38 @@ class LowLevelILFunction(object): lo = self.arch.get_reg_index(lo) return self.expr(LowLevelILOperation.LLIL_SET_REG_SPLIT, hi, lo, value.index, size = size, flags = flags) + def set_reg_stack_top_relative(self, size, reg_stack, entry, value, flags = 0): + """ + ``set_reg_stack_top_relative`` sets the top-relative entry ``entry`` of size ``size`` in register + stack ``reg_stack`` to the expression ``value`` + + :param int size: size of the register parameter in bytes + :param str reg_stack: the register stack name + :param LowLevelILExpr entry: an expression for which stack entry to set + :param LowLevelILExpr value: an expression to set the entry to + :param str flags: which flags are set by this operation + :return: The expression ``reg_stack[entry] = value`` + :rtype: LowLevelILExpr + """ + reg_stack = self.arch.get_reg_stack_index(reg_stack) + return self.expr(LowLevelILOperation.LLIL_SET_REG_STACK_REL, reg_stack, entry.index, value.index, + size = size, flags = flags) + + def reg_stack_push(self, size, reg_stack, value, flags = 0): + """ + ``reg_stack_push`` pushes the expression ``value`` of size ``size`` onto the top of the register + stack ``reg_stack`` + + :param int size: size of the register parameter in bytes + :param str reg_stack: the register stack name + :param LowLevelILExpr value: an expression to push + :param str flags: which flags are set by this operation + :return: The expression ``reg_stack.push(value)`` + :rtype: LowLevelILExpr + """ + reg_stack = self.arch.get_reg_stack_index(reg_stack) + return self.expr(LowLevelILOperation.LLIL_REG_STACK_PUSH, reg_stack, value.index, size = size, flags = flags) + def set_flag(self, flag, value): """ ``set_flag`` sets the flag ``flag`` to the LowLevelILExpr ``value`` @@ -811,6 +915,33 @@ class LowLevelILFunction(object): lo = self.arch.get_reg_index(lo) return self.expr(LowLevelILOperation.LLIL_REG_SPLIT, hi, lo, size=size) + def reg_stack_top_relative(self, size, reg_stack, entry): + """ + ``reg_stack_top_relative`` returns a register stack entry of size ``size`` at top-relative + location ``entry`` in register stack with name ``reg_stack`` + + :param int size: the size of the register in bytes + :param str reg_stack: the name of the register stack + :param LowLevelILExpr entry: an expression for which stack entry to fetch + :return: The expression ``reg_stack[entry]`` + :rtype: LowLevelILExpr + """ + reg_stack = self.arch.get_reg_stack_index(reg_stack) + return self.expr(LowLevelILOperation.LLIL_REG_STACK_REL, reg_stack, entry.index, size=size) + + def reg_stack_pop(self, size, reg_stack): + """ + ``reg_stack_pop`` returns the top entry of size ``size`` in register stack with name ``reg_stack``, and + removes the entry from the stack + + :param int size: the size of the register in bytes + :param str reg_stack: the name of the register stack + :return: The expression ``reg_stack.pop`` + :rtype: LowLevelILExpr + """ + reg_stack = self.arch.get_reg_stack_index(reg_stack) + return self.expr(LowLevelILOperation.LLIL_REG_STACK_POP, reg_stack, size=size) + def const(self, size, value): """ ``const`` returns an expression for the constant integer ``value`` with size ``size`` @@ -833,6 +964,38 @@ class LowLevelILFunction(object): """ return self.expr(LowLevelILOperation.LLIL_CONST_PTR, value, size=size) + def float_const_raw(self, size, value): + """ + ``float_const_raw`` returns an expression for the constant raw binary floating point + value ``value`` with size ``size`` + + :param int size: the size of the constant in bytes + :param int value: integer value for the raw binary representation of the constant + :return: A constant expression of given value and size + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_FLOAT_CONST, value, size=size) + + def float_const_single(self, value): + """ + ``float_const_single`` returns an expression for the single precision floating point value ``value`` + + :param float value: float value for the constant + :return: A constant expression of given value and size + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_FLOAT_CONST, struct.unpack("I", struct.pack("f", value))[0], size=4) + + def float_const_double(self, value): + """ + ``float_const_double`` returns an expression for the double precision floating point value ``value`` + + :param float value: float value for the constant + :return: A constant expression of given value and size + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_FLOAT_CONST, struct.unpack("Q", struct.pack("d", value))[0], size=8) + def flag(self, reg): """ ``flag`` returns a flag expression for the given flag name. diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py index 05b558d2..144c7e0b 100644 --- a/python/mediumlevelil.py +++ b/python/mediumlevelil.py @@ -27,6 +27,7 @@ import function import basicblock import lowlevelil import types +import struct class SSAVariable(object): @@ -90,6 +91,7 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_ADDRESS_OF_FIELD: [("src", "var"), ("offset", "int")], MediumLevelILOperation.MLIL_CONST: [("constant", "int")], MediumLevelILOperation.MLIL_CONST_PTR: [("constant", "int")], + MediumLevelILOperation.MLIL_FLOAT_CONST: [("constant", "float")], MediumLevelILOperation.MLIL_IMPORT: [("constant", "int")], MediumLevelILOperation.MLIL_ADD: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_ADC: [("left", "expr"), ("right", "expr"), ("carry", "expr")], @@ -211,6 +213,13 @@ class MediumLevelILInstruction(object): name, operand_type = operand if operand_type == "int": value = instr.operands[i] + elif operand_type == "float": + if instr.size == 4: + value = struct.unpack("f", struct.pack("I", instr.operands[i] & 0xffffffff))[0] + elif instr.size == 8: + value = struct.unpack("d", struct.pack("Q", instr.operands[i]))[0] + else: + value = instr.operands[i] elif operand_type == "expr": value = MediumLevelILInstruction(func, instr.operands[i]) elif operand_type == "var": -- cgit v1.3.1 From 6430776b3de5ee6eb922a9356080ad07d5a92856 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Tue, 16 Jan 2018 16:25:30 -0500 Subject: Add classes and groups for semantic flags resolution --- architecture.cpp | 267 ++++++++++++++++++++++++++++-- binaryninjaapi.h | 48 +++++- binaryninjacore.h | 50 +++++- lowlevelilinstruction.cpp | 59 ++++++- lowlevelilinstruction.h | 16 ++ mediumlevelilinstruction.cpp | 8 + python/architecture.py | 382 +++++++++++++++++++++++++++++++++++++++---- python/lowlevelil.py | 58 ++++++- python/mediumlevelil.py | 1 + 9 files changed, 832 insertions(+), 57 deletions(-) (limited to 'python/mediumlevelil.py') diff --git a/architecture.cpp b/architecture.cpp index 3ca41741..571794c6 100644 --- a/architecture.cpp +++ b/architecture.cpp @@ -224,6 +224,22 @@ char* Architecture::GetFlagWriteTypeNameCallback(void* ctxt, uint32_t flags) } +char* Architecture::GetSemanticFlagClassNameCallback(void* ctxt, uint32_t semClass) +{ + Architecture* arch = (Architecture*)ctxt; + string result = arch->GetSemanticFlagClassName(semClass); + return BNAllocString(result.c_str()); +} + + +char* Architecture::GetSemanticFlagGroupNameCallback(void* ctxt, uint32_t semGroup) +{ + Architecture* arch = (Architecture*)ctxt; + string result = arch->GetSemanticFlagGroupName(semGroup); + return BNAllocString(result.c_str()); +} + + uint32_t* Architecture::GetFullWidthRegistersCallback(void* ctxt, size_t* count) { Architecture* arch = (Architecture*)ctxt; @@ -276,6 +292,32 @@ uint32_t* Architecture::GetAllFlagWriteTypesCallback(void* ctxt, size_t* count) } +uint32_t* Architecture::GetAllSemanticFlagClassesCallback(void* ctxt, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector regs = arch->GetAllSemanticFlagClasses(); + *count = regs.size(); + + uint32_t* result = new uint32_t[regs.size()]; + for (size_t i = 0; i < regs.size(); i++) + result[i] = regs[i]; + return result; +} + + +uint32_t* Architecture::GetAllSemanticFlagGroupsCallback(void* ctxt, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector regs = arch->GetAllSemanticFlagGroups(); + *count = regs.size(); + + uint32_t* result = new uint32_t[regs.size()]; + for (size_t i = 0; i < regs.size(); i++) + result[i] = regs[i]; + return result; +} + + BNFlagRole Architecture::GetFlagRoleCallback(void* ctxt, uint32_t flag) { Architecture* arch = (Architecture*)ctxt; @@ -283,10 +325,24 @@ BNFlagRole Architecture::GetFlagRoleCallback(void* ctxt, uint32_t flag) } -uint32_t* Architecture::GetFlagsRequiredForFlagConditionCallback(void* ctxt, BNLowLevelILFlagCondition cond, size_t* count) +uint32_t* Architecture::GetFlagsRequiredForFlagConditionCallback(void* ctxt, BNLowLevelILFlagCondition cond, + uint32_t semClass, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector flags = arch->GetFlagsRequiredForFlagCondition(cond, semClass); + *count = flags.size(); + + uint32_t* result = new uint32_t[flags.size()]; + for (size_t i = 0; i < flags.size(); i++) + result[i] = flags[i]; + return result; +} + + +uint32_t* Architecture::GetFlagsRequiredForSemanticFlagGroupCallback(void* ctxt, uint32_t semGroup, size_t* count) { Architecture* arch = (Architecture*)ctxt; - vector flags = arch->GetFlagsRequiredForFlagCondition(cond); + vector flags = arch->GetFlagsRequiredForSemanticFlagGroup(semGroup); *count = flags.size(); uint32_t* result = new uint32_t[flags.size()]; @@ -296,6 +352,31 @@ uint32_t* Architecture::GetFlagsRequiredForFlagConditionCallback(void* ctxt, BNL } +BNFlagConditionForSemanticClass* Architecture::GetFlagConditionsForSemanticFlagGroupCallback(void* ctxt, + uint32_t semGroup, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + map conditions = arch->GetFlagConditionsForSemanticFlagGroup(semGroup); + *count = conditions.size(); + + BNFlagConditionForSemanticClass* result = new BNFlagConditionForSemanticClass[conditions.size()]; + size_t i = 0; + for (auto& j : conditions) + { + result[i].semanticClass = j.first; + result[i].condition = j.second; + i++; + } + return result; +} + + +void Architecture::FreeFlagConditionsForSemanticFlagGroupCallback(void*, BNFlagConditionForSemanticClass* conditions) +{ + delete[] conditions; +} + + uint32_t* Architecture::GetFlagsWrittenByFlagWriteTypeCallback(void* ctxt, uint32_t writeType, size_t* count) { Architecture* arch = (Architecture*)ctxt; @@ -309,6 +390,13 @@ uint32_t* Architecture::GetFlagsWrittenByFlagWriteTypeCallback(void* ctxt, uint3 } +uint32_t Architecture::GetSemanticClassForFlagWriteTypeCallback(void* ctxt, uint32_t writeType) +{ + Architecture* arch = (Architecture*)ctxt; + return arch->GetSemanticClassForFlagWriteType(writeType); +} + + size_t Architecture::GetFlagWriteLowLevelILCallback(void* ctxt, BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, BNLowLevelILFunction* il) { @@ -318,12 +406,20 @@ size_t Architecture::GetFlagWriteLowLevelILCallback(void* ctxt, BNLowLevelILOper } -size_t Architecture::GetFlagConditionLowLevelILCallback(void* ctxt, BNLowLevelILFlagCondition cond, +size_t Architecture::GetFlagConditionLowLevelILCallback(void* ctxt, BNLowLevelILFlagCondition cond, uint32_t semClass, BNLowLevelILFunction* il) { Architecture* arch = (Architecture*)ctxt; LowLevelILFunction func(il); - return arch->GetFlagConditionLowLevelIL(cond, func); + return arch->GetFlagConditionLowLevelIL(cond, semClass, func); +} + + +size_t Architecture::GetSemanticFlagGroupLowLevelILCallback(void* ctxt, uint32_t semGroup, BNLowLevelILFunction* il) +{ + Architecture* arch = (Architecture*)ctxt; + LowLevelILFunction func(il); + return arch->GetSemanticFlagGroupLowLevelIL(semGroup, func); } @@ -490,15 +586,24 @@ void Architecture::Register(Architecture* arch) callbacks.getRegisterName = GetRegisterNameCallback; callbacks.getFlagName = GetFlagNameCallback; callbacks.getFlagWriteTypeName = GetFlagWriteTypeNameCallback; + callbacks.getSemanticFlagClassName = GetSemanticFlagClassNameCallback; + callbacks.getSemanticFlagGroupName = GetSemanticFlagGroupNameCallback; callbacks.getFullWidthRegisters = GetFullWidthRegistersCallback; callbacks.getAllRegisters = GetAllRegistersCallback; callbacks.getAllFlags = GetAllFlagsCallback; callbacks.getAllFlagWriteTypes = GetAllFlagWriteTypesCallback; + callbacks.getAllSemanticFlagClasses = GetAllSemanticFlagClassesCallback; + callbacks.getAllSemanticFlagGroups = GetAllSemanticFlagGroupsCallback; callbacks.getFlagRole = GetFlagRoleCallback; callbacks.getFlagsRequiredForFlagCondition = GetFlagsRequiredForFlagConditionCallback; + callbacks.getFlagsRequiredForSemanticFlagGroup = GetFlagsRequiredForSemanticFlagGroupCallback; + callbacks.getFlagConditionsForSemanticFlagGroup = GetFlagConditionsForSemanticFlagGroupCallback; + callbacks.freeFlagConditionsForSemanticFlagGroup = FreeFlagConditionsForSemanticFlagGroupCallback; callbacks.getFlagsWrittenByFlagWriteType = GetFlagsWrittenByFlagWriteTypeCallback; + callbacks.getSemanticClassForFlagWriteType = GetSemanticClassForFlagWriteTypeCallback; callbacks.getFlagWriteLowLevelIL = GetFlagWriteLowLevelILCallback; callbacks.getFlagConditionLowLevelIL = GetFlagConditionLowLevelILCallback; + callbacks.getSemanticFlagGroupLowLevelIL = GetSemanticFlagGroupLowLevelILCallback; callbacks.freeRegisterList = FreeRegisterListCallback; callbacks.getRegisterInfo = GetRegisterInfoCallback; callbacks.getStackPointerRegister = GetStackPointerRegisterCallback; @@ -621,6 +726,24 @@ string Architecture::GetFlagWriteTypeName(uint32_t flags) } +string Architecture::GetSemanticFlagClassName(uint32_t semClass) +{ + if (semClass == 0) + return ""; + char flagStr[32]; + sprintf(flagStr, "semantic%" PRIu32, semClass); + return flagStr; +} + + +string Architecture::GetSemanticFlagGroupName(uint32_t semGroup) +{ + char flagStr[32]; + sprintf(flagStr, "group%" PRIu32, semGroup); + return flagStr; +} + + vector Architecture::GetFullWidthRegisters() { return vector(); @@ -645,24 +768,54 @@ vector Architecture::GetAllFlagWriteTypes() } +vector Architecture::GetAllSemanticFlagClasses() +{ + return vector(); +} + + +vector Architecture::GetAllSemanticFlagGroups() +{ + return vector(); +} + + BNFlagRole Architecture::GetFlagRole(uint32_t) { return SpecialFlagRole; } -vector Architecture::GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition) +vector Architecture::GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition, uint32_t) { return vector(); } +vector Architecture::GetFlagsRequiredForSemanticFlagGroup(uint32_t) +{ + return vector(); +} + + +map Architecture::GetFlagConditionsForSemanticFlagGroup(uint32_t) +{ + return map(); +} + + vector Architecture::GetFlagsWrittenByFlagWriteType(uint32_t) { return vector(); } +uint32_t Architecture::GetSemanticClassForFlagWriteType(uint32_t) +{ + return 0; +} + + size_t Architecture::GetFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount,LowLevelILFunction& il) { @@ -681,7 +834,7 @@ size_t Architecture::GetDefaultFlagWriteLowLevelIL(BNLowLevelILOperation op, siz } -ExprId Architecture::GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, LowLevelILFunction& il) +ExprId Architecture::GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, uint32_t, LowLevelILFunction& il) { return BNGetDefaultArchitectureFlagConditionLowLevelIL(m_object, cond, il.GetObject()); } @@ -693,6 +846,12 @@ ExprId Architecture::GetDefaultFlagConditionLowLevelIL(BNLowLevelILFlagCondition } +ExprId Architecture::GetSemanticFlagGroupLowLevelIL(uint32_t, LowLevelILFunction& il) +{ + return il.Unimplemented(); +} + + BNRegisterInfo Architecture::GetRegisterInfo(uint32_t) { BNRegisterInfo result; @@ -1064,6 +1223,24 @@ string CoreArchitecture::GetFlagWriteTypeName(uint32_t flags) } +string CoreArchitecture::GetSemanticFlagClassName(uint32_t semClass) +{ + char* name = BNGetArchitectureSemanticFlagClassName(m_object, semClass); + string result = name; + BNFreeString(name); + return result; +} + + +string CoreArchitecture::GetSemanticFlagGroupName(uint32_t semGroup) +{ + char* name = BNGetArchitectureSemanticFlagGroupName(m_object, semGroup); + string result = name; + BNFreeString(name); + return result; +} + + vector CoreArchitecture::GetFullWidthRegisters() { size_t count; @@ -1120,16 +1297,58 @@ vector CoreArchitecture::GetAllFlagWriteTypes() } +vector CoreArchitecture::GetAllSemanticFlagClasses() +{ + size_t count; + uint32_t* regs = BNGetAllArchitectureSemanticFlagClasses(m_object, &count); + + vector result; + for (size_t i = 0; i < count; i++) + result.push_back(regs[i]); + + BNFreeRegisterList(regs); + return result; +} + + +vector CoreArchitecture::GetAllSemanticFlagGroups() +{ + size_t count; + uint32_t* regs = BNGetAllArchitectureSemanticFlagGroups(m_object, &count); + + vector result; + for (size_t i = 0; i < count; i++) + result.push_back(regs[i]); + + BNFreeRegisterList(regs); + return result; +} + + BNFlagRole CoreArchitecture::GetFlagRole(uint32_t flag) { return BNGetArchitectureFlagRole(m_object, flag); } -vector CoreArchitecture::GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition cond) +vector CoreArchitecture::GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition cond, uint32_t semClass) +{ + size_t count; + uint32_t* flags = BNGetArchitectureFlagsRequiredForFlagCondition(m_object, cond, semClass, &count); + + vector result; + for (size_t i = 0; i < count; i++) + result.push_back(flags[i]); + + BNFreeRegisterList(flags); + return result; +} + + +vector CoreArchitecture::GetFlagsRequiredForSemanticFlagGroup(uint32_t semGroup) { size_t count; - uint32_t* flags = BNGetArchitectureFlagsRequiredForFlagCondition(m_object, cond, &count); + uint32_t* flags = BNGetArchitectureFlagsRequiredForSemanticFlagGroup(m_object, semGroup, &count); vector result; for (size_t i = 0; i < count; i++) @@ -1140,6 +1359,21 @@ vector CoreArchitecture::GetFlagsRequiredForFlagCondition(BNLowLevelIL } +map CoreArchitecture::GetFlagConditionsForSemanticFlagGroup(uint32_t semGroup) +{ + size_t count; + BNFlagConditionForSemanticClass* conditions = BNGetArchitectureFlagConditionsForSemanticFlagGroup(m_object, + semGroup, &count); + + map result; + for (size_t i = 0; i < count; i++) + result[conditions[i].semanticClass] = conditions[i].condition; + + BNFreeFlagConditionsForSemanticFlagGroup(conditions); + return result; +} + + vector CoreArchitecture::GetFlagsWrittenByFlagWriteType(uint32_t writeType) { size_t count; @@ -1154,6 +1388,12 @@ vector CoreArchitecture::GetFlagsWrittenByFlagWriteType(uint32_t write } +uint32_t CoreArchitecture::GetSemanticClassForFlagWriteType(uint32_t writeType) +{ + return BNGetArchitectureSemanticClassForFlagWriteType(m_object, writeType); +} + + size_t CoreArchitecture::GetFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, LowLevelILFunction& il) { @@ -1162,9 +1402,16 @@ size_t CoreArchitecture::GetFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t } -ExprId CoreArchitecture::GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, LowLevelILFunction& il) +ExprId CoreArchitecture::GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, + uint32_t semClass, LowLevelILFunction& il) +{ + return (ExprId)BNGetArchitectureFlagConditionLowLevelIL(m_object, cond, semClass, il.GetObject()); +} + + +ExprId CoreArchitecture::GetSemanticFlagGroupLowLevelIL(uint32_t semGroup, LowLevelILFunction& il) { - return (ExprId)BNGetArchitectureFlagConditionLowLevelIL(m_object, cond, il.GetObject()); + return (ExprId)BNGetArchitectureSemanticFlagGroupLowLevelIL(m_object, semGroup, il.GetObject()); } diff --git a/binaryninjaapi.h b/binaryninjaapi.h index b90f72a2..cbd51d05 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -1601,17 +1601,28 @@ namespace BinaryNinja static char* GetRegisterNameCallback(void* ctxt, uint32_t reg); static char* GetFlagNameCallback(void* ctxt, uint32_t flag); static char* GetFlagWriteTypeNameCallback(void* ctxt, uint32_t flags); + static char* GetSemanticFlagClassNameCallback(void* ctxt, uint32_t semClass); + static char* GetSemanticFlagGroupNameCallback(void* ctxt, uint32_t semGroup); static uint32_t* GetFullWidthRegistersCallback(void* ctxt, size_t* count); static uint32_t* GetAllRegistersCallback(void* ctxt, size_t* count); static uint32_t* GetAllFlagsCallback(void* ctxt, size_t* count); static uint32_t* GetAllFlagWriteTypesCallback(void* ctxt, size_t* count); + static uint32_t* GetAllSemanticFlagClassesCallback(void* ctxt, size_t* count); + static uint32_t* GetAllSemanticFlagGroupsCallback(void* ctxt, size_t* count); static BNFlagRole GetFlagRoleCallback(void* ctxt, uint32_t flag); - static uint32_t* GetFlagsRequiredForFlagConditionCallback(void* ctxt, BNLowLevelILFlagCondition cond, size_t* count); + static uint32_t* GetFlagsRequiredForFlagConditionCallback(void* ctxt, BNLowLevelILFlagCondition cond, + uint32_t semClass, size_t* count); + static uint32_t* GetFlagsRequiredForSemanticFlagGroupCallback(void* ctxt, uint32_t semGroup, size_t* count); + static BNFlagConditionForSemanticClass* GetFlagConditionsForSemanticFlagGroupCallback(void* ctxt, + uint32_t semGroup, size_t* count); + static void FreeFlagConditionsForSemanticFlagGroupCallback(void* ctxt, BNFlagConditionForSemanticClass* conditions); static uint32_t* GetFlagsWrittenByFlagWriteTypeCallback(void* ctxt, uint32_t writeType, size_t* count); + static uint32_t GetSemanticClassForFlagWriteTypeCallback(void* ctxt, uint32_t writeType); static size_t GetFlagWriteLowLevelILCallback(void* ctxt, BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, BNLowLevelILFunction* il); static size_t GetFlagConditionLowLevelILCallback(void* ctxt, BNLowLevelILFlagCondition cond, - BNLowLevelILFunction* il); + uint32_t semClass, BNLowLevelILFunction* il); + static size_t GetSemanticFlagGroupLowLevelILCallback(void* ctxt, uint32_t semGroup, BNLowLevelILFunction* il); static void FreeRegisterListCallback(void* ctxt, uint32_t* regs); static void GetRegisterInfoCallback(void* ctxt, uint32_t reg, BNRegisterInfo* result); static uint32_t GetStackPointerRegisterCallback(void* ctxt); @@ -1668,19 +1679,28 @@ namespace BinaryNinja virtual std::string GetRegisterName(uint32_t reg); virtual std::string GetFlagName(uint32_t flag); virtual std::string GetFlagWriteTypeName(uint32_t flags); + virtual std::string GetSemanticFlagClassName(uint32_t semClass); + virtual std::string GetSemanticFlagGroupName(uint32_t semGroup); virtual std::vector GetFullWidthRegisters(); virtual std::vector GetAllRegisters(); virtual std::vector GetAllFlags(); virtual std::vector GetAllFlagWriteTypes(); + virtual std::vector GetAllSemanticFlagClasses(); + virtual std::vector GetAllSemanticFlagGroups(); virtual BNFlagRole GetFlagRole(uint32_t flag); - virtual std::vector GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition cond); + virtual std::vector GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition cond, + uint32_t semClass = 0); + virtual std::vector GetFlagsRequiredForSemanticFlagGroup(uint32_t semGroup); + virtual std::map GetFlagConditionsForSemanticFlagGroup(uint32_t semGroup); virtual std::vector GetFlagsWrittenByFlagWriteType(uint32_t writeType); + virtual uint32_t GetSemanticClassForFlagWriteType(uint32_t writeType); virtual ExprId GetFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, LowLevelILFunction& il); ExprId GetDefaultFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t size, BNFlagRole role, BNRegisterOrConstant* operands, size_t operandCount, LowLevelILFunction& il); - virtual ExprId GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, LowLevelILFunction& il); + virtual ExprId GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, uint32_t semClass, LowLevelILFunction& il); ExprId GetDefaultFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, LowLevelILFunction& il); + virtual ExprId GetSemanticFlagGroupLowLevelIL(uint32_t semGroup, LowLevelILFunction& il); virtual BNRegisterInfo GetRegisterInfo(uint32_t reg); virtual uint32_t GetStackPointerRegister(); virtual uint32_t GetLinkRegister(); @@ -1804,16 +1824,26 @@ namespace BinaryNinja virtual std::string GetRegisterName(uint32_t reg) override; virtual std::string GetFlagName(uint32_t flag) override; virtual std::string GetFlagWriteTypeName(uint32_t flags) override; + virtual std::string GetSemanticFlagClassName(uint32_t semClass) override; + virtual std::string GetSemanticFlagGroupName(uint32_t semGroup) override; virtual std::vector GetFullWidthRegisters() override; virtual std::vector GetAllRegisters() override; virtual std::vector GetAllFlags() override; virtual std::vector GetAllFlagWriteTypes() override; + virtual std::vector GetAllSemanticFlagClasses() override; + virtual std::vector GetAllSemanticFlagGroups() override; virtual BNFlagRole GetFlagRole(uint32_t flag) override; - virtual std::vector GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition cond) override; + virtual std::vector GetFlagsRequiredForFlagCondition(BNLowLevelILFlagCondition cond, + uint32_t semClass = 0) override; + virtual std::vector GetFlagsRequiredForSemanticFlagGroup(uint32_t semGroup) override; + virtual std::map GetFlagConditionsForSemanticFlagGroup(uint32_t semGroup) override; virtual std::vector GetFlagsWrittenByFlagWriteType(uint32_t writeType) override; + virtual uint32_t GetSemanticClassForFlagWriteType(uint32_t writeType) override; virtual ExprId GetFlagWriteLowLevelIL(BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, LowLevelILFunction& il) override; - virtual ExprId GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, LowLevelILFunction& il) override; + virtual ExprId GetFlagConditionLowLevelIL(BNLowLevelILFlagCondition cond, + uint32_t semClass, LowLevelILFunction& il) override; + virtual ExprId GetSemanticFlagGroupLowLevelIL(uint32_t semGroup, LowLevelILFunction& il) override; virtual BNRegisterInfo GetRegisterInfo(uint32_t reg) override; virtual uint32_t GetStackPointerRegister() override; virtual uint32_t GetLinkRegister() override; @@ -2584,7 +2614,9 @@ namespace BinaryNinja const ILSourceLocation& loc = ILSourceLocation()); ExprId Return(size_t dest, const ILSourceLocation& loc = ILSourceLocation()); ExprId NoReturn(const ILSourceLocation& loc = ILSourceLocation()); - ExprId FlagCondition(BNLowLevelILFlagCondition cond, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FlagCondition(BNLowLevelILFlagCondition cond, uint32_t semClass = 0, + const ILSourceLocation& loc = ILSourceLocation()); + ExprId FlagGroup(uint32_t semGroup, const ILSourceLocation& loc = ILSourceLocation()); ExprId CompareEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId CompareNotEqual(size_t size, ExprId a, ExprId b, @@ -2641,6 +2673,7 @@ namespace BinaryNinja ExprId FloatCompareLessEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareGreaterEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareGreaterThan(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatCompareOrdered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareUnordered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId Goto(BNLowLevelILLabel& label, const ILSourceLocation& loc = ILSourceLocation()); @@ -2944,6 +2977,7 @@ namespace BinaryNinja ExprId FloatCompareLessEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareGreaterEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareGreaterThan(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatCompareOrdered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareUnordered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId Goto(BNMediumLevelILLabel& label, const ILSourceLocation& loc = ILSourceLocation()); diff --git a/binaryninjacore.h b/binaryninjacore.h index baca94be..388d3643 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -335,6 +335,7 @@ extern "C" LLIL_IF, LLIL_GOTO, LLIL_FLAG_COND, // Valid only in Lifted IL + LLIL_FLAG_GROUP, // Valid only in Lifted IL LLIL_CMP_E, LLIL_CMP_NE, LLIL_CMP_SLT, @@ -372,6 +373,7 @@ extern "C" LLIL_FCMP_LE, LLIL_FCMP_GE, LLIL_FCMP_GT, + LLIL_FCMP_O, LLIL_FCMP_UO, // The following instructions are only used in SSA form @@ -418,7 +420,15 @@ extern "C" LLFC_NEG, LLFC_POS, LLFC_O, - LLFC_NO + LLFC_NO, + LLFC_FE, + LLFC_FNE, + LLFC_FLT, + LLFC_FLE, + LLFC_FGE, + LLFC_FGT, + LLFC_FO, + LLFC_FUO }; enum BNFlagRole @@ -869,6 +879,7 @@ extern "C" MLIL_FCMP_LE, MLIL_FCMP_GE, MLIL_FCMP_GT, + MLIL_FCMP_O, MLIL_FCMP_UO, // The following instructions are only used in SSA form @@ -1058,6 +1069,12 @@ extern "C" size_t count; }; + struct BNFlagConditionForSemanticClass + { + uint32_t semanticClass; + BNLowLevelILFlagCondition condition; + }; + struct BNCustomArchitecture { void* context; @@ -1077,16 +1094,27 @@ extern "C" char* (*getRegisterName)(void* ctxt, uint32_t reg); char* (*getFlagName)(void* ctxt, uint32_t flag); char* (*getFlagWriteTypeName)(void* ctxt, uint32_t flags); + char* (*getSemanticFlagClassName)(void* ctxt, uint32_t semClass); + char* (*getSemanticFlagGroupName)(void* ctxt, uint32_t semGroup); uint32_t* (*getFullWidthRegisters)(void* ctxt, size_t* count); uint32_t* (*getAllRegisters)(void* ctxt, size_t* count); uint32_t* (*getAllFlags)(void* ctxt, size_t* count); uint32_t* (*getAllFlagWriteTypes)(void* ctxt, size_t* count); + uint32_t* (*getAllSemanticFlagClasses)(void* ctxt, size_t* count); + uint32_t* (*getAllSemanticFlagGroups)(void* ctxt, size_t* count); BNFlagRole (*getFlagRole)(void* ctxt, uint32_t flag); - uint32_t* (*getFlagsRequiredForFlagCondition)(void* ctxt, BNLowLevelILFlagCondition cond, size_t* count); + uint32_t* (*getFlagsRequiredForFlagCondition)(void* ctxt, BNLowLevelILFlagCondition cond, + uint32_t semClass, size_t* count); + uint32_t* (*getFlagsRequiredForSemanticFlagGroup)(void* ctxt, uint32_t semGroup, size_t* count); + BNFlagConditionForSemanticClass* (*getFlagConditionsForSemanticFlagGroup)(void* ctxt, uint32_t semGroup, size_t* count); + void (*freeFlagConditionsForSemanticFlagGroup)(void* ctxt, BNFlagConditionForSemanticClass* conditions); uint32_t* (*getFlagsWrittenByFlagWriteType)(void* ctxt, uint32_t writeType, size_t* count); + uint32_t (*getSemanticClassForFlagWriteType)(void* ctxt, uint32_t writeType); size_t (*getFlagWriteLowLevelIL)(void* ctxt, BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, BNLowLevelILFunction* il); - size_t (*getFlagConditionLowLevelIL)(void* ctxt, BNLowLevelILFlagCondition cond, BNLowLevelILFunction* il); + size_t (*getFlagConditionLowLevelIL)(void* ctxt, BNLowLevelILFlagCondition cond, + uint32_t semClass, BNLowLevelILFunction* il); + size_t (*getSemanticFlagGroupLowLevelIL)(void* ctxt, uint32_t semGroup, BNLowLevelILFunction* il); void (*freeRegisterList)(void* ctxt, uint32_t* regs); void (*getRegisterInfo)(void* ctxt, uint32_t reg, BNRegisterInfo* result); uint32_t (*getStackPointerRegister)(void* ctxt); @@ -2042,24 +2070,36 @@ extern "C" BINARYNINJACOREAPI char* BNGetArchitectureRegisterName(BNArchitecture* arch, uint32_t reg); BINARYNINJACOREAPI char* BNGetArchitectureFlagName(BNArchitecture* arch, uint32_t flag); BINARYNINJACOREAPI char* BNGetArchitectureFlagWriteTypeName(BNArchitecture* arch, uint32_t flags); + BINARYNINJACOREAPI char* BNGetArchitectureSemanticFlagClassName(BNArchitecture* arch, uint32_t semClass); + BINARYNINJACOREAPI char* BNGetArchitectureSemanticFlagGroupName(BNArchitecture* arch, uint32_t semGroup); BINARYNINJACOREAPI uint32_t* BNGetFullWidthArchitectureRegisters(BNArchitecture* arch, size_t* count); BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureRegisters(BNArchitecture* arch, size_t* count); BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureFlags(BNArchitecture* arch, size_t* count); BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureFlagWriteTypes(BNArchitecture* arch, size_t* count); + BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureSemanticFlagClasses(BNArchitecture* arch, size_t* count); + BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureSemanticFlagGroups(BNArchitecture* arch, size_t* count); BINARYNINJACOREAPI BNFlagRole BNGetArchitectureFlagRole(BNArchitecture* arch, uint32_t flag); BINARYNINJACOREAPI uint32_t* BNGetArchitectureFlagsRequiredForFlagCondition(BNArchitecture* arch, BNLowLevelILFlagCondition cond, - size_t* count); + uint32_t semClass, size_t* count); + BINARYNINJACOREAPI uint32_t* BNGetArchitectureFlagsRequiredForSemanticFlagGroup(BNArchitecture* arch, + uint32_t semGroup, size_t* count); + BINARYNINJACOREAPI BNFlagConditionForSemanticClass* BNGetArchitectureFlagConditionsForSemanticFlagGroup(BNArchitecture* arch, + uint32_t semGroup, size_t* count); + BINARYNINJACOREAPI void BNFreeFlagConditionsForSemanticFlagGroup(BNFlagConditionForSemanticClass* conditions); BINARYNINJACOREAPI uint32_t* BNGetArchitectureFlagsWrittenByFlagWriteType(BNArchitecture* arch, uint32_t writeType, size_t* count); + BINARYNINJACOREAPI uint32_t BNGetArchitectureSemanticClassForFlagWriteType(BNArchitecture* arch, uint32_t writeType); BINARYNINJACOREAPI size_t BNGetArchitectureFlagWriteLowLevelIL(BNArchitecture* arch, BNLowLevelILOperation op, size_t size, uint32_t flagWriteType, uint32_t flag, BNRegisterOrConstant* operands, size_t operandCount, BNLowLevelILFunction* il); BINARYNINJACOREAPI size_t BNGetDefaultArchitectureFlagWriteLowLevelIL(BNArchitecture* arch, BNLowLevelILOperation op, size_t size, BNFlagRole role, BNRegisterOrConstant* operands, size_t operandCount, BNLowLevelILFunction* il); BINARYNINJACOREAPI size_t BNGetArchitectureFlagConditionLowLevelIL(BNArchitecture* arch, BNLowLevelILFlagCondition cond, - BNLowLevelILFunction* il); + uint32_t semClass, BNLowLevelILFunction* il); BINARYNINJACOREAPI size_t BNGetDefaultArchitectureFlagConditionLowLevelIL(BNArchitecture* arch, BNLowLevelILFlagCondition cond, BNLowLevelILFunction* il); + BINARYNINJACOREAPI size_t BNGetArchitectureSemanticFlagGroupLowLevelIL(BNArchitecture* arch, + uint32_t semGroup, BNLowLevelILFunction* il); BINARYNINJACOREAPI uint32_t* BNGetModifiedArchitectureRegistersOnWrite(BNArchitecture* arch, uint32_t reg, size_t* count); BINARYNINJACOREAPI void BNFreeRegisterList(uint32_t* regs); BINARYNINJACOREAPI BNRegisterInfo BNGetArchitectureRegisterInfo(BNArchitecture* arch, uint32_t reg); diff --git a/lowlevelilinstruction.cpp b/lowlevelilinstruction.cpp index 6b67ef72..4b1acff3 100644 --- a/lowlevelilinstruction.cpp +++ b/lowlevelilinstruction.cpp @@ -49,6 +49,8 @@ unordered_map {DestSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, {DestSSARegisterStackLowLevelOperandUsage, SSARegisterStackLowLevelOperand}, {DestSSAFlagLowLevelOperandUsage, SSAFlagLowLevelOperand}, + {SemanticFlagClassLowLevelOperandUsage, SemanticFlagClassLowLevelOperand}, + {SemanticFlagGroupLowLevelOperandUsage, SemanticFlagGroupLowLevelOperand}, {PartialRegisterLowLevelOperandUsage, RegisterLowLevelOperand}, {PartialSSARegisterStackSourceLowLevelOperandUsage, SSARegisterStackLowLevelOperand}, {StackSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, @@ -140,7 +142,8 @@ unordered_map> {LLIL_IF, {ConditionExprLowLevelOperandUsage, TrueTargetLowLevelOperandUsage, FalseTargetLowLevelOperandUsage}}, {LLIL_GOTO, {TargetLowLevelOperandUsage}}, - {LLIL_FLAG_COND, {FlagConditionLowLevelOperandUsage}}, + {LLIL_FLAG_COND, {FlagConditionLowLevelOperandUsage, SemanticFlagClassLowLevelOperandUsage}}, + {LLIL_FLAG_GROUP, {SemanticFlagGroupLowLevelOperandUsage}}, {LLIL_TRAP, {VectorLowLevelOperandUsage}}, {LLIL_CALL_SSA, {OutputSSARegistersLowLevelOperandUsage, OutputMemoryVersionLowLevelOperandUsage, DestExprLowLevelOperandUsage, StackSSARegisterLowLevelOperandUsage, @@ -886,6 +889,22 @@ BNLowLevelILFlagCondition LowLevelILOperand::GetFlagCondition() const } +uint32_t LowLevelILOperand::GetSemanticFlagClass() const +{ + if (m_type != SemanticFlagClassLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsRegister(m_operandIndex); +} + + +uint32_t LowLevelILOperand::GetSemanticFlagGroup() const +{ + if (m_type != SemanticFlagGroupLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsRegister(m_operandIndex); +} + + SSARegister LowLevelILOperand::GetSSARegister() const { if (m_type != SSARegisterLowLevelOperand) @@ -1710,7 +1729,9 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, return dest->Undefined(*this); return dest->If(subExprHandler(GetConditionExpr()), *labelA, *labelB, *this); case LLIL_FLAG_COND: - return dest->FlagCondition(GetFlagCondition(), *this); + return dest->FlagCondition(GetFlagCondition(), GetSemanticFlagClass(), *this); + case LLIL_FLAG_GROUP: + return dest->FlagGroup(GetSemanticFlagGroup(), *this); case LLIL_TRAP: return dest->Trap(GetVector(), *this); case LLIL_CALL_SSA: @@ -1964,6 +1985,24 @@ SSAFlag LowLevelILInstruction::GetDestSSAFlag() const } +uint32_t LowLevelILInstruction::GetSemanticFlagClass() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(SemanticFlagClassLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsRegister(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + +uint32_t LowLevelILInstruction::GetSemanticFlagGroup() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(SemanticFlagGroupLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsRegister(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + uint32_t LowLevelILInstruction::GetPartialRegister() const { size_t operandIndex; @@ -2748,9 +2787,15 @@ ExprId LowLevelILFunction::NoReturn(const ILSourceLocation& loc) } -ExprId LowLevelILFunction::FlagCondition(BNLowLevelILFlagCondition cond, const ILSourceLocation& loc) +ExprId LowLevelILFunction::FlagCondition(BNLowLevelILFlagCondition cond, uint32_t semClass, const ILSourceLocation& loc) { - return AddExprWithLocation(LLIL_FLAG_COND, loc, 0, 0, (ExprId)cond); + return AddExprWithLocation(LLIL_FLAG_COND, loc, 0, 0, (ExprId)cond, semClass); +} + + +ExprId LowLevelILFunction::FlagGroup(uint32_t semGroup, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_FLAG_GROUP, loc, 0, 0, semGroup); } @@ -2988,6 +3033,12 @@ ExprId LowLevelILFunction::FloatCompareGreaterThan(size_t size, ExprId a, ExprId } +ExprId LowLevelILFunction::FloatCompareOrdered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_FCMP_O, loc, size, 0, a, b); +} + + ExprId LowLevelILFunction::FloatCompareUnordered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_FCMP_UO, loc, size, 0, a, b); diff --git a/lowlevelilinstruction.h b/lowlevelilinstruction.h index a0a867af..bb5041a6 100644 --- a/lowlevelilinstruction.h +++ b/lowlevelilinstruction.h @@ -108,6 +108,8 @@ namespace BinaryNinja RegisterStackLowLevelOperand, FlagLowLevelOperand, FlagConditionLowLevelOperand, + SemanticFlagClassLowLevelOperand, + SemanticFlagGroupLowLevelOperand, SSARegisterLowLevelOperand, SSARegisterStackLowLevelOperand, SSAFlagLowLevelOperand, @@ -135,6 +137,8 @@ namespace BinaryNinja DestSSARegisterLowLevelOperandUsage, DestSSARegisterStackLowLevelOperandUsage, DestSSAFlagLowLevelOperandUsage, + SemanticFlagClassLowLevelOperandUsage, + SemanticFlagGroupLowLevelOperandUsage, PartialRegisterLowLevelOperandUsage, PartialSSARegisterStackSourceLowLevelOperandUsage, StackSSARegisterLowLevelOperandUsage, @@ -587,6 +591,8 @@ namespace BinaryNinja template SSARegister GetDestSSARegister() const { return As().GetDestSSARegister(); } template SSARegisterStack GetDestSSARegisterStack() const { return As().GetDestSSARegisterStack(); } template SSAFlag GetDestSSAFlag() const { return As().GetDestSSAFlag(); } + template uint32_t GetSemanticFlagClass() const { return As().GetSemanticFlagClass(); } + template uint32_t GetSemanticFlagGroup() const { return As().GetSemanticFlagGroup(); } template uint32_t GetPartialRegister() const { return As().GetPartialRegister(); } template SSARegister GetStackSSARegister() const { return As().GetStackSSARegister(); } template SSARegister GetTopSSARegister() const { return As().GetTopSSARegister(); } @@ -645,6 +651,8 @@ namespace BinaryNinja SSARegister GetDestSSARegister() const; SSARegisterStack GetDestSSARegisterStack() const; SSAFlag GetDestSSAFlag() const; + uint32_t GetSemanticFlagClass() const; + uint32_t GetSemanticFlagGroup() const; uint32_t GetPartialRegister() const; SSARegister GetStackSSARegister() const; SSARegister GetTopSSARegister() const; @@ -696,6 +704,8 @@ namespace BinaryNinja uint32_t GetRegister() const; uint32_t GetRegisterStack() const; uint32_t GetFlag() const; + uint32_t GetSemanticFlagClass() const; + uint32_t GetSemanticFlagGroup() const; BNLowLevelILFlagCondition GetFlagCondition() const; SSARegister GetSSARegister() const; SSARegisterStack GetSSARegisterStack() const; @@ -974,6 +984,11 @@ namespace BinaryNinja template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { BNLowLevelILFlagCondition GetFlagCondition() const { return GetRawOperandAsFlagCondition(0); } + uint32_t GetSemanticFlagClass() const { return GetRawOperandAsRegister(1); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetSemanticFlagGroup() const { return GetRawOperandAsRegister(0); } }; template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase @@ -1083,6 +1098,7 @@ namespace BinaryNinja template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; + template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILTwoOperandWithCarryInstruction {}; diff --git a/mediumlevelilinstruction.cpp b/mediumlevelilinstruction.cpp index c3b4014f..e911c298 100644 --- a/mediumlevelilinstruction.cpp +++ b/mediumlevelilinstruction.cpp @@ -1331,6 +1331,7 @@ void MediumLevelILInstruction::VisitExprs(const std::functionAddExprWithLocation(operation, *this, size, subExprHandler(AsTwoOperand().GetLeftExpr()), subExprHandler(AsTwoOperand().GetRightExpr())); @@ -2706,6 +2708,12 @@ ExprId MediumLevelILFunction::FloatCompareGreaterThan(size_t size, ExprId a, Exp } +ExprId MediumLevelILFunction::FloatCompareOrdered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_FCMP_O, loc, size, a, b); +} + + ExprId MediumLevelILFunction::FloatCompareUnordered(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc) { return AddExprWithLocation(MLIL_FCMP_UO, loc, size, a, b); diff --git a/python/architecture.py b/python/architecture.py index 08049d46..d2ab586e 100644 --- a/python/architecture.py +++ b/python/architecture.py @@ -33,7 +33,6 @@ import callingconvention import platform import log import databuffer -import types class _ArchitectureMetaClass(type): @@ -120,9 +119,14 @@ class Architecture(object): global_regs = [] flags = [] flag_write_types = [] + semantic_flag_classes = [] + semantic_flag_groups = [] flag_roles = {} flags_required_for_flag_condition = {} + flags_required_for_semantic_flag_group = {} + flag_conditions_for_semantic_flag_group = {} flags_written_by_flag_write_type = {} + semantic_class_for_flag_write_type = {} reg_stacks = {} __metaclass__ = _ArchitectureMetaClass next_address = 0 @@ -166,16 +170,40 @@ class Architecture(object): core.BNFreeRegisterList(flags) count = ctypes.c_ulonglong() - types = core.BNGetAllArchitectureFlagWriteTypes(self.handle, count) + write_types = core.BNGetAllArchitectureFlagWriteTypes(self.handle, count) self._flag_write_types = {} self._flag_write_types_by_index = {} self.__dict__["flag_write_types"] = [] for i in xrange(0, count.value): - name = core.BNGetArchitectureFlagWriteTypeName(self.handle, types[i]) - self._flag_write_types[name] = types[i] - self._flag_write_types_by_index[types[i]] = name + name = core.BNGetArchitectureFlagWriteTypeName(self.handle, write_types[i]) + self._flag_write_types[name] = write_types[i] + self._flag_write_types_by_index[write_types[i]] = name self.flag_write_types.append(name) - core.BNFreeRegisterList(types) + core.BNFreeRegisterList(write_types) + + count = ctypes.c_ulonglong() + sem_classes = core.BNGetAllArchitectureSemanticFlagClasses(self.handle, count) + self._semantic_flag_classes = {} + self._semantic_flag_classes_by_index = {} + self.__dict__["semantic_flag_classes"] = [] + for i in xrange(0, count.value): + name = core.BNGetArchitectureSemanticFlagClassName(self.handle, sem_classes[i]) + self._semantic_flag_classes[name] = sem_classes[i] + self._semantic_flag_classes_by_index[sem_classes[i]] = name + self.semantic_flag_classes.append(name) + core.BNFreeRegisterList(sem_classes) + + count = ctypes.c_ulonglong() + sem_groups = core.BNGetAllArchitectureSemanticFlagGroups(self.handle, count) + self._semantic_flag_groups = {} + self._semantic_flag_groups_by_index = {} + self.__dict__["semantic_flag_groups"] = [] + for i in xrange(0, count.value): + name = core.BNGetArchitectureSemanticFlagGroupName(self.handle, sem_groups[i]) + self._semantic_flag_groups[name] = sem_groups[i] + self._semantic_flag_groups_by_index[sem_groups[i]] = name + self.semantic_flag_groups.append(name) + core.BNFreeRegisterList(sem_groups) self._flag_roles = {} self.__dict__["flag_roles"] = {} @@ -184,19 +212,48 @@ class Architecture(object): self.__dict__["flag_roles"][flag] = role self._flag_roles[self._flags[flag]] = role - self._flags_required_for_flag_condition = {} self.__dict__["flags_required_for_flag_condition"] = {} for cond in LowLevelILFlagCondition: count = ctypes.c_ulonglong() - flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, count) + flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, 0, count) + flag_names = [] + for i in xrange(0, count.value): + flag_names.append(self._flags_by_index[flags[i]]) + core.BNFreeRegisterList(flags) + self.__dict__["flags_required_for_flag_condition"][cond] = flag_names + + self._flags_required_by_semantic_flag_group = {} + self.__dict__["flags_required_for_semantic_flag_group"] = {} + for group in self.semantic_flag_groups: + count = ctypes.c_ulonglong() + flags = core.BNGetArchitectureFlagsRequiredForSemanticFlagGroup(self.handle, + self._semantic_flag_groups[group], count) flag_indexes = [] flag_names = [] for i in xrange(0, count.value): flag_indexes.append(flags[i]) flag_names.append(self._flags_by_index[flags[i]]) core.BNFreeRegisterList(flags) - self._flags_required_for_flag_condition[cond] = flag_indexes - self.__dict__["flags_required_for_flag_condition"][cond] = flag_names + self._flags_required_by_semantic_flag_group[self._semantic_flag_groups[group]] = flag_indexes + self.__dict__["flags_required_for_semantic_flag_group"][cond] = flag_names + + self._flag_conditions_for_semantic_flag_group = {} + self.__dict__["flag_conditions_for_semantic_flag_group"] = {} + for group in self.semantic_flag_groups: + count = ctypes.c_ulonglong() + conditions = core.BNGetArchitectureFlagConditionsForSemanticFlagGroup(self.handle, + self._semantic_flag_groups[group], count) + class_index_cond = {} + class_cond = {} + for i in xrange(0, count.value): + class_index_cond[conditions[i].semanticClass] = conditions[i].condition + if conditions[i].semanticClass == 0: + class_cond[None] = conditions[i].condition + elif conditions[i].semanticClass in self._semantic_flag_classes_by_index: + class_cond[self._semantic_flag_classes_by_index[conditions[i].semanticClass]] = conditions[i].condition + core.BNFreeFlagConditionsForSemanticFlagGroup(conditions) + self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_index_cond + self.__dict__["flag_conditions_for_semantic_flag_group"][group] = class_cond self._flags_written_by_flag_write_type = {} self.__dict__["flags_written_by_flag_write_type"] = {} @@ -213,6 +270,18 @@ class Architecture(object): self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flag_indexes self.__dict__["flags_written_by_flag_write_type"][write_type] = flag_names + self._semantic_class_for_flag_write_type = {} + self.__dict__["semantic_class_for_flag_write_type"] = {} + for write_type in self.flag_write_types: + sem_class = core.BNGetArchitectureSemanticClassForFlagWriteType(self.handle, + self._flag_write_types[write_type]) + if sem_class == 0: + sem_class_name = None + else: + sem_class_name = self._semantic_flag_classes_by_index[sem_class] + self._semantic_class_for_flag_write_type[self._flag_write_types[write_type]] = sem_class + self.__dict__["semantic_class_for_flag_write_type"][write_type] = sem_class_name + count = ctypes.c_ulonglong() regs = core.BNGetArchitectureGlobalRegisters(self.handle, count) self.__dict__["global_regs"] = [] @@ -260,19 +329,33 @@ class Architecture(object): self._cb.getRegisterName = self._cb.getRegisterName.__class__(self._get_register_name) self._cb.getFlagName = self._cb.getFlagName.__class__(self._get_flag_name) self._cb.getFlagWriteTypeName = self._cb.getFlagWriteTypeName.__class__(self._get_flag_write_type_name) + self._cb.getFlagSemanticClassName = self._cb.getFlagSemanticClassName.__class__(self._get_semantic_flag_class_name) + self._cb.getFlagSemanticGroupName = self._cb.getFlagSemanticGroupName.__class__(self._get_semantic_flag_group_name) self._cb.getFullWidthRegisters = self._cb.getFullWidthRegisters.__class__(self._get_full_width_registers) self._cb.getAllRegisters = self._cb.getAllRegisters.__class__(self._get_all_registers) self._cb.getAllFlags = self._cb.getAllRegisters.__class__(self._get_all_flags) self._cb.getAllFlagWriteTypes = self._cb.getAllRegisters.__class__(self._get_all_flag_write_types) + self._cb.getAllFlagSemanticClasses = self._cb.getAllFlagSemanticClasses.__class__(self._get_all_semantic_flag_classes) + self._cb.getAllFlagSemanticGroups = self._cb.getAllFlagSemanticGroups.__class__(self._get_all_semantic_flag_groups) self._cb.getFlagRole = self._cb.getFlagRole.__class__(self._get_flag_role) self._cb.getFlagsRequiredForFlagCondition = self._cb.getFlagsRequiredForFlagCondition.__class__( self._get_flags_required_for_flag_condition) + self._cb.getFlagsRequiredForSemanticFlagGroup = self._cb.getFlagsRequiredForSemanticFlagGroup.__class__( + self._get_flags_required_for_semantic_flag_group) + self._cb.getFlagConditionsForSemanticFlagGroup = self._cb.getFlagConditionsForSemanticFlagGroup.__class__( + self._get_flag_conditions_for_semantic_flag_group) + self._cb.freeFlagConditionsForSemanticFlagGroup = self._cb.freeFlagConditionsForSemanticFlagGroup.__class__( + self._free_flag_conditions_for_semantic_flag_group) self._cb.getFlagsWrittenByFlagWriteType = self._cb.getFlagsWrittenByFlagWriteType.__class__( self._get_flags_written_by_flag_write_type) + self._cb.getSemanticClassForFlagWriteType = self._cb.getSemanticClassForFlagWriteType.__class__( + self._get_semantic_class_for_flag_write_type) self._cb.getFlagWriteLowLevelIL = self._cb.getFlagWriteLowLevelIL.__class__( self._get_flag_write_low_level_il) self._cb.getFlagConditionLowLevelIL = self._cb.getFlagConditionLowLevelIL.__class__( self._get_flag_condition_low_level_il) + self._cb.getSemanticFlagGroupLowLevelIL = self._cb.getSemanticFlagGroupLowLevelIL.__class__( + self._get_semantic_flag_group_low_level_il) self._cb.freeRegisterList = self._cb.freeRegisterList.__class__(self._free_register_list) self._cb.getRegisterInfo = self._cb.getRegisterInfo.__class__(self._get_register_info) self._cb.getStackPointerRegister = self._cb.getStackPointerRegister.__class__( @@ -362,6 +445,26 @@ class Architecture(object): self._flag_write_types_by_index[write_type_index] = write_type write_type_index += 1 + self._semantic_flag_classes = {} + self._semantic_flag_classes_by_index = {} + self.__dict__["semantic_flag_classes"] = self.__class__.semantic_flag_classes + semantic_class_index = 1 + for sem_class in self.__class__.semantic_flag_classes: + if sem_class not in self._semantic_flag_classes: + self._semantic_flag_classes[sem_class] = semantic_class_index + self._semantic_flag_classes_by_index[semantic_class_index] = sem_class + semantic_class_index += 1 + + self._semantic_flag_groups = {} + self._semantic_flag_groups_by_index = {} + self.__dict__["semantic_flag_groups"] = self.__class__.semantic_flag_groups + semantic_group_index = 0 + for sem_group in self.__class__.semantic_flag_groups: + if sem_group not in self._semantic_flag_groups: + self._semantic_flag_groups[sem_group] = semantic_group_index + self._semantic_flag_groups_by_index[semantic_group_index] = sem_group + semantic_group_index += 1 + self._flag_roles = {} self.__dict__["flag_roles"] = self.__class__.flag_roles for flag in self.__class__.flag_roles: @@ -370,13 +473,26 @@ class Architecture(object): role = FlagRole[role] self._flag_roles[self._flags[flag]] = role - self._flags_required_for_flag_condition = {} self.__dict__["flags_required_for_flag_condition"] = self.__class__.flags_required_for_flag_condition - for cond in self.__class__.flags_required_for_flag_condition: + + self._flags_required_by_semantic_flag_group = {} + self.__dict__["flags_required_for_semantic_flag_group"] = self.__class__.flags_required_for_semantic_flag_group + for group in self.__class__.flags_required_for_semantic_flag_group: flags = [] - for flag in self.__class__.flags_required_for_flag_condition[cond]: + for flag in self.__class__.flags_required_for_semantic_flag_group[group]: flags.append(self._flags[flag]) - self._flags_required_for_flag_condition[cond] = flags + self._flags_required_by_semantic_flag_group[self._semantic_flag_groups[group]] = flags + + self._flag_conditions_for_semantic_flag_group = {} + self.__dict__["flag_conditions_for_semantic_flag_group"] = self.__class__.flag_conditions_for_semantic_flag_group + for group in self.__class__.flag_conditions_for_semantic_flag_group: + class_cond = {} + for sem_class in self.__class__.flag_conditions_for_semantic_flag_group[group]: + if sem_class is None: + class_cond[0] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class] + else: + class_cond[self._semantic_flag_classes[sem_class]] = self.__class__.flag_conditions_for_semantic_flag_group[group][sem_class] + self._flag_conditions_for_semantic_flag_group[self._semantic_flag_groups[group]] = class_cond self._flags_written_by_flag_write_type = {} self.__dict__["flags_written_by_flag_write_type"] = self.__class__.flags_written_by_flag_write_type @@ -386,10 +502,21 @@ class Architecture(object): flags.append(self._flags[flag]) self._flags_written_by_flag_write_type[self._flag_write_types[write_type]] = flags + self._semantic_class_for_flag_write_type = {} + self.__dict__["semantic_class_for_flag_write_type"] = self.__class__.semantic_class_for_flag_write_type + for write_type in self.__class__.semantic_class_for_flag_write_type: + sem_class = self.__class__.semantic_class_for_flag_write_type[write_type] + if sem_class in self._semantic_flag_classes: + sem_class_index = self._semantic_flag_classes[sem_class] + else: + sem_class_index = 0 + self._semantic_class_for_flag_write_type[self._flag_write_types[write_type]] = sem_class_index + self.__dict__["global_regs"] = self.__class__.global_regs self._pending_reg_lists = {} self._pending_token_lists = {} + self._pending_condition_lists = {} def __eq__(self, value): if not isinstance(value, Architecture): @@ -605,6 +732,24 @@ class Architecture(object): log.log_error(traceback.format_exc()) return core.BNAllocString("") + def _get_semantic_flag_class_name(self, ctxt, sem_class): + try: + if sem_class in self._semantic_flag_class_by_index: + return core.BNAllocString(self._semantic_flag_class_by_index[sem_class]) + return core.BNAllocString("") + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + return core.BNAllocString("") + + def _get_semantic_flag_group_name(self, ctxt, sem_group): + try: + if sem_group in self._semantic_flag_group_by_index: + return core.BNAllocString(self._semantic_flag_group_by_index[sem_group]) + return core.BNAllocString("") + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + return core.BNAllocString("") + def _get_full_width_registers(self, ctxt, count): try: regs = self._full_width_regs.values() @@ -652,11 +797,11 @@ class Architecture(object): def _get_all_flag_write_types(self, ctxt, count): try: - types = self._flag_write_types_by_index.keys() - count[0] = len(types) - type_buf = (ctypes.c_uint * len(types))() - for i in xrange(0, len(types)): - type_buf[i] = types[i] + write_types = self._flag_write_types_by_index.keys() + count[0] = len(write_types) + type_buf = (ctypes.c_uint * len(write_types))() + for i in xrange(0, len(write_types)): + type_buf[i] = write_types[i] result = ctypes.cast(type_buf, ctypes.c_void_p) self._pending_reg_lists[result.value] = (result, type_buf) return result.value @@ -665,6 +810,36 @@ class Architecture(object): count[0] = 0 return None + def _get_all_semantic_flag_classes(self, ctxt, count): + try: + sem_classes = self._semantic_flag_classes_by_index.keys() + count[0] = len(sem_classes) + class_buf = (ctypes.c_uint * len(sem_classes))() + for i in xrange(0, len(sem_classes)): + class_buf[i] = sem_classes[i] + result = ctypes.cast(class_buf, ctypes.c_void_p) + self._pending_reg_lists[result.value] = (result, class_buf) + return result.value + except KeyError: + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _get_all_semantic_flag_groups(self, ctxt, count): + try: + sem_groups = self._semantic_flag_groups_by_index.keys() + count[0] = len(sem_groups) + group_buf = (ctypes.c_uint * len(sem_groups))() + for i in xrange(0, len(sem_groups)): + group_buf[i] = sem_groups[i] + result = ctypes.cast(group_buf, ctypes.c_void_p) + self._pending_reg_lists[result.value] = (result, group_buf) + return result.value + except KeyError: + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + def _get_flag_role(self, ctxt, flag): try: if flag in self._flag_roles: @@ -674,12 +849,16 @@ class Architecture(object): log.log_error(traceback.format_exc()) return None - def _get_flags_required_for_flag_condition(self, ctxt, cond, count): + def _get_flags_required_for_flag_condition(self, ctxt, cond, sem_class, count): try: - if cond in self._flags_required_for_flag_condition: - flags = self._flags_required_for_flag_condition[cond] + if sem_class in self._semantic_flag_classes_by_index: + sem_class = self._semantic_flag_classes_by_index[sem_class] else: - flags = [] + sem_class = 0 + flag_names = self.perform_get_flags_required_for_flag_condition(cond, sem_class) + flags = [] + for name in flag_names: + flags.append(self._flags[name]) count[0] = len(flags) flag_buf = (ctypes.c_uint * len(flags))() for i in xrange(0, len(flags)): @@ -692,6 +871,59 @@ class Architecture(object): count[0] = 0 return None + def perform_get_flags_required_for_flag_condition(self, cond, sem_class): + if cond in self.flags_required_for_flag_condition: + return self.flags_required_for_flag_condition[cond] + return [] + + def _get_flags_required_for_semantic_flag_group(self, ctxt, sem_group, count): + try: + if sem_group in self._flags_required_by_semantic_flag_group: + flags = self._flags_required_by_semantic_flag_group[sem_group] + else: + flags = [] + count[0] = len(flags) + flag_buf = (ctypes.c_uint * len(flags))() + for i in xrange(0, len(flags)): + flag_buf[i] = flags[i] + result = ctypes.cast(flag_buf, ctypes.c_void_p) + self._pending_reg_lists[result.value] = (result, flag_buf) + return result.value + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _get_flag_conditions_for_semantic_flag_group(self, ctxt, sem_group, count): + try: + if sem_group in self._flag_conditions_by_semantic_flag_group: + class_cond = self._flag_conditions_by_semantic_flag_group[sem_group] + else: + class_cond = {} + count[0] = len(class_cond) + cond_buf = (core.BNFlagConditionForSemanticClass * len(class_cond))() + i = 0 + for class_index in class_cond.keys(): + cond_buf[i].semanticClass = class_index + cond_buf[i].condition = class_cond[class_index] + i += 1 + result = ctypes.cast(cond_buf, ctypes.c_void_p) + self._pending_conditions[result.value] = (result, cond_buf) + return result.value + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _free_flag_conditions_for_semantic_flag_group(self, ctxt, conditions): + try: + buf = ctypes.cast(conditions, ctypes.c_void_p) + if buf.value not in self._pending_conditions: + raise ValueError("freeing condition list that wasn't allocated") + del self._pending_conditions[buf.value] + except (ValueError, KeyError): + log.log_error(traceback.format_exc()) + def _get_flags_written_by_flag_write_type(self, ctxt, write_type, count): try: if write_type in self._flags_written_by_flag_write_type: @@ -710,6 +942,16 @@ class Architecture(object): count[0] = 0 return None + def _get_semantic_class_for_flag_write_type(self, ctxt, write_type): + try: + if write_type in self._semantic_class_for_flag_write_type: + return self._semantic_class_for_flag_write_type[write_type] + else: + return 0 + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + return 0 + def _get_flag_write_low_level_il(self, ctxt, op, size, write_type, flag, operands, operand_count, il): try: write_type_name = None @@ -730,9 +972,25 @@ class Architecture(object): log.log_error(traceback.format_exc()) return False - def _get_flag_condition_low_level_il(self, ctxt, cond, il): + def _get_flag_condition_low_level_il(self, ctxt, cond, sem_class, il): try: - return self.perform_get_flag_condition_low_level_il(cond, + if sem_class in self._semantic_flag_classes_by_index: + sem_class_name = self._semantic_flag_classes_by_index[sem_class] + else: + sem_class_name = None + return self.perform_get_flag_condition_low_level_il(cond, sem_class_name, + lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))).index + except OSError: + log.log_error(traceback.format_exc()) + return 0 + + def _get_semantic_flag_group_low_level_il(self, ctxt, sem_group, il): + try: + if sem_group in self._semantic_flag_groups_by_index: + sem_group_name = self._semantic_flag_groups_by_index[sem_group] + else: + sem_group_name = None + return self.perform_get_semantic_flag_group_low_level_il(sem_group_name, lowlevelil.LowLevelILFunction(self, core.BNNewLowLevelILFunctionReference(il))).index except OSError: log.log_error(traceback.format_exc()) @@ -1054,17 +1312,30 @@ class Architecture(object): return self.get_default_flag_write_low_level_il(op, size, self._flag_roles[flag], operands, il) @abc.abstractmethod - def perform_get_flag_condition_low_level_il(self, cond, il): + def perform_get_flag_condition_low_level_il(self, cond, sem_class, il): """ .. note:: Architecture subclasses should implement this method. .. warning:: This method should never be called directly. - :param LowLevelILFlagCondition cond: - :param LowLevelILFunction il: + :param LowLevelILFlagCondition cond: Flag condition to be computed + :param str sem_class: Semantic class to be used (None for default semantics) + :param LowLevelILFunction il: LowLevelILFunction object to append LowLevelILExpr objects to :rtype: LowLevelILExpr """ return self.get_default_flag_condition_low_level_il(cond, il) + @abc.abstractmethod + def perform_get_semantic_flag_group_low_level_il(self, sem_group, il): + """ + .. note:: Architecture subclasses should implement this method. + .. warning:: This method should never be called directly. + + :param str sem_group: Semantic group to be computed + :param LowLevelILFunction il: LowLevelILFunction object to append LowLevelILExpr objects to + :rtype: LowLevelILExpr + """ + return il.unimplemented() + @abc.abstractmethod def perform_assemble(self, code, addr): """ @@ -1407,6 +1678,22 @@ class Architecture(object): return flag.index return flag + def get_semantic_flag_class_index(self, sem_class): + if sem_class is None: + return 0 + elif isinstance(sem_class, str): + return self._semantic_flag_classes[sem_class] + elif isinstance(sem_class, lowlevelil.ILSemanticFlagClass): + return sem_class.index + return sem_class + + def get_semantic_flag_group_index(self, sem_group): + if isinstance(sem_group, str): + return self._semantic_flag_groups[sem_group] + elif isinstance(sem_group, lowlevelil.ILSemanticFlagGroup): + return sem_group.index + return sem_group + def get_flag_write_type_name(self, write_type): """ ``get_flag_write_type_name`` gets the flag write type name for the given flag. @@ -1437,6 +1724,26 @@ class Architecture(object): """ return self._flag_write_types[write_type] + def get_semantic_flag_class_by_name(self, sem_class): + """ + ``get_semantic_flag_class_by_name`` gets the semantic flag class index by name. + + :param int sem_class: semantic flag class + :return: semantic flag class index + :rtype: str + """ + return self._semantic_flag_classes[sem_class] + + def get_semantic_flag_group_by_name(self, sem_group): + """ + ``get_semantic_flag_group_by_name`` gets the semantic flag group index by name. + + :param int sem_group: semantic flag group + :return: semantic flag group index + :rtype: str + """ + return self._semantic_flag_groups[sem_group] + def get_flag_write_low_level_il(self, op, size, write_type, flag, operands, il): """ :param LowLevelILOperation op: @@ -1502,6 +1809,25 @@ class Architecture(object): """ return lowlevelil.LowLevelILExpr(core.BNGetDefaultArchitectureFlagConditionLowLevelIL(self.handle, cond, il.handle)) + def get_semantic_flag_group_low_level_il(self, sem_group, il): + """ + :param str sem_group: + :param LowLevelILFunction il: + :rtype: LowLevelILExpr + """ + group_index = self.get_semantic_flag_group_index(sem_group) + return lowlevelil.LowLevelILExpr(core.BNGetArchitectureSemanticFlagGroupLowLevelIL(self.handle, group_index, il.handle)) + + def get_flags_required_for_flag_condition(self, cond, sem_class = None): + sem_class = self.get_semantic_flag_class_index(sem_class) + count = ctypes.c_ulonglong() + flags = core.BNGetArchitectureFlagsRequiredForFlagCondition(self.handle, cond, sem_class, count) + flag_names = [] + for i in xrange(0, count.value): + flag_names.append(self._flags_by_index[flags[i]]) + core.BNFreeRegisterList(flags) + return flag_names + def get_modified_regs_on_write(self, reg): """ ``get_modified_regs_on_write`` returns a list of register names that are modified when ``reg`` is written. diff --git a/python/lowlevelil.py b/python/lowlevelil.py index 42c34ee0..a2d77c9f 100644 --- a/python/lowlevelil.py +++ b/python/lowlevelil.py @@ -99,6 +99,38 @@ class ILFlag(object): return self.name +class ILSemanticFlagClass(object): + def __init__(self, arch, sem_class): + self.arch = arch + self.index = sem_class + self.name = self.arch.get_semantic_flag_class_name(self.index) + + def __str__(self): + return self.name + + def __repr__(self): + return self.name + + def __eq__(self, other): + return self.index == other.index + + +class ILSemanticFlagGroup(object): + def __init__(self, arch, sem_group): + self.arch = arch + self.index = sem_group + self.name = self.arch.get_semantic_flag_group_name(self.index) + + def __str__(self): + return self.name + + def __repr__(self): + return self.name + + def __eq__(self, other): + return self.index == other.index + + class SSARegister(object): def __init__(self, reg, version): self.reg = reg @@ -202,7 +234,8 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_NORET: [], LowLevelILOperation.LLIL_IF: [("condition", "expr"), ("true", "int"), ("false", "int")], LowLevelILOperation.LLIL_GOTO: [("dest", "int")], - LowLevelILOperation.LLIL_FLAG_COND: [("condition", "cond")], + LowLevelILOperation.LLIL_FLAG_COND: [("condition", "cond", "semantic_class", "sem_class")], + LowLevelILOperation.LLIL_FLAG_GROUP: [("semantic_group", "sem_group")], LowLevelILOperation.LLIL_CMP_E: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_CMP_NE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_CMP_SLT: [("left", "expr"), ("right", "expr")], @@ -238,6 +271,7 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_FCMP_LE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_GE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_GT: [("left", "expr"), ("right", "expr")], + LowLevelILOperation.LLIL_FCMP_O: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_UO: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_SET_REG_SSA: [("dest", "reg_ssa"), ("src", "expr")], LowLevelILOperation.LLIL_SET_REG_SSA_PARTIAL: [("full_reg", "reg_ssa"), ("dest", "reg"), ("src", "expr")], @@ -324,6 +358,10 @@ class LowLevelILInstruction(object): flag = ILFlag(func.arch, instr.operands[i]) i += 1 value = SSAFlag(flag, instr.operands[i]) + elif operand_type == "sem_class": + value = ILSemanticFlagClass(func.arch, instr.operands[i]) + elif operand_type == "sem_group": + value = ILSemanticFlagGroup(func.arch, instr.operands[i]) elif operand_type == "cond": value = LowLevelILFlagCondition(instr.operands[i]) elif operand_type == "int_list": @@ -1507,11 +1545,12 @@ class LowLevelILFunction(object): """ return self.expr(LowLevelILOperation.LLIL_NORET) - def flag_condition(self, cond): + def flag_condition(self, cond, sem_class = None): """ ``flag_condition`` returns a flag_condition expression for the given LowLevelILFlagCondition :param LowLevelILFlagCondition cond: Flag condition expression to retrieve + :param str sem_class: Optional semantic flag class :return: A flag_condition expression :rtype: LowLevelILExpr """ @@ -1519,7 +1558,19 @@ class LowLevelILFunction(object): cond = LowLevelILFlagCondition[cond] elif isinstance(cond, LowLevelILFlagCondition): cond = cond.value - return self.expr(LowLevelILOperation.LLIL_FLAG_COND, cond) + class_index = self.arch.get_semantic_flag_class_index(sem_class) + return self.expr(LowLevelILOperation.LLIL_FLAG_COND, cond, class_index) + + def flag_group(self, sem_group): + """ + ``flag_group`` returns a flag_group expression for the given semantic flag group + + :param str sem_group: Semantic flag group to access + :return: A flag_group expression + :rtype: LowLevelILExpr + """ + group = self.arch.get_semantic_flag_group_index(sem_group) + return self.expr(LowLevelILOperation.LLIL_FLAG_GROUP, group) def compare_equal(self, size, a, b): """ @@ -2174,6 +2225,7 @@ class LowLevelILBasicBlock(basicblock.BasicBlock): def __hash__(self): return hash((self.start, self.end, self.il_function)) + def LLIL_TEMP(n): return n | 0x80000000 diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py index 85feba0a..8594ea36 100644 --- a/python/mediumlevelil.py +++ b/python/mediumlevelil.py @@ -169,6 +169,7 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_FCMP_LE: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FCMP_GE: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FCMP_GT: [("left", "expr"), ("right", "expr")], + MediumLevelILOperation.MLIL_FCMP_O: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FCMP_UO: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_SET_VAR_SSA: [("dest", "var_ssa"), ("src", "expr")], MediumLevelILOperation.MLIL_SET_VAR_SSA_FIELD: [("prev", "var_ssa_dest_and_src"), ("offset", "int"), ("src", "expr")], -- cgit v1.3.1 From 2f3873928078e8c21911ffeb5476781b31886514 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Wed, 31 Jan 2018 20:24:16 -0500 Subject: Adding CPU intrinsics support --- architecture.cpp | 159 +++++++++++++++++++ binaryninjaapi.h | 39 +++++ binaryninjacore.h | 40 ++++- lowlevelil.cpp | 25 +++ lowlevelilinstruction.cpp | 355 ++++++++++++++++++++++++++++++++++++++++++- lowlevelilinstruction.h | 129 ++++++++++++++++ mediumlevelilinstruction.cpp | 71 ++++++++- mediumlevelilinstruction.h | 20 +++ python/architecture.py | 154 +++++++++++++++++++ python/function.py | 23 ++- python/lowlevelil.py | 109 ++++++++++--- python/mediumlevelil.py | 4 + 12 files changed, 1095 insertions(+), 33 deletions(-) (limited to 'python/mediumlevelil.py') diff --git a/architecture.cpp b/architecture.cpp index 78a67105..223af13d 100644 --- a/architecture.cpp +++ b/architecture.cpp @@ -491,6 +491,79 @@ void Architecture::GetRegisterStackInfoCallback(void* ctxt, uint32_t regStack, B } +char* Architecture::GetIntrinsicNameCallback(void* ctxt, uint32_t intrinsic) +{ + Architecture* arch = (Architecture*)ctxt; + string result = arch->GetIntrinsicName(intrinsic); + return BNAllocString(result.c_str()); +} + + +uint32_t* Architecture::GetAllIntrinsicsCallback(void* ctxt, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector regs = arch->GetAllIntrinsics(); + *count = regs.size(); + + uint32_t* result = new uint32_t[regs.size()]; + for (size_t i = 0; i < regs.size(); i++) + result[i] = regs[i]; + return result; +} + + +BNNameAndType* Architecture::GetIntrinsicInputsCallback(void* ctxt, uint32_t intrinsic, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector inputs = arch->GetIntrinsicInputs(intrinsic); + *count = inputs.size(); + + BNNameAndType* result = new BNNameAndType[inputs.size()]; + for (size_t i = 0; i < inputs.size(); i++) + { + result[i].name = BNAllocString(inputs[i].name.c_str()); + result[i].type = BNNewTypeReference(inputs[i].type.GetValue()->GetObject()); + result[i].typeConfidence = inputs[i].type.GetConfidence(); + } + return result; +} + + +void Architecture::FreeNameAndTypeListCallback(void*, BNNameAndType* nt, size_t count) +{ + for (size_t i = 0; i < count; i++) + { + BNFreeString(nt[i].name); + BNFreeType(nt[i].type); + } + delete[] nt; +} + + +BNTypeWithConfidence* Architecture::GetIntrinsicOutputsCallback(void* ctxt, uint32_t intrinsic, size_t* count) +{ + Architecture* arch = (Architecture*)ctxt; + vector>> outputs = arch->GetIntrinsicOutputs(intrinsic); + *count = outputs.size(); + + BNTypeWithConfidence* result = new BNTypeWithConfidence[outputs.size()]; + for (size_t i = 0; i < outputs.size(); i++) + { + result[i].type = BNNewTypeReference(outputs[i].GetValue()->GetObject()); + result[i].confidence = outputs[i].GetConfidence(); + } + return result; +} + + +void Architecture::FreeTypeListCallback(void*, BNTypeWithConfidence* types, size_t count) +{ + for (size_t i = 0; i < count; i++) + BNFreeType(types[i].type); + delete[] types; +} + + bool Architecture::AssembleCallback(void* ctxt, const char* code, uint64_t addr, BNDataBuffer* result, char** errors) { Architecture* arch = (Architecture*)ctxt; @@ -612,6 +685,12 @@ void Architecture::Register(Architecture* arch) callbacks.getRegisterStackName = GetRegisterStackNameCallback; callbacks.getAllRegisterStacks = GetAllRegisterStacksCallback; callbacks.getRegisterStackInfo = GetRegisterStackInfoCallback; + callbacks.getIntrinsicName = GetIntrinsicNameCallback; + callbacks.getAllIntrinsics = GetAllIntrinsicsCallback; + callbacks.getIntrinsicInputs = GetIntrinsicInputsCallback; + callbacks.freeNameAndTypeList = FreeNameAndTypeListCallback; + callbacks.getIntrinsicOutputs = GetIntrinsicOutputsCallback; + callbacks.freeTypeList = FreeTypeListCallback; callbacks.assemble = AssembleCallback; callbacks.isNeverBranchPatchAvailable = IsNeverBranchPatchAvailableCallback; callbacks.isAlwaysBranchPatchAvailable = IsAlwaysBranchPatchAvailableCallback; @@ -920,6 +999,32 @@ uint32_t Architecture::GetRegisterStackForRegister(uint32_t reg) } +string Architecture::GetIntrinsicName(uint32_t intrinsic) +{ + char intrinsicStr[32]; + sprintf(intrinsicStr, "intrinsic_%" PRIu32, intrinsic); + return intrinsicStr; +} + + +vector Architecture::GetAllIntrinsics() +{ + return vector(); +} + + +vector Architecture::GetIntrinsicInputs(uint32_t) +{ + return vector(); +} + + +vector>> Architecture::GetIntrinsicOutputs(uint32_t) +{ + return vector>>(); +} + + vector Architecture::GetModifiedRegistersOnWrite(uint32_t reg) { size_t count; @@ -1477,6 +1582,60 @@ BNRegisterStackInfo CoreArchitecture::GetRegisterStackInfo(uint32_t regStack) } +string CoreArchitecture::GetIntrinsicName(uint32_t intrinsic) +{ + char* name = BNGetArchitectureIntrinsicName(m_object, intrinsic); + string result = name; + BNFreeString(name); + return result; +} + + +vector CoreArchitecture::GetAllIntrinsics() +{ + size_t count; + uint32_t* regs = BNGetAllArchitectureIntrinsics(m_object, &count); + + vector result; + for (size_t i = 0; i < count; i++) + result.push_back(regs[i]); + + BNFreeRegisterList(regs); + return result; +} + + +vector CoreArchitecture::GetIntrinsicInputs(uint32_t intrinsic) +{ + size_t count; + BNNameAndType* inputs = BNGetArchitectureIntrinsicInputs(m_object, intrinsic, &count); + + vector result; + for (size_t i = 0; i < count; i++) + { + result.push_back(NameAndType(inputs[i].name, Confidence>( + new Type(BNNewTypeReference(inputs[i].type)), inputs[i].typeConfidence))); + } + + BNFreeNameAndTypeList(inputs, count); + return result; +} + + +vector>> CoreArchitecture::GetIntrinsicOutputs(uint32_t intrinsic) +{ + size_t count; + BNTypeWithConfidence* outputs = BNGetArchitectureIntrinsicOutputs(m_object, intrinsic, &count); + + vector>> result; + for (size_t i = 0; i < count; i++) + result.push_back(Confidence>(new Type(BNNewTypeReference(outputs[i].type)), outputs[i].confidence)); + + BNFreeOutputTypeList(outputs, count); + return result; +} + + bool CoreArchitecture::Assemble(const string& code, uint64_t addr, DataBuffer& result, string& errors) { char* errorStr = nullptr; diff --git a/binaryninjaapi.h b/binaryninjaapi.h index b74fa971..d1ca9cdb 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -1566,6 +1566,16 @@ namespace BinaryNinja void AddBranch(BNBranchType type, uint64_t target = 0, Architecture* arch = nullptr, bool hasDelaySlot = false); }; + struct NameAndType + { + std::string name; + Confidence> type; + + NameAndType() {} + NameAndType(const Confidence>& t): type(t) {} + NameAndType(const std::string& n, const Confidence>& t): name(n), type(t) {} + }; + class LowLevelILFunction; class FunctionRecognizer; class CallingConvention; @@ -1633,6 +1643,13 @@ namespace BinaryNinja static uint32_t* GetAllRegisterStacksCallback(void* ctxt, size_t* count); static void GetRegisterStackInfoCallback(void* ctxt, uint32_t regStack, BNRegisterStackInfo* result); + static char* GetIntrinsicNameCallback(void* ctxt, uint32_t intrinsic); + static uint32_t* GetAllIntrinsicsCallback(void* ctxt, size_t* count); + static BNNameAndType* GetIntrinsicInputsCallback(void* ctxt, uint32_t intrinsic, size_t* count); + static void FreeNameAndTypeListCallback(void* ctxt, BNNameAndType* nt, size_t count); + static BNTypeWithConfidence* GetIntrinsicOutputsCallback(void* ctxt, uint32_t intrinsic, size_t* count); + static void FreeTypeListCallback(void* ctxt, BNTypeWithConfidence* types, size_t count); + static bool AssembleCallback(void* ctxt, const char* code, uint64_t addr, BNDataBuffer* result, char** errors); static bool IsNeverBranchPatchAvailableCallback(void* ctxt, const uint8_t* data, uint64_t addr, size_t len); static bool IsAlwaysBranchPatchAvailableCallback(void* ctxt, const uint8_t* data, uint64_t addr, size_t len); @@ -1714,6 +1731,11 @@ namespace BinaryNinja virtual BNRegisterStackInfo GetRegisterStackInfo(uint32_t regStack); uint32_t GetRegisterStackForRegister(uint32_t reg); + virtual std::string GetIntrinsicName(uint32_t intrinsic); + virtual std::vector GetAllIntrinsics(); + virtual std::vector GetIntrinsicInputs(uint32_t intrinsic); + virtual std::vector>> GetIntrinsicOutputs(uint32_t intrinsic); + virtual bool Assemble(const std::string& code, uint64_t addr, DataBuffer& result, std::string& errors); /*! IsNeverBranchPatchAvailable returns true if the instruction at addr can be patched to never branch. @@ -1853,6 +1875,11 @@ namespace BinaryNinja virtual std::vector GetAllRegisterStacks() override; virtual BNRegisterStackInfo GetRegisterStackInfo(uint32_t regStack) override; + virtual std::string GetIntrinsicName(uint32_t intrinsic) override; + virtual std::vector GetAllIntrinsics() override; + virtual std::vector GetIntrinsicInputs(uint32_t intrinsic) override; + virtual std::vector>> GetIntrinsicOutputs(uint32_t intrinsic) override; + virtual bool Assemble(const std::string& code, uint64_t addr, DataBuffer& result, std::string& errors) override; virtual bool IsNeverBranchPatchAvailable(const uint8_t* data, uint64_t addr, size_t len) override; @@ -2452,9 +2479,11 @@ namespace BinaryNinja }; struct LowLevelILInstruction; + struct RegisterOrFlag; struct SSARegister; struct SSARegisterStack; struct SSAFlag; + struct SSARegisterOrFlag; class LowLevelILFunction: public CoreRefCountObject @@ -2641,6 +2670,10 @@ namespace BinaryNinja ExprId TestBit(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId BoolToInt(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); ExprId SystemCall(const ILSourceLocation& loc = ILSourceLocation()); + ExprId Intrinsic(const std::vector& outputs, uint32_t intrinsic, + const std::vector& params, const ILSourceLocation& loc = ILSourceLocation()); + ExprId IntrinsicSSA(const std::vector& outputs, uint32_t intrinsic, + const std::vector& params, const ILSourceLocation& loc = ILSourceLocation()); ExprId Breakpoint(const ILSourceLocation& loc = ILSourceLocation()); ExprId Trap(uint32_t num, const ILSourceLocation& loc = ILSourceLocation()); ExprId Undefined(const ILSourceLocation& loc = ILSourceLocation()); @@ -2686,9 +2719,11 @@ namespace BinaryNinja ExprId AddLabelList(const std::vector& labels); ExprId AddOperandList(const std::vector operands); ExprId AddIndexList(const std::vector operands); + ExprId AddRegisterOrFlagList(const std::vector& regs); ExprId AddSSARegisterList(const std::vector& regs); ExprId AddSSARegisterStackList(const std::vector& regStacks); ExprId AddSSAFlagList(const std::vector& flags); + ExprId AddSSARegisterOrFlagList(const std::vector& regs); ExprId GetExprForRegisterOrConstant(const BNRegisterOrConstant& operand, size_t size); ExprId GetNegExprForRegisterOrConstant(const BNRegisterOrConstant& operand, size_t size); @@ -2954,6 +2989,10 @@ namespace BinaryNinja const ILSourceLocation& loc = ILSourceLocation()); ExprId Breakpoint(const ILSourceLocation& loc = ILSourceLocation()); ExprId Trap(int64_t vector, const ILSourceLocation& loc = ILSourceLocation()); + ExprId Intrinsic(const std::vector& outputs, uint32_t intrinsic, + const std::vector& params, const ILSourceLocation& loc = ILSourceLocation()); + ExprId IntrinsicSSA(const std::vector& outputs, uint32_t intrinsic, + const std::vector& params, const ILSourceLocation& loc = ILSourceLocation()); ExprId Undefined(const ILSourceLocation& loc = ILSourceLocation()); ExprId Unimplemented(const ILSourceLocation& loc = ILSourceLocation()); ExprId UnimplementedMemoryRef(size_t size, ExprId target, diff --git a/binaryninjacore.h b/binaryninjacore.h index bc58092d..a946df31 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -352,6 +352,7 @@ extern "C" LLIL_SYSCALL, LLIL_BP, LLIL_TRAP, + LLIL_INTRINSIC, LLIL_UNDEF, LLIL_UNIMPL, LLIL_UNIMPL_MEM, @@ -394,11 +395,12 @@ extern "C" LLIL_FLAG_BIT_SSA, LLIL_CALL_SSA, LLIL_SYSCALL_SSA, - LLIL_CALL_PARAM_SSA, // Only valid within the LLIL_CALL_SSA or LLIL_SYSCALL_SSA instructions + LLIL_CALL_PARAM, // Only valid within the LLIL_CALL_SSA, LLIL_SYSCALL_SSA, LLIL_INTRINSIC, LLIL_INTRINSIC_SSA instructions LLIL_CALL_STACK_SSA, // Only valid within the LLIL_CALL_SSA or LLIL_SYSCALL_SSA instructions LLIL_CALL_OUTPUT_SSA, // Only valid within the LLIL_CALL_SSA or LLIL_SYSCALL_SSA instructions LLIL_LOAD_SSA, LLIL_STORE_SSA, + LLIL_INTRINSIC_SSA, LLIL_REG_PHI, LLIL_REG_STACK_PHI, LLIL_FLAG_PHI, @@ -858,6 +860,7 @@ extern "C" MLIL_ADD_OVERFLOW, MLIL_SYSCALL, // Not valid in SSA form (see MLIL_SYSCALL_SSA) MLIL_SYSCALL_UNTYPED, // Not valid in SSA form (see MLIL_SYSCALL_UNTYPED_SSA) + MLIL_INTRINSIC, // Not valid in SSA form (see MLIL_INTRINSIC_SSA) MLIL_BP, MLIL_TRAP, MLIL_UNDEF, @@ -905,6 +908,7 @@ extern "C" MLIL_LOAD_STRUCT_SSA, MLIL_STORE_SSA, MLIL_STORE_STRUCT_SSA, + MLIL_INTRINSIC_SSA, MLIL_VAR_PHI, MLIL_MEM_PHI }; @@ -1077,6 +1081,19 @@ extern "C" BNLowLevelILFlagCondition condition; }; + struct BNNameAndType + { + char* name; + BNType* type; + uint8_t typeConfidence; + }; + + struct BNTypeWithConfidence + { + BNType* type; + uint8_t confidence; + }; + struct BNCustomArchitecture { void* context; @@ -1127,6 +1144,13 @@ extern "C" uint32_t* (*getAllRegisterStacks)(void* ctxt, size_t* count); void (*getRegisterStackInfo)(void* ctxt, uint32_t regStack, BNRegisterStackInfo* result); + char* (*getIntrinsicName)(void* ctxt, uint32_t intrinsic); + uint32_t* (*getAllIntrinsics)(void* ctxt, size_t* count); + BNNameAndType* (*getIntrinsicInputs)(void* ctxt, uint32_t intrinsic, size_t* count); + void (*freeNameAndTypeList)(void* ctxt, BNNameAndType* nt, size_t count); + BNTypeWithConfidence* (*getIntrinsicOutputs)(void* ctxt, uint32_t intrinsic, size_t* count); + void (*freeTypeList)(void* ctxt, BNTypeWithConfidence* types, size_t count); + bool (*assemble)(void* ctxt, const char* code, uint64_t addr, BNDataBuffer* result, char** errors); bool (*isNeverBranchPatchAvailable)(void* ctxt, const uint8_t* data, uint64_t addr, size_t len); @@ -1203,12 +1227,6 @@ extern "C" char* (*serialize)(void* ctxt); }; - struct BNTypeWithConfidence - { - BNType* type; - uint8_t confidence; - }; - struct BNCallingConventionWithConfidence { BNCallingConvention* convention; @@ -2116,6 +2134,14 @@ extern "C" BINARYNINJACOREAPI BNRegisterStackInfo BNGetArchitectureRegisterStackInfo(BNArchitecture* arch, uint32_t regStack); BINARYNINJACOREAPI uint32_t BNGetArchitectureRegisterStackForRegister(BNArchitecture* arch, uint32_t reg); + BINARYNINJACOREAPI char* BNGetArchitectureIntrinsicName(BNArchitecture* arch, uint32_t intrinsic); + BINARYNINJACOREAPI uint32_t* BNGetAllArchitectureIntrinsics(BNArchitecture* arch, size_t* count); + BINARYNINJACOREAPI BNNameAndType* BNGetArchitectureIntrinsicInputs(BNArchitecture* arch, uint32_t intrinsic, size_t* count); + BINARYNINJACOREAPI void BNFreeNameAndTypeList(BNNameAndType* nt, size_t count); + BINARYNINJACOREAPI BNTypeWithConfidence* BNGetArchitectureIntrinsicOutputs(BNArchitecture* arch, uint32_t intrinsic, + size_t* count); + BINARYNINJACOREAPI void BNFreeOutputTypeList(BNTypeWithConfidence* types, size_t count); + BINARYNINJACOREAPI bool BNAssemble(BNArchitecture* arch, const char* code, uint64_t addr, BNDataBuffer* result, char** errors); BINARYNINJACOREAPI bool BNIsArchitectureNeverBranchPatchAvailable(BNArchitecture* arch, const uint8_t* data, diff --git a/lowlevelil.cpp b/lowlevelil.cpp index c72d4b68..0f2b29be 100644 --- a/lowlevelil.cpp +++ b/lowlevelil.cpp @@ -216,6 +216,17 @@ ExprId LowLevelILFunction::AddIndexList(const vector operands) } +ExprId LowLevelILFunction::AddRegisterOrFlagList(const vector& regs) +{ + uint64_t* operandList = new uint64_t[regs.size()]; + for (size_t i = 0; i < regs.size(); i++) + operandList[i] = regs[i].ToIdentifier(); + ExprId result = (ExprId)BNLowLevelILAddOperandList(m_object, operandList, regs.size()); + delete[] operandList; + return result; +} + + ExprId LowLevelILFunction::AddSSARegisterList(const vector& regs) { uint64_t* operandList = new uint64_t[regs.size() * 2]; @@ -258,6 +269,20 @@ ExprId LowLevelILFunction::AddSSAFlagList(const vector& flags) } +ExprId LowLevelILFunction::AddSSARegisterOrFlagList(const vector& regs) +{ + uint64_t* operandList = new uint64_t[regs.size() * 2]; + for (size_t i = 0; i < regs.size(); i++) + { + operandList[i * 2] = regs[i].regOrFlag.ToIdentifier(); + operandList[(i * 2) + 1] = regs[i].version; + } + ExprId result = (ExprId)BNLowLevelILAddOperandList(m_object, operandList, regs.size() * 2); + delete[] operandList; + return result; +} + + ExprId LowLevelILFunction::GetExprForRegisterOrConstant(const BNRegisterOrConstant& operand, size_t size) { if (operand.constant) diff --git a/lowlevelilinstruction.cpp b/lowlevelilinstruction.cpp index 9909e8ee..2c00db68 100644 --- a/lowlevelilinstruction.cpp +++ b/lowlevelilinstruction.cpp @@ -64,6 +64,7 @@ unordered_map {HighSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, {LowRegisterLowLevelOperandUsage, RegisterLowLevelOperand}, {LowSSARegisterLowLevelOperandUsage, SSARegisterLowLevelOperand}, + {IntrinsicLowLevelOperandUsage, IntrinsicLowLevelOperand}, {ConstantLowLevelOperandUsage, IntegerLowLevelOperand}, {VectorLowLevelOperandUsage, IntegerLowLevelOperand}, {StackAdjustmentLowLevelOperandUsage, IntegerLowLevelOperand}, @@ -80,6 +81,8 @@ unordered_map {SourceSSARegistersLowLevelOperandUsage, SSARegisterListLowLevelOperand}, {SourceSSARegisterStacksLowLevelOperandUsage, SSARegisterStackListLowLevelOperand}, {SourceSSAFlagsLowLevelOperandUsage, SSAFlagListLowLevelOperand}, + {OutputRegisterOrFlagListLowLevelOperandUsage, RegisterOrFlagListLowLevelOperand}, + {OutputSSARegisterOrFlagListLowLevelOperandUsage, SSARegisterOrFlagListLowLevelOperand}, {SourceMemoryVersionsLowLevelOperandUsage, IndexListLowLevelOperand}, {TargetListLowLevelOperandUsage, IndexListLowLevelOperand}, {RegisterStackAdjustmentsLowLevelOperandUsage, RegisterStackAdjustmentsLowLevelOperand} @@ -202,6 +205,10 @@ unordered_map> {LLIL_ZX, {SourceExprLowLevelOperandUsage}}, {LLIL_LOW_PART, {SourceExprLowLevelOperandUsage}}, {LLIL_BOOL_TO_INT, {SourceExprLowLevelOperandUsage}}, + {LLIL_INTRINSIC, {OutputRegisterOrFlagListLowLevelOperandUsage, IntrinsicLowLevelOperandUsage, + ParameterExprsLowLevelOperandUsage}}, + {LLIL_INTRINSIC_SSA, {OutputSSARegisterOrFlagListLowLevelOperandUsage, IntrinsicLowLevelOperandUsage, + ParameterExprsLowLevelOperandUsage}}, {LLIL_UNIMPL_MEM, {SourceExprLowLevelOperandUsage}}, {LLIL_FADD, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, {LLIL_FSUB, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, @@ -268,6 +275,8 @@ static unordered_map() const } +const RegisterOrFlag LowLevelILRegisterOrFlagList::ListIterator::operator*() +{ + return RegisterOrFlag::FromIdentifier(*pos); +} + + +LowLevelILRegisterOrFlagList::LowLevelILRegisterOrFlagList(LowLevelILFunction* func, + const BNLowLevelILInstruction& instr, size_t count): m_list(func, instr, count) +{ +} + + +LowLevelILRegisterOrFlagList::const_iterator LowLevelILRegisterOrFlagList::begin() const +{ + const_iterator result; + result.pos = m_list.begin(); + return result; +} + + +LowLevelILRegisterOrFlagList::const_iterator LowLevelILRegisterOrFlagList::end() const +{ + const_iterator result; + result.pos = m_list.end(); + return result; +} + + +size_t LowLevelILRegisterOrFlagList::size() const +{ + return m_list.size(); +} + + +const RegisterOrFlag LowLevelILRegisterOrFlagList::operator[](size_t i) const +{ + if (i >= size()) + throw LowLevelILInstructionAccessException(); + auto iter = begin(); + for (size_t j = 0; j < i; j++) + ++iter; + return *iter; +} + + +LowLevelILRegisterOrFlagList::operator vector() const +{ + vector result; + for (auto& i : *this) + result.push_back(i); + return result; +} + + const SSARegister LowLevelILSSARegisterList::ListIterator::operator*() { LowLevelILIntegerList::const_iterator cur = pos; @@ -818,6 +1004,64 @@ LowLevelILSSAFlagList::operator vector() const } +const SSARegisterOrFlag LowLevelILSSARegisterOrFlagList::ListIterator::operator*() +{ + LowLevelILIntegerList::const_iterator cur = pos; + RegisterOrFlag rf = RegisterOrFlag::FromIdentifier(*cur); + ++cur; + size_t version = (size_t)*cur; + return SSARegisterOrFlag(rf, version); +} + + +LowLevelILSSARegisterOrFlagList::LowLevelILSSARegisterOrFlagList(LowLevelILFunction* func, + const BNLowLevelILInstruction& instr, size_t count): m_list(func, instr, count & (~1)) +{ +} + + +LowLevelILSSARegisterOrFlagList::const_iterator LowLevelILSSARegisterOrFlagList::begin() const +{ + const_iterator result; + result.pos = m_list.begin(); + return result; +} + + +LowLevelILSSARegisterOrFlagList::const_iterator LowLevelILSSARegisterOrFlagList::end() const +{ + const_iterator result; + result.pos = m_list.end(); + return result; +} + + +size_t LowLevelILSSARegisterOrFlagList::size() const +{ + return m_list.size() / 2; +} + + +const SSARegisterOrFlag LowLevelILSSARegisterOrFlagList::operator[](size_t i) const +{ + if (i >= size()) + throw LowLevelILInstructionAccessException(); + auto iter = begin(); + for (size_t j = 0; j < i; j++) + ++iter; + return *iter; +} + + +LowLevelILSSARegisterOrFlagList::operator vector() const +{ + vector result; + for (auto& i : *this) + result.push_back(i); + return result; +} + + LowLevelILOperand::LowLevelILOperand(const LowLevelILInstruction& instr, LowLevelILOperandUsage usage, size_t operandIndex): m_instr(instr), m_usage(usage), m_operandIndex(operandIndex) @@ -905,6 +1149,14 @@ uint32_t LowLevelILOperand::GetSemanticFlagGroup() const } +uint32_t LowLevelILOperand::GetIntrinsic() const +{ + if (m_type != IntrinsicLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsRegister(m_operandIndex); +} + + SSARegister LowLevelILOperand::GetSSARegister() const { if (m_type != SSARegisterLowLevelOperand) @@ -952,6 +1204,14 @@ LowLevelILInstructionList LowLevelILOperand::GetExprList() const } +LowLevelILRegisterOrFlagList LowLevelILOperand::GetRegisterOrFlagList() const +{ + if (m_type != RegisterOrFlagListLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsRegisterOrFlagList(m_operandIndex); +} + + LowLevelILSSARegisterList LowLevelILOperand::GetSSARegisterList() const { if (m_type != SSARegisterListLowLevelOperand) @@ -978,6 +1238,14 @@ LowLevelILSSAFlagList LowLevelILOperand::GetSSAFlagList() const } +LowLevelILSSARegisterOrFlagList LowLevelILOperand::GetSSARegisterOrFlagList() const +{ + if (m_type != SSARegisterOrFlagListLowLevelOperand) + throw LowLevelILInstructionAccessException(); + return m_instr.GetRawOperandAsSSARegisterOrFlagList(m_operandIndex); +} + + map LowLevelILOperand::GetRegisterStackAdjustments() const { if (m_type != RegisterStackAdjustmentsLowLevelOperand) @@ -1174,6 +1442,12 @@ LowLevelILInstructionList LowLevelILInstructionBase::GetRawOperandAsExprList(siz } +LowLevelILRegisterOrFlagList LowLevelILInstructionBase::GetRawOperandAsRegisterOrFlagList(size_t operand) const +{ + return LowLevelILRegisterOrFlagList(function, function->GetRawExpr(operands[operand + 1]), operands[operand]); +} + + LowLevelILSSARegisterList LowLevelILInstructionBase::GetRawOperandAsSSARegisterList(size_t operand) const { return LowLevelILSSARegisterList(function, function->GetRawExpr(operands[operand + 1]), operands[operand]); @@ -1192,6 +1466,12 @@ LowLevelILSSAFlagList LowLevelILInstructionBase::GetRawOperandAsSSAFlagList(size } +LowLevelILSSARegisterOrFlagList LowLevelILInstructionBase::GetRawOperandAsSSARegisterOrFlagList(size_t operand) const +{ + return LowLevelILSSARegisterOrFlagList(function, function->GetRawExpr(operands[operand + 1]), operands[operand]); +} + + map LowLevelILInstructionBase::GetRawOperandAsRegisterStackAdjustments(size_t operand) const { LowLevelILIntegerList list(function, function->GetRawExpr(operands[operand + 1]), operands[operand]); @@ -1224,6 +1504,14 @@ void LowLevelILInstructionBase::UpdateRawOperandAsSSARegisterList(size_t operand } +void LowLevelILInstructionBase::UpdateRawOperandAsSSARegisterOrFlagList(size_t operandIndex, + const vector& outputs) +{ + UpdateRawOperand(operandIndex, outputs.size() * 2); + UpdateRawOperand(operandIndex + 1, function->AddSSARegisterOrFlagList(outputs)); +} + + RegisterValue LowLevelILInstructionBase::GetValue() const { return function->GetExprValue(*(const LowLevelILInstruction*)this); @@ -1585,6 +1873,14 @@ void LowLevelILInstruction::VisitExprs(const std::function()) + i.VisitExprs(func); + break; + case LLIL_INTRINSIC_SSA: + for (auto& i : GetParameterExprs()) + i.VisitExprs(func); + break; default: break; } @@ -1839,6 +2135,16 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, subExprHandler(AsTwoOperandWithCarry().GetLeftExpr()), subExprHandler(AsTwoOperandWithCarry().GetRightExpr()), subExprHandler(AsTwoOperandWithCarry().GetCarryExpr())); + case LLIL_INTRINSIC: + for (auto& i : GetParameterExprs()) + params.push_back(subExprHandler(i)); + return dest->Intrinsic(GetOutputRegisterOrFlagList(), GetIntrinsic(), + params, *this); + case LLIL_INTRINSIC_SSA: + for (auto& i : GetParameterExprs()) + params.push_back(subExprHandler(i)); + return dest->IntrinsicSSA(GetOutputSSARegisterOrFlagList(), GetIntrinsic(), + params, *this); default: throw LowLevelILInstructionAccessException(); } @@ -2103,6 +2409,15 @@ SSARegister LowLevelILInstruction::GetLowSSARegister() const } +uint32_t LowLevelILInstruction::GetIntrinsic() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(IntrinsicLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsRegister(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + int64_t LowLevelILInstruction::GetConstant() const { size_t operandIndex; @@ -2242,6 +2557,24 @@ LowLevelILSSAFlagList LowLevelILInstruction::GetSourceSSAFlags() const } +LowLevelILRegisterOrFlagList LowLevelILInstruction::GetOutputRegisterOrFlagList() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(OutputRegisterOrFlagListLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsRegisterOrFlagList(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + +LowLevelILSSARegisterOrFlagList LowLevelILInstruction::GetOutputSSARegisterOrFlagList() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(OutputSSARegisterOrFlagListLowLevelOperandUsage, operandIndex)) + return GetRawOperandAsSSARegisterOrFlagList(operandIndex); + throw LowLevelILInstructionAccessException(); +} + + LowLevelILIndexList LowLevelILInstruction::GetSourceMemoryVersions() const { size_t operandIndex; @@ -2759,7 +3092,7 @@ ExprId LowLevelILFunction::CallSSA(const vector& output, ExprId des AddExprWithLocation(LLIL_CALL_OUTPUT_SSA, loc, 0, 0, newMemoryVer, output.size() * 2, AddSSARegisterList(output)), dest, AddExprWithLocation(LLIL_CALL_STACK_SSA, loc, 0, 0, stack.reg, stack.version, prevMemoryVer), - AddExprWithLocation(LLIL_CALL_PARAM_SSA, loc, 0, 0, + AddExprWithLocation(LLIL_CALL_PARAM, loc, 0, 0, params.size(), AddOperandList(params))); } @@ -2771,7 +3104,7 @@ ExprId LowLevelILFunction::SystemCallSSA(const vector& output, cons AddExprWithLocation(LLIL_CALL_OUTPUT_SSA, loc, 0, 0, newMemoryVer, output.size() * 2, AddSSARegisterList(output)), AddExprWithLocation(LLIL_CALL_STACK_SSA, loc, 0, 0, stack.reg, stack.version, prevMemoryVer), - AddExprWithLocation(LLIL_CALL_PARAM_SSA, loc, 0, 0, + AddExprWithLocation(LLIL_CALL_PARAM, loc, 0, 0, params.size(), AddOperandList(params))); } @@ -2878,6 +3211,24 @@ ExprId LowLevelILFunction::SystemCall(const ILSourceLocation& loc) } +ExprId LowLevelILFunction::Intrinsic(const vector& outputs, uint32_t intrinsic, + const vector& params, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_INTRINSIC, loc, 0, 0, + outputs.size(), AddRegisterOrFlagList(outputs), intrinsic, + AddExprWithLocation(LLIL_CALL_PARAM, loc, 0, 0, params.size(), AddOperandList(params))); +} + + +ExprId LowLevelILFunction::IntrinsicSSA(const vector& outputs, uint32_t intrinsic, + const vector& params, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_INTRINSIC_SSA, loc, 0, 0, + outputs.size() * 2, AddSSARegisterOrFlagList(outputs), intrinsic, + AddExprWithLocation(LLIL_CALL_PARAM, loc, 0, 0, params.size(), AddOperandList(params))); +} + + ExprId LowLevelILFunction::Breakpoint(const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_BP, loc, 0, 0); diff --git a/lowlevelilinstruction.h b/lowlevelilinstruction.h index bb5041a6..4679f556 100644 --- a/lowlevelilinstruction.h +++ b/lowlevelilinstruction.h @@ -54,6 +54,31 @@ namespace BinaryNinja class LowLevelILOperand; class LowLevelILOperandList; + struct RegisterOrFlag + { + bool isFlag; + uint32_t index; + + RegisterOrFlag(); + RegisterOrFlag(bool flag, uint32_t i); + + bool IsRegister() const { return !isFlag; } + bool IsFlag() const { return isFlag; } + uint32_t GetRegister() const; + uint32_t GetFlag() const; + + RegisterOrFlag& operator=(const RegisterOrFlag& v); + bool operator==(const RegisterOrFlag& v) const; + bool operator!=(const RegisterOrFlag& v) const; + bool operator<(const RegisterOrFlag& v) const; + + uint64_t ToIdentifier() const; + static RegisterOrFlag FromIdentifier(uint64_t id); + + static RegisterOrFlag Register(uint32_t reg) { return RegisterOrFlag(false, reg); } + static RegisterOrFlag Flag(uint32_t flag) { return RegisterOrFlag(true, flag); } + }; + struct SSARegister { uint32_t reg; @@ -99,6 +124,23 @@ namespace BinaryNinja bool operator<(const SSAFlag& v) const; }; + struct SSARegisterOrFlag + { + RegisterOrFlag regOrFlag; + size_t version; + + SSARegisterOrFlag(); + SSARegisterOrFlag(const RegisterOrFlag& rf, size_t i); + SSARegisterOrFlag(const SSARegister& v); + SSARegisterOrFlag(const SSAFlag& v); + SSARegisterOrFlag(const SSARegisterOrFlag& v); + + SSARegisterOrFlag& operator=(const SSARegisterOrFlag& v); + bool operator==(const SSARegisterOrFlag& v) const; + bool operator!=(const SSARegisterOrFlag& v) const; + bool operator<(const SSARegisterOrFlag& v) const; + }; + enum LowLevelILOperandType { IntegerLowLevelOperand, @@ -108,6 +150,7 @@ namespace BinaryNinja RegisterStackLowLevelOperand, FlagLowLevelOperand, FlagConditionLowLevelOperand, + IntrinsicLowLevelOperand, SemanticFlagClassLowLevelOperand, SemanticFlagGroupLowLevelOperand, SSARegisterLowLevelOperand, @@ -115,9 +158,11 @@ namespace BinaryNinja SSAFlagLowLevelOperand, IndexListLowLevelOperand, ExprListLowLevelOperand, + RegisterOrFlagListLowLevelOperand, SSARegisterListLowLevelOperand, SSARegisterStackListLowLevelOperand, SSAFlagListLowLevelOperand, + SSARegisterOrFlagListLowLevelOperand, RegisterStackAdjustmentsLowLevelOperand }; @@ -152,6 +197,7 @@ namespace BinaryNinja HighSSARegisterLowLevelOperandUsage, LowRegisterLowLevelOperandUsage, LowSSARegisterLowLevelOperandUsage, + IntrinsicLowLevelOperandUsage, ConstantLowLevelOperandUsage, VectorLowLevelOperandUsage, StackAdjustmentLowLevelOperandUsage, @@ -168,6 +214,8 @@ namespace BinaryNinja SourceSSARegistersLowLevelOperandUsage, SourceSSARegisterStacksLowLevelOperandUsage, SourceSSAFlagsLowLevelOperandUsage, + OutputRegisterOrFlagListLowLevelOperandUsage, + OutputSSARegisterOrFlagListLowLevelOperandUsage, SourceMemoryVersionsLowLevelOperandUsage, TargetListLowLevelOperandUsage, RegisterStackAdjustmentsLowLevelOperandUsage @@ -365,6 +413,33 @@ namespace BinaryNinja operator std::vector() const; }; + class LowLevelILRegisterOrFlagList + { + struct ListIterator + { + LowLevelILIntegerList::const_iterator pos; + bool operator==(const ListIterator& a) const { return pos == a.pos; } + bool operator!=(const ListIterator& a) const { return pos != a.pos; } + bool operator<(const ListIterator& a) const { return pos < a.pos; } + ListIterator& operator++() { ++pos; return *this; } + const RegisterOrFlag operator*(); + }; + + LowLevelILIntegerList m_list; + + public: + typedef ListIterator const_iterator; + + LowLevelILRegisterOrFlagList(LowLevelILFunction* func, const BNLowLevelILInstruction& instr, size_t count); + + const_iterator begin() const; + const_iterator end() const; + size_t size() const; + const RegisterOrFlag operator[](size_t i) const; + + operator std::vector() const; + }; + class LowLevelILSSARegisterList { struct ListIterator @@ -446,6 +521,33 @@ namespace BinaryNinja operator std::vector() const; }; + class LowLevelILSSARegisterOrFlagList + { + struct ListIterator + { + LowLevelILIntegerList::const_iterator pos; + bool operator==(const ListIterator& a) const { return pos == a.pos; } + bool operator!=(const ListIterator& a) const { return pos != a.pos; } + bool operator<(const ListIterator& a) const { return pos < a.pos; } + ListIterator& operator++() { ++pos; ++pos; return *this; } + const SSARegisterOrFlag operator*(); + }; + + LowLevelILIntegerList m_list; + + public: + typedef ListIterator const_iterator; + + LowLevelILSSARegisterOrFlagList(LowLevelILFunction* func, const BNLowLevelILInstruction& instr, size_t count); + + const_iterator begin() const; + const_iterator end() const; + size_t size() const; + const SSARegisterOrFlag operator[](size_t i) const; + + operator std::vector() const; + }; + struct LowLevelILInstructionBase: public BNLowLevelILInstruction { #ifdef BINARYNINJACORE_LIBRARY @@ -474,13 +576,16 @@ namespace BinaryNinja SSAFlag GetRawOperandAsSSAFlag(size_t operand) const; LowLevelILIndexList GetRawOperandAsIndexList(size_t operand) const; LowLevelILInstructionList GetRawOperandAsExprList(size_t operand) const; + LowLevelILRegisterOrFlagList GetRawOperandAsRegisterOrFlagList(size_t operand) const; LowLevelILSSARegisterList GetRawOperandAsSSARegisterList(size_t operand) const; LowLevelILSSARegisterStackList GetRawOperandAsSSARegisterStackList(size_t operand) const; LowLevelILSSAFlagList GetRawOperandAsSSAFlagList(size_t operand) const; + LowLevelILSSARegisterOrFlagList GetRawOperandAsSSARegisterOrFlagList(size_t operand) const; std::map GetRawOperandAsRegisterStackAdjustments(size_t operand) const; void UpdateRawOperand(size_t operandIndex, ExprId value); void UpdateRawOperandAsSSARegisterList(size_t operandIndex, const std::vector& regs); + void UpdateRawOperandAsSSARegisterOrFlagList(size_t operandIndex, const std::vector& outputs); RegisterValue GetValue() const; PossibleValueSet GetPossibleValues() const; @@ -604,6 +709,7 @@ namespace BinaryNinja template SSARegister GetHighSSARegister() const { return As().GetHighSSARegister(); } template uint32_t GetLowRegister() const { return As().GetLowRegister(); } template SSARegister GetLowSSARegister() const { return As().GetLowSSARegister(); } + template uint32_t GetIntrinsic() const { return As().GetIntrinsic(); } template int64_t GetConstant() const { return As().GetConstant(); } template int64_t GetVector() const { return As().GetVector(); } template size_t GetStackAdjustment() const { return As().GetStackAdjustment(); } @@ -619,6 +725,8 @@ namespace BinaryNinja template LowLevelILSSARegisterList GetSourceSSARegisters() const { return As().GetSourceSSARegisters(); } template LowLevelILSSARegisterStackList GetSourceSSARegisterStacks() const { return As().GetSourceSSARegisterStacks(); } template LowLevelILSSAFlagList GetSourceSSAFlags() const { return As().GetSourceSSAFlags(); } + template LowLevelILRegisterOrFlagList GetOutputRegisterOrFlagList() const { return As().GetOutputRegisterOrFlagList(); } + template LowLevelILSSARegisterOrFlagList GetOutputSSARegisterOrFlagList() const { return As().GetOutputSSARegisterOrFlagList(); } template LowLevelILIndexList GetSourceMemoryVersions() const { return As().GetSourceMemoryVersions(); } template LowLevelILIndexList GetTargetList() const { return As().GetTargetList(); } template std::map GetRegisterStackAdjustments() const { return As().GetRegisterStackAdjustments(); } @@ -632,6 +740,7 @@ namespace BinaryNinja template void SetDestMemoryVersion(size_t version) { As().SetDestMemoryVersion(version); } template void SetSourceMemoryVersion(size_t version) { As().SetSourceMemoryVersion(version); } template void SetOutputSSARegisters(const std::vector& regs) { As().SetOutputSSARegisters(regs); } + template void SetOutputSSARegisterOrFlagList(const std::vector& outputs) { As().SetOutputSSARegisterOrFlagList(outputs); } bool GetOperandIndexForUsage(LowLevelILOperandUsage usage, size_t& operandIndex) const; @@ -664,6 +773,7 @@ namespace BinaryNinja SSARegister GetHighSSARegister() const; uint32_t GetLowRegister() const; SSARegister GetLowSSARegister() const; + uint32_t GetIntrinsic() const; int64_t GetConstant() const; int64_t GetVector() const; size_t GetStackAdjustment() const; @@ -679,6 +789,8 @@ namespace BinaryNinja LowLevelILSSARegisterList GetSourceSSARegisters() const; LowLevelILSSARegisterStackList GetSourceSSARegisterStacks() const; LowLevelILSSAFlagList GetSourceSSAFlags() const; + LowLevelILRegisterOrFlagList GetOutputRegisterOrFlagList() const; + LowLevelILSSARegisterOrFlagList GetOutputSSARegisterOrFlagList() const; LowLevelILIndexList GetSourceMemoryVersions() const; LowLevelILIndexList GetTargetList() const; std::map GetRegisterStackAdjustments() const; @@ -706,6 +818,7 @@ namespace BinaryNinja uint32_t GetFlag() const; uint32_t GetSemanticFlagClass() const; uint32_t GetSemanticFlagGroup() const; + uint32_t GetIntrinsic() const; BNLowLevelILFlagCondition GetFlagCondition() const; SSARegister GetSSARegister() const; SSARegisterStack GetSSARegisterStack() const; @@ -715,6 +828,8 @@ namespace BinaryNinja LowLevelILSSARegisterList GetSSARegisterList() const; LowLevelILSSARegisterStackList GetSSARegisterStackList() const; LowLevelILSSAFlagList GetSSAFlagList() const; + LowLevelILRegisterOrFlagList GetRegisterOrFlagList() const; + LowLevelILSSARegisterOrFlagList GetSSARegisterOrFlagList() const; std::map GetRegisterStackAdjustments() const; }; @@ -1022,6 +1137,20 @@ namespace BinaryNinja void SetOutputSSARegisters(const std::vector& regs) { GetRawOperandAsExpr(0).UpdateRawOperandAsSSARegisterList(1, regs); } }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + LowLevelILRegisterOrFlagList GetOutputRegisterOrFlagList() const { return GetRawOperandAsRegisterOrFlagList(0); } + uint32_t GetIntrinsic() const { return GetRawOperandAsRegister(2); } + LowLevelILInstructionList GetParameterExprs() const { return GetRawOperandAsExpr(3).GetRawOperandAsExprList(0); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + LowLevelILSSARegisterOrFlagList GetOutputSSARegisterOrFlagList() const { return GetRawOperandAsSSARegisterOrFlagList(0); } + uint32_t GetIntrinsic() const { return GetRawOperandAsRegister(2); } + LowLevelILInstructionList GetParameterExprs() const { return GetRawOperandAsExpr(3).GetRawOperandAsExprList(0); } + void SetOutputSSARegisterOrFlagList(const std::vector& outputs) { UpdateRawOperandAsSSARegisterOrFlagList(0, outputs); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { SSARegister GetDestSSARegister() const { return GetRawOperandAsSSARegister(0); } diff --git a/mediumlevelilinstruction.cpp b/mediumlevelilinstruction.cpp index e911c298..7e1e663f 100644 --- a/mediumlevelilinstruction.cpp +++ b/mediumlevelilinstruction.cpp @@ -54,6 +54,7 @@ unordered_map {OffsetMediumLevelOperandUsage, IntegerMediumLevelOperand}, {ConstantMediumLevelOperandUsage, IntegerMediumLevelOperand}, {VectorMediumLevelOperandUsage, IntegerMediumLevelOperand}, + {IntrinsicMediumLevelOperandUsage, IntrinsicMediumLevelOperand}, {TargetMediumLevelOperandUsage, IndexMediumLevelOperand}, {TrueTargetMediumLevelOperandUsage, IndexMediumLevelOperand}, {FalseTargetMediumLevelOperandUsage, IndexMediumLevelOperand}, @@ -64,6 +65,7 @@ unordered_map {OutputVariablesMediumLevelOperandUsage, VariableListMediumLevelOperand}, {OutputVariablesSubExprMediumLevelOperandUsage, VariableListMediumLevelOperand}, {OutputSSAVariablesMediumLevelOperandUsage, SSAVariableListMediumLevelOperand}, + {OutputSSAVariablesSubExprMediumLevelOperandUsage, SSAVariableListMediumLevelOperand}, {OutputSSAMemoryVersionMediumLevelOperandUsage, IndexMediumLevelOperand}, {ParameterExprsMediumLevelOperandUsage, ExprListMediumLevelOperand}, {SourceExprsMediumLevelOperandUsage, ExprListMediumLevelOperand}, @@ -127,23 +129,27 @@ unordered_map> {MLIL_SYSCALL, {OutputVariablesMediumLevelOperandUsage, ParameterExprsMediumLevelOperandUsage}}, {MLIL_SYSCALL_UNTYPED, {OutputVariablesSubExprMediumLevelOperandUsage, ParameterVariablesMediumLevelOperandUsage, StackExprMediumLevelOperandUsage}}, - {MLIL_CALL_SSA, {OutputSSAVariablesMediumLevelOperandUsage, + {MLIL_CALL_SSA, {OutputSSAVariablesSubExprMediumLevelOperandUsage, OutputSSAMemoryVersionMediumLevelOperandUsage, DestExprMediumLevelOperandUsage, ParameterExprsMediumLevelOperandUsage, SourceMemoryVersionMediumLevelOperandUsage}}, - {MLIL_CALL_UNTYPED_SSA, {OutputSSAVariablesMediumLevelOperandUsage, + {MLIL_CALL_UNTYPED_SSA, {OutputSSAVariablesSubExprMediumLevelOperandUsage, OutputSSAMemoryVersionMediumLevelOperandUsage, DestExprMediumLevelOperandUsage, ParameterSSAVariablesMediumLevelOperandUsage, ParameterSSAMemoryVersionMediumLevelOperandUsage, StackExprMediumLevelOperandUsage}}, - {MLIL_SYSCALL_SSA, {OutputSSAVariablesMediumLevelOperandUsage, + {MLIL_SYSCALL_SSA, {OutputSSAVariablesSubExprMediumLevelOperandUsage, OutputSSAMemoryVersionMediumLevelOperandUsage, ParameterExprsMediumLevelOperandUsage, SourceMemoryVersionMediumLevelOperandUsage}}, - {MLIL_SYSCALL_UNTYPED_SSA, {OutputSSAVariablesMediumLevelOperandUsage, + {MLIL_SYSCALL_UNTYPED_SSA, {OutputSSAVariablesSubExprMediumLevelOperandUsage, OutputSSAMemoryVersionMediumLevelOperandUsage, ParameterSSAVariablesMediumLevelOperandUsage, ParameterSSAMemoryVersionMediumLevelOperandUsage, StackExprMediumLevelOperandUsage}}, {MLIL_RET, {SourceExprsMediumLevelOperandUsage}}, {MLIL_IF, {ConditionExprMediumLevelOperandUsage, TrueTargetMediumLevelOperandUsage, FalseTargetMediumLevelOperandUsage}}, {MLIL_GOTO, {TargetMediumLevelOperandUsage}}, + {MLIL_INTRINSIC, {OutputVariablesMediumLevelOperandUsage, IntrinsicMediumLevelOperandUsage, + ParameterExprsMediumLevelOperandUsage}}, + {MLIL_INTRINSIC_SSA, {OutputSSAVariablesMediumLevelOperandUsage, IntrinsicMediumLevelOperandUsage, + ParameterExprsMediumLevelOperandUsage}}, {MLIL_TRAP, {VectorMediumLevelOperandUsage}}, {MLIL_VAR_PHI, {DestSSAVariableMediumLevelOperandUsage, SourceSSAVariablesMediumLevelOperandUsages}}, {MLIL_MEM_PHI, {DestMemoryVersionMediumLevelOperandUsage, SourceMemoryVersionsMediumLevelOperandUsage}}, @@ -243,7 +249,7 @@ static unordered_map()) + i.VisitExprs(func); + break; + case MLIL_INTRINSIC_SSA: + for (auto& i : GetParameterExprs()) + i.VisitExprs(func); + break; default: break; } @@ -1609,6 +1631,16 @@ ExprId MediumLevelILInstruction::CopyTo(MediumLevelILFunction* dest, return dest->Breakpoint(*this); case MLIL_TRAP: return dest->Trap(GetVector(), *this); + case MLIL_INTRINSIC: + for (auto& i : GetParameterExprs()) + params.push_back(subExprHandler(i)); + return dest->Intrinsic(GetOutputVariables(), + GetIntrinsic(), params, *this); + case MLIL_INTRINSIC_SSA: + for (auto& i : GetParameterExprs()) + params.push_back(subExprHandler(i)); + return dest->IntrinsicSSA(GetOutputSSAVariables(), + GetIntrinsic(), params, *this); case MLIL_UNDEF: return dest->Undefined(*this); case MLIL_UNIMPL: @@ -1796,6 +1828,15 @@ int64_t MediumLevelILInstruction::GetVector() const } +uint32_t MediumLevelILInstruction::GetIntrinsic() const +{ + size_t operandIndex; + if (GetOperandIndexForUsage(IntrinsicMediumLevelOperandUsage, operandIndex)) + return (uint32_t)GetRawOperandAsInteger(operandIndex); + throw MediumLevelILInstructionAccessException(); +} + + size_t MediumLevelILInstruction::GetTarget() const { size_t operandIndex; @@ -1878,6 +1919,8 @@ MediumLevelILSSAVariableList MediumLevelILInstruction::GetOutputSSAVariables() c { size_t operandIndex; if (GetOperandIndexForUsage(OutputSSAVariablesMediumLevelOperandUsage, operandIndex)) + return GetRawOperandAsSSAVariableList(operandIndex); + if (GetOperandIndexForUsage(OutputSSAVariablesSubExprMediumLevelOperandUsage, operandIndex)) return GetRawOperandAsExpr(operandIndex).GetRawOperandAsSSAVariableList(1); throw MediumLevelILInstructionAccessException(); } @@ -2577,6 +2620,22 @@ ExprId MediumLevelILFunction::Trap(int64_t vector, const ILSourceLocation& loc) } +ExprId MediumLevelILFunction::Intrinsic(const vector& outputs, uint32_t intrinsic, + const vector& params, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_INTRINSIC, loc, 0, outputs.size(), AddVariableList(outputs), + intrinsic, params.size(), AddOperandList(params)); +} + + +ExprId MediumLevelILFunction::IntrinsicSSA(const vector& outputs, uint32_t intrinsic, + const vector& params, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_INTRINSIC_SSA, loc, 0, outputs.size() * 2, AddSSAVariableList(outputs), + intrinsic, params.size(), AddOperandList(params)); +} + + ExprId MediumLevelILFunction::Undefined(const ILSourceLocation& loc) { return AddExprWithLocation(MLIL_UNDEF, loc, 0); diff --git a/mediumlevelilinstruction.h b/mediumlevelilinstruction.h index 8e671aaf..de92764d 100644 --- a/mediumlevelilinstruction.h +++ b/mediumlevelilinstruction.h @@ -70,6 +70,7 @@ namespace BinaryNinja { IntegerMediumLevelOperand, IndexMediumLevelOperand, + IntrinsicMediumLevelOperand, ExprMediumLevelOperand, VariableMediumLevelOperand, SSAVariableMediumLevelOperand, @@ -100,6 +101,7 @@ namespace BinaryNinja OffsetMediumLevelOperandUsage, ConstantMediumLevelOperandUsage, VectorMediumLevelOperandUsage, + IntrinsicMediumLevelOperandUsage, TargetMediumLevelOperandUsage, TrueTargetMediumLevelOperandUsage, FalseTargetMediumLevelOperandUsage, @@ -110,6 +112,7 @@ namespace BinaryNinja OutputVariablesMediumLevelOperandUsage, OutputVariablesSubExprMediumLevelOperandUsage, OutputSSAVariablesMediumLevelOperandUsage, + OutputSSAVariablesSubExprMediumLevelOperandUsage, OutputSSAMemoryVersionMediumLevelOperandUsage, ParameterExprsMediumLevelOperandUsage, SourceExprsMediumLevelOperandUsage, @@ -485,6 +488,7 @@ namespace BinaryNinja template uint64_t GetOffset() const { return As().GetOffset(); } template int64_t GetConstant() const { return As().GetConstant(); } template int64_t GetVector() const { return As().GetVector(); } + template uint32_t GetIntrinsic() const { return As().GetIntrinsic(); } template size_t GetTarget() const { return As().GetTarget(); } template size_t GetTrueTarget() const { return As().GetTrueTarget(); } template size_t GetFalseTarget() const { return As().GetFalseTarget(); } @@ -535,6 +539,7 @@ namespace BinaryNinja uint64_t GetOffset() const; int64_t GetConstant() const; int64_t GetVector() const; + uint32_t GetIntrinsic() const; size_t GetTarget() const; size_t GetTrueTarget() const; size_t GetFalseTarget() const; @@ -567,6 +572,7 @@ namespace BinaryNinja uint64_t GetInteger() const; size_t GetIndex() const; + uint32_t GetIntrinsic() const; MediumLevelILInstruction GetExpr() const; Variable GetVariable() const; SSAVariable GetSSAVariable() const; @@ -902,6 +908,20 @@ namespace BinaryNinja size_t GetTarget() const { return GetRawOperandAsIndex(0); } }; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILInstructionBase + { + MediumLevelILVariableList GetOutputVariables() const { return GetRawOperandAsVariableList(0); } + uint32_t GetIntrinsic() const { return (uint32_t)GetRawOperandAsInteger(2); } + MediumLevelILInstructionList GetParameterExprs() const { return GetRawOperandAsExprList(3); } + }; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILInstructionBase + { + MediumLevelILSSAVariableList GetOutputSSAVariables() const { return GetRawOperandAsSSAVariableList(0); } + uint32_t GetIntrinsic() const { return (uint32_t)GetRawOperandAsInteger(2); } + MediumLevelILInstructionList GetParameterExprs() const { return GetRawOperandAsExprList(3); } + void SetOutputSSAVariables(const std::vector& vars) { UpdateRawOperandAsSSAVariableList(0, vars); } + }; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILInstructionBase { int64_t GetVector() const { return GetRawOperandAsInteger(0); } diff --git a/python/architecture.py b/python/architecture.py index 2b422962..3ccd2b11 100644 --- a/python/architecture.py +++ b/python/architecture.py @@ -33,6 +33,7 @@ import callingconvention import platform import log import databuffer +import types class _ArchitectureMetaClass(type): @@ -128,6 +129,7 @@ class Architecture(object): flags_written_by_flag_write_type = {} semantic_class_for_flag_write_type = {} reg_stacks = {} + intrinsics = {} __metaclass__ = _ArchitectureMetaClass next_address = 0 @@ -304,6 +306,27 @@ class Architecture(object): top = core.BNGetArchitectureRegisterName(self.handle, info.stackTopReg) self.reg_stacks[name] = function.RegisterStackInfo(storage, top_rel, top, regs[i]) core.BNFreeRegisterList(regs) + + count = ctypes.c_ulonglong() + intrinsics = core.BNGetAllArchitectureIntrinsics(self.handle, count) + self.__dict__["intrinsics"] = {} + for i in xrange(0, count.value): + name = core.BNGetArchitectureIntrinsicName(self.handle, intrinsics[i]) + input_count = ctypes.c_ulonglong() + inputs = core.BNGetArchitectureIntrinsicInputs(self.handle, intrinsics[i], input_count) + input_list = [] + for j in xrange(0, input_count.value): + input_name = inputs[j].name + type_obj = types.Type(core.BNNewTypeReference(inputs[j].type), confidence = inputs[j].typeConfidence) + input_list.append(function.IntrinsicInput(type_obj, input_name)) + core.BNFreeNameAndTypeList(inputs, input_count.value) + output_count = ctypes.c_ulonglong() + outputs = core.BNGetArchitectureIntrinsicOutputs(self.handle, intrinsics[i], output_count) + output_list = [] + for j in xrange(0, output_count.value): + output_list.append(types.Type(core.BNNewTypeReference(outputs[j].type), confidence = outputs[j].confidence)) + core.BNFreeOutputTypeList(outputs, output_count.value) + self.intrinsics[name] = function.IntrinsicInfo(input_list, output_list) else: startup._init_plugins() @@ -365,6 +388,12 @@ class Architecture(object): self._cb.getRegisterStackName = self._cb.getRegisterStackName.__class__(self._get_register_stack_name) self._cb.getAllRegisterStacks = self._cb.getAllRegisterStacks.__class__(self._get_all_register_stacks) self._cb.getRegisterStackInfo = self._cb.getRegisterStackInfo.__class__(self._get_register_stack_info) + self._cb.getIntrinsicName = self._cb.getIntrinsicName.__class__(self._get_intrinsic_name) + self._cb.getAllIntrinsics = self._cb.getAllIntrinsics.__class__(self._get_all_intrinsics) + self._cb.getIntrinsicInputs = self._cb.getIntrinsicInputs.__class__(self._get_intrinsic_inputs) + self._cb.freeNameAndTypeList = self._cb.freeNameAndTypeList.__class__(self._free_name_and_type_list) + self._cb.getIntrinsicOutputs = self._cb.getIntrinsicOutputs.__class__(self._get_intrinsic_outputs) + self._cb.freeTypeList = self._cb.freeTypeList.__class__(self._free_type_list) self._cb.assemble = self._cb.assemble.__class__(self._assemble) self._cb.isNeverBranchPatchAvailable = self._cb.isNeverBranchPatchAvailable.__class__( self._is_never_branch_patch_available) @@ -514,9 +543,28 @@ class Architecture(object): self.__dict__["global_regs"] = self.__class__.global_regs + self._intrinsics = {} + self._intrinsics_by_index = {} + self.__dict__["intrinsics"] = self.__class__.intrinsics + intrinsic_index = 0 + for intrinsic in self.__class__.intrinsics.keys(): + if intrinsic not in self._intrinsics: + info = self.__class__.intrinsics[intrinsic] + for i in xrange(0, len(info.inputs)): + if isinstance(info.inputs[i], types.Type): + info.inputs[i] = function.IntrinsicInput(info.inputs[i]) + elif isinstance(info.inputs[i], tuple): + info.inputs[i] = function.IntrinsicInput(info.inputs[i][0], info.inputs[i][1]) + info.index = intrinsic_index + self._intrinsics[intrinsic] = intrinsic_index + self._intrinsics_by_index[intrinsic_index] = (intrinsic, info) + intrinsic_index += 1 + self._pending_reg_lists = {} self._pending_token_lists = {} self._pending_condition_lists = {} + self._pending_name_and_type_lists = {} + self._pending_type_lists = {} def __eq__(self, value): if not isinstance(value, Architecture): @@ -1116,6 +1164,95 @@ class Architecture(object): result[0].topRelativeCount = 0 result[0].stackTopReg = 0 + def _get_intrinsic_name(self, ctxt, intrinsic): + try: + if intrinsic in self._intrinsics_by_index: + return core.BNAllocString(self._intrinsics_by_index[intrinsic][0]) + return core.BNAllocString("") + except (KeyError, OSError): + log.log_error(traceback.format_exc()) + return core.BNAllocString("") + + def _get_all_intrinsics(self, ctxt, count): + try: + regs = self._intrinsics_by_index.keys() + count[0] = len(regs) + reg_buf = (ctypes.c_uint * len(regs))() + for i in xrange(0, len(regs)): + reg_buf[i] = regs[i] + result = ctypes.cast(reg_buf, ctypes.c_void_p) + self._pending_reg_lists[result.value] = (result, reg_buf) + return result.value + except KeyError: + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _get_intrinsic_inputs(self, ctxt, intrinsic, count): + try: + if intrinsic in self._intrinsics_by_index: + inputs = self._intrinsics_by_index[intrinsic][1].inputs + count[0] = len(inputs) + input_buf = (core.BNNameAndType * len(inputs))() + for i in xrange(0, len(inputs)): + input_buf[i].name = inputs[i].name + input_buf[i].type = core.BNNewTypeReference(inputs[i].type.handle) + input_buf[i].typeConfidence = inputs[i].type.confidence + result = ctypes.cast(input_buf, ctypes.c_void_p) + self._pending_name_and_type_lists[result.value] = (result, input_buf, len(inputs)) + return result.value + count[0] = 0 + return None + except: + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _free_name_and_type_list(self, ctxt, buf_raw): + try: + buf = ctypes.cast(buf_raw, ctypes.c_void_p) + if buf.value not in self._pending_name_and_type_lists: + raise ValueError("freeing name and type list that wasn't allocated") + name_and_types = self._pending_name_and_type_lists[buf.value][1] + count = self._pending_name_and_type_lists[buf.value][2] + for i in xrange(0, count): + core.BNFreeType(name_and_types[i].type) + del self._pending_name_and_type_lists[buf.value] + except (ValueError, KeyError): + log.log_error(traceback.format_exc()) + + def _get_intrinsic_outputs(self, ctxt, intrinsic, count): + try: + if intrinsic in self._intrinsics_by_index: + outputs = self._intrinsics_by_index[intrinsic][1].outputs + count[0] = len(outputs) + output_buf = (core.BNTypeWithConfidence * len(outputs))() + for i in xrange(0, len(outputs)): + output_buf[i].type = core.BNNewTypeReference(outputs[i].handle) + output_buf[i].confidence = outputs[i].confidence + result = ctypes.cast(output_buf, ctypes.c_void_p) + self._pending_type_lists[result.value] = (result, output_buf, len(outputs)) + return result.value + count[0] = 0 + return None + except: + log.log_error(traceback.format_exc()) + count[0] = 0 + return None + + def _free_type_list(self, ctxt, buf_raw): + try: + buf = ctypes.cast(buf_raw, ctypes.c_void_p) + if buf.value not in self._pending_type_lists: + raise ValueError("freeing type list that wasn't allocated") + types = self._pending_type_lists[buf.value][1] + count = self._pending_type_lists[buf.value][2] + for i in xrange(0, count): + core.BNFreeType(types[i].type) + del self._pending_type_lists[buf.value] + except (ValueError, KeyError): + log.log_error(traceback.format_exc()) + def _assemble(self, ctxt, code, addr, result, errors): try: data, error_str = self.perform_assemble(code, addr) @@ -1701,6 +1838,23 @@ class Architecture(object): return sem_group.index return sem_group + def get_intrinsic_name(self, intrinsic): + """ + ``get_intrinsic_name`` gets an intrinsic name from an intrinsic number. + + :param int intrinsic: intrinsic number + :return: the corresponding intrinsic string + :rtype: str + """ + return core.BNGetArchitectureIntrinsicName(self.handle, intrinsic) + + def get_intrinsic_index(self, intrinsic): + if isinstance(intrinsic, str): + return self._intrinsics[intrinsic] + elif isinstance(intrinsic, lowlevelil.ILIntrinsic): + return intrinsic.index + return intrinsic + def get_flag_write_type_name(self, write_type): """ ``get_flag_write_type_name`` gets the flag write type name for the given flag. diff --git a/python/function.py b/python/function.py index 10583b58..7607657f 100644 --- a/python/function.py +++ b/python/function.py @@ -427,7 +427,7 @@ class Function(object): """Function platform (read-only)""" if self._platform: return self._platform - else: + else: plat = core.BNGetFunctionPlatform(self.handle) if plat is None: return None @@ -1878,6 +1878,27 @@ class RegisterStackInfo(object): return "" % (len(self.storage_regs), self.stack_top_reg) +class IntrinsicInput(object): + def __init__(self, type_obj, name=""): + self.name = name + self.type = type_obj + + def __repr__(self): + if len(self.name) == 0: + return "" % str(self.type) + return "" % (str(self.type), self.name) + + +class IntrinsicInfo(object): + def __init__(self, inputs, outputs, index=None): + self.inputs = inputs + self.outputs = outputs + self.index = index + + def __repr__(self): + return " %s>" % (repr(self.inputs), repr(self.outputs)) + + class InstructionBranch(object): def __init__(self, branch_type, target = 0, arch = None): self.type = branch_type diff --git a/python/lowlevelil.py b/python/lowlevelil.py index a2d77c9f..33296ce8 100644 --- a/python/lowlevelil.py +++ b/python/lowlevelil.py @@ -131,6 +131,25 @@ class ILSemanticFlagGroup(object): return self.index == other.index +class ILIntrinsic(object): + def __init__(self, arch, intrinsic): + self.arch = arch + self.index = intrinsic + self.name = self.arch.get_intrinsic_name(self.index) + if self.name in self.arch.intrinsics: + self.inputs = self.arch.intrinsics[self.name].inputs + self.outputs = self.arch.intrinsics[self.name].outputs + + def __str__(self): + return self.name + + def __repr__(self): + return self.name + + def __eq__(self, other): + return self.index == other.index + + class SSARegister(object): def __init__(self, reg, version): self.reg = reg @@ -158,6 +177,15 @@ class SSAFlag(object): return "" % (repr(self.flag), self.version) +class SSARegisterOrFlag(object): + def __init__(self, reg_or_flag, version): + self.reg_or_flag = reg_or_flag + self.version = version + + def __repr__(self): + return "" % (repr(self.reg_or_flag), self.version) + + class LowLevelILOperationAndSize(object): def __init__(self, operation, size): self.operation = operation @@ -250,6 +278,8 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_BOOL_TO_INT: [("src", "expr")], LowLevelILOperation.LLIL_ADD_OVERFLOW: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_SYSCALL: [], + LowLevelILOperation.LLIL_INTRINSIC: [("output", "reg_or_flag_list"), ("intrinsic", "intrinsic"), ("param", "expr")], + LowLevelILOperation.LLIL_INTRINSIC_SSA: [("output", "reg_or_flag_ssa_list"), ("intrinsic", "intrinsic"), ("param", "expr")], LowLevelILOperation.LLIL_BP: [], LowLevelILOperation.LLIL_TRAP: [("vector", "int")], LowLevelILOperation.LLIL_UNDEF: [], @@ -292,7 +322,7 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_SYSCALL_SSA: [("output", "expr"), ("stack", "expr"), ("param", "expr")], LowLevelILOperation.LLIL_CALL_OUTPUT_SSA: [("dest_memory", "int"), ("dest", "reg_ssa_list")], LowLevelILOperation.LLIL_CALL_STACK_SSA: [("src", "reg_ssa"), ("src_memory", "int")], - LowLevelILOperation.LLIL_CALL_PARAM_SSA: [("src", "expr_list")], + LowLevelILOperation.LLIL_CALL_PARAM: [("src", "expr_list")], LowLevelILOperation.LLIL_LOAD_SSA: [("src", "expr"), ("src_memory", "int")], LowLevelILOperation.LLIL_STORE_SSA: [("dest", "expr"), ("dest_memory", "int"), ("src_memory", "int"), ("src", "expr")], LowLevelILOperation.LLIL_REG_PHI: [("dest", "reg_ssa"), ("src", "reg_ssa_list")], @@ -336,6 +366,8 @@ class LowLevelILInstruction(object): value = ILRegister(func.arch, instr.operands[i]) elif operand_type == "reg_stack": value = ILRegisterStack(func.arch, instr.operands[i]) + elif operand_type == "intrinsic": + value = ILIntrinsic(func.arch, instr.operands[i]) elif operand_type == "reg_ssa": reg = ILRegister(func.arch, instr.operands[i]) i += 1 @@ -369,25 +401,36 @@ class LowLevelILInstruction(object): operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) i += 1 value = [] - for i in xrange(count.value): - value.append(operand_list[i]) + for j in xrange(count.value): + value.append(operand_list[j]) core.BNLowLevelILFreeOperandList(operand_list) elif operand_type == "expr_list": count = ctypes.c_ulonglong() operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) i += 1 value = [] - for i in xrange(count.value): - value.append(LowLevelILInstruction(func, operand_list[i])) + for j in xrange(count.value): + value.append(LowLevelILInstruction(func, operand_list[j])) + core.BNLowLevelILFreeOperandList(operand_list) + elif operand_type == "reg_or_flag_list": + count = ctypes.c_ulonglong() + operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) + i += 1 + value = [] + for j in xrange(count.value): + if (operand_list[j] & (1 << 32)) != 0: + value.append(ILFlag(func.arch, operand_list[j] & 0xffffffff)) + else: + value.append(ILRegister(func.arch, operand_list[j] & 0xffffffff)) core.BNLowLevelILFreeOperandList(operand_list) elif operand_type == "reg_ssa_list": count = ctypes.c_ulonglong() operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) i += 1 value = [] - for i in xrange(count.value / 2): - reg = operand_list[i * 2] - reg_version = operand_list[(i * 2) + 1] + for j in xrange(count.value / 2): + reg = operand_list[j * 2] + reg_version = operand_list[(j * 2) + 1] value.append(SSARegister(ILRegister(func.arch, reg), reg_version)) core.BNLowLevelILFreeOperandList(operand_list) elif operand_type == "reg_stack_ssa_list": @@ -395,9 +438,9 @@ class LowLevelILInstruction(object): operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) i += 1 value = [] - for i in xrange(count.value / 2): - reg_stack = operand_list[i * 2] - reg_version = operand_list[(i * 2) + 1] + for j in xrange(count.value / 2): + reg_stack = operand_list[j * 2] + reg_version = operand_list[(j * 2) + 1] value.append(SSARegisterStack(ILRegisterStack(func.arch, reg_stack), reg_version)) core.BNLowLevelILFreeOperandList(operand_list) elif operand_type == "flag_ssa_list": @@ -405,19 +448,32 @@ class LowLevelILInstruction(object): operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) i += 1 value = [] - for i in xrange(count.value / 2): - flag = operand_list[i * 2] - flag_version = operand_list[(i * 2) + 1] + for j in xrange(count.value / 2): + flag = operand_list[j * 2] + flag_version = operand_list[(j * 2) + 1] value.append(SSAFlag(ILFlag(func.arch, flag), flag_version)) core.BNLowLevelILFreeOperandList(operand_list) + elif operand_type == "reg_or_flag_ssa_list": + count = ctypes.c_ulonglong() + operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) + i += 1 + value = [] + for j in xrange(count.value / 2): + if (operand_list[j * 2] & (1 << 32)) != 0: + reg_or_flag = ILFlag(func.arch, operand_list[j * 2] & 0xffffffff) + else: + reg_or_flag = ILRegister(func.arch, operand_list[j * 2] & 0xffffffff) + reg_version = operand_list[(j * 2) + 1] + value.append(SSARegisterOrFlag(reg_or_flag, reg_version)) + core.BNLowLevelILFreeOperandList(operand_list) elif operand_type == "reg_stack_adjust": count = ctypes.c_ulonglong() operand_list = core.BNLowLevelILGetOperandList(func.handle, self.expr_index, i, count) i += 1 value = {} - for i in xrange(count.value / 2): - reg_stack = operand_list[i * 2] - adjust = operand_list[(i * 2) + 1] + for j in xrange(count.value / 2): + reg_stack = operand_list[j * 2] + adjust = operand_list[(j * 2) + 1] if adjust & 0x80000000: adjust |= ~0x80000000 value[func.arch.get_reg_stack_name(reg_stack)] = adjust @@ -1714,6 +1770,25 @@ class LowLevelILFunction(object): """ return self.expr(LowLevelILOperation.LLIL_SYSCALL) + def intrinsic(self, outputs, intrinsic, params): + """ + ``intrinsic`` return an intrinsic expression. + + :return: an intrinsic expression. + :rtype: LowLevelILExpr + """ + output_list = [] + for output in outputs: + if isinstance(output, ILFlag): + output_list.append((1 << 32) | output.index) + else: + output_list.append(output.index) + param_list = [] + for param in params: + param_list.append(param.index) + return self.expr(LowLevelILOperation.LLIL_INTRINSIC, len(outputs), self.add_operand_list(output_list), + self.arch.get_intrinsic_index(intrinsic), len(params), self.add_operand_list(param_list)) + def breakpoint(self): """ ``breakpoint`` returns a processor breakpoint expression. diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py index 8594ea36..3c4ba3fd 100644 --- a/python/mediumlevelil.py +++ b/python/mediumlevelil.py @@ -150,6 +150,8 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_SYSCALL_UNTYPED: [("output", "expr"), ("params", "expr"), ("stack", "expr")], MediumLevelILOperation.MLIL_BP: [], MediumLevelILOperation.MLIL_TRAP: [("vector", "int")], + MediumLevelILOperation.MLIL_INTRINSIC: [("output", "var_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")], + MediumLevelILOperation.MLIL_INTRINSIC_SSA: [("output", "var_ssa_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")], MediumLevelILOperation.MLIL_UNDEF: [], MediumLevelILOperation.MLIL_UNIMPL: [], MediumLevelILOperation.MLIL_UNIMPL_MEM: [("src", "expr")], @@ -223,6 +225,8 @@ class MediumLevelILInstruction(object): value = instr.operands[i] elif operand_type == "expr": value = MediumLevelILInstruction(func, instr.operands[i]) + elif operand_type == "intrinsic": + value = lowlevelil.ILIntrinsic(func.arch, instr.operands[i]) elif operand_type == "var": value = function.Variable.from_identifier(self.function.source_function, instr.operands[i]) elif operand_type == "var_ssa": -- cgit v1.3.1 From 331bfd4e4a648de8aba4fefd8301703a6a3440c9 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Fri, 2 Feb 2018 18:02:57 -0500 Subject: Add rounding instructions --- binaryninjaapi.h | 8 +++++++ binaryninjacore.h | 8 +++++++ lowlevelilinstruction.cpp | 36 ++++++++++++++++++++++++++++++ lowlevelilinstruction.h | 4 ++++ mediumlevelilinstruction.cpp | 36 ++++++++++++++++++++++++++++++ mediumlevelilinstruction.h | 4 ++++ python/lowlevelil.py | 52 ++++++++++++++++++++++++++++++++++++++++++++ python/mediumlevelil.py | 4 ++++ 8 files changed, 152 insertions(+) (limited to 'python/mediumlevelil.py') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 3decc4e9..650299ed 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -2702,6 +2702,10 @@ namespace BinaryNinja ExprId FloatToInt(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); ExprId IntToFloat(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatConvert(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RoundToInt(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); + ExprId Floor(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); + ExprId Ceil(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatTrunc(size_t size, ExprId a, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareNotEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareLessThan(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); @@ -3012,6 +3016,10 @@ namespace BinaryNinja ExprId FloatToInt(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); ExprId IntToFloat(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatConvert(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RoundToInt(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); + ExprId Floor(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); + ExprId Ceil(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FloatTrunc(size_t size, ExprId a, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareNotEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatCompareLessThan(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc = ILSourceLocation()); diff --git a/binaryninjacore.h b/binaryninjacore.h index a946df31..945badce 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -368,6 +368,10 @@ extern "C" LLIL_FLOAT_TO_INT, LLIL_INT_TO_FLOAT, LLIL_FLOAT_CONV, + LLIL_ROUND_TO_INT, + LLIL_FLOOR, + LLIL_CEIL, + LLIL_FTRUNC, LLIL_FCMP_E, LLIL_FCMP_NE, LLIL_FCMP_LT, @@ -878,6 +882,10 @@ extern "C" MLIL_FLOAT_TO_INT, MLIL_INT_TO_FLOAT, MLIL_FLOAT_CONV, + MLIL_ROUND_TO_INT, + MLIL_FLOOR, + MLIL_CEIL, + MLIL_FTRUNC, MLIL_FCMP_E, MLIL_FCMP_NE, MLIL_FCMP_LT, diff --git a/lowlevelilinstruction.cpp b/lowlevelilinstruction.cpp index 1a834435..c38d742f 100644 --- a/lowlevelilinstruction.cpp +++ b/lowlevelilinstruction.cpp @@ -220,6 +220,10 @@ unordered_map> {LLIL_FLOAT_TO_INT, {SourceExprLowLevelOperandUsage}}, {LLIL_INT_TO_FLOAT, {SourceExprLowLevelOperandUsage}}, {LLIL_FLOAT_CONV, {SourceExprLowLevelOperandUsage}}, + {LLIL_ROUND_TO_INT, {SourceExprLowLevelOperandUsage}}, + {LLIL_FLOOR, {SourceExprLowLevelOperandUsage}}, + {LLIL_CEIL, {SourceExprLowLevelOperandUsage}}, + {LLIL_FTRUNC, {SourceExprLowLevelOperandUsage}}, {LLIL_FCMP_E, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, {LLIL_FCMP_NE, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, {LLIL_FCMP_LT, {LeftExprLowLevelOperandUsage, RightExprLowLevelOperandUsage}}, @@ -1816,6 +1820,10 @@ void LowLevelILInstruction::VisitExprs(const std::functionAddExprWithLocation(operation, *this, size, flags, subExprHandler(AsOneOperand().GetSourceExpr())); case LLIL_ADD: @@ -3349,6 +3361,30 @@ ExprId LowLevelILFunction::FloatConvert(size_t size, ExprId a, uint32_t flags, c } +ExprId LowLevelILFunction::RoundToInt(size_t size, ExprId a, uint32_t flags, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_ROUND_TO_INT, loc, size, flags, a); +} + + +ExprId LowLevelILFunction::Floor(size_t size, ExprId a, uint32_t flags, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_FLOOR, loc, size, flags, a); +} + + +ExprId LowLevelILFunction::Ceil(size_t size, ExprId a, uint32_t flags, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_CEIL, loc, size, flags, a); +} + + +ExprId LowLevelILFunction::FloatTrunc(size_t size, ExprId a, uint32_t flags, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_FTRUNC, loc, size, flags, a); +} + + ExprId LowLevelILFunction::FloatCompareEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_FCMP_E, loc, size, 0, a, b); diff --git a/lowlevelilinstruction.h b/lowlevelilinstruction.h index 4679f556..3cd1c8f4 100644 --- a/lowlevelilinstruction.h +++ b/lowlevelilinstruction.h @@ -1249,4 +1249,8 @@ namespace BinaryNinja template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; + template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; + template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; + template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; + template <> struct LowLevelILInstructionAccessor: public LowLevelILOneOperandInstruction {}; } diff --git a/mediumlevelilinstruction.cpp b/mediumlevelilinstruction.cpp index 7e1e663f..c4800837 100644 --- a/mediumlevelilinstruction.cpp +++ b/mediumlevelilinstruction.cpp @@ -215,6 +215,10 @@ unordered_map> {MLIL_FLOAT_TO_INT, {SourceExprMediumLevelOperandUsage}}, {MLIL_INT_TO_FLOAT, {SourceExprMediumLevelOperandUsage}}, {MLIL_FLOAT_CONV, {SourceExprMediumLevelOperandUsage}}, + {MLIL_ROUND_TO_INT, {SourceExprMediumLevelOperandUsage}}, + {MLIL_FLOOR, {SourceExprMediumLevelOperandUsage}}, + {MLIL_CEIL, {SourceExprMediumLevelOperandUsage}}, + {MLIL_FTRUNC, {SourceExprMediumLevelOperandUsage}}, {MLIL_FCMP_E, {LeftExprMediumLevelOperandUsage, RightExprMediumLevelOperandUsage}}, {MLIL_FCMP_NE, {LeftExprMediumLevelOperandUsage, RightExprMediumLevelOperandUsage}}, {MLIL_FCMP_LT, {LeftExprMediumLevelOperandUsage, RightExprMediumLevelOperandUsage}}, @@ -1300,6 +1304,10 @@ void MediumLevelILInstruction::VisitExprs(const std::functionAddExprWithLocation(operation, *this, size, subExprHandler(AsOneOperand().GetSourceExpr())); case MLIL_ADD: @@ -2731,6 +2743,30 @@ ExprId MediumLevelILFunction::FloatConvert(size_t size, ExprId a, const ILSource } +ExprId MediumLevelILFunction::RoundToInt(size_t size, ExprId a, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_ROUND_TO_INT, loc, size, a); +} + + +ExprId MediumLevelILFunction::Floor(size_t size, ExprId a, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_FLOOR, loc, size, a); +} + + +ExprId MediumLevelILFunction::Ceil(size_t size, ExprId a, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_CEIL, loc, size, a); +} + + +ExprId MediumLevelILFunction::FloatTrunc(size_t size, ExprId a, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_FTRUNC, loc, size, a); +} + + ExprId MediumLevelILFunction::FloatCompareEqual(size_t size, ExprId a, ExprId b, const ILSourceLocation& loc) { return AddExprWithLocation(MLIL_FCMP_E, loc, size, a, b); diff --git a/mediumlevelilinstruction.h b/mediumlevelilinstruction.h index de92764d..cdda87f5 100644 --- a/mediumlevelilinstruction.h +++ b/mediumlevelilinstruction.h @@ -1012,4 +1012,8 @@ namespace BinaryNinja template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILOneOperandInstruction {}; } diff --git a/python/lowlevelil.py b/python/lowlevelil.py index 273d3aeb..8a132478 100644 --- a/python/lowlevelil.py +++ b/python/lowlevelil.py @@ -295,6 +295,10 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_FLOAT_TO_INT: [("src", "expr")], LowLevelILOperation.LLIL_INT_TO_FLOAT: [("src", "expr")], LowLevelILOperation.LLIL_FLOAT_CONV: [("src", "expr")], + LowLevelILOperation.LLIL_ROUND_TO_INT: [("src", "expr")], + LowLevelILOperation.LLIL_FLOOR: [("src", "expr")], + LowLevelILOperation.LLIL_CEIL: [("src", "expr")], + LowLevelILOperation.LLIL_FTRUNC: [("src", "expr")], LowLevelILOperation.LLIL_FCMP_E: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_NE: [("left", "expr"), ("right", "expr")], LowLevelILOperation.LLIL_FCMP_LT: [("left", "expr"), ("right", "expr")], @@ -1967,6 +1971,54 @@ class LowLevelILFunction(object): """ return self.expr(LowLevelILOperation.LLIL_FLOAT_CONV, value.index, size=size, flags=flags) + def round_to_int(self, size, value, flags=None): + """ + ``round_to_int`` rounds a floating point value to the nearest integer + + :param int size: the size of the result in bytes + :param LowLevelILExpr value: the expression to negate + :param str flags: optional, flags to set + :return: The expression ``roundint.{}(value)`` + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_ROUND_TO_INT, value.index, size=size, flags=flags) + + def floor(self, size, value, flags=None): + """ + ``floor`` rounds a floating point value to an integer towards negative infinity + + :param int size: the size of the result in bytes + :param LowLevelILExpr value: the expression to negate + :param str flags: optional, flags to set + :return: The expression ``roundint.{}(value)`` + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_FLOOR, value.index, size=size, flags=flags) + + def ceil(self, size, value, flags=None): + """ + ``ceil`` rounds a floating point value to an integer towards positive infinity + + :param int size: the size of the result in bytes + :param LowLevelILExpr value: the expression to negate + :param str flags: optional, flags to set + :return: The expression ``roundint.{}(value)`` + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_CEIL, value.index, size=size, flags=flags) + + def float_trunc(self, size, value, flags=None): + """ + ``float_trunc`` rounds a floating point value to an integer towards zero + + :param int size: the size of the result in bytes + :param LowLevelILExpr value: the expression to negate + :param str flags: optional, flags to set + :return: The expression ``roundint.{}(value)`` + :rtype: LowLevelILExpr + """ + return self.expr(LowLevelILOperation.LLIL_FTRUNC, value.index, size=size, flags=flags) + def float_compare_equal(self, size, a, b): """ ``float_compare_equal`` returns floating point comparison expression of size ``size`` checking if diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py index 3c4ba3fd..a842c3c4 100644 --- a/python/mediumlevelil.py +++ b/python/mediumlevelil.py @@ -165,6 +165,10 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_FLOAT_TO_INT: [("src", "expr")], MediumLevelILOperation.MLIL_INT_TO_FLOAT: [("src", "expr")], MediumLevelILOperation.MLIL_FLOAT_CONV: [("src", "expr")], + MediumLevelILOperation.MLIL_ROUND_TO_INT: [("src", "expr")], + MediumLevelILOperation.MLIL_FLOOR: [("src", "expr")], + MediumLevelILOperation.MLIL_CEIL: [("src", "expr")], + MediumLevelILOperation.MLIL_FTRUNC: [("src", "expr")], MediumLevelILOperation.MLIL_FCMP_E: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FCMP_NE: [("left", "expr"), ("right", "expr")], MediumLevelILOperation.MLIL_FCMP_LT: [("left", "expr"), ("right", "expr")], -- cgit v1.3.1 From 79b5bdcf42f6abf1c8b2c4bda4c30b41319c4aa5 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Fri, 9 Feb 2018 17:17:53 -0500 Subject: Add instructions for tracking freed register stack slots --- binaryninjaapi.h | 10 ++++++++ binaryninjacore.h | 6 +++++ lowlevelilinstruction.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++ lowlevelilinstruction.h | 27 ++++++++++++++++++++ mediumlevelilinstruction.cpp | 21 ++++++++++++++++ mediumlevelilinstruction.h | 12 +++++++++ python/lowlevelil.py | 4 +++ python/mediumlevelil.py | 2 ++ 8 files changed, 141 insertions(+) (limited to 'python/mediumlevelil.py') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index d7535184..187740b9 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -2572,10 +2572,17 @@ namespace BinaryNinja const ILSourceLocation& loc = ILSourceLocation()); ExprId RegisterStackPop(size_t size, uint32_t regStack, uint32_t flags = 0, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RegisterStackFreeReg(uint32_t reg, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RegisterStackFreeTopRelative(uint32_t regStack, ExprId entry, + const ILSourceLocation& loc = ILSourceLocation()); ExprId RegisterStackTopRelativeSSA(size_t size, const SSARegisterStack& regStack, ExprId entry, const SSARegister& top, const ILSourceLocation& loc = ILSourceLocation()); ExprId RegisterStackAbsoluteSSA(size_t size, const SSARegisterStack& regStack, uint32_t reg, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RegisterStackFreeTopRelativeSSA(uint32_t regStack, size_t destVersion, size_t srcVersion, + ExprId entry, const SSARegister& top, const ILSourceLocation& loc = ILSourceLocation()); + ExprId RegisterStackFreeAbsoluteSSA(uint32_t regStack, size_t destVersion, size_t srcVersion, + uint32_t reg, const ILSourceLocation& loc = ILSourceLocation()); ExprId Const(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); ExprId ConstPointer(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); ExprId FloatConstRaw(size_t size, uint64_t val, const ILSourceLocation& loc = ILSourceLocation()); @@ -3013,6 +3020,9 @@ namespace BinaryNinja const std::vector& params, const ILSourceLocation& loc = ILSourceLocation()); ExprId IntrinsicSSA(const std::vector& outputs, uint32_t intrinsic, const std::vector& params, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FreeVarSlot(const Variable& var, const ILSourceLocation& loc = ILSourceLocation()); + ExprId FreeVarSlotSSA(const Variable& var, size_t newVersion, size_t prevVersion, + const ILSourceLocation& loc = ILSourceLocation()); ExprId Undefined(const ILSourceLocation& loc = ILSourceLocation()); ExprId Unimplemented(const ILSourceLocation& loc = ILSourceLocation()); ExprId UnimplementedMemoryRef(size_t size, ExprId target, diff --git a/binaryninjacore.h b/binaryninjacore.h index a9c38ed6..528df6bd 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -291,6 +291,8 @@ extern "C" LLIL_REG_SPLIT, // Not valid in SSA form (see LLIL_REG_SPLIT_SSA) LLIL_REG_STACK_REL, // Not valid in SSA form (see LLIL_REG_STACK_REL_SSA) LLIL_REG_STACK_POP, // Not valid in SSA form (expanded) + LLIL_REG_STACK_FREE_REG, // Not valid in SSA form (see LLIL_REG_STACK_FREE_REL_SSA, LLIL_REG_STACK_FREE_ABS_SSA) + LLIL_REG_STACK_FREE_REL, // Not valid in SSA from (see LLIL_REG_STACK_FREE_REL_SSA) LLIL_CONST, LLIL_CONST_PTR, LLIL_FLOAT_CONST, @@ -394,6 +396,8 @@ extern "C" LLIL_REG_SPLIT_SSA, LLIL_REG_STACK_REL_SSA, LLIL_REG_STACK_ABS_SSA, + LLIL_REG_STACK_FREE_REL_SSA, + LLIL_REG_STACK_FREE_ABS_SSA, LLIL_SET_FLAG_SSA, LLIL_FLAG_SSA, LLIL_FLAG_BIT_SSA, @@ -865,6 +869,7 @@ extern "C" MLIL_SYSCALL, // Not valid in SSA form (see MLIL_SYSCALL_SSA) MLIL_SYSCALL_UNTYPED, // Not valid in SSA form (see MLIL_SYSCALL_UNTYPED_SSA) MLIL_INTRINSIC, // Not valid in SSA form (see MLIL_INTRINSIC_SSA) + MLIL_FREE_VAR_SLOT, // Not valid in SSA from (see MLIL_FREE_VAR_SLOT_SSA) MLIL_BP, MLIL_TRAP, MLIL_UNDEF, @@ -917,6 +922,7 @@ extern "C" MLIL_STORE_SSA, MLIL_STORE_STRUCT_SSA, MLIL_INTRINSIC_SSA, + MLIL_FREE_VAR_SLOT_SSA, MLIL_VAR_PHI, MLIL_MEM_PHI }; diff --git a/lowlevelilinstruction.cpp b/lowlevelilinstruction.cpp index c38d742f..32425784 100644 --- a/lowlevelilinstruction.cpp +++ b/lowlevelilinstruction.cpp @@ -129,9 +129,16 @@ unordered_map> {LLIL_REG_SPLIT_SSA, {HighSSARegisterLowLevelOperandUsage, LowSSARegisterLowLevelOperandUsage}}, {LLIL_REG_STACK_REL, {SourceRegisterStackLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, {LLIL_REG_STACK_POP, {SourceRegisterStackLowLevelOperandUsage}}, + {LLIL_REG_STACK_FREE_REG, {DestRegisterLowLevelOperandUsage}}, + {LLIL_REG_STACK_FREE_REL, {DestRegisterStackLowLevelOperandUsage, DestExprLowLevelOperandUsage}}, {LLIL_REG_STACK_REL_SSA, {SourceSSARegisterStackLowLevelOperandUsage, TopSSARegisterLowLevelOperandUsage, SourceExprLowLevelOperandUsage}}, {LLIL_REG_STACK_ABS_SSA, {SourceSSARegisterStackLowLevelOperandUsage, SourceRegisterLowLevelOperandUsage}}, + {LLIL_REG_STACK_FREE_REL_SSA, {DestSSARegisterStackLowLevelOperandUsage, + PartialSSARegisterStackSourceLowLevelOperandUsage, DestExprLowLevelOperandUsage, + TopSSARegisterLowLevelOperandUsage}}, + {LLIL_REG_STACK_FREE_ABS_SSA, {DestSSARegisterStackLowLevelOperandUsage, + PartialSSARegisterStackSourceLowLevelOperandUsage, DestRegisterLowLevelOperandUsage}}, {LLIL_FLAG, {SourceFlagLowLevelOperandUsage}}, {LLIL_FLAG_BIT, {SourceFlagLowLevelOperandUsage, BitIndexLowLevelOperandUsage}}, {LLIL_FLAG_SSA, {SourceSSAFlagLowLevelOperandUsage}}, @@ -1762,9 +1769,15 @@ void LowLevelILInstruction::VisitExprs(const std::function().VisitExprs(func); break; + case LLIL_REG_STACK_FREE_REL: + GetDestExpr().VisitExprs(func); + break; case LLIL_REG_STACK_REL_SSA: GetSourceExpr().VisitExprs(func); break; + case LLIL_REG_STACK_FREE_REL_SSA: + GetDestExpr().VisitExprs(func); + break; case LLIL_LOAD: GetSourceExpr().VisitExprs(func); break; @@ -1985,6 +1998,11 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, subExprHandler(GetSourceExpr()), *this); case LLIL_REG_STACK_POP: return dest->RegisterStackPop(size, GetSourceRegisterStack(), flags, *this); + case LLIL_REG_STACK_FREE_REG: + return dest->RegisterStackFreeReg(GetDestRegister(), *this); + case LLIL_REG_STACK_FREE_REL: + return dest->RegisterStackFreeTopRelative(GetDestRegisterStack(), + subExprHandler(GetDestExpr()), *this); case LLIL_REG_STACK_REL_SSA: return dest->RegisterStackTopRelativeSSA(size, GetSourceSSARegisterStack(), subExprHandler(GetSourceExpr()), @@ -1992,6 +2010,17 @@ ExprId LowLevelILInstruction::CopyTo(LowLevelILFunction* dest, case LLIL_REG_STACK_ABS_SSA: return dest->RegisterStackAbsoluteSSA(size, GetSourceSSARegisterStack(), GetSourceRegister(), *this); + case LLIL_REG_STACK_FREE_REL_SSA: + return dest->RegisterStackFreeTopRelativeSSA(GetDestSSARegisterStack().regStack, + GetDestSSARegisterStack().version, + GetSourceSSARegisterStack().version, + subExprHandler(GetDestExpr()), + GetTopSSARegister(), *this); + case LLIL_REG_STACK_FREE_ABS_SSA: + return dest->RegisterStackFreeAbsoluteSSA(GetDestSSARegisterStack().regStack, + GetDestSSARegisterStack().version, + GetSourceSSARegisterStack().version, + GetDestRegister(), *this); case LLIL_FLAG: return dest->Flag(GetSourceFlag(), *this); case LLIL_FLAG_SSA: @@ -2787,6 +2816,18 @@ ExprId LowLevelILFunction::RegisterStackPop(size_t size, uint32_t regStack, uint } +ExprId LowLevelILFunction::RegisterStackFreeReg(uint32_t reg, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_FREE_REG, loc, 0, 0, reg); +} + + +ExprId LowLevelILFunction::RegisterStackFreeTopRelative(uint32_t regStack, ExprId entry, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_FREE_REG, loc, 0, 0, regStack, entry); +} + + ExprId LowLevelILFunction::RegisterStackTopRelativeSSA(size_t size, const SSARegisterStack& regStack, ExprId entry, const SSARegister& top, const ILSourceLocation& loc) { @@ -2802,6 +2843,24 @@ ExprId LowLevelILFunction::RegisterStackAbsoluteSSA(size_t size, const SSARegist } +ExprId LowLevelILFunction::RegisterStackFreeTopRelativeSSA(uint32_t regStack, + size_t destVersion, size_t srcVersion, ExprId entry, const SSARegister& top, + const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_FREE_REL_SSA, loc, 0, 0, + AddExprWithLocation(LLIL_REG_STACK_DEST_SSA, loc, 0, 0, regStack, destVersion, srcVersion), + entry, AddExprWithLocation(LLIL_REG_SSA, loc, 0, 0, top.reg, top.version)); +} + + +ExprId LowLevelILFunction::RegisterStackFreeAbsoluteSSA(uint32_t regStack, + size_t destVersion, size_t srcVersion, uint32_t reg, const ILSourceLocation& loc) +{ + return AddExprWithLocation(LLIL_REG_STACK_FREE_ABS_SSA, loc, 0, 0, + AddExprWithLocation(LLIL_REG_STACK_DEST_SSA, loc, 0, 0, regStack, destVersion, srcVersion), reg); +} + + ExprId LowLevelILFunction::Const(size_t size, uint64_t val, const ILSourceLocation& loc) { return AddExprWithLocation(LLIL_CONST, loc, size, 0, val); diff --git a/lowlevelilinstruction.h b/lowlevelilinstruction.h index 3cd1c8f4..675baa3c 100644 --- a/lowlevelilinstruction.h +++ b/lowlevelilinstruction.h @@ -1013,6 +1013,15 @@ namespace BinaryNinja { uint32_t GetSourceRegisterStack() const { return GetRawOperandAsRegister(0); } }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetDestRegister() const { return GetRawOperandAsRegister(0); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + uint32_t GetDestRegisterStack() const { return GetRawOperandAsRegister(0); } + LowLevelILInstruction GetDestExpr() const { return GetRawOperandAsExpr(1); } + }; template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsSSARegisterStack(0); } @@ -1027,6 +1036,24 @@ namespace BinaryNinja uint32_t GetSourceRegister() const { return GetRawOperandAsRegister(2); } void SetSourceSSAVersion(size_t version) { UpdateRawOperand(1, version); } }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetDestSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsSSARegisterStack(0); } + SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsPartialSSARegisterStackSource(0); } + LowLevelILInstruction GetDestExpr() const { return GetRawOperandAsExpr(1); } + SSARegister GetTopSSARegister() const { return GetRawOperandAsExpr(2).GetRawOperandAsSSARegister(0); } + void SetDestSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(1, version); } + void SetSourceSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(2, version); } + void SetTopSSAVersion(size_t version) { GetRawOperandAsExpr(2).UpdateRawOperand(1, version); } + }; + template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase + { + SSARegisterStack GetDestSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsSSARegisterStack(0); } + SSARegisterStack GetSourceSSARegisterStack() const { return GetRawOperandAsExpr(0).GetRawOperandAsPartialSSARegisterStackSource(0); } + uint32_t GetDestRegister() const { return GetRawOperandAsRegister(1); } + void SetDestSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(1, version); } + void SetSourceSSAVersion(size_t version) { GetRawOperandAsExpr(0).UpdateRawOperand(2, version); } + }; template <> struct LowLevelILInstructionAccessor: public LowLevelILInstructionBase { uint32_t GetSourceFlag() const { return GetRawOperandAsRegister(0); } diff --git a/mediumlevelilinstruction.cpp b/mediumlevelilinstruction.cpp index c4800837..39ab4f28 100644 --- a/mediumlevelilinstruction.cpp +++ b/mediumlevelilinstruction.cpp @@ -150,6 +150,8 @@ unordered_map> ParameterExprsMediumLevelOperandUsage}}, {MLIL_INTRINSIC_SSA, {OutputSSAVariablesMediumLevelOperandUsage, IntrinsicMediumLevelOperandUsage, ParameterExprsMediumLevelOperandUsage}}, + {MLIL_FREE_VAR_SLOT, {DestVariableMediumLevelOperandUsage}}, + {MLIL_FREE_VAR_SLOT_SSA, {DestSSAVariableMediumLevelOperandUsage, PartialSSAVariableSourceMediumLevelOperandUsage}}, {MLIL_TRAP, {VectorMediumLevelOperandUsage}}, {MLIL_VAR_PHI, {DestSSAVariableMediumLevelOperandUsage, SourceSSAVariablesMediumLevelOperandUsages}}, {MLIL_MEM_PHI, {DestMemoryVersionMediumLevelOperandUsage, SourceMemoryVersionsMediumLevelOperandUsage}}, @@ -1653,6 +1655,12 @@ ExprId MediumLevelILInstruction::CopyTo(MediumLevelILFunction* dest, params.push_back(subExprHandler(i)); return dest->IntrinsicSSA(GetOutputSSAVariables(), GetIntrinsic(), params, *this); + case MLIL_FREE_VAR_SLOT: + return dest->FreeVarSlot(GetDestVariable(), *this); + case MLIL_FREE_VAR_SLOT_SSA: + return dest->FreeVarSlotSSA(GetDestSSAVariable().var, + GetDestSSAVariable().version, + GetSourceSSAVariable().version, *this); case MLIL_UNDEF: return dest->Undefined(*this); case MLIL_UNIMPL: @@ -2648,6 +2656,19 @@ ExprId MediumLevelILFunction::IntrinsicSSA(const vector& outputs, u } +ExprId MediumLevelILFunction::FreeVarSlot(const Variable& var, const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_FREE_VAR_SLOT, loc, 0, var.ToIdentifier()); +} + + +ExprId MediumLevelILFunction::FreeVarSlotSSA(const Variable& var, size_t newVersion, size_t prevVersion, + const ILSourceLocation& loc) +{ + return AddExprWithLocation(MLIL_FREE_VAR_SLOT_SSA, loc, 0, var.ToIdentifier(), newVersion, prevVersion); +} + + ExprId MediumLevelILFunction::Undefined(const ILSourceLocation& loc) { return AddExprWithLocation(MLIL_UNDEF, loc, 0); diff --git a/mediumlevelilinstruction.h b/mediumlevelilinstruction.h index cdda87f5..a0c4fd9b 100644 --- a/mediumlevelilinstruction.h +++ b/mediumlevelilinstruction.h @@ -922,6 +922,18 @@ namespace BinaryNinja void SetOutputSSAVariables(const std::vector& vars) { UpdateRawOperandAsSSAVariableList(0, vars); } }; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILInstructionBase + { + Variable GetDestVariable() const { return GetRawOperandAsVariable(0); } + }; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILInstructionBase + { + SSAVariable GetDestSSAVariable() const { return GetRawOperandAsSSAVariable(0); } + SSAVariable GetSourceSSAVariable() const { return GetRawOperandAsPartialSSAVariableSource(0); } + void SetDestSSAVersion(size_t version) { UpdateRawOperand(1, version); } + void SetSourceSSAVersion(size_t version) { UpdateRawOperand(2, version); } + }; + template <> struct MediumLevelILInstructionAccessor: public MediumLevelILInstructionBase { int64_t GetVector() const { return GetRawOperandAsInteger(0); } diff --git a/python/lowlevelil.py b/python/lowlevelil.py index 8a132478..e64e20fd 100644 --- a/python/lowlevelil.py +++ b/python/lowlevelil.py @@ -219,6 +219,8 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_REG_SPLIT: [("hi", "reg"), ("lo", "reg")], LowLevelILOperation.LLIL_REG_STACK_REL: [("stack", "reg_stack"), ("src", "expr")], LowLevelILOperation.LLIL_REG_STACK_POP: [("stack", "reg_stack")], + LowLevelILOperation.LLIL_REG_STACK_FREE_REG: [("dest", "reg")], + LowLevelILOperation.LLIL_REG_STACK_FREE_REL: [("stack", "reg_stack"), ("dest", "expr")], LowLevelILOperation.LLIL_CONST: [("constant", "int")], LowLevelILOperation.LLIL_CONST_PTR: [("constant", "int")], LowLevelILOperation.LLIL_FLOAT_CONST: [("constant", "float")], @@ -319,6 +321,8 @@ class LowLevelILInstruction(object): LowLevelILOperation.LLIL_REG_SPLIT_SSA: [("hi", "reg_ssa"), ("lo", "reg_ssa")], LowLevelILOperation.LLIL_REG_STACK_REL_SSA: [("stack", "reg_stack_ssa"), ("src", "expr"), ("top", "expr")], LowLevelILOperation.LLIL_REG_STACK_ABS_SSA: [("stack", "reg_stack_ssa"), ("src", "reg")], + LowLevelILOperation.LLIL_REG_STACK_FREE_REL_SSA: [("stack", "expr"), ("dest", "expr"), ("top", "expr")], + LowLevelILOperation.LLIL_REG_STACK_FREE_ABS_SSA: [("stack", "expr"), ("dest", "reg")], LowLevelILOperation.LLIL_SET_FLAG_SSA: [("dest", "flag_ssa"), ("src", "expr")], LowLevelILOperation.LLIL_FLAG_SSA: [("src", "flag_ssa")], LowLevelILOperation.LLIL_FLAG_BIT_SSA: [("src", "flag_ssa"), ("bit", "int")], diff --git a/python/mediumlevelil.py b/python/mediumlevelil.py index a842c3c4..caf19e8e 100644 --- a/python/mediumlevelil.py +++ b/python/mediumlevelil.py @@ -152,6 +152,8 @@ class MediumLevelILInstruction(object): MediumLevelILOperation.MLIL_TRAP: [("vector", "int")], MediumLevelILOperation.MLIL_INTRINSIC: [("output", "var_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")], MediumLevelILOperation.MLIL_INTRINSIC_SSA: [("output", "var_ssa_list"), ("intrinsic", "intrinsic"), ("params", "expr_list")], + MediumLevelILOperation.MLIL_FREE_VAR_SLOT: [("dest", "var")], + MediumLevelILOperation.MLIL_FREE_VAR_SLOT_SSA: [("prev", "var_ssa_dest_and_src")], MediumLevelILOperation.MLIL_UNDEF: [], MediumLevelILOperation.MLIL_UNIMPL: [], MediumLevelILOperation.MLIL_UNIMPL_MEM: [("src", "expr")], -- cgit v1.3.1