diff options
| -rw-r--r-- | basicblock.cpp | 16 | ||||
| -rw-r--r-- | binaryninjaapi.h | 104 | ||||
| -rw-r--r-- | binaryninjacore.h | 190 | ||||
| -rw-r--r-- | binaryview.cpp | 8 | ||||
| -rw-r--r-- | flowgraph.cpp | 261 | ||||
| -rw-r--r-- | flowgraphnode.cpp | 203 | ||||
| -rw-r--r-- | function.cpp | 22 | ||||
| -rw-r--r-- | functiongraph.cpp | 224 | ||||
| -rw-r--r-- | functiongraphblock.cpp | 146 | ||||
| -rw-r--r-- | interaction.cpp | 140 | ||||
| -rw-r--r-- | python/__init__.py | 1 | ||||
| -rw-r--r-- | python/basicblock.py | 12 | ||||
| -rw-r--r-- | python/binaryview.py | 7 | ||||
| -rw-r--r-- | python/flowgraph.py | 465 | ||||
| -rw-r--r-- | python/function.py | 400 | ||||
| -rw-r--r-- | python/highlight.py | 10 | ||||
| -rw-r--r-- | python/interaction.py | 172 |
17 files changed, 1521 insertions, 860 deletions
diff --git a/basicblock.cpp b/basicblock.cpp index 33f57d40..9cf9ed56 100644 --- a/basicblock.cpp +++ b/basicblock.cpp @@ -72,6 +72,21 @@ void DisassemblySettings::SetMaximumSymbolWidth(size_t width) } +DisassemblyTextLine::DisassemblyTextLine() +{ + addr = 0; + instrIndex = BN_INVALID_EXPR; + highlight.style = StandardHighlightColor; + highlight.color = NoHighlightColor; + highlight.mixColor = NoHighlightColor; + highlight.mix = 0; + highlight.r = 0; + highlight.g = 0; + highlight.b = 0; + highlight.alpha = 0; +} + + BasicBlock::BasicBlock(BNBasicBlock* block) { m_object = block; @@ -277,6 +292,7 @@ vector<DisassemblyTextLine> BasicBlock::GetDisassemblyText(DisassemblySettings* DisassemblyTextLine line; line.addr = lines[i].addr; line.instrIndex = lines[i].instrIndex; + line.highlight = lines[i].highlight; line.tokens.reserve(lines[i].count); for (size_t j = 0; j < lines[i].count; j++) { diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 05c8c4e3..3582b265 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -494,6 +494,8 @@ namespace BinaryNinja class MainThreadActionHandler; class InteractionHandler; class QualifiedName; + class FlowGraph; + class ReportCollection; struct FormInputField; /*! Logs to the error console with the given BNLogLevel. @@ -627,6 +629,8 @@ namespace BinaryNinja const std::string& plainText = ""); void ShowHTMLReport(const std::string& title, const std::string& contents, const std::string& plainText = ""); + void ShowGraphReport(const std::string& title, FlowGraph* graph); + void ShowReportCollection(const std::string& title, ReportCollection* reports); bool GetTextLineInput(std::string& result, const std::string& prompt, const std::string& title); bool GetIntegerInput(int64_t& result, const std::string& prompt, const std::string& title); @@ -988,6 +992,9 @@ namespace BinaryNinja uint64_t addr; size_t instrIndex; std::vector<InstructionTextToken> tokens; + BNHighlightColor highlight; + + DisassemblyTextLine(); }; struct LinearDisassemblyPosition @@ -1313,6 +1320,7 @@ namespace BinaryNinja void ShowPlainTextReport(const std::string& title, const std::string& contents); void ShowMarkdownReport(const std::string& title, const std::string& contents, const std::string& plainText); void ShowHTMLReport(const std::string& title, const std::string& contents, const std::string& plainText); + void ShowGraphReport(const std::string& title, FlowGraph* graph); bool GetAddressInput(uint64_t& result, const std::string& prompt, const std::string& title); bool GetAddressInput(uint64_t& result, const std::string& prompt, const std::string& title, uint64_t currentAddress); @@ -2327,7 +2335,7 @@ namespace BinaryNinja static PossibleValueSet FromAPIObject(BNPossibleValueSet& value); }; - class FunctionGraph; + class FlowGraph; class MediumLevelILFunction; class Function: public CoreRefCountObject<BNFunction, BNNewFunctionReference, BNFreeFunction> @@ -2338,6 +2346,7 @@ namespace BinaryNinja Function(BNFunction* func); virtual ~Function(); + Ref<BinaryView> GetView() const; Ref<Architecture> GetArchitecture() const; Ref<Platform> GetPlatform() const; uint64_t GetStart() const; @@ -2415,7 +2424,7 @@ namespace BinaryNinja void ApplyImportedTypes(Symbol* sym); void ApplyAutoDiscoveredType(Type* type); - Ref<FunctionGraph> CreateFunctionGraph(); + Ref<FlowGraph> CreateFunctionGraph(BNFunctionGraphType type, DisassemblySettings* settings = nullptr); std::map<int64_t, std::vector<VariableNameAndType>> GetStackLayout(); void CreateAutoStackVariable(int64_t offset, const Confidence<Ref<Type>>& type, const std::string& name); @@ -2495,6 +2504,8 @@ namespace BinaryNinja bool IsAnalysisSkipped(); BNFunctionAnalysisSkipOverride GetAnalysisSkipOverride(); void SetAnalysisSkipOverride(BNFunctionAnalysisSkipOverride skip); + + Ref<FlowGraph> GetUnresolvedStackAdjustmentGraph(); }; class AdvancedFunctionAnalysisDataRequestor @@ -2511,79 +2522,87 @@ namespace BinaryNinja void SetFunction(Function* func); }; - struct FunctionGraphEdge + class FlowGraphNode; + + struct FlowGraphEdge { BNBranchType type; - Ref<BasicBlock> target; + Ref<FlowGraphNode> target; std::vector<BNPoint> points; bool backEdge; }; - class FunctionGraphBlock: public CoreRefCountObject<BNFunctionGraphBlock, - BNNewFunctionGraphBlockReference, BNFreeFunctionGraphBlock> + class FlowGraphNode: public CoreRefCountObject<BNFlowGraphNode, + BNNewFlowGraphNodeReference, BNFreeFlowGraphNode> { std::vector<DisassemblyTextLine> m_cachedLines; - std::vector<FunctionGraphEdge> m_cachedEdges; + std::vector<FlowGraphEdge> m_cachedEdges; bool m_cachedLinesValid, m_cachedEdgesValid; public: - FunctionGraphBlock(BNFunctionGraphBlock* block); + FlowGraphNode(FlowGraph* graph); + FlowGraphNode(BNFlowGraphNode* node); Ref<BasicBlock> GetBasicBlock() const; - Ref<Architecture> GetArchitecture() const; - uint64_t GetStart() const; - uint64_t GetEnd() const; + void SetBasicBlock(BasicBlock* block); int GetX() const; int GetY() const; int GetWidth() const; int GetHeight() const; const std::vector<DisassemblyTextLine>& GetLines(); - const std::vector<FunctionGraphEdge>& GetOutgoingEdges(); + void SetLines(const std::vector<DisassemblyTextLine>& lines); + const std::vector<FlowGraphEdge>& GetOutgoingEdges(); + void AddOutgoingEdge(BNBranchType type, FlowGraphNode* target); + + BNHighlightColor GetHighlight() const; + void SetHighlight(const BNHighlightColor& color); }; - class FunctionGraph: public RefCountObject + class FlowGraph: public RefCountObject { - BNFunctionGraph* m_graph; + BNFlowGraph* m_graph; std::function<void()> m_completeFunc; - std::map<BNFunctionGraphBlock*, Ref<FunctionGraphBlock>> m_cachedBlocks; + std::map<BNFlowGraphNode*, Ref<FlowGraphNode>> m_cachedNodes; static void CompleteCallback(void* ctxt); public: - FunctionGraph(BNFunctionGraph* graph); - ~FunctionGraph(); + FlowGraph(BNFlowGraph* graph); + ~FlowGraph(); - BNFunctionGraph* GetGraphObject() const { return m_graph; } + BNFlowGraph* GetGraphObject() const { return m_graph; } Ref<Function> GetFunction() const; + void SetFunction(Function* func); - int GetHorizontalBlockMargin() const; - int GetVerticalBlockMargin() const; - void SetBlockMargins(int horiz, int vert); - - Ref<DisassemblySettings> GetSettings(); + int GetHorizontalNodeMargin() const; + int GetVerticalNodeMargin() const; + void SetNodeMargins(int horiz, int vert); - void StartLayout(BNFunctionGraphType = NormalFunctionGraph); + void StartLayout(); bool IsLayoutComplete(); void OnComplete(const std::function<void()>& func); void Abort(); - std::vector<Ref<FunctionGraphBlock>> GetBlocks(); - bool HasBlocks() const; + std::vector<Ref<FlowGraphNode>> GetNodes(); + Ref<FlowGraphNode> GetNode(size_t i); + bool HasNodes() const; + size_t AddNode(FlowGraphNode* node); int GetWidth() const; int GetHeight() const; - std::vector<Ref<FunctionGraphBlock>> GetBlocksInRegion(int left, int top, int right, int bottom); - - bool IsOptionSet(BNDisassemblyOption option) const; - void SetOption(BNDisassemblyOption option, bool state = true); + std::vector<Ref<FlowGraphNode>> GetNodesInRegion(int left, int top, int right, int bottom); bool IsILGraph() const; bool IsLowLevelILGraph() const; bool IsMediumLevelILGraph() const; Ref<LowLevelILFunction> GetLowLevelILFunction() const; Ref<MediumLevelILFunction> GetMediumLevelILFunction() const; + void SetLowLevelILFunction(LowLevelILFunction* func); + void SetMediumLevelILFunction(MediumLevelILFunction* func); + + void Show(const std::string& title); }; struct LowLevelILLabel: public BNLowLevelILLabel @@ -3776,6 +3795,29 @@ namespace BinaryNinja static FormInputField DirectoryName(const std::string& prompt, const std::string& defaultName = ""); }; + class ReportCollection: public CoreRefCountObject<BNReportCollection, + BNNewReportCollectionReference, BNFreeReportCollection> + { + public: + ReportCollection(); + ReportCollection(BNReportCollection* reports); + + size_t GetCount() const; + BNReportType GetType(size_t i) const; + Ref<BinaryView> GetView(size_t i) const; + std::string GetTitle(size_t i) const; + std::string GetContents(size_t i) const; + std::string GetPlainText(size_t i) const; + Ref<FlowGraph> GetFlowGraph(size_t i) const; + + void AddPlainTextReport(Ref<BinaryView> view, const std::string& title, const std::string& contents); + void AddMarkdownReport(Ref<BinaryView> view, const std::string& title, const std::string& contents, + const std::string& plainText = ""); + void AddHTMLReport(Ref<BinaryView> view, const std::string& title, const std::string& contents, + const std::string& plainText = ""); + void AddGraphReport(Ref<BinaryView> view, const std::string& title, Ref<FlowGraph> graph); + }; + class InteractionHandler { public: @@ -3784,6 +3826,8 @@ namespace BinaryNinja const std::string& plainText); virtual void ShowHTMLReport(Ref<BinaryView> view, const std::string& title, const std::string& contents, const std::string& plainText); + virtual void ShowGraphReport(Ref<BinaryView> view, const std::string& title, Ref<FlowGraph> graph); + virtual void ShowReportCollection(const std::string& title, Ref<ReportCollection> reports); virtual bool GetTextLineInput(std::string& result, const std::string& prompt, const std::string& title) = 0; virtual bool GetIntegerInput(int64_t& result, const std::string& prompt, const std::string& title); diff --git a/binaryninjacore.h b/binaryninjacore.h index 216301c0..c057b378 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -120,8 +120,8 @@ extern "C" struct BNArchitecture; struct BNFunction; struct BNBasicBlock; - struct BNFunctionGraph; - struct BNFunctionGraphBlock; + struct BNFlowGraph; + struct BNFlowGraphNode; struct BNSymbol; struct BNTemporaryFile; struct BNLowLevelILFunction; @@ -142,6 +142,7 @@ extern "C" struct BNRepoPlugin; struct BNRepositoryManager; struct BNMetadata; + struct BNReportCollection; typedef bool (*BNLoadPluginCallback)(const char* repoPath, const char* pluginPath, void* ctx); @@ -1193,21 +1194,51 @@ extern "C" float y; }; - struct BNFunctionGraphEdge + struct BNFlowGraphEdge { BNBranchType type; - BNBasicBlock* target; + BNFlowGraphNode* target; BNPoint* points; size_t pointCount; bool backEdge; }; + enum BNHighlightColorStyle + { + StandardHighlightColor = 0, + MixedHighlightColor = 1, + CustomHighlightColor = 2 + }; + + enum BNHighlightStandardColor + { + NoHighlightColor = 0, + BlueHighlightColor = 1, + GreenHighlightColor = 2, + CyanHighlightColor = 3, + RedHighlightColor = 4, + MagentaHighlightColor = 5, + YellowHighlightColor = 6, + OrangeHighlightColor = 7, + WhiteHighlightColor = 8, + BlackHighlightColor = 9 + }; + + struct BNHighlightColor + { + BNHighlightColorStyle style; + BNHighlightStandardColor color; + BNHighlightStandardColor mixColor; + uint8_t mix, r, g, b, alpha; + }; + struct BNDisassemblyTextLine { uint64_t addr; size_t instrIndex; BNInstructionTextToken* tokens; size_t count; + BNHighlightColor highlight; }; struct BNLinearDisassemblyLine @@ -1545,35 +1576,6 @@ extern "C" BNMetadata** values; }; - enum BNHighlightColorStyle - { - StandardHighlightColor = 0, - MixedHighlightColor = 1, - CustomHighlightColor = 2 - }; - - enum BNHighlightStandardColor - { - NoHighlightColor = 0, - BlueHighlightColor = 1, - GreenHighlightColor = 2, - CyanHighlightColor = 3, - RedHighlightColor = 4, - MagentaHighlightColor = 5, - YellowHighlightColor = 6, - OrangeHighlightColor = 7, - WhiteHighlightColor = 8, - BlackHighlightColor = 9 - }; - - struct BNHighlightColor - { - BNHighlightColorStyle style; - BNHighlightStandardColor color; - BNHighlightStandardColor mixColor; - uint8_t mix, r, g, b, alpha; - }; - enum BNMessageBoxIcon { InformationIcon, @@ -1635,6 +1637,8 @@ extern "C" const char* plaintext); void (*showHTMLReport)(void* ctxt, BNBinaryView* view, const char* title, const char* contents, const char* plaintext); + void (*showGraphReport)(void* ctxt, BNBinaryView* view, const char* title, BNFlowGraph* graph); + void (*showReportCollection)(void* ctxt, const char* title, BNReportCollection* reports); bool (*getTextLineInput)(void* ctxt, char** result, const char* prompt, const char* title); bool (*getIntegerInput)(void* ctxt, int64_t* result, const char* prompt, const char* title); bool (*getAddressInput)(void* ctxt, uint64_t* result, const char* prompt, const char* title, @@ -1760,6 +1764,14 @@ extern "C" AlwaysSkipFunctionAnalysis }; + enum BNReportType + { + PlainTextReportType, + MarkdownReportType, + HTMLReportType, + FlowGraphReportType + }; + BINARYNINJACOREAPI char* BNAllocString(const char* contents); BINARYNINJACOREAPI void BNFreeString(char* str); BINARYNINJACOREAPI char** BNAllocStringList(const char** contents, size_t size); @@ -2533,6 +2545,8 @@ extern "C" BINARYNINJACOREAPI BNPerformanceInfo* BNGetFunctionAnalysisPerformanceInfo(BNFunction* func, size_t* count); BINARYNINJACOREAPI void BNFreeAnalysisPerformanceInfo(BNPerformanceInfo* info, size_t count); + BINARYNINJACOREAPI BNFlowGraph* BNGetUnresolvedStackAdjustmentGraph(BNFunction* func); + // Disassembly settings BINARYNINJACOREAPI BNDisassemblySettings* BNCreateDisassemblySettings(void); BINARYNINJACOREAPI BNDisassemblySettings* BNNewDisassemblySettingsReference(BNDisassemblySettings* settings); @@ -2548,56 +2562,61 @@ extern "C" BINARYNINJACOREAPI size_t BNGetDisassemblyMaximumSymbolWidth(BNDisassemblySettings* settings); BINARYNINJACOREAPI void BNSetDisassemblyMaximumSymbolWidth(BNDisassemblySettings* settings, size_t width); - // Function graph - BINARYNINJACOREAPI BNFunctionGraph* BNCreateFunctionGraph(BNFunction* func); - BINARYNINJACOREAPI BNFunctionGraph* BNNewFunctionGraphReference(BNFunctionGraph* graph); - BINARYNINJACOREAPI void BNFreeFunctionGraph(BNFunctionGraph* graph); - BINARYNINJACOREAPI BNFunction* BNGetFunctionForFunctionGraph(BNFunctionGraph* graph); + // Flow graphs + BINARYNINJACOREAPI BNFlowGraph* BNCreateFlowGraph(); + BINARYNINJACOREAPI BNFlowGraph* BNCreateFunctionGraph(BNFunction* func, BNFunctionGraphType type, + BNDisassemblySettings* settings); + BINARYNINJACOREAPI BNFlowGraph* BNNewFlowGraphReference(BNFlowGraph* graph); + BINARYNINJACOREAPI void BNFreeFlowGraph(BNFlowGraph* graph); + BINARYNINJACOREAPI BNFunction* BNGetFunctionForFlowGraph(BNFlowGraph* graph); + BINARYNINJACOREAPI void BNSetFunctionForFlowGraph(BNFlowGraph* graph, BNFunction* func); - BINARYNINJACOREAPI int BNGetHorizontalFunctionGraphBlockMargin(BNFunctionGraph* graph); - BINARYNINJACOREAPI int BNGetVerticalFunctionGraphBlockMargin(BNFunctionGraph* graph); - BINARYNINJACOREAPI void BNSetFunctionGraphBlockMargins(BNFunctionGraph* graph, int horiz, int vert); + BINARYNINJACOREAPI int BNGetHorizontalFlowGraphNodeMargin(BNFlowGraph* graph); + BINARYNINJACOREAPI int BNGetVerticalFlowGraphNodeMargin(BNFlowGraph* graph); + BINARYNINJACOREAPI void BNSetFlowGraphNodeMargins(BNFlowGraph* graph, int horiz, int vert); - BINARYNINJACOREAPI BNDisassemblySettings* BNGetFunctionGraphSettings(BNFunctionGraph* graph); + BINARYNINJACOREAPI void BNStartFlowGraphLayout(BNFlowGraph* graph); + BINARYNINJACOREAPI bool BNIsFlowGraphLayoutComplete(BNFlowGraph* graph); + BINARYNINJACOREAPI void BNSetFlowGraphCompleteCallback(BNFlowGraph* graph, void* ctxt, void (*func)(void* ctxt)); + BINARYNINJACOREAPI void BNAbortFlowGraph(BNFlowGraph* graph); + BINARYNINJACOREAPI bool BNIsILFlowGraph(BNFlowGraph* graph); + BINARYNINJACOREAPI bool BNIsLowLevelILFlowGraph(BNFlowGraph* graph); + BINARYNINJACOREAPI bool BNIsMediumLevelILFlowGraph(BNFlowGraph* graph); + BINARYNINJACOREAPI BNLowLevelILFunction* BNGetFlowGraphLowLevelILFunction(BNFlowGraph* graph); + BINARYNINJACOREAPI BNMediumLevelILFunction* BNGetFlowGraphMediumLevelILFunction(BNFlowGraph* graph); + BINARYNINJACOREAPI void BNSetFlowGraphLowLevelILFunction(BNFlowGraph* graph, BNLowLevelILFunction* func); + BINARYNINJACOREAPI void BNSetFlowGraphMediumLevelILFunction(BNFlowGraph* graph, BNMediumLevelILFunction* func); - BINARYNINJACOREAPI void BNStartFunctionGraphLayout(BNFunctionGraph* graph, BNFunctionGraphType type); - BINARYNINJACOREAPI bool BNIsFunctionGraphLayoutComplete(BNFunctionGraph* graph); - BINARYNINJACOREAPI void BNSetFunctionGraphCompleteCallback(BNFunctionGraph* graph, void* ctxt, void (*func)(void* ctxt)); - BINARYNINJACOREAPI void BNAbortFunctionGraph(BNFunctionGraph* graph); - BINARYNINJACOREAPI BNFunctionGraphType BNGetFunctionGraphType(BNFunctionGraph* graph); - BINARYNINJACOREAPI bool BNIsILFunctionGraph(BNFunctionGraph* graph); - BINARYNINJACOREAPI bool BNIsLowLevelILFunctionGraph(BNFunctionGraph* graph); - BINARYNINJACOREAPI bool BNIsMediumLevelILFunctionGraph(BNFunctionGraph* graph); - BINARYNINJACOREAPI BNLowLevelILFunction* BNGetFunctionGraphLowLevelILFunction(BNFunctionGraph* graph); - BINARYNINJACOREAPI BNMediumLevelILFunction* BNGetFunctionGraphMediumLevelILFunction(BNFunctionGraph* graph); + BINARYNINJACOREAPI BNFlowGraphNode** BNGetFlowGraphNodes(BNFlowGraph* graph, size_t* count); + BINARYNINJACOREAPI BNFlowGraphNode* BNGetFlowGraphNode(BNFlowGraph* graph, size_t i); + BINARYNINJACOREAPI BNFlowGraphNode** BNGetFlowGraphNodesInRegion( + BNFlowGraph* graph, int left, int top, int right, int bottom, size_t* count); + BINARYNINJACOREAPI void BNFreeFlowGraphNodeList(BNFlowGraphNode** nodes, size_t count); + BINARYNINJACOREAPI bool BNFlowGraphHasNodes(BNFlowGraph* graph); + BINARYNINJACOREAPI size_t BNAddFlowGraphNode(BNFlowGraph* graph, BNFlowGraphNode* node); - BINARYNINJACOREAPI BNFunctionGraphBlock** BNGetFunctionGraphBlocks(BNFunctionGraph* graph, size_t* count); - BINARYNINJACOREAPI BNFunctionGraphBlock** BNGetFunctionGraphBlocksInRegion( - BNFunctionGraph* graph, int left, int top, int right, int bottom, size_t* count); - BINARYNINJACOREAPI void BNFreeFunctionGraphBlockList(BNFunctionGraphBlock** blocks, size_t count); - BINARYNINJACOREAPI bool BNFunctionGraphHasBlocks(BNFunctionGraph* graph); + BINARYNINJACOREAPI int BNGetFlowGraphWidth(BNFlowGraph* graph); + BINARYNINJACOREAPI int BNGetFlowGraphHeight(BNFlowGraph* graph); - BINARYNINJACOREAPI int BNGetFunctionGraphWidth(BNFunctionGraph* graph); - BINARYNINJACOREAPI int BNGetFunctionGraphHeight(BNFunctionGraph* graph); + BINARYNINJACOREAPI BNFlowGraphNode* BNCreateFlowGraphNode(BNFlowGraph* graph); + BINARYNINJACOREAPI BNFlowGraphNode* BNNewFlowGraphNodeReference(BNFlowGraphNode* node); + BINARYNINJACOREAPI void BNFreeFlowGraphNode(BNFlowGraphNode* node); - BINARYNINJACOREAPI bool BNIsFunctionGraphOptionSet(BNFunctionGraph* graph, BNDisassemblyOption option); - BINARYNINJACOREAPI void BNSetFunctionGraphOption(BNFunctionGraph* graph, BNDisassemblyOption option, bool state); + BINARYNINJACOREAPI BNBasicBlock* BNGetFlowGraphBasicBlock(BNFlowGraphNode* node); + BINARYNINJACOREAPI void BNSetFlowGraphBasicBlock(BNFlowGraphNode* node, BNBasicBlock* block); + BINARYNINJACOREAPI int BNGetFlowGraphNodeX(BNFlowGraphNode* node); + BINARYNINJACOREAPI int BNGetFlowGraphNodeY(BNFlowGraphNode* node); + BINARYNINJACOREAPI int BNGetFlowGraphNodeWidth(BNFlowGraphNode* node); + BINARYNINJACOREAPI int BNGetFlowGraphNodeHeight(BNFlowGraphNode* node); - BINARYNINJACOREAPI BNFunctionGraphBlock* BNNewFunctionGraphBlockReference(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI void BNFreeFunctionGraphBlock(BNFunctionGraphBlock* block); + BINARYNINJACOREAPI BNDisassemblyTextLine* BNGetFlowGraphNodeLines(BNFlowGraphNode* node, size_t* count); + BINARYNINJACOREAPI void BNSetFlowGraphNodeLines(BNFlowGraphNode* node, BNDisassemblyTextLine* lines, size_t count); + BINARYNINJACOREAPI BNFlowGraphEdge* BNGetFlowGraphNodeOutgoingEdges(BNFlowGraphNode* node, size_t* count); + BINARYNINJACOREAPI void BNFreeFlowGraphNodeOutgoingEdgeList(BNFlowGraphEdge* edges, size_t count); + BINARYNINJACOREAPI void BNAddFlowGraphNodeOutgoingEdge(BNFlowGraphNode* node, BNBranchType type, BNFlowGraphNode* target); - BINARYNINJACOREAPI BNBasicBlock* BNGetFunctionGraphBasicBlock(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI BNArchitecture* BNGetFunctionGraphBlockArchitecture(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI uint64_t BNGetFunctionGraphBlockStart(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI uint64_t BNGetFunctionGraphBlockEnd(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI int BNGetFunctionGraphBlockX(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI int BNGetFunctionGraphBlockY(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI int BNGetFunctionGraphBlockWidth(BNFunctionGraphBlock* block); - BINARYNINJACOREAPI int BNGetFunctionGraphBlockHeight(BNFunctionGraphBlock* block); - - BINARYNINJACOREAPI BNDisassemblyTextLine* BNGetFunctionGraphBlockLines(BNFunctionGraphBlock* block, size_t* count); - BINARYNINJACOREAPI BNFunctionGraphEdge* BNGetFunctionGraphBlockOutgoingEdges(BNFunctionGraphBlock* block, size_t* count); - BINARYNINJACOREAPI void BNFreeFunctionGraphBlockOutgoingEdgeList(BNFunctionGraphEdge* edges, size_t count); + BINARYNINJACOREAPI BNHighlightColor BNGetFlowGraphNodeHighlight(BNFlowGraphNode* node); + BINARYNINJACOREAPI void BNSetFlowGraphNodeHighlight(BNFlowGraphNode* node, BNHighlightColor color); // Symbols BINARYNINJACOREAPI BNSymbol* BNCreateSymbol(BNSymbolType type, const char* shortName, const char* fullName, @@ -3265,6 +3284,8 @@ extern "C" const char* plaintext); BINARYNINJACOREAPI void BNShowHTMLReport(BNBinaryView* view, const char* title, const char* contents, const char* plaintext); + BINARYNINJACOREAPI void BNShowGraphReport(BNBinaryView* view, const char* title, BNFlowGraph* graph); + BINARYNINJACOREAPI void BNShowReportCollection(const char* title, BNReportCollection* reports); BINARYNINJACOREAPI bool BNGetTextLineInput(char** result, const char* prompt, const char* title); BINARYNINJACOREAPI bool BNGetIntegerInput(int64_t* result, const char* prompt, const char* title); BINARYNINJACOREAPI bool BNGetAddressInput(uint64_t* result, const char* prompt, const char* title, @@ -3280,6 +3301,25 @@ extern "C" BINARYNINJACOREAPI BNMessageBoxButtonResult BNShowMessageBox(const char* title, const char* text, BNMessageBoxButtonSet buttons, BNMessageBoxIcon icon); + BINARYNINJACOREAPI BNReportCollection* BNCreateReportCollection(void); + BINARYNINJACOREAPI BNReportCollection* BNNewReportCollectionReference(BNReportCollection* reports); + BINARYNINJACOREAPI void BNFreeReportCollection(BNReportCollection* reports); + BINARYNINJACOREAPI size_t BNGetReportCollectionCount(BNReportCollection* reports); + BINARYNINJACOREAPI BNReportType BNGetReportType(BNReportCollection* reports, size_t i); + BINARYNINJACOREAPI BNBinaryView* BNGetReportView(BNReportCollection* reports, size_t i); + BINARYNINJACOREAPI char* BNGetReportTitle(BNReportCollection* reports, size_t i); + BINARYNINJACOREAPI char* BNGetReportContents(BNReportCollection* reports, size_t i); + BINARYNINJACOREAPI char* BNGetReportPlainText(BNReportCollection* reports, size_t i); + BINARYNINJACOREAPI BNFlowGraph* BNGetReportFlowGraph(BNReportCollection* reports, size_t i); + BINARYNINJACOREAPI void BNAddPlainTextReportToCollection(BNReportCollection* reports, BNBinaryView* view, + const char* title, const char* contents); + BINARYNINJACOREAPI void BNAddMarkdownReportToCollection(BNReportCollection* reports, BNBinaryView* view, + const char* title, const char* contents, const char* plaintext); + BINARYNINJACOREAPI void BNAddHTMLReportToCollection(BNReportCollection* reports, BNBinaryView* view, + const char* title, const char* contents, const char* plaintext); + BINARYNINJACOREAPI void BNAddGraphReportToCollection(BNReportCollection* reports, BNBinaryView* view, + const char* title, BNFlowGraph* graph); + BINARYNINJACOREAPI bool BNDemangleGNU3(BNArchitecture* arch, const char* mangledName, BNType** outType, diff --git a/binaryview.cpp b/binaryview.cpp index 0a9a7118..18dd1bef 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -1460,6 +1460,7 @@ vector<LinearDisassemblyLine> BinaryView::GetPreviousLinearDisassemblyLines(Line line.lineOffset = lines[i].lineOffset; line.contents.addr = lines[i].contents.addr; line.contents.instrIndex = lines[i].contents.instrIndex; + line.contents.highlight = lines[i].contents.highlight; line.contents.tokens.reserve(lines[i].contents.count); for (size_t j = 0; j < lines[i].contents.count; j++) { @@ -1509,6 +1510,7 @@ vector<LinearDisassemblyLine> BinaryView::GetNextLinearDisassemblyLines(LinearDi line.lineOffset = lines[i].lineOffset; line.contents.addr = lines[i].contents.addr; line.contents.instrIndex = lines[i].contents.instrIndex; + line.contents.highlight = lines[i].contents.highlight; line.contents.tokens.reserve(lines[i].contents.count); for (size_t j = 0; j < lines[i].contents.count; j++) { @@ -1701,6 +1703,12 @@ void BinaryView::ShowHTMLReport(const string& title, const string& contents, con } +void BinaryView::ShowGraphReport(const string& title, FlowGraph* graph) +{ + BNShowGraphReport(m_object, title.c_str(), graph->GetGraphObject()); +} + + bool BinaryView::GetAddressInput(uint64_t& result, const string& prompt, const string& title) { uint64_t currentAddress = 0; diff --git a/flowgraph.cpp b/flowgraph.cpp new file mode 100644 index 00000000..e557f540 --- /dev/null +++ b/flowgraph.cpp @@ -0,0 +1,261 @@ +// Copyright (c) 2015-2017 Vector 35 LLC +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#include "binaryninjaapi.h" + +using namespace BinaryNinja; +using namespace std; + + +FlowGraph::FlowGraph(BNFlowGraph* graph): m_graph(graph) +{ +} + + +FlowGraph::~FlowGraph() +{ + // This object is going away, so ensure that any pending completion routines are + // no longer called + Abort(); + + BNFreeFlowGraph(m_graph); +} + + +void FlowGraph::CompleteCallback(void* ctxt) +{ + FlowGraph* graph = (FlowGraph*)ctxt; + graph->m_completeFunc(); +} + + +Ref<Function> FlowGraph::GetFunction() const +{ + BNFunction* func = BNGetFunctionForFlowGraph(m_graph); + if (!func) + return nullptr; + return new Function(BNNewFunctionReference(func)); +} + + +void FlowGraph::SetFunction(Function* func) +{ + BNSetFunctionForFlowGraph(m_graph, func ? func->GetObject() : nullptr); +} + + +int FlowGraph::GetHorizontalNodeMargin() const +{ + return BNGetHorizontalFlowGraphNodeMargin(m_graph); +} + + +int FlowGraph::GetVerticalNodeMargin() const +{ + return BNGetVerticalFlowGraphNodeMargin(m_graph); +} + + +void FlowGraph::SetNodeMargins(int horiz, int vert) +{ + BNSetFlowGraphNodeMargins(m_graph, horiz, vert); +} + + +void FlowGraph::StartLayout() +{ + BNStartFlowGraphLayout(m_graph); +} + + +bool FlowGraph::IsLayoutComplete() +{ + return BNIsFlowGraphLayoutComplete(m_graph); +} + + +void FlowGraph::OnComplete(const std::function<void()>& func) +{ + m_completeFunc = func; + BNSetFlowGraphCompleteCallback(m_graph, this, CompleteCallback); +} + + +void FlowGraph::Abort() +{ + // Must clear the callback with the core before clearing our own function object, as until it + // is cleared in the core it can be called at any time from a different thread. + BNAbortFlowGraph(m_graph); + m_completeFunc = []() {}; +} + + +vector<Ref<FlowGraphNode>> FlowGraph::GetNodes() +{ + size_t count; + BNFlowGraphNode** nodes = BNGetFlowGraphNodes(m_graph, &count); + + vector<Ref<FlowGraphNode>> result; + result.reserve(count); + for (size_t i = 0; i < count; i++) + { + auto node = m_cachedNodes.find(nodes[i]); + if (node == m_cachedNodes.end()) + { + FlowGraphNode* newNode = new FlowGraphNode(BNNewFlowGraphNodeReference(nodes[i])); + m_cachedNodes[nodes[i]] = newNode; + result.push_back(newNode); + } + else + { + result.push_back(node->second); + } + } + + BNFreeFlowGraphNodeList(nodes, count); + return result; +} + + +Ref<FlowGraphNode> FlowGraph::GetNode(size_t i) +{ + BNFlowGraphNode* node = BNGetFlowGraphNode(m_graph, i); + if (!node) + return nullptr; + + auto nodeIter = m_cachedNodes.find(node); + if (nodeIter == m_cachedNodes.end()) + { + FlowGraphNode* newNode = new FlowGraphNode(node); + m_cachedNodes[node] = newNode; + return newNode; + } + else + { + BNFreeFlowGraphNode(node); + return nodeIter->second; + } +} + + +bool FlowGraph::HasNodes() const +{ + return BNFlowGraphHasNodes(m_graph); +} + + +size_t FlowGraph::AddNode(FlowGraphNode* node) +{ + m_cachedNodes[node->GetObject()] = node; + return BNAddFlowGraphNode(m_graph, node->GetObject()); +} + + +int FlowGraph::GetWidth() const +{ + return BNGetFlowGraphWidth(m_graph); +} + + +int FlowGraph::GetHeight() const +{ + return BNGetFlowGraphHeight(m_graph); +} + + +vector<Ref<FlowGraphNode>> FlowGraph::GetNodesInRegion(int left, int top, int right, int bottom) +{ + size_t count; + BNFlowGraphNode** nodes = BNGetFlowGraphNodesInRegion(m_graph, left, top, right, bottom, &count); + + vector<Ref<FlowGraphNode>> result; + result.reserve(count); + for (size_t i = 0; i < count; i++) + { + auto node = m_cachedNodes.find(nodes[i]); + if (node == m_cachedNodes.end()) + { + FlowGraphNode* newNode = new FlowGraphNode(BNNewFlowGraphNodeReference(nodes[i])); + m_cachedNodes[nodes[i]] = newNode; + result.push_back(newNode); + } + else + { + result.push_back(node->second); + } + } + + BNFreeFlowGraphNodeList(nodes, count); + return result; +} + + +bool FlowGraph::IsILGraph() const +{ + return BNIsILFlowGraph(m_graph); +} + + +bool FlowGraph::IsLowLevelILGraph() const +{ + return BNIsLowLevelILFlowGraph(m_graph); +} + + +bool FlowGraph::IsMediumLevelILGraph() const +{ + return BNIsMediumLevelILFlowGraph(m_graph); +} + + +Ref<LowLevelILFunction> FlowGraph::GetLowLevelILFunction() const +{ + BNLowLevelILFunction* func = BNGetFlowGraphLowLevelILFunction(m_graph); + if (!func) + return nullptr; + return new LowLevelILFunction(func); +} + + +Ref<MediumLevelILFunction> FlowGraph::GetMediumLevelILFunction() const +{ + BNMediumLevelILFunction* func = BNGetFlowGraphMediumLevelILFunction(m_graph); + if (!func) + return nullptr; + return new MediumLevelILFunction(func); +} + + +void FlowGraph::SetLowLevelILFunction(LowLevelILFunction* func) +{ + BNSetFlowGraphLowLevelILFunction(m_graph, func ? func->GetObject() : nullptr); +} + + +void FlowGraph::SetMediumLevelILFunction(MediumLevelILFunction* func) +{ + BNSetFlowGraphMediumLevelILFunction(m_graph, func ? func->GetObject() : nullptr); +} + + +void FlowGraph::Show(const string& title) +{ + ShowGraphReport(title, this); +} diff --git a/flowgraphnode.cpp b/flowgraphnode.cpp new file mode 100644 index 00000000..a49cb0d0 --- /dev/null +++ b/flowgraphnode.cpp @@ -0,0 +1,203 @@ +// Copyright (c) 2015-2017 Vector 35 LLC +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +#include "binaryninjaapi.h" + +using namespace BinaryNinja; +using namespace std; + + +FlowGraphNode::FlowGraphNode(FlowGraph* graph) +{ + m_object = BNCreateFlowGraphNode(graph->GetGraphObject()); + m_cachedLinesValid = false; + m_cachedEdgesValid = false; +} + + +FlowGraphNode::FlowGraphNode(BNFlowGraphNode* node) +{ + m_object = node; + m_cachedLinesValid = false; + m_cachedEdgesValid = false; +} + + +Ref<BasicBlock> FlowGraphNode::GetBasicBlock() const +{ + return new BasicBlock(BNGetFlowGraphBasicBlock(m_object)); +} + + +void FlowGraphNode::SetBasicBlock(BasicBlock* block) +{ + BNSetFlowGraphBasicBlock(m_object, block ? block->GetObject() : nullptr); +} + + +int FlowGraphNode::GetX() const +{ + return BNGetFlowGraphNodeX(m_object); +} + + +int FlowGraphNode::GetY() const +{ + return BNGetFlowGraphNodeY(m_object); +} + + +int FlowGraphNode::GetWidth() const +{ + return BNGetFlowGraphNodeWidth(m_object); +} + + +int FlowGraphNode::GetHeight() const +{ + return BNGetFlowGraphNodeHeight(m_object); +} + + +const vector<DisassemblyTextLine>& FlowGraphNode::GetLines() +{ + if (m_cachedLinesValid) + return m_cachedLines; + + size_t count; + BNDisassemblyTextLine* lines = BNGetFlowGraphNodeLines(m_object, &count); + + vector<DisassemblyTextLine> result; + result.reserve(count); + for (size_t i = 0; i < count; i++) + { + DisassemblyTextLine line; + line.addr = lines[i].addr; + line.instrIndex = lines[i].instrIndex; + line.highlight = lines[i].highlight; + line.tokens.reserve(lines[i].count); + for (size_t j = 0; j < lines[i].count; j++) + { + InstructionTextToken token; + token.type = lines[i].tokens[j].type; + token.text = lines[i].tokens[j].text; + token.value = lines[i].tokens[j].value; + token.size = lines[i].tokens[j].size; + token.operand = lines[i].tokens[j].operand; + token.context = lines[i].tokens[j].context; + token.confidence = lines[i].tokens[j].confidence; + token.address = lines[i].tokens[j].address; + line.tokens.push_back(token); + } + result.push_back(line); + } + + BNFreeDisassemblyTextLines(lines, count); + m_cachedLines = result; + m_cachedLinesValid = true; + return m_cachedLines; +} + + +void FlowGraphNode::SetLines(const vector<DisassemblyTextLine>& lines) +{ + BNDisassemblyTextLine* buf = new BNDisassemblyTextLine[lines.size()]; + for (size_t i = 0; i < lines.size(); i++) + { + const DisassemblyTextLine& line = lines[i]; + buf[i].addr = line.addr; + buf[i].instrIndex = line.instrIndex; + buf[i].highlight = line.highlight; + buf[i].tokens = new BNInstructionTextToken[line.tokens.size()]; + buf[i].count = line.tokens.size(); + for (size_t j = 0; j < line.tokens.size(); j++) + { + const InstructionTextToken& token = line.tokens[j]; + buf[i].tokens[j].type = token.type; + buf[i].tokens[j].text = BNAllocString(token.text.c_str()); + buf[i].tokens[j].value = token.value; + buf[i].tokens[j].size = token.size; + buf[i].tokens[j].operand = token.operand; + buf[i].tokens[j].context = token.context; + buf[i].tokens[j].confidence = token.confidence; + buf[i].tokens[j].address = token.address; + } + } + + BNSetFlowGraphNodeLines(m_object, buf, lines.size()); + + for (size_t i = 0; i < lines.size(); i++) + { + for (size_t j = 0; j < buf[i].count; j++) + BNFreeString(buf[i].tokens[j].text); + delete[] buf[i].tokens; + } + delete[] buf; + + m_cachedLines = lines; + m_cachedLinesValid = true; +} + + +const vector<FlowGraphEdge>& FlowGraphNode::GetOutgoingEdges() +{ + if (m_cachedEdgesValid) + return m_cachedEdges; + + size_t count; + BNFlowGraphEdge* edges = BNGetFlowGraphNodeOutgoingEdges(m_object, &count); + + vector<FlowGraphEdge> result; + result.reserve(count); + for (size_t i = 0; i < count; i++) + { + FlowGraphEdge edge; + edge.type = edges[i].type; + edge.target = edges[i].target ? new FlowGraphNode(BNNewFlowGraphNodeReference(edges[i].target)) : nullptr; + edge.points.insert(edge.points.begin(), &edges[i].points[0], &edges[i].points[edges[i].pointCount]); + edge.backEdge = edges[i].backEdge; + result.push_back(edge); + } + + BNFreeFlowGraphNodeOutgoingEdgeList(edges, count); + m_cachedEdges = result; + m_cachedEdgesValid = true; + return m_cachedEdges; +} + + +void FlowGraphNode::AddOutgoingEdge(BNBranchType type, FlowGraphNode* target) +{ + BNAddFlowGraphNodeOutgoingEdge(m_object, type, target->GetObject()); + m_cachedEdges.clear(); + m_cachedEdgesValid = false; +} + + +BNHighlightColor FlowGraphNode::GetHighlight() const +{ + return BNGetFlowGraphNodeHighlight(m_object); +} + + +void FlowGraphNode::SetHighlight(const BNHighlightColor& color) +{ + BNSetFlowGraphNodeHighlight(m_object, color); +} diff --git a/function.cpp b/function.cpp index 835ab144..62a8e1b0 100644 --- a/function.cpp +++ b/function.cpp @@ -119,6 +119,12 @@ Function::~Function() } +Ref<BinaryView> Function::GetView() const +{ + return new BinaryView(BNGetFunctionData(m_object)); +} + + Ref<Platform> Function::GetPlatform() const { return new Platform(BNGetFunctionPlatform(m_object)); @@ -802,10 +808,10 @@ void Function::ApplyAutoDiscoveredType(Type* type) } -Ref<FunctionGraph> Function::CreateFunctionGraph() +Ref<FlowGraph> Function::CreateFunctionGraph(BNFunctionGraphType type, DisassemblySettings* settings) { - BNFunctionGraph* graph = BNCreateFunctionGraph(m_object); - return new FunctionGraph(graph); + BNFlowGraph* graph = BNCreateFunctionGraph(m_object, type, settings ? settings->GetObject() : nullptr); + return new FlowGraph(graph); } @@ -1338,6 +1344,7 @@ vector<DisassemblyTextLine> Function::GetTypeTokens(DisassemblySettings* setting DisassemblyTextLine line; line.addr = lines[i].addr; line.instrIndex = lines[i].instrIndex; + line.highlight = lines[i].highlight; line.tokens.reserve(lines[i].count); for (size_t j = 0; j < lines[i].count; j++) { @@ -1384,6 +1391,15 @@ void Function::SetAnalysisSkipOverride(BNFunctionAnalysisSkipOverride skip) } +Ref<FlowGraph> Function::GetUnresolvedStackAdjustmentGraph() +{ + BNFlowGraph* graph = BNGetUnresolvedStackAdjustmentGraph(m_object); + if (!graph) + return nullptr; + return new FlowGraph(graph); +} + + AdvancedFunctionAnalysisDataRequestor::AdvancedFunctionAnalysisDataRequestor(Function* func): m_func(func) { if (m_func) diff --git a/functiongraph.cpp b/functiongraph.cpp deleted file mode 100644 index 9948d70e..00000000 --- a/functiongraph.cpp +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (c) 2015-2017 Vector 35 LLC -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -// IN THE SOFTWARE. - -#include "binaryninjaapi.h" - -using namespace BinaryNinja; -using namespace std; - - -FunctionGraph::FunctionGraph(BNFunctionGraph* graph): m_graph(graph) -{ -} - - -FunctionGraph::~FunctionGraph() -{ - // This object is going away, so ensure that any pending completion routines are - // no longer called - Abort(); - - BNFreeFunctionGraph(m_graph); -} - - -void FunctionGraph::CompleteCallback(void* ctxt) -{ - FunctionGraph* graph = (FunctionGraph*)ctxt; - graph->m_completeFunc(); -} - - -Ref<Function> FunctionGraph::GetFunction() const -{ - return new Function(BNNewFunctionReference(BNGetFunctionForFunctionGraph(m_graph))); -} - - -int FunctionGraph::GetHorizontalBlockMargin() const -{ - return BNGetHorizontalFunctionGraphBlockMargin(m_graph); -} - - -int FunctionGraph::GetVerticalBlockMargin() const -{ - return BNGetVerticalFunctionGraphBlockMargin(m_graph); -} - - -void FunctionGraph::SetBlockMargins(int horiz, int vert) -{ - BNSetFunctionGraphBlockMargins(m_graph, horiz, vert); -} - - -Ref<DisassemblySettings> FunctionGraph::GetSettings() -{ - return new DisassemblySettings(BNGetFunctionGraphSettings(m_graph)); -} - - -void FunctionGraph::StartLayout(BNFunctionGraphType type) -{ - BNStartFunctionGraphLayout(m_graph, type); -} - - -bool FunctionGraph::IsLayoutComplete() -{ - return BNIsFunctionGraphLayoutComplete(m_graph); -} - - -void FunctionGraph::OnComplete(const std::function<void()>& func) -{ - m_completeFunc = func; - BNSetFunctionGraphCompleteCallback(m_graph, this, CompleteCallback); -} - - -void FunctionGraph::Abort() -{ - // Must clear the callback with the core before clearing our own function object, as until it - // is cleared in the core it can be called at any time from a different thread. - BNAbortFunctionGraph(m_graph); - m_completeFunc = []() {}; -} - - -vector<Ref<FunctionGraphBlock>> FunctionGraph::GetBlocks() -{ - size_t count; - BNFunctionGraphBlock** blocks = BNGetFunctionGraphBlocks(m_graph, &count); - - vector<Ref<FunctionGraphBlock>> result; - result.reserve(count); - for (size_t i = 0; i < count; i++) - { - auto block = m_cachedBlocks.find(blocks[i]); - if (block == m_cachedBlocks.end()) - { - FunctionGraphBlock* newBlock = new FunctionGraphBlock(BNNewFunctionGraphBlockReference(blocks[i])); - m_cachedBlocks[blocks[i]] = newBlock; - result.push_back(newBlock); - } - else - { - result.push_back(block->second); - } - } - - BNFreeFunctionGraphBlockList(blocks, count); - return result; -} - - -bool FunctionGraph::HasBlocks() const -{ - return BNFunctionGraphHasBlocks(m_graph); -} - - -int FunctionGraph::GetWidth() const -{ - return BNGetFunctionGraphWidth(m_graph); -} - - -int FunctionGraph::GetHeight() const -{ - return BNGetFunctionGraphHeight(m_graph); -} - - -vector<Ref<FunctionGraphBlock>> FunctionGraph::GetBlocksInRegion(int left, int top, int right, int bottom) -{ - size_t count; - BNFunctionGraphBlock** blocks = BNGetFunctionGraphBlocksInRegion(m_graph, left, top, right, bottom, &count); - - vector<Ref<FunctionGraphBlock>> result; - result.reserve(count); - for (size_t i = 0; i < count; i++) - { - auto block = m_cachedBlocks.find(blocks[i]); - if (block == m_cachedBlocks.end()) - { - FunctionGraphBlock* newBlock = new FunctionGraphBlock(BNNewFunctionGraphBlockReference(blocks[i])); - m_cachedBlocks[blocks[i]] = newBlock; - result.push_back(newBlock); - } - else - { - result.push_back(block->second); - } - } - - BNFreeFunctionGraphBlockList(blocks, count); - return result; -} - - -bool FunctionGraph::IsOptionSet(BNDisassemblyOption option) const -{ - return BNIsFunctionGraphOptionSet(m_graph, option); -} - - -void FunctionGraph::SetOption(BNDisassemblyOption option, bool state) -{ - BNSetFunctionGraphOption(m_graph, option, state); -} - - -bool FunctionGraph::IsILGraph() const -{ - return BNIsILFunctionGraph(m_graph); -} - - -bool FunctionGraph::IsLowLevelILGraph() const -{ - return BNIsLowLevelILFunctionGraph(m_graph); -} - - -bool FunctionGraph::IsMediumLevelILGraph() const -{ - return BNIsMediumLevelILFunctionGraph(m_graph); -} - - -Ref<LowLevelILFunction> FunctionGraph::GetLowLevelILFunction() const -{ - BNLowLevelILFunction* func = BNGetFunctionGraphLowLevelILFunction(m_graph); - if (!func) - return nullptr; - return new LowLevelILFunction(func); -} - - -Ref<MediumLevelILFunction> FunctionGraph::GetMediumLevelILFunction() const -{ - BNMediumLevelILFunction* func = BNGetFunctionGraphMediumLevelILFunction(m_graph); - if (!func) - return nullptr; - return new MediumLevelILFunction(func); -} diff --git a/functiongraphblock.cpp b/functiongraphblock.cpp deleted file mode 100644 index 469fb175..00000000 --- a/functiongraphblock.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2015-2017 Vector 35 LLC -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -// IN THE SOFTWARE. - -#include "binaryninjaapi.h" - -using namespace BinaryNinja; -using namespace std; - - -FunctionGraphBlock::FunctionGraphBlock(BNFunctionGraphBlock* block) -{ - m_object = block; - m_cachedLinesValid = false; - m_cachedEdgesValid = false; -} - - -Ref<BasicBlock> FunctionGraphBlock::GetBasicBlock() const -{ - return new BasicBlock(BNGetFunctionGraphBasicBlock(m_object)); -} - - -Ref<Architecture> FunctionGraphBlock::GetArchitecture() const -{ - return new CoreArchitecture(BNGetFunctionGraphBlockArchitecture(m_object)); -} - - -uint64_t FunctionGraphBlock::GetStart() const -{ - return BNGetFunctionGraphBlockStart(m_object); -} - - -uint64_t FunctionGraphBlock::GetEnd() const -{ - return BNGetFunctionGraphBlockEnd(m_object); -} - - -int FunctionGraphBlock::GetX() const -{ - return BNGetFunctionGraphBlockX(m_object); -} - - -int FunctionGraphBlock::GetY() const -{ - return BNGetFunctionGraphBlockY(m_object); -} - - -int FunctionGraphBlock::GetWidth() const -{ - return BNGetFunctionGraphBlockWidth(m_object); -} - - -int FunctionGraphBlock::GetHeight() const -{ - return BNGetFunctionGraphBlockHeight(m_object); -} - - -const vector<DisassemblyTextLine>& FunctionGraphBlock::GetLines() -{ - if (m_cachedLinesValid) - return m_cachedLines; - - size_t count; - BNDisassemblyTextLine* lines = BNGetFunctionGraphBlockLines(m_object, &count); - - vector<DisassemblyTextLine> result; - result.reserve(count); - for (size_t i = 0; i < count; i++) - { - DisassemblyTextLine line; - line.addr = lines[i].addr; - line.instrIndex = lines[i].instrIndex; - line.tokens.reserve(lines[i].count); - for (size_t j = 0; j < lines[i].count; j++) - { - InstructionTextToken token; - token.type = lines[i].tokens[j].type; - token.text = lines[i].tokens[j].text; - token.value = lines[i].tokens[j].value; - token.size = lines[i].tokens[j].size; - token.operand = lines[i].tokens[j].operand; - token.context = lines[i].tokens[j].context; - token.confidence = lines[i].tokens[j].confidence; - token.address = lines[i].tokens[j].address; - line.tokens.push_back(token); - } - result.push_back(line); - } - - BNFreeDisassemblyTextLines(lines, count); - m_cachedLines = result; - m_cachedLinesValid = true; - return m_cachedLines; -} - - -const vector<FunctionGraphEdge>& FunctionGraphBlock::GetOutgoingEdges() -{ - if (m_cachedEdgesValid) - return m_cachedEdges; - - size_t count; - BNFunctionGraphEdge* edges = BNGetFunctionGraphBlockOutgoingEdges(m_object, &count); - - vector<FunctionGraphEdge> result; - result.reserve(count); - for (size_t i = 0; i < count; i++) - { - FunctionGraphEdge edge; - edge.type = edges[i].type; - edge.target = edges[i].target ? new BasicBlock(BNNewBasicBlockReference(edges[i].target)) : nullptr; - edge.points.insert(edge.points.begin(), &edges[i].points[0], &edges[i].points[edges[i].pointCount]); - edge.backEdge = edges[i].backEdge; - result.push_back(edge); - } - - BNFreeFunctionGraphBlockOutgoingEdgeList(edges, count); - m_cachedEdges = result; - m_cachedEdgesValid = true; - return m_cachedEdges; -} diff --git a/interaction.cpp b/interaction.cpp index 2f84c4ec..61c9dfb3 100644 --- a/interaction.cpp +++ b/interaction.cpp @@ -117,6 +117,16 @@ void InteractionHandler::ShowHTMLReport(Ref<BinaryView> view, const string& titl } +void InteractionHandler::ShowGraphReport(Ref<BinaryView>, const std::string&, Ref<FlowGraph>) +{ +} + + +void InteractionHandler::ShowReportCollection(const string&, Ref<ReportCollection>) +{ +} + + bool InteractionHandler::GetIntegerInput(int64_t& result, const string& prompt, const string& title) { while (true) @@ -194,6 +204,21 @@ static void ShowHTMLReportCallback(void* ctxt, BNBinaryView* view, const char* t } +static void ShowGraphReportCallback(void* ctxt, BNBinaryView* view, const char* title, BNFlowGraph* graph) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + handler->ShowGraphReport(view ? new BinaryView(BNNewViewReference(view)) : nullptr, title, + new FlowGraph(BNNewFlowGraphReference(graph))); +} + + +static void ShowReportCollectionCallback(void* ctxt, const char* title, BNReportCollection* reports) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + handler->ShowReportCollection(title, new ReportCollection(reports)); +} + + static bool GetTextLineInputCallback(void* ctxt, char** result, const char* prompt, const char* title) { InteractionHandler* handler = (InteractionHandler*)ctxt; @@ -360,6 +385,8 @@ void BinaryNinja::RegisterInteractionHandler(InteractionHandler* handler) cb.showPlainTextReport = ShowPlainTextReportCallback; cb.showMarkdownReport = ShowMarkdownReportCallback; cb.showHTMLReport = ShowHTMLReportCallback; + cb.showGraphReport = ShowGraphReportCallback; + cb.showReportCollection = ShowReportCollectionCallback; cb.getTextLineInput = GetTextLineInputCallback; cb.getIntegerInput = GetIntegerInputCallback; cb.getAddressInput = GetAddressInputCallback; @@ -400,6 +427,22 @@ void BinaryNinja::ShowHTMLReport(const string& title, const string& contents, co } +void BinaryNinja::ShowGraphReport(const string& title, FlowGraph* graph) +{ + Ref<Function> func = graph->GetFunction(); + if (func) + BNShowGraphReport(func->GetView()->GetObject(), title.c_str(), graph->GetGraphObject()); + else + BNShowGraphReport(nullptr, title.c_str(), graph->GetGraphObject()); +} + + +void BinaryNinja::ShowReportCollection(const string& title, ReportCollection* reports) +{ + BNShowReportCollection(title.c_str(), reports->GetObject()); +} + + bool BinaryNinja::GetTextLineInput(string& result, const string& prompt, const string& title) { char* value = nullptr; @@ -553,3 +596,100 @@ BNMessageBoxButtonResult BinaryNinja::ShowMessageBox(const string& title, const { return BNShowMessageBox(title.c_str(), text.c_str(), buttons, icon); } + + +ReportCollection::ReportCollection() +{ + m_object = BNCreateReportCollection(); +} + + +ReportCollection::ReportCollection(BNReportCollection* reports) +{ + m_object = reports; +} + + +size_t ReportCollection::GetCount() const +{ + return BNGetReportCollectionCount(m_object); +} + + +BNReportType ReportCollection::GetType(size_t i) const +{ + return BNGetReportType(m_object, i); +} + + +Ref<BinaryView> ReportCollection::GetView(size_t i) const +{ + BNBinaryView* view = BNGetReportView(m_object, i); + if (!view) + return nullptr; + return new BinaryView(view); +} + + +string ReportCollection::GetTitle(size_t i) const +{ + char* str = BNGetReportTitle(m_object, i); + string result = str; + BNFreeString(str); + return result; +} + + +string ReportCollection::GetContents(size_t i) const +{ + char* str = BNGetReportContents(m_object, i); + string result = str; + BNFreeString(str); + return result; +} + + +string ReportCollection::GetPlainText(size_t i) const +{ + char* str = BNGetReportPlainText(m_object, i); + string result = str; + BNFreeString(str); + return result; +} + + +Ref<FlowGraph> ReportCollection::GetFlowGraph(size_t i) const +{ + BNFlowGraph* graph = BNGetReportFlowGraph(m_object, i); + if (!graph) + return nullptr; + return new FlowGraph(graph); +} + + +void ReportCollection::AddPlainTextReport(Ref<BinaryView> view, const string& title, const string& contents) +{ + BNAddPlainTextReportToCollection(m_object, view ? view->GetObject() : nullptr, title.c_str(), contents.c_str()); +} + + +void ReportCollection::AddMarkdownReport(Ref<BinaryView> view, const string& title, const string& contents, + const string& plainText) +{ + BNAddMarkdownReportToCollection(m_object, view ? view->GetObject() : nullptr, title.c_str(), contents.c_str(), + plainText.c_str()); +} + + +void ReportCollection::AddHTMLReport(Ref<BinaryView> view, const string& title, const string& contents, + const string& plainText) +{ + BNAddHTMLReportToCollection(m_object, view ? view->GetObject() : nullptr, title.c_str(), contents.c_str(), + plainText.c_str()); +} + + +void ReportCollection::AddGraphReport(Ref<BinaryView> view, const string& title, Ref<FlowGraph> graph) +{ + BNAddGraphReportToCollection(m_object, view ? view->GetObject() : nullptr, title.c_str(), graph->GetGraphObject()); +} diff --git a/python/__init__.py b/python/__init__.py index 729e4f8a..05ba4c2b 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -53,6 +53,7 @@ from .scriptingprovider import * from .pluginmanager import * from .setting import * from .metadata import * +from .flowgraph import * def shutdown(): diff --git a/python/basicblock.py b/python/basicblock.py index c55e15f0..3f615bba 100644 --- a/python/basicblock.py +++ b/python/basicblock.py @@ -243,14 +243,7 @@ class BasicBlock(object): >>> current_basic_block.highlight <color: blue> """ - color = core.BNGetBasicBlockHighlight(self.handle) - if color.style == HighlightColorStyle.StandardHighlightColor: - return highlight.HighlightColor(color=color.color, alpha=color.alpha) - elif color.style == HighlightColorStyle.MixedHighlightColor: - return highlight.HighlightColor(color=color.color, mix_color=color.mixColor, mix=color.mix, alpha=color.alpha) - elif color.style == HighlightColorStyle.CustomHighlightColor: - return highlight.HighlightColor(red=color.r, green=color.g, blue=color.b, alpha=color.alpha) - return highlight.HighlightColor(color=HighlightStandardColor.NoHighlightColor) + return highlight.HighlightColor._from_core_struct(core.BNGetBasicBlockHighlight(self.handle)) @highlight.setter def highlight(self, value): @@ -341,6 +334,7 @@ class BasicBlock(object): il_instr = self.il_function[lines[i].instrIndex] else: il_instr = None + color = highlight.HighlightColor._from_core_struct(lines[i].highlight) tokens = [] for j in xrange(0, lines[i].count): token_type = InstructionTextTokenType(lines[i].tokens[j].type) @@ -352,7 +346,7 @@ class BasicBlock(object): confidence = lines[i].tokens[j].confidence address = lines[i].tokens[j].address tokens.append(function.InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) - result.append(function.DisassemblyTextLine(addr, tokens, il_instr)) + result.append(function.DisassemblyTextLine(tokens, addr, il_instr, color)) core.BNFreeDisassemblyTextLines(lines, count.value) return result diff --git a/python/binaryview.py b/python/binaryview.py index 0cf25e70..ede279ad 100644 --- a/python/binaryview.py +++ b/python/binaryview.py @@ -41,6 +41,7 @@ import basicblock import types import lineardisassembly import metadata +import highlight class BinaryDataNotification(object): @@ -2961,6 +2962,7 @@ class BinaryView(object): func = function.Function(self, core.BNNewFunctionReference(lines[i].function)) if lines[i].block: block = basicblock.BasicBlock(self, core.BNNewBasicBlockReference(lines[i].block)) + color = highlight.HighlightColor._from_core_struct(lines[i].contents.highlight) addr = lines[i].contents.addr tokens = [] for j in xrange(0, lines[i].contents.count): @@ -2973,7 +2975,7 @@ class BinaryView(object): confidence = lines[i].contents.tokens[j].confidence address = lines[i].contents.tokens[j].address tokens.append(function.InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) - contents = function.DisassemblyTextLine(addr, tokens) + contents = function.DisassemblyTextLine(tokens, addr, color = color) result.append(lineardisassembly.LinearDisassemblyLine(lines[i].type, func, block, lines[i].lineOffset, contents)) func = None @@ -3352,6 +3354,9 @@ class BinaryView(object): def show_html_report(self, title, contents, plaintext = ""): core.BNShowHTMLReport(self.handle, title, contents, plaintext) + def show_graph_report(self, title, graph): + core.BNShowHTMLReport(self.handle, title, graph.handle) + def get_address_input(self, prompt, title, current_address = None): if current_address is None: current_address = self.file.offset diff --git a/python/flowgraph.py b/python/flowgraph.py new file mode 100644 index 00000000..1568bc77 --- /dev/null +++ b/python/flowgraph.py @@ -0,0 +1,465 @@ +# Copyright (c) 2018 Vector 35 LLC +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. + +import ctypes +import threading +import traceback + +# Binary Ninja components +import _binaryninjacore as core +from enums import (BranchType, InstructionTextTokenType, HighlightColorStyle, HighlightStandardColor) +import function +import binaryview +import lowlevelil +import mediumlevelil +import basicblock +import architecture +import log +import interaction +import highlight + + +class FlowGraphEdge(object): + def __init__(self, branch_type, source, target, points, back_edge): + self.type = BranchType(branch_type) + self.source = source + self.target = target + self.points = points + self.back_edge = back_edge + + def __repr__(self): + return "<%s: %s>" % (self.type.name, repr(self.target)) + + +class FlowGraphNode(object): + def __init__(self, graph, handle = None): + if handle is None: + handle = core.BNCreateFlowGraphNode(graph.handle) + self.handle = handle + self.graph = graph + + def __del__(self): + core.BNFreeFlowGraphNode(self.handle) + + def __eq__(self, value): + if not isinstance(value, FlowGraphNode): + return False + return ctypes.addressof(self.handle.contents) == ctypes.addressof(value.handle.contents) + + def __ne__(self, value): + if not isinstance(value, FlowGraphNode): + return True + return ctypes.addressof(self.handle.contents) != ctypes.addressof(value.handle.contents) + + @property + def basic_block(self): + """Basic block associated with this part of the flow graph (read-only)""" + block = core.BNGetFlowGraphBasicBlock(self.handle) + if not block: + return None + func_handle = core.BNGetBasicBlockFunction(block) + if not func_handle: + core.BNFreeBasicBlock(block) + return None + + view = binaryview.BinaryView(handle = core.BNGetFunctionData(func_handle)) + func = function.Function(view, func_handle) + + if core.BNIsLowLevelILBasicBlock(block): + block = lowlevelil.LowLevelILBasicBlock(view, block, + lowlevelil.LowLevelILFunction(func.arch, core.BNGetBasicBlockLowLevelILFunction(block), func)) + elif core.BNIsMediumLevelILBasicBlock(block): + block = mediumlevelil.MediumLevelILBasicBlock(view, block, + mediumlevelil.MediumLevelILFunction(func.arch, core.BNGetBasicBlockMediumLevelILFunction(block), func)) + else: + block = basicblock.BasicBlock(view, block) + return block + + @property + def x(self): + """Flow graph block X (read-only)""" + return core.BNGetFlowGraphNodeX(self.handle) + + @property + def y(self): + """Flow graph block Y (read-only)""" + return core.BNGetFlowGraphNodeY(self.handle) + + @property + def width(self): + """Flow graph block width (read-only)""" + return core.BNGetFlowGraphNodeWidth(self.handle) + + @property + def height(self): + """Flow graph block height (read-only)""" + return core.BNGetFlowGraphNodeHeight(self.handle) + + @property + def lines(self): + """Flow graph block list of lines""" + count = ctypes.c_ulonglong() + lines = core.BNGetFlowGraphNodeLines(self.handle, count) + block = self.basic_block + result = [] + for i in xrange(0, count.value): + addr = lines[i].addr + if (lines[i].instrIndex != 0xffffffffffffffff) and (block is not None) and hasattr(block, 'il_function'): + il_instr = block.il_function[lines[i].instrIndex] + else: + il_instr = None + color = highlight.HighlightColor._from_core_struct(lines[i].highlight) + tokens = [] + for j in xrange(0, lines[i].count): + token_type = InstructionTextTokenType(lines[i].tokens[j].type) + text = lines[i].tokens[j].text + value = lines[i].tokens[j].value + size = lines[i].tokens[j].size + operand = lines[i].tokens[j].operand + context = lines[i].tokens[j].context + confidence = lines[i].tokens[j].confidence + address = lines[i].tokens[j].address + tokens.append(function.InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) + result.append(function.DisassemblyTextLine(tokens, addr, il_instr, color)) + core.BNFreeDisassemblyTextLines(lines, count.value) + return result + + @lines.setter + def lines(self, lines): + if isinstance(lines, str): + lines = lines.split('\n') + line_buf = (core.BNDisassemblyTextLine * len(lines))() + for i in xrange(0, len(lines)): + line = lines[i] + if isinstance(line, str): + line = function.DisassemblyTextLine([function.InstructionTextToken(InstructionTextTokenType.TextToken, line)]) + if not isinstance(line, function.DisassemblyTextLine): + line = function.DisassemblyTextLine(line) + if line.address is None: + if len(line.tokens) > 0: + line_buf[i].addr = line.tokens[0].address + else: + line_buf[i].addr = 0 + else: + line_buf[i].addr = line.address + if line.il_instruction is not None: + line_buf[i].instrIndex = line.il_instruction.instr_index + else: + line_buf[i].instrIndex = 0xffffffffffffffff + color = line.highlight + if not isinstance(color, HighlightStandardColor) and not isinstance(color, highlight.HighlightColor): + raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor") + if isinstance(color, HighlightStandardColor): + color = highlight.HighlightColor(color) + line_buf[i].highlight = color._get_core_struct() + line_buf[i].count = len(line.tokens) + line_buf[i].tokens = (core.BNInstructionTextToken * len(line.tokens))() + for j in xrange(0, len(line.tokens)): + line_buf[i].tokens[j].type = line.tokens[j].type + line_buf[i].tokens[j].text = line.tokens[j].text + line_buf[i].tokens[j].value = line.tokens[j].value + line_buf[i].tokens[j].size = line.tokens[j].size + line_buf[i].tokens[j].operand = line.tokens[j].operand + line_buf[i].tokens[j].context = line.tokens[j].context + line_buf[i].tokens[j].confidence = line.tokens[j].confidence + line_buf[i].tokens[j].address = line.tokens[j].address + core.BNSetFlowGraphNodeLines(self.handle, line_buf, len(lines)) + + @property + def outgoing_edges(self): + """Flow graph block list of outgoing edges (read-only)""" + count = ctypes.c_ulonglong() + edges = core.BNGetFlowGraphNodeOutgoingEdges(self.handle, count) + result = [] + for i in xrange(0, count.value): + branch_type = BranchType(edges[i].type) + target = edges[i].target + if target: + target = FlowGraphNode(self.graph, core.BNNewFlowGraphNodeReference(target)) + points = [] + for j in xrange(0, edges[i].pointCount): + points.append((edges[i].points[j].x, edges[i].points[j].y)) + result.append(FlowGraphEdge(branch_type, self, target, points, edges[i].backEdge)) + core.BNFreeFlowGraphNodeOutgoingEdgeList(edges, count.value) + return result + + @property + def highlight(self): + """Gets or sets the highlight color for the node + + :Example: + >>> g = FlowGraph() + >>> node = FlowGraphNode(g) + >>> node.highlight = HighlightStandardColor.BlueHighlightColor + >>> node.highlight + <color: blue> + """ + return highlight.HighlightColor._from_core_struct(core.BNGetFlowGraphNodeHighlight(self.handle)) + + @highlight.setter + def highlight(self, color): + if not isinstance(color, HighlightStandardColor) and not isinstance(color, highlight.HighlightColor): + raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor") + if isinstance(color, HighlightStandardColor): + color = highlight.HighlightColor(color) + core.BNSetFlowGraphNodeHighlight(self.handle, color._get_core_struct()) + + def __repr__(self): + block = self.basic_block + if block: + arch = block.arch + if arch: + return "<graph node: %s@%#x-%#x>" % (arch.name, block.start, block.end) + else: + return "<graph node: %#x-%#x>" % (block.start, block.end) + return "<graph node>" + + def __iter__(self): + count = ctypes.c_ulonglong() + lines = core.BNGetFlowGraphNodeLines(self.handle, count) + block = self.basic_block + try: + for i in xrange(0, count.value): + addr = lines[i].addr + if (lines[i].instrIndex != 0xffffffffffffffff) and (block is not None) and hasattr(block, 'il_function'): + il_instr = block.il_function[lines[i].instrIndex] + else: + il_instr = None + tokens = [] + for j in xrange(0, lines[i].count): + token_type = InstructionTextTokenType(lines[i].tokens[j].type) + text = lines[i].tokens[j].text + value = lines[i].tokens[j].value + size = lines[i].tokens[j].size + operand = lines[i].tokens[j].operand + context = lines[i].tokens[j].context + confidence = lines[i].tokens[j].confidence + address = lines[i].tokens[j].address + tokens.append(function.InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) + yield function.DisassemblyTextLine(tokens, addr, il_instr) + finally: + core.BNFreeDisassemblyTextLines(lines, count.value) + + def add_outgoing_edge(self, edge_type, target): + core.BNAddFlowGraphNodeOutgoingEdge(self.handle, edge_type, target.handle) + + +class FlowGraph(object): + def __init__(self, handle = None): + if handle is None: + handle = core.BNCreateFlowGraph() + self.handle = handle + self._on_complete = None + self._cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._complete) + + def __del__(self): + self.abort() + core.BNFreeFlowGraph(self.handle) + + def __eq__(self, value): + if not isinstance(value, FlowGraph): + return False + return ctypes.addressof(self.handle.contents) == ctypes.addressof(value.handle.contents) + + def __ne__(self, value): + if not isinstance(value, FlowGraph): + return True + return ctypes.addressof(self.handle.contents) != ctypes.addressof(value.handle.contents) + + @property + def function(self): + """Function for a flow graph""" + func = core.BNGetFunctionForFlowGraph(self.handle) + if func is None: + return None + return function.Function(binaryview.BinaryView(handle = core.BNGetFunctionData(func)), func) + + @function.setter + def function(self, func): + if func is not None: + func = func.handle + core.BNSetFunctionForFlowGraph(self.handle, func) + + @property + def complete(self): + """Whether flow graph layout is complete (read-only)""" + return core.BNIsFlowGraphLayoutComplete(self.handle) + + @property + def nodes(self): + """List of nodes in graph (read-only)""" + count = ctypes.c_ulonglong() + blocks = core.BNGetFlowGraphNodes(self.handle, count) + result = [] + for i in xrange(0, count.value): + result.append(FlowGraphNode(self, core.BNNewFlowGraphNodeReference(blocks[i]))) + core.BNFreeFlowGraphNodeList(blocks, count.value) + return result + + @property + def has_nodes(self): + """Whether the flow graph has at least one node (read-only)""" + return core.BNFlowGraphHasNodes(self.handle) + + @property + def width(self): + """Flow graph width (read-only)""" + return core.BNGetFlowGraphWidth(self.handle) + + @property + def height(self): + """Flow graph height (read-only)""" + return core.BNGetFlowGraphHeight(self.handle) + + @property + def horizontal_block_margin(self): + return core.BNGetHorizontalFlowGraphBlockMargin(self.handle) + + @horizontal_block_margin.setter + def horizontal_block_margin(self, value): + core.BNSetFlowGraphBlockMargins(self.handle, value, self.vertical_block_margin) + + @property + def vertical_block_margin(self): + return core.BNGetVerticalFlowGraphBlockMargin(self.handle) + + @vertical_block_margin.setter + def vertical_block_margin(self, value): + core.BNSetFlowGraphBlockMargins(self.handle, self.horizontal_block_margin, value) + + @property + def is_il(self): + return core.BNIsILFlowGraph(self.handle) + + @property + def is_low_level_il(self): + return core.BNIsLowLevelILFlowGraph(self.handle) + + @property + def is_medium_level_il(self): + return core.BNIsMediumLevelILFlowGraph(self.handle) + + @property + def il_function(self): + if self.is_low_level_il: + il_func = core.BNGetFlowGraphLowLevelILFunction(self.handle) + if not il_func: + return None + function = self.function + if function is None: + return None + return lowlevelil.LowLevelILFunction(function.arch, il_func, function) + if self.is_medium_level_il: + il_func = core.BNGetFlowGraphMediumLevelILFunction(self.handle) + if not il_func: + return None + function = self.function + if function is None: + return None + return mediumlevelil.MediumLevelILFunction(function.arch, il_func, function) + return None + + @il_function.setter + def il_function(self, func): + if isinstance(func, lowlevelil.LowLevelILFunction): + core.BNSetFlowGraphLowLevelILFunction(self.handle, func.handle) + core.BNSetFlowGraphMediumLevelILFunction(self.handle, None) + elif isinstance(func, mediumlevelil.MediumLevelILFunction): + core.BNSetFlowGraphLowLevelILFunction(self.handle, None) + core.BNSetFlowGraphMediumLevelILFunction(self.handle, func.handle) + elif func is None: + core.BNSetFlowGraphLowLevelILFunction(self.handle, None) + core.BNSetFlowGraphMediumLevelILFunction(self.handle, None) + else: + raise TypeError("expected IL function for setting il_function property") + + def __setattr__(self, name, value): + try: + object.__setattr__(self, name, value) + except AttributeError: + raise AttributeError("attribute '%s' is read only" % name) + + def __repr__(self): + function = self.function + if function is None: + return "<flow graph>" + return "<graph of %s>" % repr(function) + + def __iter__(self): + count = ctypes.c_ulonglong() + nodes = core.BNGetFlowGraphNodes(self.handle, count) + try: + for i in xrange(0, count.value): + yield FlowGraphNode(self, core.BNNewFlowGraphNodeReference(nodes[i])) + finally: + core.BNFreeFlowGraphNodeList(nodes, count.value) + + def _complete(self, ctxt): + try: + if self._on_complete is not None: + self._on_complete() + except: + log.log_error(traceback.format_exc()) + + def layout(self): + core.BNStartFlowGraphLayout(self.handle) + + def _wait_complete(self): + self._wait_cond.acquire() + self._wait_cond.notify() + self._wait_cond.release() + + def layout_and_wait(self): + self._wait_cond = threading.Condition() + self.on_complete(self._wait_complete) + self.layout() + + self._wait_cond.acquire() + while not self.complete: + self._wait_cond.wait() + self._wait_cond.release() + + def on_complete(self, callback): + self._on_complete = callback + core.BNSetFlowGraphCompleteCallback(self.handle, None, self._cb) + + def abort(self): + core.BNAbortFlowGraph(self.handle) + + def get_nodes_in_region(self, left, top, right, bottom): + count = ctypes.c_ulonglong() + nodes = core.BNGetFlowGraphNodesInRegion(self.handle, left, top, right, bottom, count) + result = [] + for i in xrange(0, count.value): + result.append(FlowGraphNode(self, core.BNNewFlowGraphNodeReference(nodes[i]))) + core.BNFreeFlowGraphNodeList(nodes, count.value) + return result + + def append(self, node): + return core.BNAddFlowGraphNode(self.handle, node.handle) + + def __getitem__(self, i): + node = core.BNGetFlowGraphNode(self.handle, i) + if node is None: + return None + return FlowGraphNode(self, node) + + def show(self, title): + interaction.show_graph_report(title, self) diff --git a/python/function.py b/python/function.py index 6db44e6d..dca9dda6 100644 --- a/python/function.py +++ b/python/function.py @@ -39,6 +39,7 @@ import mediumlevelil import binaryview import log import callingconvention +import flowgraph class LookupTableEntry(object): @@ -844,6 +845,14 @@ class Function(object): def analysis_skip_override(self, override): core.BNSetFunctionAnalysisSkipOverride(self.handle, override) + @property + def unresolved_stack_adjustment_graph(self): + """Flow graph of unresolved stack adjustments (read-only)""" + graph = core.BNGetUnresolvedStackAdjustmentGraph(self.handle) + if not graph: + return None + return flowgraph.FlowGraph(graph) + def __iter__(self): count = ctypes.c_ulonglong() blocks = core.BNGetFunctionBasicBlockList(self.handle, count) @@ -1108,8 +1117,12 @@ class Function(object): core.BNFreeRegisterList(flags) return result - def create_graph(self): - return FunctionGraph(self._view, core.BNCreateFunctionGraph(self.handle)) + def create_graph(self, graph_type = FunctionGraphType.NormalFunctionGraph, settings = None): + if settings is not None: + settings_obj = settings.handle + else: + settings_obj = None + return flowgraph.FlowGraph(core.BNCreateFunctionGraph(self.handle, graph_type, settings_obj)) def apply_imported_types(self, sym): core.BNApplyImportedTypes(self.handle, sym.handle) @@ -1461,6 +1474,7 @@ class Function(object): result = [] for i in xrange(0, count.value): addr = lines[i].addr + color = highlight.HighlightColor._from_core_struct(lines[i].highlight) tokens = [] for j in xrange(0, lines[i].count): token_type = InstructionTextTokenType(lines[i].tokens[j].type) @@ -1472,7 +1486,7 @@ class Function(object): confidence = lines[i].tokens[j].confidence address = lines[i].tokens[j].address tokens.append(InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) - result.append(DisassemblyTextLine(addr, tokens)) + result.append(DisassemblyTextLine(tokens, addr, color = color)) core.BNFreeDisassemblyTextLines(lines, count.value) return result @@ -1598,10 +1612,18 @@ class AdvancedFunctionAnalysisDataRequestor(object): class DisassemblyTextLine(object): - def __init__(self, addr, tokens, il_instr = None): - self.address = addr + def __init__(self, tokens, address = None, il_instr = None, color = None): + self.address = address self.tokens = tokens self.il_instruction = il_instr + if color is None: + self.highlight = highlight.HighlightColor() + else: + if not isinstance(color, HighlightStandardColor) and not isinstance(color, highlight.HighlightColor): + raise ValueError("Specified color is not one of HighlightStandardColor, highlight.HighlightColor") + if isinstance(color, HighlightStandardColor): + color = highlight.HighlightColor(color) + self.highlight = color def __str__(self): result = "" @@ -1610,192 +1632,11 @@ class DisassemblyTextLine(object): return result def __repr__(self): + if self.address is None: + return str(self) return "<%#x: %s>" % (self.address, str(self)) -class FunctionGraphEdge(object): - def __init__(self, branch_type, source, target, points, back_edge): - self.type = BranchType(branch_type) - self.source = source - self.target = target - self.points = points - self.back_edge = back_edge - - def __repr__(self): - return "<%s: %s>" % (self.type.name, repr(self.target)) - - -class FunctionGraphBlock(object): - def __init__(self, handle, graph): - self.handle = handle - self.graph = graph - - def __del__(self): - core.BNFreeFunctionGraphBlock(self.handle) - - def __eq__(self, value): - if not isinstance(value, FunctionGraphBlock): - return False - return ctypes.addressof(self.handle.contents) == ctypes.addressof(value.handle.contents) - - def __ne__(self, value): - if not isinstance(value, FunctionGraphBlock): - return True - return ctypes.addressof(self.handle.contents) != ctypes.addressof(value.handle.contents) - - @property - def basic_block(self): - """Basic block associated with this part of the function graph (read-only)""" - block = core.BNGetFunctionGraphBasicBlock(self.handle) - func_handle = core.BNGetBasicBlockFunction(block) - if func_handle is None: - core.BNFreeBasicBlock(block) - return None - - view = binaryview.BinaryView(handle = core.BNGetFunctionData(func_handle)) - func = Function(view, func_handle) - - if core.BNIsLowLevelILBasicBlock(block): - block = lowlevelil.LowLevelILBasicBlock(view, block, - lowlevelil.LowLevelILFunction(func.arch, core.BNGetBasicBlockLowLevelILFunction(block), func)) - elif core.BNIsMediumLevelILBasicBlock(block): - block = mediumlevelil.MediumLevelILBasicBlock(view, block, - mediumlevelil.MediumLevelILFunction(func.arch, core.BNGetBasicBlockMediumLevelILFunction(block), func)) - else: - block = basicblock.BasicBlock(view, block) - return block - - @property - def arch(self): - """Function graph block architecture (read-only)""" - arch = core.BNGetFunctionGraphBlockArchitecture(self.handle) - if arch is None: - return None - return architecture.CoreArchitecture._from_cache(arch) - - @property - def start(self): - """Function graph block start (read-only)""" - return core.BNGetFunctionGraphBlockStart(self.handle) - - @property - def end(self): - """Function graph block end (read-only)""" - return core.BNGetFunctionGraphBlockEnd(self.handle) - - @property - def x(self): - """Function graph block X (read-only)""" - return core.BNGetFunctionGraphBlockX(self.handle) - - @property - def y(self): - """Function graph block Y (read-only)""" - return core.BNGetFunctionGraphBlockY(self.handle) - - @property - def width(self): - """Function graph block width (read-only)""" - return core.BNGetFunctionGraphBlockWidth(self.handle) - - @property - def height(self): - """Function graph block height (read-only)""" - return core.BNGetFunctionGraphBlockHeight(self.handle) - - @property - def lines(self): - """Function graph block list of lines (read-only)""" - count = ctypes.c_ulonglong() - lines = core.BNGetFunctionGraphBlockLines(self.handle, count) - block = self.basic_block - result = [] - for i in xrange(0, count.value): - addr = lines[i].addr - if (lines[i].instrIndex != 0xffffffffffffffff) and hasattr(block, 'il_function'): - il_instr = block.il_function[lines[i].instrIndex] - else: - il_instr = None - tokens = [] - for j in xrange(0, lines[i].count): - token_type = InstructionTextTokenType(lines[i].tokens[j].type) - text = lines[i].tokens[j].text - value = lines[i].tokens[j].value - size = lines[i].tokens[j].size - operand = lines[i].tokens[j].operand - context = lines[i].tokens[j].context - confidence = lines[i].tokens[j].confidence - address = lines[i].tokens[j].address - tokens.append(InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) - result.append(DisassemblyTextLine(addr, tokens, il_instr)) - core.BNFreeDisassemblyTextLines(lines, count.value) - return result - - @property - def outgoing_edges(self): - """Function graph block list of outgoing edges (read-only)""" - count = ctypes.c_ulonglong() - edges = core.BNGetFunctionGraphBlockOutgoingEdges(self.handle, count) - result = [] - for i in xrange(0, count.value): - branch_type = BranchType(edges[i].type) - target = edges[i].target - if target: - func = core.BNGetBasicBlockFunction(target) - if func is None: - core.BNFreeBasicBlock(target) - target = None - else: - target = basicblock.BasicBlock(binaryview.BinaryView(handle = core.BNGetFunctionData(func)), - core.BNNewBasicBlockReference(target)) - core.BNFreeFunction(func) - points = [] - for j in xrange(0, edges[i].pointCount): - points.append((edges[i].points[j].x, edges[i].points[j].y)) - result.append(FunctionGraphEdge(branch_type, self, target, points, edges[i].backEdge)) - core.BNFreeFunctionGraphBlockOutgoingEdgeList(edges, count.value) - return result - - def __setattr__(self, name, value): - try: - object.__setattr__(self, name, value) - except AttributeError: - raise AttributeError("attribute '%s' is read only" % name) - - def __repr__(self): - arch = self.arch - if arch: - return "<graph block: %s@%#x-%#x>" % (arch.name, self.start, self.end) - else: - return "<graph block: %#x-%#x>" % (self.start, self.end) - - def __iter__(self): - count = ctypes.c_ulonglong() - lines = core.BNGetFunctionGraphBlockLines(self.handle, count) - block = self.basic_block - try: - for i in xrange(0, count.value): - addr = lines[i].addr - if (lines[i].instrIndex != 0xffffffffffffffff) and hasattr(block, 'il_function'): - il_instr = block.il_function[lines[i].instrIndex] - else: - il_instr = None - tokens = [] - for j in xrange(0, lines[i].count): - token_type = InstructionTextTokenType(lines[i].tokens[j].type) - text = lines[i].tokens[j].text - value = lines[i].tokens[j].value - size = lines[i].tokens[j].size - operand = lines[i].tokens[j].operand - context = lines[i].tokens[j].context - confidence = lines[i].tokens[j].confidence - address = lines[i].tokens[j].address - tokens.append(InstructionTextToken(token_type, text, value, size, operand, context, address, confidence)) - yield DisassemblyTextLine(addr, tokens, il_instr) - finally: - core.BNFreeDisassemblyTextLines(lines, count.value) - - class DisassemblySettings(object): def __init__(self, handle = None): if handle is None: @@ -1833,189 +1674,6 @@ class DisassemblySettings(object): core.BNSetDisassemblySettingsOption(self.handle, option, state) -class FunctionGraph(object): - def __init__(self, view, handle): - self.view = view - self.handle = handle - self._on_complete = None - self._cb = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(self._complete) - - def __del__(self): - self.abort() - core.BNFreeFunctionGraph(self.handle) - - def __eq__(self, value): - if not isinstance(value, FunctionGraph): - return False - return ctypes.addressof(self.handle.contents) == ctypes.addressof(value.handle.contents) - - def __ne__(self, value): - if not isinstance(value, FunctionGraph): - return True - return ctypes.addressof(self.handle.contents) != ctypes.addressof(value.handle.contents) - - @property - def function(self): - """Function for a function graph (read-only)""" - func = core.BNGetFunctionForFunctionGraph(self.handle) - if func is None: - return None - return Function(self.view, func) - - @property - def complete(self): - """Whether function graph layout is complete (read-only)""" - return core.BNIsFunctionGraphLayoutComplete(self.handle) - - @property - def type(self): - """Function graph type (read-only)""" - return FunctionGraphType(core.BNGetFunctionGraphType(self.handle)) - - @property - def blocks(self): - """List of basic blocks in function (read-only)""" - count = ctypes.c_ulonglong() - blocks = core.BNGetFunctionGraphBlocks(self.handle, count) - result = [] - for i in xrange(0, count.value): - result.append(FunctionGraphBlock(core.BNNewFunctionGraphBlockReference(blocks[i]), self)) - core.BNFreeFunctionGraphBlockList(blocks, count.value) - return result - - @property - def has_blocks(self): - """Whether the function graph has at least one block (read-only)""" - return core.BNFunctionGraphHasBlocks(self.handle) - - @property - def width(self): - """Function graph width (read-only)""" - return core.BNGetFunctionGraphWidth(self.handle) - - @property - def height(self): - """Function graph height (read-only)""" - return core.BNGetFunctionGraphHeight(self.handle) - - @property - def horizontal_block_margin(self): - return core.BNGetHorizontalFunctionGraphBlockMargin(self.handle) - - @horizontal_block_margin.setter - def horizontal_block_margin(self, value): - core.BNSetFunctionGraphBlockMargins(self.handle, value, self.vertical_block_margin) - - @property - def vertical_block_margin(self): - return core.BNGetVerticalFunctionGraphBlockMargin(self.handle) - - @vertical_block_margin.setter - def vertical_block_margin(self, value): - core.BNSetFunctionGraphBlockMargins(self.handle, self.horizontal_block_margin, value) - - @property - def settings(self): - return DisassemblySettings(core.BNGetFunctionGraphSettings(self.handle)) - - @property - def is_il(self): - return core.BNIsILFunctionGraph(self.handle) - - @property - def is_low_level_il(self): - return core.BNIsLowLevelILFunctionGraph(self.handle) - - @property - def is_medium_level_il(self): - return core.BNIsMediumLevelILFunctionGraph(self.handle) - - @property - def il_function(self): - if self.is_low_level_il: - il_func = core.BNGetFunctionGraphLowLevelILFunction(self.handle) - if not il_func: - return None - return lowlevelil.LowLevelILFunction(self.function.arch, il_func, self.function) - if self.is_medium_level_il: - il_func = core.BNGetFunctionGraphMediumLevelILFunction(self.handle) - if not il_func: - return None - return mediumlevelil.MediumLevelILFunction(self.function.arch, il_func, self.function) - return None - - def __setattr__(self, name, value): - try: - object.__setattr__(self, name, value) - except AttributeError: - raise AttributeError("attribute '%s' is read only" % name) - - def __repr__(self): - return "<graph of %s>" % repr(self.function) - - def __iter__(self): - count = ctypes.c_ulonglong() - blocks = core.BNGetFunctionGraphBlocks(self.handle, count) - try: - for i in xrange(0, count.value): - yield FunctionGraphBlock(core.BNNewFunctionGraphBlockReference(blocks[i]), self) - finally: - core.BNFreeFunctionGraphBlockList(blocks, count.value) - - def _complete(self, ctxt): - try: - if self._on_complete is not None: - self._on_complete() - except: - log.log_error(traceback.format_exc()) - - def layout(self, graph_type = FunctionGraphType.NormalFunctionGraph): - if isinstance(graph_type, str): - graph_type = FunctionGraphType[graph_type] - core.BNStartFunctionGraphLayout(self.handle, graph_type) - - def _wait_complete(self): - self._wait_cond.acquire() - self._wait_cond.notify() - self._wait_cond.release() - - def layout_and_wait(self, graph_type=FunctionGraphType.NormalFunctionGraph): - self._wait_cond = threading.Condition() - self.on_complete(self._wait_complete) - self.layout(graph_type) - - self._wait_cond.acquire() - while not self.complete: - self._wait_cond.wait() - self._wait_cond.release() - - def on_complete(self, callback): - self._on_complete = callback - core.BNSetFunctionGraphCompleteCallback(self.handle, None, self._cb) - - def abort(self): - core.BNAbortFunctionGraph(self.handle) - - def get_blocks_in_region(self, left, top, right, bottom): - count = ctypes.c_ulonglong() - blocks = core.BNGetFunctionGraphBlocksInRegion(self.handle, left, top, right, bottom, count) - result = [] - for i in xrange(0, count.value): - result.append(FunctionGraphBlock(core.BNNewFunctionGraphBlockReference(blocks[i]), self)) - core.BNFreeFunctionGraphBlockList(blocks, count.value) - return result - - def is_option_set(self, option): - if isinstance(option, str): - option = DisassemblyOption[option] - return core.BNIsFunctionGraphOptionSet(self.handle, option) - - def set_option(self, option, state = True): - if isinstance(option, str): - option = DisassemblyOption[option] - core.BNSetFunctionGraphOption(self.handle, option, state) - - class RegisterInfo(object): def __init__(self, full_width_reg, size, offset=0, extend=ImplicitRegisterExtend.NoExtend, index=None): self.full_width_reg = full_width_reg diff --git a/python/highlight.py b/python/highlight.py index 96bc543d..87329202 100644 --- a/python/highlight.py +++ b/python/highlight.py @@ -110,3 +110,13 @@ class HighlightColor(object): result.b = self.blue return result + + @staticmethod + def _from_core_struct(color): + if color.style == HighlightColorStyle.StandardHighlightColor: + return HighlightColor(color=color.color, alpha=color.alpha) + elif color.style == HighlightColorStyle.MixedHighlightColor: + return HighlightColor(color=color.color, mix_color=color.mixColor, mix=color.mix, alpha=color.alpha) + elif color.style == HighlightColorStyle.CustomHighlightColor: + return HighlightColor(red=color.r, green=color.g, blue=color.b, alpha=color.alpha) + return HighlightColor(color=HighlightStandardColor.NoHighlightColor) diff --git a/python/interaction.py b/python/interaction.py index 4f6ed67d..81aeb04f 100644 --- a/python/interaction.py +++ b/python/interaction.py @@ -23,9 +23,10 @@ import traceback # Binary Ninja components import _binaryninjacore as core -from enums import FormInputFieldType, MessageBoxIcon, MessageBoxButtonSet, MessageBoxButtonResult +from enums import FormInputFieldType, MessageBoxIcon, MessageBoxButtonSet, MessageBoxButtonResult, ReportType import binaryview import log +import flowgraph class LabelField(object): @@ -249,6 +250,8 @@ class InteractionHandler(object): self._cb.showPlainTextReport = self._cb.showPlainTextReport.__class__(self._show_plain_text_report) self._cb.showMarkdownReport = self._cb.showMarkdownReport.__class__(self._show_markdown_report) self._cb.showHTMLReport = self._cb.showHTMLReport.__class__(self._show_html_report) + self._cb.showGraphReport = self._cb.showGraphReport.__class__(self._show_graph_report) + self._cb.showReportCollection = self._cb.showReportCollection.__class__(self._show_report_collection) self._cb.getTextLineInput = self._cb.getTextLineInput.__class__(self._get_text_line_input) self._cb.getIntegerInput = self._cb.getIntegerInput.__class__(self._get_int_input) self._cb.getAddressInput = self._cb.getAddressInput.__class__(self._get_address_input) @@ -293,6 +296,22 @@ class InteractionHandler(object): except: log.log_error(traceback.format_exc()) + def _show_graph_report(self, ctxt, view, title, graph): + try: + if view: + view = binaryview.BinaryView(handle = core.BNNewViewReference(view)) + else: + view = None + self.show_graph_report(view, title, flowgraph.FlowGraph(core.BNNewFlowGraphReference(graph))) + except: + log.log_error(traceback.format_exc()) + + def _show_report_collection(self, ctxt, title, reports): + try: + self.show_report_collection(title, ReportCollection(core.BNNewReportCollectionReference(reports))) + except: + log.log_error(traceback.format_exc()) + def _get_text_line_input(self, ctxt, result, prompt, title): try: value = self.get_text_line_input(prompt, title) @@ -426,6 +445,12 @@ class InteractionHandler(object): if len(plaintext) != 0: self.show_plain_text_report(view, title, plaintext) + def show_graph_report(self, view, title, graph): + pass + + def show_report_collection(self, title, reports): + pass + def get_text_line_input(self, prompt, title): return None @@ -461,6 +486,123 @@ class InteractionHandler(object): return MessageBoxButtonResult.CancelButton +class PlainTextReport(object): + def __init__(self, title, contents, view = None): + self.view = view + self.title = title + self.contents = contents + + def __repr__(self): + return "<plain text report: %s>" % self.title + + def __str__(self): + return self.contents + + +class MarkdownReport(object): + def __init__(self, title, contents, plaintext = "", view = None): + self.view = view + self.title = title + self.contents = contents + self.plaintext = plaintext + + def __repr__(self): + return "<markdown report: %s>" % self.title + + def __str__(self): + return self.contents + + +class HTMLReport(object): + def __init__(self, title, contents, plaintext = "", view = None): + self.view = view + self.title = title + self.contents = contents + self.plaintext = plaintext + + def __repr__(self): + return "<html report: %s>" % self.title + + def __str__(self): + return self.contents + + +class FlowGraphReport(object): + def __init__(self, title, graph, view = None): + self.view = view + self.title = title + self.graph = graph + + def __repr__(self): + return "<graph report: %s>" % self.title + + +class ReportCollection(object): + def __init__(self, handle = None): + if handle is None: + self.handle = core.BNCreateReportCollection() + else: + self.handle = handle + + def __len__(self): + return core.BNGetReportCollectionCount(self.handle) + + def _report_from_index(self, i): + report_type = core.BNGetReportType(self.handle, i) + title = core.BNGetReportTitle(self.handle, i) + view = core.BNGetReportView(self.handle, i) + if view: + view = binaryview.BinaryView(handle = view) + else: + view = None + if report_type == ReportType.PlainTextReportType: + contents = core.BNGetReportContents(self.handle, i) + return PlainTextReport(title, contents, view) + elif report_type == ReportType.MarkdownReportType: + contents = core.BNGetReportContents(self.handle, i) + plaintext = core.BNGetReportPlainText(self.handle, i) + return MarkdownReport(title, contents, plaintext, view) + elif report_type == ReportType.HTMLReportType: + contents = core.BNGetReportContents(self.handle, i) + plaintext = core.BNGetReportPlainText(self.handle, i) + return HTMLReport(title, contents, plaintext, view) + elif report_type == ReportType.FlowGraphReportType: + graph = flowgraph.FlowGraph(core.BNGetReportFlowGraph(self.handle, i)) + return FlowGraphReport(title, graph, view) + raise TypeError("invalid report type %s" % repr(report_type)) + + def __getitem__(self, i): + if isinstance(i, slice) or isinstance(i, tuple): + raise IndexError("expected integer report index") + if (i < 0) or (i >= len(self)): + raise IndexError("index out of range") + return self._report_from_index(i) + + def __iter__(self): + count = len(self) + for i in xrange(0, count): + yield self._report_from_index(i) + + def __repr__(self): + return "<reports: %s>" % repr(list(self)) + + def append(self, report): + if report.view is None: + view = None + else: + view = report.view.handle + if isinstance(report, PlainTextReport): + core.BNAddPlainTextReportToCollection(self.handle, view, report.title, report.contents) + elif isinstance(report, MarkdownReport): + core.BNAddMarkdownReportToCollection(self.handle, view, report.title, report.contents, report.plaintext) + elif isinstance(report, HTMLReport): + core.BNAddHTMLReportToCollection(self.handle, view, report.title, report.contents, report.plaintext) + elif isinstance(report, FlowGraphReport): + core.BNAddGraphReportToCollection(self.handle, view, report.title, report.graph.handle) + else: + raise TypeError("expected report object") + + def markdown_to_html(contents): """ ``markdown_to_html`` converts the provided markdown to HTML. @@ -527,6 +669,34 @@ def show_html_report(title, contents, plaintext=""): core.BNShowHTMLReport(None, title, contents, plaintext) +def show_graph_report(title, graph): + """ + ``show_graph_report`` displays a flow graph in UI applications. + + Note: This API function will have no effect outside the UI. + + :param FlowGraph graph: Flow graph to display + :rtype: None + """ + func = graph.function + if func is None: + core.BNShowGraphReport(None, title, graph.handle) + else: + core.BNShowGraphReport(func.view.handle, title, graph.handle) + + +def show_report_collection(title, reports): + """ + ``show_report_collection`` displays mulitple reports in UI applications. + + Note: This API function will have no effect outside the UI. + + :param ReportCollection reports: Reports to display + :rtype: None + """ + core.BNShowReportCollection(title, reports.handle) + + def get_text_line_input(prompt, title): """ ``get_text_line_input`` prompts the user to input a string with the given prompt and title. |
