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) --- lowlevelil.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'lowlevelil.cpp') 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]; -- cgit v1.3.1 From 1df49afa5522d73d509d20db9588294fe259085f Mon Sep 17 00:00:00 2001 From: Brian Potchik Date: Thu, 11 Jan 2018 17:10:34 -0500 Subject: API Temporary Object Elimination. --- architecture.cpp | 4 ++-- binaryninjaapi.h | 4 ++++ binaryview.cpp | 22 +++++----------------- function.cpp | 49 ++++++++++++++++++++++++------------------------- lowlevelil.cpp | 24 ++++-------------------- mediumlevelil.cpp | 24 ++++-------------------- plugin.cpp | 2 +- settings.cpp | 4 ++-- type.cpp | 36 ++++++------------------------------ 9 files changed, 52 insertions(+), 117 deletions(-) (limited to 'lowlevelil.cpp') diff --git a/architecture.cpp b/architecture.cpp index 66372bcb..821f4c7b 100644 --- a/architecture.cpp +++ b/architecture.cpp @@ -959,8 +959,8 @@ bool CoreArchitecture::GetInstructionText(const uint8_t* data, uint64_t addr, si for (size_t i = 0; i < count; i++) { - result.push_back(InstructionTextToken(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, - tokens[i].value, tokens[i].size, tokens[i].operand, tokens[i].confidence)); + result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, + tokens[i].value, tokens[i].size, tokens[i].operand, tokens[i].confidence); } BNFreeInstructionText(tokens, count); diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 72f74c5a..31bd2316 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -1017,6 +1017,9 @@ namespace BinaryNinja struct DataVariable { + DataVariable() { } + DataVariable(uint64_t a, Type* t, bool d) : address(a), type(t), autoDiscovered(d) { } + uint64_t address; Confidence> type; bool autoDiscovered; @@ -1832,6 +1835,7 @@ namespace BinaryNinja { Variable(); Variable(BNVariableSourceType type, uint32_t index, uint64_t storage); + Variable(BNVariableSourceType type, uint64_t storage); Variable(const BNVariable& var); Variable& operator=(const Variable& var); diff --git a/binaryview.cpp b/binaryview.cpp index 50011a0f..00cd294f 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -82,10 +82,7 @@ void BinaryDataNotification::DataVariableAddedCallback(void* ctxt, BNBinaryView* { BinaryDataNotification* notify = (BinaryDataNotification*)ctxt; Ref view = new BinaryView(BNNewViewReference(object)); - DataVariable varObj; - varObj.address = var->address; - varObj.type = Confidence>(new Type(BNNewTypeReference(var->type)), var->typeConfidence); - varObj.autoDiscovered = var->autoDiscovered; + DataVariable varObj(var->address, Confidence>(new Type(BNNewTypeReference(var->type)), var->typeConfidence), var->autoDiscovered); notify->OnDataVariableAdded(view, varObj); } @@ -94,10 +91,7 @@ void BinaryDataNotification::DataVariableRemovedCallback(void* ctxt, BNBinaryVie { BinaryDataNotification* notify = (BinaryDataNotification*)ctxt; Ref view = new BinaryView(BNNewViewReference(object)); - DataVariable varObj; - varObj.address = var->address; - varObj.type = Confidence>(new Type(BNNewTypeReference(var->type)), var->typeConfidence); - varObj.autoDiscovered = var->autoDiscovered; + DataVariable varObj(var->address, Confidence>(new Type(BNNewTypeReference(var->type)), var->typeConfidence), var->autoDiscovered); notify->OnDataVariableRemoved(view, varObj); } @@ -106,10 +100,7 @@ void BinaryDataNotification::DataVariableUpdatedCallback(void* ctxt, BNBinaryVie { BinaryDataNotification* notify = (BinaryDataNotification*)ctxt; Ref view = new BinaryView(BNNewViewReference(object)); - DataVariable varObj; - varObj.address = var->address; - varObj.type = Confidence>(new Type(BNNewTypeReference(var->type)), var->typeConfidence); - varObj.autoDiscovered = var->autoDiscovered; + DataVariable varObj(var->address, Confidence>(new Type(BNNewTypeReference(var->type)), var->typeConfidence), var->autoDiscovered); notify->OnDataVariableUpdated(view, varObj); } @@ -965,11 +956,8 @@ map BinaryView::GetDataVariables() map result; for (size_t i = 0; i < count; i++) { - DataVariable var; - var.address = vars[i].address; - var.type = Confidence>(new Type(BNNewTypeReference(vars[i].type)), vars[i].typeConfidence); - var.autoDiscovered = vars[i].autoDiscovered; - result[var.address] = var; + result.emplace(piecewise_construct, forward_as_tuple(vars[i].address), + forward_as_tuple(vars[i].address, Confidence>(new Type(BNNewTypeReference(vars[i].type)), vars[i].typeConfidence), vars[i].autoDiscovered)); } BNFreeDataVariables(vars, count); diff --git a/function.cpp b/function.cpp index 2d8db04c..1226e399 100644 --- a/function.cpp +++ b/function.cpp @@ -504,11 +504,7 @@ Confidence> Function::GetParameterVariables() const vector varList; for (size_t i = 0; i < vars.count; i++) { - Variable var; - var.type = vars.vars[i].type; - var.index = vars.vars[i].index; - var.storage = vars.vars[i].storage; - varList.push_back(var); + varList.emplace_back(vars.vars[i].type, vars.vars[i].index, vars.vars[i].storage); } Confidence> result(varList, vars.confidence); BNFreeParameterVariables(&vars); @@ -569,13 +565,14 @@ void Function::SetAutoCallingConvention(const Confidence> void Function::SetAutoParameterVariables(const Confidence>& vars) { BNParameterVariablesWithConfidence varConf; - varConf.vars = new BNVariable[vars.GetValue().size()]; - varConf.count = vars.GetValue().size(); - for (size_t i = 0; i < vars.GetValue().size(); i++) + varConf.vars = new BNVariable[vars->size()]; + varConf.count = vars->size(); + size_t i = 0; + for (auto it = vars->begin(); it != vars->end(); ++it, ++i) { - varConf.vars[i].type = vars.GetValue()[i].type; - varConf.vars[i].index = vars.GetValue()[i].index; - varConf.vars[i].storage = vars.GetValue()[i].storage; + varConf.vars[i].type = it->type; + varConf.vars[i].index = it->index; + varConf.vars[i].storage = it->storage; } varConf.confidence = vars.GetConfidence(); @@ -614,11 +611,12 @@ void Function::SetAutoStackAdjustment(const Confidence& stackAdjust) void Function::SetAutoClobberedRegisters(const Confidence>& clobbered) { BNRegisterSetWithConfidence regs; - regs.regs = new uint32_t[clobbered.GetValue().size()]; - regs.count = clobbered.GetValue().size(); + regs.regs = new uint32_t[clobbered->size()]; + regs.count = clobbered->size(); + size_t i = 0; - for (auto reg : clobbered.GetValue()) - regs.regs[i++] = reg; + for (auto it = clobbered->begin(); it != clobbered->end(); ++it, ++i) + regs.regs[i] = *it; regs.confidence = clobbered.GetConfidence(); BNSetAutoFunctionClobberedRegisters(m_object, ®s); delete[] regs.regs; @@ -652,13 +650,14 @@ void Function::SetCallingConvention(const Confidence>& co void Function::SetParameterVariables(const Confidence>& vars) { BNParameterVariablesWithConfidence varConf; - varConf.vars = new BNVariable[vars.GetValue().size()]; - varConf.count = vars.GetValue().size(); - for (size_t i = 0; i < vars.GetValue().size(); i++) + varConf.vars = new BNVariable[vars->size()]; + varConf.count = vars->size(); + size_t i = 0; + for (auto it = vars->begin(); it != vars->end(); ++it, ++i) { - varConf.vars[i].type = vars.GetValue()[i].type; - varConf.vars[i].index = vars.GetValue()[i].index; - varConf.vars[i].storage = vars.GetValue()[i].storage; + varConf.vars[i].type = it->type; + varConf.vars[i].index = it->index; + varConf.vars[i].storage = it->storage; } varConf.confidence = vars.GetConfidence(); @@ -697,11 +696,11 @@ void Function::SetStackAdjustment(const Confidence& stackAdjust) void Function::SetClobberedRegisters(const Confidence>& clobbered) { BNRegisterSetWithConfidence regs; - regs.regs = new uint32_t[clobbered.GetValue().size()]; - regs.count = clobbered.GetValue().size(); + regs.regs = new uint32_t[clobbered->size()]; + regs.count = clobbered->size(); size_t i = 0; - for (auto reg : clobbered.GetValue()) - regs.regs[i++] = reg; + for (auto it = clobbered->begin(); it != clobbered->end(); ++it, ++i) + regs.regs[i] = *it; regs.confidence = clobbered.GetConfidence(); BNSetUserFunctionClobberedRegisters(m_object, ®s); delete[] regs.regs; diff --git a/lowlevelil.cpp b/lowlevelil.cpp index 690f0b41..6c59b704 100644 --- a/lowlevelil.cpp +++ b/lowlevelil.cpp @@ -392,16 +392,8 @@ bool LowLevelILFunction::GetExprText(Architecture* arch, ExprId expr, vector PluginCommand::GetList() size_t count; BNPluginCommand* commands = BNGetAllPluginCommands(&count); for (size_t i = 0; i < count; i++) - result.push_back(PluginCommand(commands[i])); + result.emplace_back(commands[i]); BNFreePluginCommandList(commands); return result; } diff --git a/settings.cpp b/settings.cpp index 328cf0e3..6b9c4e3a 100644 --- a/settings.cpp +++ b/settings.cpp @@ -52,7 +52,7 @@ std::vector Setting::GetStringList(const std::string& pluginName, vector result; for (size_t i = 0; i < size; i++) - result.push_back(string(outBuffer[i])); + result.emplace_back(outBuffer[i]); for (size_t i = 0; i < defaultValue.size(); i++) BNFreeString(buffer[i]); @@ -171,4 +171,4 @@ bool Setting::RemoveSetting(const std::string& settingGroup, const std::string& bool Setting::FlushSettings() { return BNSettingFlushSettings(); -} \ No newline at end of file +} diff --git a/type.cpp b/type.cpp index 40a69ae2..c158f53e 100644 --- a/type.cpp +++ b/type.cpp @@ -476,16 +476,8 @@ vector Type::GetTokens(Platform* platform, uint8_t baseCon vector result; for (size_t i = 0; i < count; i++) { - InstructionTextToken token; - token.type = tokens[i].type; - token.text = tokens[i].text; - token.value = tokens[i].value; - token.size = tokens[i].size; - token.operand = tokens[i].operand; - token.context = tokens[i].context; - token.confidence = tokens[i].confidence; - token.address = tokens[i].address; - result.push_back(token); + result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, tokens[i].value, tokens[i].size, + tokens[i].operand, tokens[i].confidence); } BNFreeTokenList(tokens, count); @@ -502,16 +494,8 @@ vector Type::GetTokensBeforeName(Platform* platform, uint8 vector result; for (size_t i = 0; i < count; i++) { - InstructionTextToken token; - token.type = tokens[i].type; - token.text = tokens[i].text; - token.value = tokens[i].value; - token.size = tokens[i].size; - token.operand = tokens[i].operand; - token.context = tokens[i].context; - token.confidence = tokens[i].confidence; - token.address = tokens[i].address; - result.push_back(token); + result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, tokens[i].value, tokens[i].size, + tokens[i].operand, tokens[i].confidence); } BNFreeTokenList(tokens, count); @@ -528,16 +512,8 @@ vector Type::GetTokensAfterName(Platform* platform, uint8_ vector result; for (size_t i = 0; i < count; i++) { - InstructionTextToken token; - token.type = tokens[i].type; - token.text = tokens[i].text; - token.value = tokens[i].value; - token.size = tokens[i].size; - token.operand = tokens[i].operand; - token.context = tokens[i].context; - token.confidence = tokens[i].confidence; - token.address = tokens[i].address; - result.push_back(token); + result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, tokens[i].value, tokens[i].size, + tokens[i].operand, tokens[i].confidence); } BNFreeTokenList(tokens, count); -- cgit v1.3.1 From 0cc77206c79257d49013c3a3ed1bf889c85b10d1 Mon Sep 17 00:00:00 2001 From: Brian Potchik Date: Sun, 14 Jan 2018 03:42:04 -0500 Subject: Container Memory Reservations. --- architecture.cpp | 11 +++++++++++ backgroundtask.cpp | 1 + basicblock.cpp | 4 ++++ binaryview.cpp | 20 ++++++++++++++++++++ binaryviewtype.cpp | 2 ++ function.cpp | 11 +++++++++-- functiongraph.cpp | 2 ++ functiongraphblock.cpp | 3 +++ lowlevelil.cpp | 8 ++++---- lowlevelilinstruction.cpp | 7 ++++--- mediumlevelil.cpp | 9 +++++---- mediumlevelilinstruction.cpp | 6 +++--- metadata.cpp | 1 + platform.cpp | 6 ++++++ plugin.cpp | 1 + settings.cpp | 1 + transform.cpp | 2 ++ type.cpp | 12 ++++++------ update.cpp | 2 ++ 19 files changed, 87 insertions(+), 22 deletions(-) (limited to 'lowlevelil.cpp') diff --git a/architecture.cpp b/architecture.cpp index 821f4c7b..7b74e43b 100644 --- a/architecture.cpp +++ b/architecture.cpp @@ -507,6 +507,7 @@ vector> Architecture::GetList() archs = BNGetArchitectureList(&count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new CoreArchitecture(archs[i])); @@ -703,6 +704,7 @@ vector Architecture::GetModifiedRegistersOnWrite(uint32_t reg) uint32_t* regs = BNGetModifiedArchitectureRegistersOnWrite(m_object, reg, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(regs[i]); @@ -814,6 +816,7 @@ vector> Architecture::GetCallingConventions() BNCallingConvention** list = BNGetArchitectureCallingConventions(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new CoreCallingConvention(BNNewCallingConventionReference(list[i]))); @@ -957,6 +960,7 @@ bool CoreArchitecture::GetInstructionText(const uint8_t* data, uint64_t addr, si if (!BNGetInstructionText(m_object, data, addr, &len, &tokens, &count)) return false; + result.reserve(count); for (size_t i = 0; i < count; i++) { result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, @@ -1007,6 +1011,7 @@ vector CoreArchitecture::GetFullWidthRegisters() uint32_t* regs = BNGetFullWidthArchitectureRegisters(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(regs[i]); @@ -1021,6 +1026,7 @@ vector CoreArchitecture::GetAllRegisters() uint32_t* regs = BNGetAllArchitectureRegisters(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(regs[i]); @@ -1035,6 +1041,7 @@ vector CoreArchitecture::GetAllFlags() uint32_t* regs = BNGetAllArchitectureFlags(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(regs[i]); @@ -1049,6 +1056,7 @@ vector CoreArchitecture::GetAllFlagWriteTypes() uint32_t* regs = BNGetAllArchitectureFlagWriteTypes(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(regs[i]); @@ -1069,6 +1077,7 @@ vector CoreArchitecture::GetFlagsRequiredForFlagCondition(BNLowLevelIL uint32_t* flags = BNGetArchitectureFlagsRequiredForFlagCondition(m_object, cond, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(flags[i]); @@ -1083,6 +1092,7 @@ vector CoreArchitecture::GetFlagsWrittenByFlagWriteType(uint32_t write uint32_t* flags = BNGetArchitectureFlagsWrittenByFlagWriteType(m_object, writeType, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(flags[i]); @@ -1129,6 +1139,7 @@ vector CoreArchitecture::GetGlobalRegisters() uint32_t* regs = BNGetArchitectureGlobalRegisters(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(regs[i]); diff --git a/backgroundtask.cpp b/backgroundtask.cpp index aebf980c..b2d4a738 100644 --- a/backgroundtask.cpp +++ b/backgroundtask.cpp @@ -67,6 +67,7 @@ vector> BackgroundTask::GetRunningTasks() BNBackgroundTask** tasks = BNGetRunningBackgroundTasks(&count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new BackgroundTask(BNNewBackgroundTaskReference(tasks[i]))); diff --git a/basicblock.cpp b/basicblock.cpp index 89ace134..d42a1038 100644 --- a/basicblock.cpp +++ b/basicblock.cpp @@ -120,6 +120,7 @@ vector BasicBlock::GetOutgoingEdges() const BNBasicBlockEdge* array = BNGetBasicBlockOutgoingEdges(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { BasicBlockEdge edge; @@ -140,6 +141,7 @@ vector BasicBlock::GetIncomingEdges() const BNBasicBlockEdge* array = BNGetBasicBlockIncomingEdges(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { BasicBlockEdge edge; @@ -269,10 +271,12 @@ vector BasicBlock::GetDisassemblyText(DisassemblySettings* BNDisassemblyTextLine* lines = BNGetBasicBlockDisassemblyText(m_object, settings->GetObject(), &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { DisassemblyTextLine line; line.addr = lines[i].addr; + line.tokens.reserve(lines[i].count); for (size_t j = 0; j < lines[i].count; j++) { InstructionTextToken token; diff --git a/binaryview.cpp b/binaryview.cpp index 00cd294f..0ee428e1 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -670,6 +670,7 @@ vector BinaryView::GetModification(uint64_t offset, size_t len = BNGetModificationArray(m_object, offset, mod, len); vector result; + result.reserve(len); for (size_t i = 0; i < len; i++) result.push_back(mod[i]); @@ -988,6 +989,7 @@ vector> BinaryView::GetAnalysisFunctionList() BNFunction** list = BNGetAnalysisFunctionList(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Function(BNNewFunctionReference(list[i]))); @@ -1026,6 +1028,7 @@ vector> BinaryView::GetAnalysisFunctionsForAddress(uint64_t addr) BNFunction** list = BNGetAnalysisFunctionsForAddress(m_object, addr, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Function(BNNewFunctionReference(list[i]))); @@ -1058,6 +1061,7 @@ vector> BinaryView::GetBasicBlocksForAddress(uint64_t addr) BNBasicBlock** blocks = BNGetBasicBlocksForAddress(m_object, addr, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new BasicBlock(BNNewBasicBlockReference(blocks[i]))); @@ -1072,6 +1076,7 @@ vector> BinaryView::GetBasicBlocksStartingAtAddress(uint64_t add BNBasicBlock** blocks = BNGetBasicBlocksStartingAtAddress(m_object, addr, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new BasicBlock(BNNewBasicBlockReference(blocks[i]))); @@ -1086,6 +1091,7 @@ vector BinaryView::GetCodeReferences(uint64_t addr) BNReferenceSource* refs = BNGetCodeReferences(m_object, addr, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { ReferenceSource src; @@ -1106,6 +1112,7 @@ vector BinaryView::GetCodeReferences(uint64_t addr, uint64_t le BNReferenceSource* refs = BNGetCodeReferencesInRange(m_object, addr, len, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { ReferenceSource src; @@ -1144,6 +1151,7 @@ vector> BinaryView::GetSymbolsByName(const string& name) BNSymbol** syms = BNGetSymbolsByName(m_object, name.c_str(), &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Symbol(BNNewSymbolReference(syms[i]))); @@ -1158,6 +1166,7 @@ vector> BinaryView::GetSymbols() BNSymbol** syms = BNGetSymbols(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Symbol(BNNewSymbolReference(syms[i]))); @@ -1172,6 +1181,7 @@ vector> BinaryView::GetSymbols(uint64_t start, uint64_t len) BNSymbol** syms = BNGetSymbolsInRange(m_object, start, len, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Symbol(BNNewSymbolReference(syms[i]))); @@ -1186,6 +1196,7 @@ vector> BinaryView::GetSymbolsOfType(BNSymbolType type) BNSymbol** syms = BNGetSymbolsOfType(m_object, type, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Symbol(BNNewSymbolReference(syms[i]))); @@ -1200,6 +1211,7 @@ vector> BinaryView::GetSymbolsOfType(BNSymbolType type, uint64_t sta BNSymbol** syms = BNGetSymbolsOfTypeInRange(m_object, type, start, len, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Symbol(BNNewSymbolReference(syms[i]))); @@ -1412,6 +1424,7 @@ vector BinaryView::GetPreviousLinearDisassemblyLines(Line settings ? settings->GetObject() : nullptr, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { LinearDisassemblyLine line; @@ -1420,6 +1433,7 @@ vector BinaryView::GetPreviousLinearDisassemblyLines(Line line.block = lines[i].block ? new BasicBlock(BNNewBasicBlockReference(lines[i].block)) : nullptr; line.lineOffset = lines[i].lineOffset; line.contents.addr = lines[i].contents.addr; + line.contents.tokens.reserve(lines[i].contents.count); for (size_t j = 0; j < lines[i].contents.count; j++) { InstructionTextToken token; @@ -1458,6 +1472,7 @@ vector BinaryView::GetNextLinearDisassemblyLines(LinearDi settings ? settings->GetObject() : nullptr, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { LinearDisassemblyLine line; @@ -1466,6 +1481,7 @@ vector BinaryView::GetNextLinearDisassemblyLines(LinearDi line.block = lines[i].block ? new BasicBlock(BNNewBasicBlockReference(lines[i].block)) : nullptr; line.lineOffset = lines[i].lineOffset; line.contents.addr = lines[i].contents.addr; + line.contents.tokens.reserve(lines[i].contents.count); for (size_t j = 0; j < lines[i].contents.count; j++) { InstructionTextToken token; @@ -1704,6 +1720,7 @@ vector BinaryView::GetSegments() BNSegment* segments = BNGetSegments(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { Segment segment; @@ -1777,6 +1794,7 @@ vector
BinaryView::GetSections() BNSection* sections = BNGetSections(m_object, &count); vector
result; + result.reserve(count); for (size_t i = 0; i < count; i++) { Section section; @@ -1804,6 +1822,7 @@ vector
BinaryView::GetSectionsAt(uint64_t addr) BNSection* sections = BNGetSectionsAt(m_object, addr, &count); vector
result; + result.reserve(count); for (size_t i = 0; i < count; i++) { Section section; @@ -1855,6 +1874,7 @@ vector BinaryView::GetUniqueSectionNames(const vector& names) char** outgoingNames = BNGetUniqueSectionNames(m_object, incomingNames, names.size()); vector result; + result.reserve(names.size()); for (size_t i = 0; i < names.size(); i++) result.push_back(outgoingNames[i]); diff --git a/binaryviewtype.cpp b/binaryviewtype.cpp index e23838f6..e8ef4f53 100644 --- a/binaryviewtype.cpp +++ b/binaryviewtype.cpp @@ -83,6 +83,7 @@ vector> BinaryViewType::GetViewTypes() types = BNGetBinaryViewTypes(&count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new CoreBinaryViewType(types[i])); @@ -98,6 +99,7 @@ vector> BinaryViewType::GetViewTypesForData(BinaryView* data types = BNGetBinaryViewTypesForData(data->GetObject(), &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new CoreBinaryViewType(types[i])); diff --git a/function.cpp b/function.cpp index 1226e399..cb4377b2 100644 --- a/function.cpp +++ b/function.cpp @@ -174,6 +174,7 @@ vector> Function::GetBasicBlocks() const BNBasicBlock** blocks = BNGetFunctionBasicBlockList(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new BasicBlock(BNNewBasicBlockReference(blocks[i]))); @@ -379,6 +380,7 @@ vector Function::GetStackVariablesReferencedByInstructio BNStackVariableReference* refs = BNGetStackVariablesReferencedByInstruction(m_object, arch->GetObject(), addr, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { StackVariableReference ref; @@ -502,10 +504,9 @@ Confidence> Function::GetParameterVariables() const { BNParameterVariablesWithConfidence vars = BNGetFunctionParameterVariables(m_object); vector varList; + varList.reserve(vars.count); for (size_t i = 0; i < vars.count; i++) - { varList.emplace_back(vars.vars[i].type, vars.vars[i].index, vars.vars[i].storage); - } Confidence> result(varList, vars.confidence); BNFreeParameterVariables(&vars); return result; @@ -897,6 +898,7 @@ vector Function::GetIndirectBranches() BNIndirectBranchInfo* branches = BNGetIndirectBranches(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { IndirectBranchInfo b; @@ -919,6 +921,7 @@ vector Function::GetIndirectBranchesAt(Architecture* arch, u BNIndirectBranchInfo* branches = BNGetIndirectBranchesAt(m_object, arch->GetObject(), addr, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { IndirectBranchInfo b; @@ -941,9 +944,11 @@ vector> Function::GetBlockAnnotations(Architecture* BNInstructionTextLine* lines = BNGetFunctionBlockAnnotations(m_object, arch->GetObject(), addr, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) { vector line; + line.reserve(lines[i].count); for (size_t j = 0; j < lines[i].count; j++) { InstructionTextToken token; @@ -1155,10 +1160,12 @@ vector Function::GetTypeTokens(DisassemblySettings* setting settings ? settings->GetObject() : nullptr, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { DisassemblyTextLine line; line.addr = lines[i].addr; + line.tokens.reserve(lines[i].count); for (size_t j = 0; j < lines[i].count; j++) { InstructionTextToken token; diff --git a/functiongraph.cpp b/functiongraph.cpp index 7e5ec079..77754913 100644 --- a/functiongraph.cpp +++ b/functiongraph.cpp @@ -110,6 +110,7 @@ vector> FunctionGraph::GetBlocks() BNFunctionGraphBlock** blocks = BNGetFunctionGraphBlocks(m_graph, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) { auto block = m_cachedBlocks.find(blocks[i]); @@ -148,6 +149,7 @@ vector> FunctionGraph::GetBlocksInRegion(int left, int t BNFunctionGraphBlock** blocks = BNGetFunctionGraphBlocksInRegion(m_graph, left, top, right, bottom, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) { auto block = m_cachedBlocks.find(blocks[i]); diff --git a/functiongraphblock.cpp b/functiongraphblock.cpp index 20b2515b..06a35eee 100644 --- a/functiongraphblock.cpp +++ b/functiongraphblock.cpp @@ -89,10 +89,12 @@ const vector& FunctionGraphBlock::GetLines() BNDisassemblyTextLine* lines = BNGetFunctionGraphBlockLines(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { DisassemblyTextLine line; line.addr = lines[i].addr; + line.tokens.reserve(lines[i].count); for (size_t j = 0; j < lines[i].count; j++) { InstructionTextToken token; @@ -125,6 +127,7 @@ const vector& FunctionGraphBlock::GetOutgoingEdges() BNFunctionGraphEdge* edges = BNGetFunctionGraphBlockOutgoingEdges(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { FunctionGraphEdge edge; diff --git a/lowlevelil.cpp b/lowlevelil.cpp index 6c59b704..5e985a8e 100644 --- a/lowlevelil.cpp +++ b/lowlevelil.cpp @@ -176,6 +176,7 @@ vector LowLevelILFunction::GetOperandList(ExprId expr, size_t listOper size_t count; uint64_t* operands = BNLowLevelILGetOperandList(m_object, expr, listOperand, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(operands[i]); BNLowLevelILFreeOperandList(operands); @@ -390,11 +391,10 @@ bool LowLevelILFunction::GetExprText(Architecture* arch, ExprId expr, vector> LowLevelILFunction::GetBasicBlocks() const BNBasicBlock** blocks = BNGetLowLevelILBasicBlockList(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new BasicBlock(BNNewBasicBlockReference(blocks[i]))); diff --git a/lowlevelilinstruction.cpp b/lowlevelilinstruction.cpp index d85e4f17..53b1e390 100644 --- a/lowlevelilinstruction.cpp +++ b/lowlevelilinstruction.cpp @@ -178,15 +178,16 @@ unordered_map> }; -static unordered_map> - GetOperandIndexForOperandUsages() +static unordered_map> GetOperandIndexForOperandUsages() { unordered_map> result; + result.reserve(LowLevelILInstructionBase::operationOperandUsage.size()); for (auto& operation : LowLevelILInstructionBase::operationOperandUsage) { result[operation.first] = unordered_map(); size_t operand = 0; + result[operation.first].reserve(operation.second.size()); for (auto usage : operation.second) { result[operation.first][usage] = operand; @@ -377,7 +378,7 @@ uint64_t LowLevelILIntegerList::ListIterator::operator*() LowLevelILIntegerList::LowLevelILIntegerList(LowLevelILFunction* func, - const BNLowLevelILInstruction& instr, size_t count) +const BNLowLevelILInstruction& instr, size_t count) { m_start.function = func; #ifdef BINARYNINJACORE_LIBRARY diff --git a/mediumlevelil.cpp b/mediumlevelil.cpp index 2cd5a233..0a28bd49 100644 --- a/mediumlevelil.cpp +++ b/mediumlevelil.cpp @@ -157,6 +157,7 @@ vector MediumLevelILFunction::GetOperandList(ExprId expr, size_t listO size_t count; uint64_t* operands = BNMediumLevelILGetOperandList(m_object, expr, listOperand, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(operands[i]); BNMediumLevelILFreeOperandList(operands); @@ -338,11 +339,10 @@ bool MediumLevelILFunction::GetExprText(Architecture* arch, ExprId expr, vector< return false; tokens.clear(); + tokens.reserve(count); for (size_t i = 0; i < count; i++) - { tokens.emplace_back(list[i].type, list[i].context, list[i].text, list[i].address, list[i].value, list[i].size, list[i].operand, list[i].confidence); - } BNFreeInstructionText(list, count); return true; @@ -359,11 +359,10 @@ bool MediumLevelILFunction::GetInstructionText(Function* func, Architecture* arc return false; tokens.clear(); + tokens.reserve(count); for (size_t i = 0; i < count; i++) - { tokens.emplace_back(list[i].type, list[i].context, list[i].text, list[i].address, list[i].value, list[i].size, list[i].operand, list[i].confidence); - } BNFreeInstructionText(list, count); return true; @@ -396,6 +395,7 @@ vector> MediumLevelILFunction::GetBasicBlocks() const BNBasicBlock** blocks = BNGetMediumLevelILBasicBlockList(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new BasicBlock(BNNewBasicBlockReference(blocks[i]))); @@ -680,6 +680,7 @@ unordered_map MediumLevelILFunction::GetAllBranchD BNILBranchInstructionAndDependence* deps = BNGetAllMediumLevelILBranchDependence(m_object, instr, &count); unordered_map result; + result.reserve(count); for (size_t i = 0; i < count; i++) result[deps[i].branch] = deps[i].dependence; diff --git a/mediumlevelilinstruction.cpp b/mediumlevelilinstruction.cpp index ec6aa1c6..bb4d205a 100644 --- a/mediumlevelilinstruction.cpp +++ b/mediumlevelilinstruction.cpp @@ -205,14 +205,14 @@ unordered_map> }; -static unordered_map> - GetOperandIndexForOperandUsages() +static unordered_map> GetOperandIndexForOperandUsages() { unordered_map> result; + result.reserve(MediumLevelILInstructionBase::operationOperandUsage.size()); for (auto& operation : MediumLevelILInstructionBase::operationOperandUsage) { result[operation.first] = unordered_map(); - + result[operation.first].reserve(operation.second.size()); size_t operand = 0; for (auto usage : operation.second) { diff --git a/metadata.cpp b/metadata.cpp index f9c48b04..c111233f 100644 --- a/metadata.cpp +++ b/metadata.cpp @@ -144,6 +144,7 @@ vector> Metadata::GetArray() size_t size = 0; BNMetadata** data = BNMetadataGetArray(m_object, &size); vector> result; + result.reserve(size); for (size_t i = 0; i < size; i++) result.push_back(new Metadata(data[i])); return result; diff --git a/platform.cpp b/platform.cpp index a9ab888f..724901fe 100644 --- a/platform.cpp +++ b/platform.cpp @@ -72,6 +72,7 @@ vector> Platform::GetList() BNPlatform** list = BNGetPlatformList(&count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Platform(BNNewPlatformReference(list[i]))); @@ -86,6 +87,7 @@ vector> Platform::GetList(Architecture* arch) BNPlatform** list = BNGetPlatformListByArchitecture(arch->GetObject(), &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Platform(BNNewPlatformReference(list[i]))); @@ -100,6 +102,7 @@ vector> Platform::GetList(const string& os) BNPlatform** list = BNGetPlatformListByOS(os.c_str(), &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Platform(BNNewPlatformReference(list[i]))); @@ -114,6 +117,7 @@ vector> Platform::GetList(const string& os, Architecture* arch) BNPlatform** list = BNGetPlatformListByOSAndArchitecture(os.c_str(), arch->GetObject(), &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new Platform(BNNewPlatformReference(list[i]))); @@ -128,6 +132,7 @@ vector Platform::GetOSList() char** list = BNGetPlatformOSList(&count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(list[i]); @@ -178,6 +183,7 @@ vector> Platform::GetCallingConventions() const BNCallingConvention** list = BNGetPlatformCallingConventions(m_object, &count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new CoreCallingConvention(BNNewCallingConventionReference(list[i]))); diff --git a/plugin.cpp b/plugin.cpp index 2378fdab..972ce28b 100644 --- a/plugin.cpp +++ b/plugin.cpp @@ -211,6 +211,7 @@ vector PluginCommand::GetList() vector result; size_t count; BNPluginCommand* commands = BNGetAllPluginCommands(&count); + result.reserve(count); for (size_t i = 0; i < count; i++) result.emplace_back(commands[i]); BNFreePluginCommandList(commands); diff --git a/settings.cpp b/settings.cpp index 6b9c4e3a..b5899e38 100644 --- a/settings.cpp +++ b/settings.cpp @@ -51,6 +51,7 @@ std::vector Setting::GetStringList(const std::string& pluginName, char** outBuffer = (char**)BNSettingGetStringList(pluginName.c_str(), name.c_str(), (const char**)buffer, &size); vector result; + result.reserve(size); for (size_t i = 0; i < size; i++) result.emplace_back(outBuffer[i]); diff --git a/transform.cpp b/transform.cpp index 29a665d0..0a6fdfe6 100644 --- a/transform.cpp +++ b/transform.cpp @@ -157,6 +157,7 @@ vector> Transform::GetTransformTypes() BNTransform** list = BNGetTransformTypeList(&count); vector> result; + result.reserve(count); for (size_t i = 0; i < count; i++) result.push_back(new CoreTransform(list[i])); @@ -229,6 +230,7 @@ vector CoreTransform::GetParameters() const BNTransformParameterInfo* list = BNGetTransformParameterList(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { TransformParameter param; diff --git a/type.cpp b/type.cpp index c158f53e..08b64713 100644 --- a/type.cpp +++ b/type.cpp @@ -355,6 +355,7 @@ vector Type::GetParameters() const BNFunctionParameter* types = BNGetTypeParameters(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { FunctionParameter param; @@ -474,11 +475,10 @@ vector Type::GetTokens(Platform* platform, uint8_t baseCon platform ? platform->GetObject() : nullptr, baseConfidence, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) - { result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, tokens[i].value, tokens[i].size, tokens[i].operand, tokens[i].confidence); - } BNFreeTokenList(tokens, count); return result; @@ -492,11 +492,10 @@ vector Type::GetTokensBeforeName(Platform* platform, uint8 platform ? platform->GetObject() : nullptr, baseConfidence, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) - { result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, tokens[i].value, tokens[i].size, tokens[i].operand, tokens[i].confidence); - } BNFreeTokenList(tokens, count); return result; @@ -510,11 +509,10 @@ vector Type::GetTokensAfterName(Platform* platform, uint8_ platform ? platform->GetObject() : nullptr, baseConfidence, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) - { result.emplace_back(tokens[i].type, tokens[i].context, tokens[i].text, tokens[i].address, tokens[i].value, tokens[i].size, tokens[i].operand, tokens[i].confidence); - } BNFreeTokenList(tokens, count); return result; @@ -882,6 +880,7 @@ vector Structure::GetMembers() const BNStructureMember* members = BNGetStructureMembers(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { StructureMember member; @@ -1001,6 +1000,7 @@ vector Enumeration::GetMembers() const BNEnumerationMember* members = BNGetEnumerationMembers(m_object, &count); vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { EnumerationMember member; diff --git a/update.cpp b/update.cpp index 0ec69892..ecdf4162 100644 --- a/update.cpp +++ b/update.cpp @@ -53,6 +53,7 @@ vector UpdateChannel::GetList() } vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { UpdateChannel channel; @@ -149,6 +150,7 @@ vector UpdateVersion::GetChannelVersions(const string& channel) } vector result; + result.reserve(count); for (size_t i = 0; i < count; i++) { UpdateVersion version; -- 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 'lowlevelil.cpp') 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 f37eb6cc18abf4dbb5b03175e4cb980c3e9a7ae2 Mon Sep 17 00:00:00 2001 From: Ryan Snyder Date: Wed, 28 Mar 2018 13:45:43 -0400 Subject: Fix default flag write generation for some ops --- lowlevelil.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'lowlevelil.cpp') diff --git a/lowlevelil.cpp b/lowlevelil.cpp index 91db6ab3..79138159 100644 --- a/lowlevelil.cpp +++ b/lowlevelil.cpp @@ -314,7 +314,11 @@ ExprId LowLevelILFunction::GetExprForRegisterOrConstantOperation(BNLowLevelILOpe if (operandCount == 0) return AddExpr(op, size, 0); if (operandCount == 1) + { + if (op == LLIL_SET_REG) + return GetExprForRegisterOrConstant(operands[0], size); return AddExpr(op, size, 0, GetExprForRegisterOrConstant(operands[0], size)); + } if (operandCount == 2) { return AddExpr(op, size, 0, GetExprForRegisterOrConstant(operands[0], size), -- cgit v1.3.1