From c3693b77c1fa9c1b5c45483045eeab929cf7bd16 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Tue, 23 Aug 2016 22:52:32 -0400 Subject: Fix some memory leaks --- binaryview.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'binaryview.cpp') diff --git a/binaryview.cpp b/binaryview.cpp index 8a2d1c2d..cff3ed10 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -1082,31 +1082,31 @@ vector> BinaryView::GetSymbolsOfType(BNSymbolType type, uint64_t sta } -void BinaryView::DefineAutoSymbol(Symbol* sym) +void BinaryView::DefineAutoSymbol(Ref sym) { BNDefineAutoSymbol(m_object, sym->GetObject()); } -void BinaryView::UndefineAutoSymbol(Symbol* sym) +void BinaryView::UndefineAutoSymbol(Ref sym) { BNUndefineAutoSymbol(m_object, sym->GetObject()); } -void BinaryView::DefineUserSymbol(Symbol* sym) +void BinaryView::DefineUserSymbol(Ref sym) { BNDefineUserSymbol(m_object, sym->GetObject()); } -void BinaryView::UndefineUserSymbol(Symbol* sym) +void BinaryView::UndefineUserSymbol(Ref sym) { BNUndefineUserSymbol(m_object, sym->GetObject()); } -void BinaryView::DefineImportedFunction(Symbol* importAddressSym, Function* func) +void BinaryView::DefineImportedFunction(Ref importAddressSym, Ref func) { BNDefineImportedFunction(m_object, importAddressSym->GetObject(), func->GetObject()); } @@ -1397,13 +1397,13 @@ bool BinaryView::IsTypeAutoDefined(const std::string& name) } -void BinaryView::DefineType(const std::string& name, Type* type) +void BinaryView::DefineType(const std::string& name, Ref type) { BNDefineAnalysisType(m_object, name.c_str(), type->GetObject()); } -void BinaryView::DefineUserType(const std::string& name, Type* type) +void BinaryView::DefineUserType(const std::string& name, Ref type) { BNDefineUserAnalysisType(m_object, name.c_str(), type->GetObject()); } -- cgit v1.3.1 From e878199be4a74c880acd5d38c33965b47d7630d0 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Thu, 25 Aug 2016 20:42:33 -0400 Subject: Adding APIs for database save/load progress and constant references --- binaryninjaapi.h | 10 ++++++++++ binaryninjacore.h | 15 +++++++++++++++ binaryview.cpp | 13 +++++++++++++ filemetadata.cpp | 43 ++++++++++++++++++++++++++++++++++++++++++ function.cpp | 13 +++++++++++++ python/__init__.py | 55 ++++++++++++++++++++++++++++++++++++++++++++---------- 6 files changed, 139 insertions(+), 10 deletions(-) (limited to 'binaryview.cpp') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index f79e9d75..7c951dee 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -511,8 +511,14 @@ namespace BinaryNinja bool IsBackedByDatabase() const; bool CreateDatabase(const std::string& name, BinaryView* data); + bool CreateDatabase(const std::string& name, BinaryView* data, + const std::function& progressCallback); Ref OpenExistingDatabase(const std::string& path); + Ref OpenExistingDatabase(const std::string& path, + const std::function& progressCallback); bool SaveAutoSnapshot(BinaryView* data); + bool SaveAutoSnapshot(BinaryView* data, + const std::function& progressCallback); void BeginUndoActions(); void CommitUndoActions(); @@ -766,7 +772,10 @@ namespace BinaryNinja bool IsAnalysisChanged() const; bool IsBackedByDatabase() const; bool CreateDatabase(const std::string& path); + bool CreateDatabase(const std::string& path, + const std::function& progressCallback); bool SaveAutoSnapshot(); + bool SaveAutoSnapshot(const std::function& progressCallback); void BeginUndoActions(); void AddUndoAction(UndoAction* action); @@ -1626,6 +1635,7 @@ namespace BinaryNinja std::vector GetRegistersReadByInstruction(Architecture* arch, uint64_t addr); std::vector GetRegistersWrittenByInstruction(Architecture* arch, uint64_t addr); std::vector GetStackVariablesReferencedByInstruction(Architecture* arch, uint64_t addr); + std::vector GetConstantsReferencedByInstruction(Architecture* arch, uint64_t addr); Ref GetLiftedIL() const; size_t GetLiftedILForInstruction(Architecture* arch, uint64_t addr); diff --git a/binaryninjacore.h b/binaryninjacore.h index 2ba6f7e6..4d8c31d9 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -1013,6 +1013,12 @@ extern "C" void (*addAction)(void* ctxt, BNMainThreadAction* action); }; + struct BNConstantReference + { + int64_t value; + size_t size; + }; + BINARYNINJACOREAPI char* BNAllocString(const char* contents); BINARYNINJACOREAPI void BNFreeString(char* str); @@ -1105,8 +1111,14 @@ extern "C" BINARYNINJACOREAPI bool BNIsBackedByDatabase(BNFileMetadata* file); BINARYNINJACOREAPI bool BNCreateDatabase(BNBinaryView* data, const char* path); + BINARYNINJACOREAPI bool BNCreateDatabaseWithProgress(BNBinaryView* data, const char* path, + void* ctxt, void (*progress)(void* ctxt, size_t progress, size_t total)); BINARYNINJACOREAPI BNBinaryView* BNOpenExistingDatabase(BNFileMetadata* file, const char* path); + BINARYNINJACOREAPI BNBinaryView* BNOpenExistingDatabaseWithProgress(BNFileMetadata* file, const char* path, + void* ctxt, void (*progress)(void* ctxt, size_t progress, size_t total)); BINARYNINJACOREAPI bool BNSaveAutoSnapshot(BNBinaryView* data); + BINARYNINJACOREAPI bool BNSaveAutoSnapshotWithProgress(BNBinaryView* data, void* ctxt, + void (*progress)(void* ctxt, size_t progress, size_t total)); BINARYNINJACOREAPI char* BNGetFilename(BNFileMetadata* file); BINARYNINJACOREAPI void BNSetFilename(BNFileMetadata* file, const char* name); @@ -1433,6 +1445,9 @@ extern "C" BINARYNINJACOREAPI BNStackVariableReference* BNGetStackVariablesReferencedByInstruction(BNFunction* func, BNArchitecture* arch, uint64_t addr, size_t* count); BINARYNINJACOREAPI void BNFreeStackVariableReferenceList(BNStackVariableReference* refs, size_t count); + BINARYNINJACOREAPI BNConstantReference* BNGetConstantsReferencedByInstruction(BNFunction* func, + BNArchitecture* arch, uint64_t addr, size_t* count); + BINARYNINJACOREAPI void BNFreeConstantReferenceList(BNConstantReference* refs); BINARYNINJACOREAPI BNLowLevelILFunction* BNGetFunctionLiftedIL(BNFunction* func); BINARYNINJACOREAPI size_t BNGetLiftedILForInstruction(BNFunction* func, BNArchitecture* arch, uint64_t addr); diff --git a/binaryview.cpp b/binaryview.cpp index cff3ed10..14393930 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -518,12 +518,25 @@ bool BinaryView::CreateDatabase(const string& path) } +bool BinaryView::CreateDatabase(const string& path, + const function& progressCallback) +{ + return m_file->CreateDatabase(path, this, progressCallback); +} + + bool BinaryView::SaveAutoSnapshot() { return m_file->SaveAutoSnapshot(this); } +bool BinaryView::SaveAutoSnapshot(const function& progressCallback) +{ + return m_file->SaveAutoSnapshot(this, progressCallback); +} + + void BinaryView::BeginUndoActions() { m_file->BeginUndoActions(); diff --git a/filemetadata.cpp b/filemetadata.cpp index 51e152bf..b3764167 100644 --- a/filemetadata.cpp +++ b/filemetadata.cpp @@ -25,6 +25,19 @@ using namespace Json; using namespace std; +struct DatabaseProgressCallbackContext +{ + std::function func; +}; + + +static void DatabaseProgressCallback(void* ctxt, size_t progress, size_t total) +{ + DatabaseProgressCallbackContext* cb = (DatabaseProgressCallbackContext*)ctxt; + cb->func(progress, total); +} + + char* NavigationHandler::GetCurrentViewCallback(void* ctxt) { NavigationHandler* handler = (NavigationHandler*)ctxt; @@ -246,6 +259,15 @@ bool FileMetadata::CreateDatabase(const string& name, BinaryView* data) } +bool FileMetadata::CreateDatabase(const string& name, BinaryView* data, + const function& progressCallback) +{ + DatabaseProgressCallbackContext cb; + cb.func = progressCallback; + return BNCreateDatabaseWithProgress(data->GetObject(), name.c_str(), &cb, DatabaseProgressCallback); +} + + Ref FileMetadata::OpenExistingDatabase(const string& path) { BNBinaryView* data = BNOpenExistingDatabase(m_object, path.c_str()); @@ -255,12 +277,33 @@ Ref FileMetadata::OpenExistingDatabase(const string& path) } +Ref FileMetadata::OpenExistingDatabase(const string& path, + const function& progressCallback) +{ + DatabaseProgressCallbackContext cb; + cb.func = progressCallback; + BNBinaryView* data = BNOpenExistingDatabaseWithProgress(m_object, path.c_str(), &cb, DatabaseProgressCallback); + if (!data) + return nullptr; + return new BinaryView(data); +} + + bool FileMetadata::SaveAutoSnapshot(BinaryView* data) { return BNSaveAutoSnapshot(data->GetObject()); } +bool FileMetadata::SaveAutoSnapshot(BinaryView* data, + const function& progressCallback) +{ + DatabaseProgressCallbackContext cb; + cb.func = progressCallback; + return BNSaveAutoSnapshotWithProgress(data->GetObject(), &cb, DatabaseProgressCallback); +} + + void FileMetadata::BeginUndoActions() { BNBeginUndoActions(m_object); diff --git a/function.cpp b/function.cpp index c5033276..27193992 100644 --- a/function.cpp +++ b/function.cpp @@ -288,6 +288,19 @@ vector Function::GetStackVariablesReferencedByInstructio } +vector Function::GetConstantsReferencedByInstruction(Architecture* arch, uint64_t addr) +{ + size_t count; + BNConstantReference* refs = BNGetConstantsReferencedByInstruction(m_object, arch->GetObject(), addr, &count); + + vector result; + result.insert(result.end(), &refs[0], &refs[count]); + + BNFreeConstantReferenceList(refs); + return result; +} + + Ref Function::GetLiftedIL() const { return new LowLevelILFunction(BNGetFunctionLiftedIL(m_object)); diff --git a/python/__init__.py b/python/__init__.py index 027c2a1f..092e07c0 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -372,18 +372,32 @@ class FileMetadata(object): def navigate(self, view, offset): return core.BNNavigate(self.handle, str(view), offset) - def create_database(self, filename): - - return core.BNCreateDatabase(self.raw.handle, str(filename)) + def create_database(self, filename, progress_func = None): + if progress_func is None: + return core.BNCreateDatabase(self.raw.handle, str(filename)) + else: + return core.BNCreateDatabaseWithProgress(self.raw.handle, str(filename), None, + ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)( + lambda ctxt, cur, total: progress_func(cur, total))) - def open_existing_database(self, filename): - view = core.BNOpenExistingDatabase(self.handle, str(filename)) + def open_existing_database(self, filename, progress_func = None): + if progress_func is None: + view = core.BNOpenExistingDatabase(self.handle, str(filename)) + else: + view = core.BNOpenExistingDatabaseWithProgress(self.handle, str(filename), None, + ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)( + lambda ctxt, cur, total: progress_func(cur, total))) if view is None: return None return BinaryView(self, handle = view) - def save_auto_snapshot(self): - return core.BNSaveAutoSnapshot(self.raw.handle) + def save_auto_snapshot(self, progress_func = None): + if progress_func is None: + return core.BNSaveAutoSnapshot(self.raw.handle) + else: + return core.BNSaveAutoSnapshotWithProgress(self.raw.handle, None, + ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong)( + lambda ctxt, cur, total: progress_func(cur, total))) def get_view_of_type(self, name): view = core.BNGetFileViewOfType(self.handle, str(name)) @@ -1683,26 +1697,28 @@ class BinaryView(object): """ return core.LittleEndian - def create_database(self, filename): + def create_database(self, filename, progress_func = None): """ ``perform_get_database`` writes the current database (.bndb) file out to the specified file. :param str filename: path and filename to write the bndb to, this string `should` have ".bndb" appended to it. + :param callable() progress_func: optional function to be called with the current progress and total count. :return: true on success, false on failure :rtype: bool """ return self.file.create_database(filename) - def save_auto_snapshot(self): + def save_auto_snapshot(self, progress_func = None): """ ``save_auto_snapshot`` saves the current database to the already created file. .. note:: :py:method:`create_database` should have been called prior to executing this method + :param callable() progress_func: optional function to be called with the current progress and total count. :return: True if it successfully saved the snapshot, False otherwise :rtype: bool """ - return self.file.save_auto_snapshot() + return self.file.save_auto_snapshot(progress_func) def get_view_of_type(self, name): """ @@ -4248,6 +4264,16 @@ class StackVariableReference: return "" % (self.source_operand, self.name, self.referenced_offset) return "" % (self.source_operand, self.name) +class ConstantReference: + def __init__(self, val, size): + self.value = val + self.size = size + + def __repr__(self): + if self.size == 0: + return "" % self.value + return "" % (self.value, self.size) + class IndirectBranchInfo: def __init__(self, source_arch, source_addr, dest_arch, dest_addr, auto_defined): self.source_arch = source_arch @@ -4531,6 +4557,15 @@ class Function(object): core.BNFreeStackVariableReferenceList(refs, count.value) return result + def get_constants_referenced_by(self, arch, addr): + count = ctypes.c_ulonglong() + refs = core.BNGetConstantsReferencedByInstruction(self.handle, arch.handle, addr, count) + result = [] + for i in xrange(0, count.value): + result.append(ConstantReference(refs[i].value, refs[i].size)) + core.BNFreeConstantReferenceList(refs) + return result + def get_lifted_il_at(self, arch, addr): return core.BNGetLiftedILForInstruction(self.handle, arch.handle, addr) -- cgit v1.3.1 From 3978e18b09ca745fd08defb8f00fbece267beaf2 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Tue, 30 Aug 2016 21:59:40 -0400 Subject: Add API to reanalyze --- binaryninjaapi.h | 4 ++++ binaryninjacore.h | 3 +++ binaryview.cpp | 6 ++++++ function.cpp | 6 ++++++ python/__init__.py | 16 ++++++++++++++++ 5 files changed, 35 insertions(+) (limited to 'binaryview.cpp') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index f60ee159..7c417623 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -919,6 +919,8 @@ namespace BinaryNinja void UndefineUserType(const std::string& name); bool FindNextData(uint64_t start, const DataBuffer& data, uint64_t& result, BNFindFlag flags = NoFindFlags); + + void Reanalyze(); }; class BinaryData: public BinaryView @@ -1672,6 +1674,8 @@ namespace BinaryNinja size_t operand); void SetIntegerConstantDisplayType(Architecture* arch, uint64_t instrAddr, uint64_t value, size_t operand, BNIntegerDisplayType type); + + void Reanalyze(); }; struct FunctionGraphEdge diff --git a/binaryninjacore.h b/binaryninjacore.h index c293f940..3aa0a1e6 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -1565,6 +1565,9 @@ extern "C" BINARYNINJACOREAPI void BNUndefineAnalysisType(BNBinaryView* view, const char* name); BINARYNINJACOREAPI void BNUndefineUserAnalysisType(BNBinaryView* view, const char* name); + BINARYNINJACOREAPI void BNReanalyzeAllFunctions(BNBinaryView* view); + BINARYNINJACOREAPI void BNReanalyzeFunction(BNFunction* func); + // Disassembly settings BINARYNINJACOREAPI BNDisassemblySettings* BNCreateDisassemblySettings(void); BINARYNINJACOREAPI BNDisassemblySettings* BNNewDisassemblySettingsReference(BNDisassemblySettings* settings); diff --git a/binaryview.cpp b/binaryview.cpp index 14393930..6631f3d6 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -1440,6 +1440,12 @@ bool BinaryView::FindNextData(uint64_t start, const DataBuffer& data, uint64_t& } +void BinaryView::Reanalyze() +{ + BNReanalyzeAllFunctions(m_object); +} + + BinaryData::BinaryData(FileMetadata* file): BinaryView(BNCreateBinaryDataView(file->GetObject())) { } diff --git a/function.cpp b/function.cpp index 78a33bda..cbd9ec40 100644 --- a/function.cpp +++ b/function.cpp @@ -572,3 +572,9 @@ void Function::SetIntegerConstantDisplayType(Architecture* arch, uint64_t instrA { BNSetIntegerConstantDisplayType(m_object, arch->GetObject(), instrAddr, value, operand, type); } + + +void Function::Reanalyze() +{ + BNReanalyzeFunction(m_object); +} diff --git a/python/__init__.py b/python/__init__.py index e9f036ae..82aaba32 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -3231,6 +3231,14 @@ class BinaryView(object): return None return result.value + def reanalyze(self): + """ + ``reanalyze`` causes all functions to be reanalyzed. This function does not wait for the analysis to finish. + + :rtype: None + """ + core.BNReanalyzeAllFunctions(self.handle) + def __setattr__(self, name, value): try: object.__setattr__(self,name,value) @@ -4677,6 +4685,14 @@ class Function(object): display_type = core.BNIntegerDisplayType_by_name[display_type] core.BNSetIntegerConstantDisplayType(self.handle, arch.handle, instr_addr, value, operand, display_type) + def reanalyze(self): + """ + ``reanalyze`` causes this functions to be reanalyzed. This function does not wait for the analysis to finish. + + :rtype: None + """ + core.BNReanalyzeFunction(self.handle) + class BasicBlockEdge: def __init__(self, branch_type, target, arch): self.type = core.BNBranchType_names[branch_type] -- cgit v1.3.1 From 75f597bb8fcd58315537f1dcd9802bbaadcdbd36 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Wed, 31 Aug 2016 18:06:31 -0400 Subject: Add API to determine if an address is backed by the file --- binaryninjaapi.h | 3 +++ binaryninjacore.h | 2 ++ binaryview.cpp | 20 ++++++++++++++++++++ python/__init__.py | 39 ++++++++++++++++++++++++++++++++++++--- 4 files changed, 61 insertions(+), 3 deletions(-) (limited to 'binaryview.cpp') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index fed1bbd9..342dcc48 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -730,6 +730,7 @@ namespace BinaryNinja virtual bool PerformIsOffsetReadable(uint64_t offset); virtual bool PerformIsOffsetWritable(uint64_t offset); virtual bool PerformIsOffsetExecutable(uint64_t offset); + virtual bool PerformIsOffsetBackedByFile(uint64_t offset); virtual uint64_t PerformGetNextValidOffset(uint64_t offset); virtual uint64_t PerformGetStart() const { return 0; } virtual uint64_t PerformGetLength() const { return 0; } @@ -756,6 +757,7 @@ namespace BinaryNinja static bool IsOffsetReadableCallback(void* ctxt, uint64_t offset); static bool IsOffsetWritableCallback(void* ctxt, uint64_t offset); static bool IsOffsetExecutableCallback(void* ctxt, uint64_t offset); + static bool IsOffsetBackedByFileCallback(void* ctxt, uint64_t offset); static uint64_t GetNextValidOffsetCallback(void* ctxt, uint64_t offset); static uint64_t GetStartCallback(void* ctxt); static uint64_t GetLengthCallback(void* ctxt); @@ -811,6 +813,7 @@ namespace BinaryNinja bool IsOffsetReadable(uint64_t offset) const; bool IsOffsetWritable(uint64_t offset) const; bool IsOffsetExecutable(uint64_t offset) const; + bool IsOffsetBackedByFile(uint64_t offset) const; uint64_t GetNextValidOffset(uint64_t offset) const; uint64_t GetStart() const; diff --git a/binaryninjacore.h b/binaryninjacore.h index a24ce9fa..6eff4d46 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -637,6 +637,7 @@ extern "C" bool (*isOffsetReadable)(void* ctxt, uint64_t offset); bool (*isOffsetWritable)(void* ctxt, uint64_t offset); bool (*isOffsetExecutable)(void* ctxt, uint64_t offset); + bool (*isOffsetBackedByFile)(void* ctxt, uint64_t offset); uint64_t (*getNextValidOffset)(void* ctxt, uint64_t offset); uint64_t (*getStart)(void* ctxt); uint64_t (*getLength)(void* ctxt); @@ -1164,6 +1165,7 @@ extern "C" BINARYNINJACOREAPI bool BNIsOffsetReadable(BNBinaryView* view, uint64_t offset); BINARYNINJACOREAPI bool BNIsOffsetWritable(BNBinaryView* view, uint64_t offset); BINARYNINJACOREAPI bool BNIsOffsetExecutable(BNBinaryView* view, uint64_t offset); + BINARYNINJACOREAPI bool BNIsOffsetBackedByFile(BNBinaryView* view, uint64_t offset); BINARYNINJACOREAPI uint64_t BNGetNextValidOffset(BNBinaryView* view, uint64_t offset); BINARYNINJACOREAPI uint64_t BNGetStartOffset(BNBinaryView* view); BINARYNINJACOREAPI uint64_t BNGetEndOffset(BNBinaryView* view); diff --git a/binaryview.cpp b/binaryview.cpp index 6631f3d6..1c03eca5 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -258,6 +258,7 @@ BinaryView::BinaryView(const std::string& typeName, FileMetadata* file) view.isOffsetReadable = IsOffsetReadableCallback; view.isOffsetWritable = IsOffsetWritableCallback; view.isOffsetExecutable = IsOffsetExecutableCallback; + view.isOffsetBackedByFile = IsOffsetBackedByFileCallback; view.getNextValidOffset = GetNextValidOffsetCallback; view.getStart = GetStartCallback; view.getLength = GetLengthCallback; @@ -357,6 +358,13 @@ bool BinaryView::IsOffsetExecutableCallback(void* ctxt, uint64_t offset) } +bool BinaryView::IsOffsetBackedByFileCallback(void* ctxt, uint64_t offset) +{ + BinaryView* view = (BinaryView*)ctxt; + return view->PerformIsOffsetBackedByFile(offset); +} + + uint64_t BinaryView::GetNextValidOffsetCallback(void* ctxt, uint64_t offset) { BinaryView* view = (BinaryView*)ctxt; @@ -439,6 +447,12 @@ bool BinaryView::PerformIsOffsetExecutable(uint64_t offset) } +bool BinaryView::PerformIsOffsetBackedByFile(uint64_t offset) +{ + return PerformIsValidOffset(offset); +} + + uint64_t BinaryView::PerformGetNextValidOffset(uint64_t offset) { if (offset < PerformGetStart()) @@ -696,6 +710,12 @@ bool BinaryView::IsOffsetExecutable(uint64_t offset) const } +bool BinaryView::IsOffsetBackedByFile(uint64_t offset) const +{ + return BNIsOffsetBackedByFile(m_object, offset); +} + + uint64_t BinaryView::GetNextValidOffset(uint64_t offset) const { return BNGetNextValidOffset(m_object, offset); diff --git a/python/__init__.py b/python/__init__.py index b8a87aff..d199385a 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -945,6 +945,7 @@ class BinaryView(object): self._cb.isOffsetReadable = self._cb.isOffsetReadable.__class__(self._is_offset_readable) self._cb.isOffsetWritable = self._cb.isOffsetWritable.__class__(self._is_offset_writable) self._cb.isOffsetExecutable = self._cb.isOffsetExecutable.__class__(self._is_offset_executable) + self._cb.isOffsetBackedByFile = self._cb.isOffsetExecutable.__class__(self._is_offset_backed_by_file) self._cb.getNextValidOffset = self._cb.getNextValidOffset.__class__(self._get_next_valid_offset) self._cb.getStart = self._cb.getStart.__class__(self._get_start) self._cb.getLength = self._cb.getLength.__class__(self._get_length) @@ -1389,6 +1390,13 @@ class BinaryView(object): log_error(traceback.format_exc()) return False + def _is_offset_backed_by_file(self, ctxt, offset): + try: + return self.perform_is_offset_backed_by_file(offset) + except: + log_error(traceback.format_exc()) + return False + def _get_next_valid_offset(self, ctxt, offset): try: return self.perform_get_next_valid_offset(offset) @@ -1632,6 +1640,20 @@ class BinaryView(object): """ return self.is_valid_offset(addr) + def perform_is_offset_backed_by_file(self, addr): + """ + ``perform_is_offset_backed_by_file`` implements a check if a virtual address ``addr`` is backed by the file + contents. + + .. warning:: This method **must not** be called directly. + + :param int addr: a virtual address to be checked + :return: true if the virtual address is backed by the file, false if the virtual address is initialized by \ + the loader + :rtype: int + """ + return self.is_valid_offset(addr) + def perform_get_next_valid_offset(self, addr): """ ``perform_get_next_valid_offset`` implements a query for the next valid readable, writable, or executable virtual @@ -1933,7 +1955,7 @@ class BinaryView(object): def is_offset_readable(self, addr): """ - ``is_valid_offset`` checks if an virtual address ``addr`` is valid for reading. + ``is_offset_readable`` checks if an virtual address ``addr`` is valid for reading. :param int addr: a virtual address to be checked :return: true if the virtual address is valid for reading, false if the virtual address is invalid or error @@ -1943,7 +1965,7 @@ class BinaryView(object): def is_offset_writable(self, addr): """ - ``is_valid_offset`` checks if an virtual address ``addr`` is valid for writing. + ``is_offset_writable`` checks if an virtual address ``addr`` is valid for writing. :param int addr: a virtual address to be checked :return: true if the virtual address is valid for writing, false if the virtual address is invalid or error @@ -1953,7 +1975,7 @@ class BinaryView(object): def is_offset_executable(self, addr): """ - ``is_valid_offset`` checks if an virtual address ``addr`` is valid for executing. + ``is_offset_executable`` checks if an virtual address ``addr`` is valid for executing. :param int addr: a virtual address to be checked :return: true if the virtual address is valid for executing, false if the virtual address is invalid or error @@ -1961,6 +1983,17 @@ class BinaryView(object): """ return core.BNIsOffsetExecutable(self.handle, addr) + def is_offset_backed_by_file(self, addr): + """ + ``is_offset_backed_by_file`` checks if an virtual address ``addr`` is backed by the file contents. + + :param int addr: a virtual address to be checked + :return: true if the virtual address is backed by the file, false if the virtual address is initialized by \ + the loader + :rtype: bool + """ + return core.BNIsOffsetBackedByFile(self.handle, addr) + def save(self, dest): """ ``save`` saves the original binary file to the provided destination ``dest`` along with any modifications. -- cgit v1.3.1 From 6d3fe290eb20e31a33e929933c01d2ca3eb43da1 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Sat, 10 Sep 2016 00:36:27 -0400 Subject: Add API for list of basic blocks starting at an address --- binaryninjaapi.h | 1 + binaryninjacore.h | 1 + binaryview.cpp | 14 ++++++++++++++ python/__init__.py | 16 ++++++++++++++++ 4 files changed, 32 insertions(+) (limited to 'binaryview.cpp') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 9c7ff4f1..d4df479b 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -867,6 +867,7 @@ namespace BinaryNinja Ref GetRecentBasicBlockForAddress(uint64_t addr); std::vector> GetBasicBlocksForAddress(uint64_t addr); + std::vector> GetBasicBlocksStartingAtAddress(uint64_t addr); std::vector GetCodeReferences(uint64_t addr); std::vector GetCodeReferences(uint64_t addr, uint64_t len); diff --git a/binaryninjacore.h b/binaryninjacore.h index f917c2fa..51bf3391 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -1420,6 +1420,7 @@ extern "C" BINARYNINJACOREAPI void BNFreeBasicBlockList(BNBasicBlock** blocks, size_t count); BINARYNINJACOREAPI BNBasicBlock* BNGetRecentBasicBlockForAddress(BNBinaryView* view, uint64_t addr); BINARYNINJACOREAPI BNBasicBlock** BNGetBasicBlocksForAddress(BNBinaryView* view, uint64_t addr, size_t* count); + BINARYNINJACOREAPI BNBasicBlock** BNGetBasicBlocksStartingAtAddress(BNBinaryView* view, uint64_t addr, size_t* count); BINARYNINJACOREAPI BNLowLevelILFunction* BNGetFunctionLowLevelIL(BNFunction* func); BINARYNINJACOREAPI size_t BNGetLowLevelILForInstruction(BNFunction* func, BNArchitecture* arch, uint64_t addr); diff --git a/binaryview.cpp b/binaryview.cpp index 1c03eca5..0a7f23ce 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -987,6 +987,20 @@ vector> BinaryView::GetBasicBlocksForAddress(uint64_t addr) } +vector> BinaryView::GetBasicBlocksStartingAtAddress(uint64_t addr) +{ + size_t count; + BNBasicBlock** blocks = BNGetBasicBlocksStartingAtAddress(m_object, addr, &count); + + vector> result; + for (size_t i = 0; i < count; i++) + result.push_back(new BasicBlock(BNNewBasicBlockReference(blocks[i]))); + + BNFreeBasicBlockList(blocks, count); + return result; +} + + vector BinaryView::GetCodeReferences(uint64_t addr) { size_t count; diff --git a/python/__init__.py b/python/__init__.py index 7978fd2c..33202a2c 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -2288,6 +2288,22 @@ class BinaryView(object): core.BNFreeBasicBlockList(blocks, count.value) return result + def get_basic_blocks_starting_at(self, addr): + """ + ``get_basic_blocks_at`` get a list of :py:Class:`BasicBlock` objects which start at the provided virtual address. + + :param int addr: virtual address of BasicBlock desired + :return: a list of :py:Class:`BasicBlock` objects + :rtype: list(BasicBlock) + """ + count = ctypes.c_ulonglong(0) + blocks = core.BNGetBasicBlocksStartingAtAddress(self.handle, addr, count) + result = [] + for i in xrange(0, count.value): + result.append(BasicBlock(self, core.BNNewBasicBlockReference(blocks[i]))) + core.BNFreeBasicBlockList(blocks, count.value) + return result + def get_recent_basic_block_at(self, addr): block = core.BNGetRecentBasicBlockForAddress(self.handle, addr) if block is None: -- cgit v1.3.1 From 2ec606fab8754dad2135deec2e72e87d39382978 Mon Sep 17 00:00:00 2001 From: Rusty Wagner Date: Fri, 16 Sep 2016 19:09:01 -0400 Subject: Add APIs for user interaction from plugins --- binaryninjaapi.h | 50 ++++++++++ binaryninjacore.h | 39 ++++++++ binaryview.cpp | 33 +++++++ interaction.cpp | 286 +++++++++++++++++++++++++++++++++++++++++++++++++++++ python/__init__.py | 248 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 656 insertions(+) create mode 100644 interaction.cpp (limited to 'binaryview.cpp') diff --git a/binaryninjaapi.h b/binaryninjaapi.h index 3400cca7..720a8eb6 100644 --- a/binaryninjaapi.h +++ b/binaryninjaapi.h @@ -275,6 +275,7 @@ namespace BinaryNinja class DataBuffer; class MainThreadAction; class MainThreadActionHandler; + class InteractionHandler; /*! Logs to the error console with the given BNLogLevel. @@ -381,6 +382,26 @@ namespace BinaryNinja size_t GetWorkerThreadCount(); void SetWorkerThreadCount(size_t count); + std::string MarkdownToHTML(const std::string& contents); + + void RegisterInteractionHandler(InteractionHandler* handler); + + 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 = ""); + + 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); + bool GetAddressInput(uint64_t& result, const std::string& prompt, const std::string& title); + bool GetChoiceInput(size_t& idx, const std::string& prompt, const std::string& title, + const std::vector& choices); + bool GetOpenFileNameInput(std::string& result, const std::string& prompt, const std::string& ext = ""); + bool GetSaveFileNameInput(std::string& result, const std::string& prompt, const std::string& ext = "", + const std::string& defaultName = ""); + bool GetDirectoryNameInput(std::string& result, const std::string& prompt, const std::string& defaultName = ""); + class DataBuffer { BNDataBuffer* m_buffer; @@ -935,6 +956,13 @@ namespace BinaryNinja bool FindNextData(uint64_t start, const DataBuffer& data, uint64_t& result, BNFindFlag flags = NoFindFlags); void Reanalyze(); + + 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); + 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); }; class BinaryData: public BinaryView @@ -2279,4 +2307,26 @@ namespace BinaryNinja static std::vector> GetRunningTasks(); }; + + class InteractionHandler + { + public: + virtual void ShowPlainTextReport(Ref view, const std::string& title, const std::string& contents) = 0; + virtual void ShowMarkdownReport(Ref view, const std::string& title, const std::string& contents, + const std::string& plainText); + virtual void ShowHTMLReport(Ref view, const std::string& title, const std::string& contents, + const std::string& plainText); + + 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); + virtual bool GetAddressInput(uint64_t& result, const std::string& prompt, const std::string& title, + Ref view, uint64_t currentAddr); + virtual bool GetChoiceInput(size_t& idx, const std::string& prompt, const std::string& title, + const std::vector& choices) = 0; + virtual bool GetOpenFileNameInput(std::string& result, const std::string& prompt, const std::string& ext = ""); + virtual bool GetSaveFileNameInput(std::string& result, const std::string& prompt, + const std::string& ext = "", const std::string& defaultName = ""); + virtual bool GetDirectoryNameInput(std::string& result, const std::string& prompt, + const std::string& defaultName = ""); + }; } diff --git a/binaryninjacore.h b/binaryninjacore.h index 89dceba1..34806b6c 100644 --- a/binaryninjacore.h +++ b/binaryninjacore.h @@ -1050,6 +1050,26 @@ extern "C" uint8_t mix, r, g, b, alpha; }; + struct BNInteractionHandlerCallbacks + { + void* context; + void (*showPlainTextReport)(void* ctxt, BNBinaryView* view, const char* title, const char* contents); + void (*showMarkdownReport)(void* ctxt, BNBinaryView* view, const char* title, const char* contents, + const char* plaintext); + void (*showHTMLReport)(void* ctxt, BNBinaryView* view, const char* title, const char* contents, + const char* plaintext); + 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, + BNBinaryView* view, uint64_t currentAddr); + bool (*getChoiceInput)(void* ctxt, size_t* result, const char* prompt, const char* title, + const char** choices, size_t count); + bool (*getOpenFileNameInput)(void* ctxt, char** result, const char* prompt, const char* ext); + bool (*getSaveFileNameInput)(void* ctxt, char** result, const char* prompt, const char* ext, + const char* defaultName); + bool (*getDirectoryNameInput)(void* ctxt, char** result, const char* prompt, const char* defaultName); + }; + BINARYNINJACOREAPI char* BNAllocString(const char* contents); BINARYNINJACOREAPI void BNFreeString(char* str); @@ -2030,6 +2050,25 @@ extern "C" BINARYNINJACOREAPI void BNCancelBackgroundTask(BNBackgroundTask* task); BINARYNINJACOREAPI bool BNIsBackgroundTaskFinished(BNBackgroundTask* task); + // Interaction APIs + BINARYNINJACOREAPI void BNRegisterInteractionHandler(BNInteractionHandlerCallbacks* callbacks); + BINARYNINJACOREAPI char* BNMarkdownToHTML(const char* contents); + BINARYNINJACOREAPI void BNShowPlainTextReport(BNBinaryView* view, const char* title, const char* contents); + BINARYNINJACOREAPI void BNShowMarkdownReport(BNBinaryView* view, const char* title, const char* contents, + const char* plaintext); + BINARYNINJACOREAPI void BNShowHTMLReport(BNBinaryView* view, const char* title, const char* contents, + const char* plaintext); + 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, + BNBinaryView* view, uint64_t currentAddr); + BINARYNINJACOREAPI bool BNGetChoiceInput(size_t* result, const char* prompt, const char* title, + const char** choices, size_t count); + BINARYNINJACOREAPI bool BNGetOpenFileNameInput(char** result, const char* prompt, const char* ext); + BINARYNINJACOREAPI bool BNGetSaveFileNameInput(char** result, const char* prompt, const char* ext, + const char* defaultName); + BINARYNINJACOREAPI bool BNGetDirectoryNameInput(char** result, const char* prompt, const char* defaultName); + #ifdef __cplusplus } #endif diff --git a/binaryview.cpp b/binaryview.cpp index 0a7f23ce..863d57b2 100644 --- a/binaryview.cpp +++ b/binaryview.cpp @@ -1480,6 +1480,39 @@ void BinaryView::Reanalyze() } +void BinaryView::ShowPlainTextReport(const string& title, const string& contents) +{ + BNShowPlainTextReport(m_object, title.c_str(), contents.c_str()); +} + + +void BinaryView::ShowMarkdownReport(const string& title, const string& contents, const string& plainText) +{ + BNShowMarkdownReport(m_object, title.c_str(), contents.c_str(), plainText.c_str()); +} + + +void BinaryView::ShowHTMLReport(const string& title, const string& contents, const string& plainText) +{ + BNShowHTMLReport(m_object, title.c_str(), contents.c_str(), plainText.c_str()); +} + + +bool BinaryView::GetAddressInput(uint64_t& result, const string& prompt, const string& title) +{ + uint64_t currentAddress = 0; + if (m_file) + currentAddress = m_file->GetCurrentOffset(); + return BNGetAddressInput(&result, prompt.c_str(), title.c_str(), m_object, currentAddress); +} + + +bool BinaryView::GetAddressInput(uint64_t& result, const string& prompt, const string& title, uint64_t currentAddress) +{ + return BNGetAddressInput(&result, prompt.c_str(), title.c_str(), m_object, currentAddress); +} + + BinaryData::BinaryData(FileMetadata* file): BinaryView(BNCreateBinaryDataView(file->GetObject())) { } diff --git a/interaction.cpp b/interaction.cpp new file mode 100644 index 00000000..f7763679 --- /dev/null +++ b/interaction.cpp @@ -0,0 +1,286 @@ +#include +#include +#include "binaryninjaapi.h" + +using namespace std; +using namespace BinaryNinja; + + +void InteractionHandler::ShowMarkdownReport(Ref view, const string& title, const string& contents, + const string& plainText) +{ + ShowHTMLReport(view, title, MarkdownToHTML(contents), plainText); +} + + +void InteractionHandler::ShowHTMLReport(Ref view, const string& title, const string&, + const string& plainText) +{ + if (plainText.size() != 0) + ShowPlainTextReport(view, title, plainText); +} + + +bool InteractionHandler::GetIntegerInput(int64_t& result, const string& prompt, const string& title) +{ + string input; + + while (true) + { + string input; + if (!GetTextLineInput(input, prompt, title)) + return false; + if (input.size() == 0) + return false; + + errno = 0; + result = strtoll(input.c_str(), nullptr, 0); + if (errno != 0) + { + errno = 0; + result = strtoull(input.c_str(), nullptr, 0); + if (errno != 0) + continue; + } + + return true; + } +} + + +bool InteractionHandler::GetAddressInput(uint64_t& result, const string& prompt, const string& title, + Ref, uint64_t) +{ + int64_t value; + if (!GetIntegerInput(value, prompt, title)) + return false; + result = (uint64_t)value; + return true; +} + + +bool InteractionHandler::GetOpenFileNameInput(string& result, const string& prompt, const string&) +{ + return GetTextLineInput(result, prompt, "Open File"); +} + + +bool InteractionHandler::GetSaveFileNameInput(string& result, const string& prompt, const string&, const string&) +{ + return GetTextLineInput(result, prompt, "Save File"); +} + + +bool InteractionHandler::GetDirectoryNameInput(string& result, const string& prompt, const string&) +{ + return GetTextLineInput(result, prompt, "Select Directory"); +} + + +static void ShowPlainTextReportCallback(void* ctxt, BNBinaryView* view, const char* title, const char* contents) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + handler->ShowPlainTextReport(view ? new BinaryView(BNNewViewReference(view)) : nullptr, title, contents); +} + + +static void ShowMarkdownReportCallback(void* ctxt, BNBinaryView* view, const char* title, const char* contents, + const char* plaintext) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + handler->ShowMarkdownReport(view ? new BinaryView(BNNewViewReference(view)) : nullptr, title, contents, plaintext); +} + + +static void ShowHTMLReportCallback(void* ctxt, BNBinaryView* view, const char* title, const char* contents, + const char* plaintext) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + handler->ShowHTMLReport(view ? new BinaryView(BNNewViewReference(view)) : nullptr, title, contents, plaintext); +} + + +static bool GetTextLineInputCallback(void* ctxt, char** result, const char* prompt, const char* title) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + string value; + if (!handler->GetTextLineInput(value, prompt, title)) + return false; + *result = BNAllocString(value.c_str()); + return true; +} + + +static bool GetIntegerInputCallback(void* ctxt, int64_t* result, const char* prompt, const char* title) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + return handler->GetIntegerInput(*result, prompt, title); +} + + +static bool GetAddressInputCallback(void* ctxt, uint64_t* result, const char* prompt, const char* title, + BNBinaryView* view, uint64_t currentAddr) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + return handler->GetAddressInput(*result, prompt, title, view ? new BinaryView(BNNewViewReference(view)) : nullptr, + currentAddr); +} + + +static bool GetChoiceInputCallback(void* ctxt, size_t* result, const char* prompt, const char* title, + const char** choices, size_t count) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + vector choiceStrs; + for (size_t i = 0; i < count; i++) + choiceStrs.push_back(choices[i]); + return handler->GetChoiceInput(*result, prompt, title, choiceStrs); +} + + +static bool GetOpenFileNameInputCallback(void* ctxt, char** result, const char* prompt, const char* ext) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + string value; + if (!handler->GetOpenFileNameInput(value, prompt, ext)) + return false; + *result = BNAllocString(value.c_str()); + return true; +} + + +static bool GetSaveFileNameInputCallback(void* ctxt, char** result, const char* prompt, const char* ext, + const char* defaultName) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + string value; + if (!handler->GetSaveFileNameInput(value, prompt, ext, defaultName)) + return false; + *result = BNAllocString(value.c_str()); + return true; +} + + +static bool GetDirectoryNameInputCallback(void* ctxt, char** result, const char* prompt, const char* defaultName) +{ + InteractionHandler* handler = (InteractionHandler*)ctxt; + string value; + if (!handler->GetDirectoryNameInput(value, prompt, defaultName)) + return false; + *result = BNAllocString(value.c_str()); + return true; +} + + +void BinaryNinja::RegisterInteractionHandler(InteractionHandler* handler) +{ + BNInteractionHandlerCallbacks cb; + cb.context = handler; + cb.showPlainTextReport = ShowPlainTextReportCallback; + cb.showMarkdownReport = ShowMarkdownReportCallback; + cb.showHTMLReport = ShowHTMLReportCallback; + cb.getTextLineInput = GetTextLineInputCallback; + cb.getIntegerInput = GetIntegerInputCallback; + cb.getAddressInput = GetAddressInputCallback; + cb.getChoiceInput = GetChoiceInputCallback; + cb.getOpenFileNameInput = GetOpenFileNameInputCallback; + cb.getSaveFileNameInput = GetSaveFileNameInputCallback; + cb.getDirectoryNameInput = GetDirectoryNameInputCallback; + BNRegisterInteractionHandler(&cb); +} + + +string BinaryNinja::MarkdownToHTML(const string& contents) +{ + char* str = BNMarkdownToHTML(contents.c_str()); + string result = str; + BNFreeString(str); + return result; +} + + +void BinaryNinja::ShowPlainTextReport(const string& title, const string& contents) +{ + BNShowPlainTextReport(nullptr, title.c_str(), contents.c_str()); +} + + +void BinaryNinja::ShowMarkdownReport(const string& title, const string& contents, const string& plainText) +{ + BNShowMarkdownReport(nullptr, title.c_str(), contents.c_str(), plainText.c_str()); +} + + +void BinaryNinja::ShowHTMLReport(const string& title, const string& contents, const string& plainText) +{ + BNShowHTMLReport(nullptr, title.c_str(), contents.c_str(), plainText.c_str()); +} + + +bool BinaryNinja::GetTextLineInput(string& result, const string& prompt, const string& title) +{ + char* value = nullptr; + if (!BNGetTextLineInput(&value, prompt.c_str(), title.c_str())) + return false; + result = value; + BNFreeString(value); + return true; +} + + +bool BinaryNinja::GetIntegerInput(int64_t& result, const string& prompt, const string& title) +{ + return BNGetIntegerInput(&result, prompt.c_str(), title.c_str()); +} + + +bool BinaryNinja::GetAddressInput(uint64_t& result, const string& prompt, const string& title) +{ + return BNGetAddressInput(&result, prompt.c_str(), title.c_str(), nullptr, 0); +} + + +bool BinaryNinja::GetChoiceInput(size_t& idx, const string& prompt, const string& title, + const vector& choices) +{ + const char** choiceStrs = new const char*[choices.size()]; + for (size_t i = 0; i < choices.size(); i++) + choiceStrs[i] = choices[i].c_str(); + bool ok = BNGetChoiceInput(&idx, prompt.c_str(), title.c_str(), choiceStrs, choices.size()); + delete[] choiceStrs; + return ok; +} + + +bool BinaryNinja::GetOpenFileNameInput(string& result, const string& prompt, const string& ext) +{ + char* value = nullptr; + if (!BNGetOpenFileNameInput(&value, prompt.c_str(), ext.c_str())) + return false; + result = value; + BNFreeString(value); + return true; +} + + +bool BinaryNinja::GetSaveFileNameInput(string& result, const string& prompt, const string& ext, + const string& defaultName) +{ + char* value = nullptr; + if (!BNGetSaveFileNameInput(&value, prompt.c_str(), ext.c_str(), defaultName.c_str())) + return false; + result = value; + BNFreeString(value); + return true; +} + + +bool BinaryNinja::GetDirectoryNameInput(string& result, const string& prompt, const string& defaultName) +{ + char* value = nullptr; + if (!BNGetDirectoryNameInput(&value, prompt.c_str(), defaultName.c_str())) + return false; + result = value; + BNFreeString(value); + return true; +} diff --git a/python/__init__.py b/python/__init__.py index 6abbdfa6..854de5c7 100644 --- a/python/__init__.py +++ b/python/__init__.py @@ -3293,6 +3293,23 @@ class BinaryView(object): """ core.BNReanalyzeAllFunctions(self.handle) + def show_plain_text_report(self, title, contents): + core.BNShowPlainTextReport(self.handle, title, contents) + + def show_markdown_report(self, title, contents, plaintext = ""): + core.BNShowMarkdownReport(self.handle, title, contents, plaintext) + + def show_html_report(self, title, contents, plaintext = ""): + core.BNShowHTMLReport(self.handle, title, contents, plaintext) + + def get_address_input(self, prompt, title, current_address = None): + if current_address is None: + current_address = self.file.offset + value = ctypes.c_ulonglong() + if not core.BNGetAddressInput(value, prompt, title, self.handle, current_address): + return None + return value.value + def __setattr__(self, name, value): try: object.__setattr__(self,name,value) @@ -10059,6 +10076,172 @@ class BackgroundTaskThread(BackgroundTask): def join(self): self.thread.join() +class InteractionHandler(object): + _interaction_handler = None + + def __init__(self): + self._cb = core.BNInteractionHandlerCallbacks() + self._cb.context = 0 + 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.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) + self._cb.getChoiceInput = self._cb.getChoiceInput.__class__(self._get_choice_input) + self._cb.getOpenFileNameInput = self._cb.getOpenFileNameInput.__class__(self._get_open_filename_input) + self._cb.getSaveFileNameInput = self._cb.getSaveFileNameInput.__class__(self._get_save_filename_input) + self._cb.getDirectoryNameInput = self._cb.getDirectoryNameInput.__class__(self._get_directory_name_input) + + def register(self): + self.__class__._interaction_handler = self + core.BNRegisterInteractionHandler(self._cb) + + def _show_plain_text_report(self, ctxt, view, title, contents): + try: + if view: + view = BinaryView(None, handle = core.BNNewViewReference(view)) + else: + view = None + self.show_plain_text_report(view, title, contents) + except: + log_error(traceback.format_exc()) + + def _show_markdown_report(self, ctxt, view, title, contents, plaintext): + try: + if view: + view = BinaryView(None, handle = core.BNNewViewReference(view)) + else: + view = None + self.show_markdown_report(view, title, contents, plaintext) + except: + log_error(traceback.format_exc()) + + def _show_html_report(self, ctxt, view, title, contents, plaintext): + try: + if view: + view = BinaryView(None, handle = core.BNNewViewReference(view)) + else: + view = None + self.show_html_report(view, title, contents, plaintext) + except: + log_error(traceback.format_exc()) + + def _get_text_line_input(self, ctxt, result, prompt, title): + try: + value = self.get_text_line_input(prompt, title) + if value is None: + return False + result[0] = core.BNAllocString(str(value)) + return True + except: + log_error(traceback.format_exc()) + + def _get_int_input(self, ctxt, result, prompt, title): + try: + value = self.get_int_input(prompt, title) + if value is None: + return False + result[0] = value + return True + except: + log_error(traceback.format_exc()) + + def _get_address_input(self, ctxt, result, prompt, title, view, current_address): + try: + if view: + view = BinaryView(None, handle = core.BNNewViewReference(view)) + else: + view = None + value = self.get_address_input(prompt, title, view, current_address) + if value is None: + return False + result[0] = value + return True + except: + log_error(traceback.format_exc()) + + def _get_choice_input(self, ctxt, result, prompt, title, choice_buf, count): + try: + choices = [] + for i in xrange(0, count): + choices.append(choice_buf[i]) + value = self.get_choice_input(prompt, title, choices) + if value is None: + return False + result[0] = value + return True + except: + log_error(traceback.format_exc()) + + def _get_open_filename_input(self, ctxt, result, prompt, ext): + try: + value = self.get_open_filename_input(prompt, ext) + if value is None: + return False + result[0] = core.BNAllocString(str(value)) + return True + except: + log_error(traceback.format_exc()) + + def _get_save_filename_input(self, ctxt, result, prompt, ext, default_name): + try: + value = self.get_save_filename_input(prompt, ext, default_name) + if value is None: + return False + result[0] = core.BNAllocString(str(value)) + return True + except: + log_error(traceback.format_exc()) + + def _get_directory_name_input(self, ctxt, result, prompt, default_name): + try: + value = self.get_directory_name_input(prompt, default_name) + if value is None: + return False + result[0] = core.BNAllocString(str(value)) + return True + except: + log_error(traceback.format_exc()) + + def show_plain_text_report(self, view, title, contents): + pass + + def show_markdown_report(self, view, title, contents, plaintext): + self.show_html_report(view, title, markdown_to_html(contents), plaintext) + + def show_html_report(self, view, title, contents, plaintext): + if len(plaintext) != 0: + self.show_plain_text_report(view, title, plaintext) + + def get_text_line_input(self, prompt, title): + return None + + def get_int_input(self, prompt, title): + while True: + text = self.get_text_line_input(prompt, title) + if len(text) == 0: + return False + try: + return int(text) + except: + continue + + def get_address_input(self, prompt, title, view, current_address): + return get_int_input(prompt, title) + + def get_choice_input(self, prompt, title, choices): + return None + + def get_open_filename_input(self, prompt, ext): + return get_text_line_input(prompt, "Open File") + + def get_save_filename_input(self, prompt, ext, default_name): + return get_text_line_input(title, "Save File") + + def get_directory_name_input(self, prompt, default_name): + return get_text_line_input(title, "Select Directory") + def LLIL_TEMP(n): return n | 0x80000000 @@ -10374,6 +10557,71 @@ def get_worker_thread_count(): def set_worker_thread_count(count): core.BNSetWorkerThreadCount(count) +def markdown_to_html(contents): + return core.BNMarkdownToHTML(contents) + +def show_plain_text_report(title, contents): + core.BNShowPlainTextReport(None, title, contents) + +def show_markdown_report(title, contents, plaintext = ""): + core.BNShowMarkdownReport(None, title, contents, plaintext) + +def show_html_report(title, contents, plaintext = ""): + core.BNShowHTMLReport(None, title, contents, plaintext) + +def get_text_line_input(prompt, title): + value = ctypes.c_char_p() + if not core.BNGetTextLineInput(value, prompt, title): + return None + result = value.value + core.BNFreeString(ctypes.cast(value, ctypes.POINTER(ctypes.c_byte))) + return result + +def get_int_input(prompt, title): + value = ctypes.c_longlong() + if not core.BNGetIntegerInput(value, prompt, title): + return None + return value.value + +def get_address_input(prompt, title): + value = ctypes.c_ulonglong() + if not core.BNGetAddressInput(value, prompt, title, None, 0): + return None + return value.value + +def get_choice_input(prompt, title, choices): + choice_buf = (ctypes.c_char_p * len(choices))() + for i in xrange(0, len(choices)): + choice_buf[i] = str(choices[i]) + value = ctypes.c_ulonglong() + if not core.BNGetChoiceInput(value, prompt, title, choice_buf, len(choices)): + return None + return value.value + +def get_open_filename_input(prompt, ext = ""): + value = ctypes.c_char_p() + if not core.BNGetOpenFileNameInput(value, prompt, ext): + return None + result = value.value + core.BNFreeString(ctypes.cast(value, ctypes.POINTER(ctypes.c_byte))) + return result + +def get_save_filename_input(prompt, ext = "", default_name = ""): + value = ctypes.c_char_p() + if not core.BNGetSaveFileNameInput(value, prompt, ext, default_name): + return None + result = value.value + core.BNFreeString(ctypes.cast(value, ctypes.POINTER(ctypes.c_byte))) + return result + +def get_directory_name_input(prompt, default_name = ""): + value = ctypes.c_char_p() + if not core.BNGetDirectoryNameInput(value, prompt, default_name): + return None + result = value.value + core.BNFreeString(ctypes.cast(value, ctypes.POINTER(ctypes.c_byte))) + return result + bundled_plugin_path = core.BNGetBundledPluginDirectory() user_plugin_path = core.BNGetUserPluginDirectory() -- cgit v1.3.1