class JavaInspector(QWidget): """ Java Class/Methods Lists """ def __init__(self, parent=None): super(JavaInspector, self).__init__(parent) self._app_window = parent self._app_window.dwarf.onEnumerateJavaMethodsComplete.connect( self._on_method_enumeration_complete) self._app_window.dwarf.onEnumerateJavaClassesStart.connect( self._on_class_enumeration_start) self._app_window.dwarf.onEnumerateJavaClassesMatch.connect( self._on_class_enumeration_match) self._app_window.dwarf.onEnumerateJavaClassesComplete.connect( self._on_class_enumeration_complete) self._java_classes = DwarfListView(self) self._javaclass_model = QStandardItemModel(0, 1) self._javaclass_model.setHeaderData(0, Qt.Horizontal, 'Class') self._java_classes.setModel(self._javaclass_model) self._java_classes.selectionModel().selectionChanged.connect( self._class_clicked) self._java_classes.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self._java_classes.setContextMenuPolicy(Qt.CustomContextMenu) self._java_classes.customContextMenuRequested.connect( self._on_class_contextmenu) self._java_classes.doubleClicked.connect(self._class_dblclicked) self._java_methods = DwarfListView(self) self._javamethod_model = QStandardItemModel(0, 1) self._javamethod_model.setHeaderData(0, Qt.Horizontal, 'Method') self._java_methods.setModel(self._javamethod_model) self._java_methods.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self._java_methods.setContextMenuPolicy(Qt.CustomContextMenu) self._java_methods.customContextMenuRequested.connect( self._on_method_contextmenu) self._java_methods.doubleClicked.connect(self._method_dblclicked) h_box = QHBoxLayout() h_box.setContentsMargins(0, 0, 0, 0) h_box.addWidget(self._java_classes) h_box.addWidget(self._java_methods) self.setLayout(h_box) # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def update_classes(self): """ Refresh Classeslist """ self._app_window.dwarf.dwarf_api('enumerateJavaClasses') def update_methods(self, class_name): """ Refresh Methodslist """ if class_name: self._app_window.dwarf.dwarf_api('enumerateJavaMethods', class_name) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _class_clicked(self): index = self._java_classes.selectionModel().currentIndex().row() _class = self._javaclass_model.item(index, 0) if _class is None: return self._app_window.dwarf.dwarf_api('enumerateJavaMethods', _class.text()) def _on_class_enumeration_start(self): self._java_classes.clear() def _on_class_enumeration_match(self, java_class): _class_name = QStandardItem() _class_name.setText(java_class) self._javaclass_model.appendRow(_class_name) def _on_class_enumeration_complete(self): self._java_classes.sortByColumn(0, 0) def _on_method_enumeration_complete(self, data): self._java_methods.clear() _class, methods = data for method in methods: _method_name = QStandardItem() _method_name.setText(method) self._javamethod_model.appendRow(_method_name) def _class_dblclicked(self): """ Class DoubleClicked """ index = self._java_classes.selectionModel().currentIndex().row() if index: class_item = self._javaclass_model.item(index, 0) if class_item: class_name = class_item.text() if class_name: self._breakpoint_class(class_name) def _method_dblclicked(self): """ Function DoubleClicked """ class_index = self._java_classes.selectionModel().currentIndex().row() method_index = self._java_methods.selectionModel().currentIndex().row() if class_index and method_index: class_item = self._javaclass_model.item(class_index, 0) method_item = self._javamethod_model.item(method_index, 0) if class_item and method_item: class_name = class_item.text() method_name = method_item.text() if class_name and method_name: self._app_window.dwarf.breakpoint_java(class_name + '.' + method_name) def _breakpoint_class(self, class_name): if class_name: self._app_window.dwarf.breakpoint_java(class_name) def _breakpoint_class_functions(self, class_name): if class_name: self._app_window.dwarf.dwarf_api('breakpointAllJavaMethods', class_name) def _on_class_contextmenu(self, pos): """ Modules ContextMenu """ index = self._java_classes.indexAt(pos).row() glbl_pt = self._java_classes.mapToGlobal(pos) context_menu = QMenu(self) if index != -1: context_menu.addAction( 'Breakpoint constructor', lambda: self._breakpoint_class( self._javaclass_model.item(index, 0).text())) context_menu.addAction( 'Breakpoint all methods', lambda: self._breakpoint_class_functions( self._javaclass_model.item(index, 0).text())) context_menu.addSeparator() if self._java_classes.search_enabled: context_menu.addSeparator() context_menu.addAction('Search', self._java_classes._on_cm_search) context_menu.addAction('Refresh', self.update_classes) context_menu.exec_(glbl_pt) def _breakpoint_method(self, method_name): class_index = self._java_classes.selectionModel().currentIndex().row() if class_index: class_item = self._javaclass_model.item(class_index, 0) if class_item: class_name = class_item.text() if class_name and method_name: self._app_window.dwarf.breakpoint_java(class_name + '.' + method_name) def _cm_refresh_methods(self): index = self._java_classes.selectionModel().currentIndex().row() _class = self._javaclass_model.item(index, 0) if _class is None: return self.update_methods(_class.text()) def _on_method_contextmenu(self, pos): """ Modules ContextMenu """ index = self._java_methods.indexAt(pos).row() glbl_pt = self._java_methods.mapToGlobal(pos) context_menu = QMenu(self) if index != -1: context_menu.addAction( 'Breakpoint method', lambda: self._breakpoint_method( self._javamethod_model.item(index, 0).text())) context_menu.addSeparator() if self._java_methods.search_enabled: context_menu.addSeparator() context_menu.addAction('Search', self._java_methods._on_cm_search) context_menu.addAction('Refresh', self._cm_refresh_methods) context_menu.exec_(glbl_pt)
class JavaExplorerPanel(QWidget): def __init__(self, parent=None): super().__init__(parent=parent) self._app_window = parent self._handle_history = [] self._setup_ui() self._setup_models() def _setup_ui(self): self.setContentsMargins(0, 0, 0, 0) top_font = QFont() top_font.setBold(True) top_font.setPixelSize(19) # main wrapper main_wrapper = QVBoxLayout() main_wrapper.setContentsMargins(1, 1, 1, 1) # wrapwdgt wrap_wdgt = QWidget() self._top_class_name = QLabel(wrap_wdgt) self._top_class_name.setContentsMargins(10, 10, 10, 10) self._top_class_name.setAttribute(Qt.WA_TranslucentBackground, True) # keep this self._top_class_name.setFont(top_font) self._top_class_name.setStyleSheet('color: #ef5350;') wrap_wdgt.setMaximumHeight(self._top_class_name.height() + 20) main_wrapper.addWidget(wrap_wdgt) # left list left_wrap_wdgt = QWidget() left_v_box = QVBoxLayout(left_wrap_wdgt) left_v_box.setContentsMargins(0, 0, 0, 0) methods_label = QLabel('METHODS') font = methods_label.font() font.setBold(True) methods_label.setFont(font) methods_label.setContentsMargins(10, 0, 10, 2) methods_label.setAttribute(Qt.WA_TranslucentBackground, True) # keep this left_v_box.addWidget(methods_label) self._methods_list = DwarfListView() left_v_box.addWidget(self._methods_list) # center list center_wrap_wdgt = QWidget() center_v_box = QVBoxLayout(center_wrap_wdgt) center_v_box.setContentsMargins(0, 0, 0, 0) methods_label = QLabel('NATIVE FIELDS') methods_label.setFont(font) methods_label.setContentsMargins(10, 0, 10, 2) methods_label.setAttribute(Qt.WA_TranslucentBackground, True) # keep this center_v_box.addWidget(methods_label) self._native_fields_list = DwarfListView() self._native_fields_list.doubleClicked.connect( self._on_native_field_dblclicked) center_v_box.addWidget(self._native_fields_list) # right list right_wrap_wdgt = QWidget() right_v_box = QVBoxLayout(right_wrap_wdgt) right_v_box.setContentsMargins(0, 0, 0, 0) methods_label = QLabel('FIELDS') methods_label.setFont(font) methods_label.setContentsMargins(10, 0, 10, 2) methods_label.setAttribute(Qt.WA_TranslucentBackground, True) # keep this right_v_box.addWidget(methods_label) self._fields_list = DwarfListView() self._fields_list.doubleClicked.connect(self._on_field_dblclicked) right_v_box.addWidget(self._fields_list) # main splitter main_splitter = QSplitter(Qt.Horizontal) main_splitter.setContentsMargins(0, 0, 0, 0) main_splitter.addWidget(left_wrap_wdgt) main_splitter.addWidget(center_wrap_wdgt) main_splitter.addWidget(right_wrap_wdgt) main_splitter.setSizes([250, 100, 100]) main_wrapper.addWidget(main_splitter) main_wrapper.setSpacing(0) self.setLayout(main_wrapper) def _setup_models(self): # left list self._methods_model = QStandardItemModel(0, 3) self._methods_model.setHeaderData(0, Qt.Horizontal, 'Name') self._methods_model.setHeaderData(1, Qt.Horizontal, 'Return') self._methods_model.setHeaderData(2, Qt.Horizontal, 'Arguments') self._methods_list.setModel(self._methods_model) self._methods_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self._methods_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) # center list self._native_fields_model = QStandardItemModel(0, 2) self._native_fields_model.setHeaderData(0, Qt.Horizontal, 'Name') self._native_fields_model.setHeaderData(1, Qt.Horizontal, 'Value') self._native_fields_list.setModel(self._native_fields_model) self._native_fields_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) # right list self._fields_model = QStandardItemModel(0, 2) self._fields_model.setHeaderData(0, Qt.Horizontal, 'Name') self._fields_model.setHeaderData(1, Qt.Horizontal, 'Class') self._fields_list.setModel(self._fields_model) self._fields_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def _set_data(self, data): if 'class' not in data: return self._top_class_name.setText(data['class']) data = data['data'] self._methods_list.clear() self._native_fields_list.clear() self._fields_list.clear() for key in data: ref = data[key] if ref['type'] == 'function': if not key.startswith('$'): self._add_method(key, ref) elif ref['type'] == 'object': if ref['handle'] is not None: if not key.startswith('$'): self._add_field(key, ref['value'], ref['handle'], ref['handle_class']) else: if not key.startswith('$'): self._add_field(key, ref['value'], is_native=True) self._methods_list.sortByColumn(0, 0) self._native_fields_list.sortByColumn(0, 0) self._fields_list.sortByColumn(0, 0) def _add_method(self, name, ref): ref_overloads = ref['overloads'] for _, ref_overload in enumerate(ref_overloads): args = [] if 'args' in ref_overload: for arg in ref_overload['args']: if 'className' in arg: args.append(arg['className']) self._methods_model.appendRow([ QStandardItem(name), QStandardItem(ref_overload['return']['className']), QStandardItem('(%s)' % ', '.join(args)), ]) def _add_field(self, name, value, handle=None, handle_class=None, is_native=False): if handle: handle = {'handle': handle, 'handle_class': handle_class} handle_item = QStandardItem(name) handle_item.setData(handle, Qt.UserRole + 1) else: handle_item = QStandardItem(name) if not is_native: self._fields_model.appendRow( [handle_item, QStandardItem(str(value))]) else: self._native_fields_model.appendRow( [handle_item, QStandardItem(str(value))]) def _set_handle(self, handle): data = self._app_window.dwarf.dwarf_api('jvmExplorer', handle) if not data: return self._handle_history.append({'handle': handle}) self._set_data(data) def _set_handle_arg(self, arg): data = self._app_window.dwarf.dwarf_api('jvmExplorer', arg) if not data: return self._handle_history.append({'handle': arg}) self._set_data(data) def init(self): data = self._app_window.dwarf.dwarf_api('jvmExplorer') if not data: return self._handle_history.append({'handle': None}) self._set_data(data) def clear_panel(self): self._top_class_name.setText('') self._handle_history = [] self._methods_list.clear() self._native_fields_list.clear() self._fields_list.clear() def _back(self): if len(self._handle_history) < 2: return self._handle_history.pop() data = self._handle_history.pop(len(self._handle_history) - 1)['handle'] if isinstance(data, int): self._set_handle_arg(data) else: if data is not None: self._set_handle(data) else: self.init() # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _on_field_dblclicked(self, _): field_row = self._fields_list.selectionModel().currentIndex().row() if field_row >= 0: field_handle = self._fields_model.item(field_row, 0).data(Qt.UserRole + 1) if field_handle: self._set_handle(field_handle) def _on_native_field_dblclicked(self, _): field_row = self._native_fields_list.selectionModel().currentIndex( ).row() if field_row: field_handle = self._native_fields_model.item( field_row, 0).data(Qt.UserRole + 1) if field_handle: self._set_handle(field_handle) def keyPressEvent(self, event): # pylint: disable=invalid-name key = event.key() if key == Qt.Key_Backspace or key == Qt.Key_Escape: self._back() return super().keyPressEvent(event)
class DataPanel(QSplitter): def __init__(self, app): super(DataPanel, self).__init__(app) self.app = app self.data = {} self.setOrientation(Qt.Horizontal) self._key_list_model = QStandardItemModel(0, 1) self.key_lists = DwarfListView(parent=self.app) self.key_lists.setHeaderHidden(True) self.key_lists.setModel(self._key_list_model) self.key_lists.selectionModel().selectionChanged.connect( self.item_selected) self.key_lists.setContextMenuPolicy(Qt.CustomContextMenu) self.key_lists.customContextMenuRequested.connect( self._on_context_menu) self.addWidget(self.key_lists) self.editor = QPlainTextEdit() self.addWidget(self.editor) self.hex_view = HexEditor(self.app) self.hex_view.have_context_menu = False self.hex_view.setVisible(False) self.addWidget(self.hex_view) #self.setStretchFactor(0, 8) self.setStretchFactor(1, 4) self.setStretchFactor(2, 4) def clear(self): self._key_list_model.clear() self.editor.setPlainText('') self.hex_view.clear_panel() def append_data(self, data_type, key, text_data): if key not in self.data: self._key_list_model.appendRow([QStandardItem(key)]) self.data[key] = [data_type, text_data] def item_selected(self, item1, item2): item = self._key_list_model.itemFromIndex(item1.indexes()[0]) if self.data[item.text()][0] == 'plain': self.hex_view.setVisible(False) self.editor.setVisible(True) self.editor.setPlainText(self.data[item.text()][1]) else: data = self.data[item.text()][1] try: as_tx = data.decode('utf8') self.editor.setVisible(True) self.editor.setPlainText(as_tx) except: self.editor.setVisible(False) self.hex_view.setVisible(True) self.hex_view.bytes_per_line = 16 self.hex_view.set_data(data) def _on_context_menu(self, pos): context_menu = QMenu(self) index = self.key_lists.indexAt(pos).row() if index != -1: context_menu.addAction('Clear', self.clear) global_pt = self.key_lists.mapToGlobal(pos) context_menu.exec(global_pt)
class ModulesPanel(QSplitter): """ ModulesPanel Signals: onAddBreakpoint([ptr, funcname]) - MenuItem AddBreakpoint onDumpBinary([ptr, size#int]) - MenuItem DumpBinary onModuleSelected([ptr, size#int]) - ModuleDoubleClicked onModuleFuncSelected(ptr) - FunctionDoubleClicked """ # pylint: disable=too-many-instance-attributes onAddBreakpoint = pyqtSignal(list, name='onAddBreakpoint') onDumpBinary = pyqtSignal(list, name='onDumpBinary') onModuleSelected = pyqtSignal(list, name='onModuleSelected') onModuleFuncSelected = pyqtSignal(str, name='onModuleFuncSelected') def __init__(self, parent=None): # pylint: disable=too-many-statements super(ModulesPanel, self).__init__(parent) self._app_window = parent if self._app_window.dwarf is None: print('ModulesPanel created before Dwarf exists') return self._app_window.dwarf.onSetModules.connect(self.set_modules) self._app_window.dwarf.onModuleLoaded.connect(self.on_module_loaded) self._uppercase_hex = True self._sized = False self.setContentsMargins(0, 0, 0, 0) # setup models self.modules_list = None self.modules_model = QStandardItemModel(0, 4, self) self.modules_model.setHeaderData(0, Qt.Horizontal, 'Name') self.modules_model.setHeaderData(1, Qt.Horizontal, 'Base') self.modules_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.modules_model.setHeaderData(2, Qt.Horizontal, 'Size') self.modules_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.modules_model.setHeaderData(3, Qt.Horizontal, 'Path') self.imports_list = None self.imports_model = QStandardItemModel(0, 4, self) self.imports_model.setHeaderData(0, Qt.Horizontal, 'Import') self.imports_model.setHeaderData(1, Qt.Horizontal, 'Address') self.imports_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.imports_model.setHeaderData(2, Qt.Horizontal, 'Module') self.imports_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.imports_model.setHeaderData(3, Qt.Horizontal, 'Type') self.exports_list = None self.exports_model = QStandardItemModel(0, 3, self) self.exports_model.setHeaderData(0, Qt.Horizontal, 'Export') self.exports_model.setHeaderData(1, Qt.Horizontal, 'Address') self.exports_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.exports_model.setHeaderData(2, Qt.Horizontal, 'Type') self.symbols_list = None self.symbols_model = QStandardItemModel(0, 3, self) self.symbols_model.setHeaderData(0, Qt.Horizontal, 'Symbol') self.symbols_model.setHeaderData(1, Qt.Horizontal, 'Address') self.symbols_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.symbols_model.setHeaderData(2, Qt.Horizontal, 'Type') # setup ui self.modules_list = DwarfListView() self.modules_list.setContextMenuPolicy(Qt.CustomContextMenu) self.modules_list.customContextMenuRequested.connect( self._on_modules_contextmenu) self.modules_list.setEditTriggers(self.modules_list.NoEditTriggers) self.modules_list.clicked.connect(self._module_clicked) self.modules_list.doubleClicked.connect(self._module_dblclicked) self.modules_list.setModel(self.modules_model) self.modules_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.modules_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) self.modules_list.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents) self.modules_list.selectionModel().selectionChanged.connect( self._module_clicked) self.addWidget(self.modules_list) v_splitter = QSplitter(Qt.Vertical) self.imports_list = DwarfListView() self.imports_list.setContextMenuPolicy(Qt.CustomContextMenu) self.imports_list.customContextMenuRequested.connect( self._on_imports_contextmenu) self.imports_list.setEditTriggers(self.modules_list.NoEditTriggers) self.imports_list.doubleClicked.connect(self._import_dblclicked) self.imports_list.setModel(self.imports_model) self.imports_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.imports_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) self.imports_list.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents) self.imports_list.setVisible(False) self.exports_list = DwarfListView() self.exports_list.setContextMenuPolicy(Qt.CustomContextMenu) self.exports_list.customContextMenuRequested.connect( self._on_exports_contextmenu) self.exports_list.setEditTriggers(self.modules_list.NoEditTriggers) self.exports_list.doubleClicked.connect(self._export_dblclicked) self.exports_list.setModel(self.exports_model) self.exports_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.exports_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) self.exports_list.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents) self.exports_list.setVisible(False) self.symbols_list = DwarfListView() self.symbols_list.setContextMenuPolicy(Qt.CustomContextMenu) self.symbols_list.doubleClicked.connect(self._symbol_dblclicked) self.symbols_list.setModel(self.symbols_model) self.symbols_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents) self.symbols_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) self.symbols_list.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents) self.symbols_list.setVisible(False) v_splitter.addWidget(self.imports_list) v_splitter.addWidget(self.exports_list) v_splitter.addWidget(self.symbols_list) v_splitter.setSizes([100, 100, 100]) self.addWidget(v_splitter) self.update_modules() # ************************************************************************ # **************************** Properties ******************************** # ************************************************************************ @property def uppercase_hex(self): """ HexDisplayStyle """ return self._uppercase_hex @uppercase_hex.setter def uppercase_hex(self, value): """ HexDisplayStyle """ if isinstance(value, bool): self._uppercase_hex = value elif isinstance(value, str): self._uppercase_hex = (value == 'upper') # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def set_modules(self, modules): """ Fills the ModulesList with data """ if self.modules_list is None: return self.modules_list.clear() for module in modules: self.add_module(module) self.modules_list.resizeColumnToContents(0) self.modules_list.resizeColumnToContents(1) self.modules_list.resizeColumnToContents(2) self.modules_list.resizeColumnToContents(3) def on_module_loaded(self, data): module = data[0] self.add_module(module) def add_module(self, module): name = QStandardItem() name.setTextAlignment(Qt.AlignLeft) if 'name' in module: name.setText(module['name']) base = QStandardItem() base.setTextAlignment(Qt.AlignCenter) str_fmt = '0x{0:X}' if not self.uppercase_hex: str_fmt = '0x{0:x}' if 'base' in module: base.setText(str_fmt.format(int(module['base'], 16))) size = QStandardItem() size.setTextAlignment(Qt.AlignRight) if 'size' in module: size.setText("{0:,d}".format(int(module['size']))) path = QStandardItem() path.setTextAlignment(Qt.AlignLeft) if 'path' in module: path.setText(module['path']) self.modules_model.appendRow([name, base, size, path]) module_info = ModuleInfo(module) if 'exports' in module and module['exports']: module_info.apply_exports(module['exports']) if 'imports' in module and module['imports']: module_info.apply_imports(module['imports']) if 'symbols' in module and module['symbols']: module_info.apply_symbols(module['symbols']) module_info._updated_details = True def update_modules(self): """ DwarfApiCall updateModules """ return self._app_window.dwarf.dwarf_api('updateModules') def set_imports(self, imports): """ Fills the ImportsList with data """ if self.imports_list is None: return self.imports_list.clear() for import_ in imports: name = QStandardItem() name.setTextAlignment(Qt.AlignLeft) if 'name' in import_: name.setText(import_['name']) address = QStandardItem() address.setTextAlignment(Qt.AlignCenter) str_fmt = '0x{0:X}' if not self.uppercase_hex: str_fmt = '0x{0:x}' if 'address' in import_: address.setText(str_fmt.format(int(import_['address'], 16))) module = QStandardItem() if 'module' in import_: module.setTextAlignment(Qt.AlignLeft) module.setText(import_['module']) type_ = QStandardItem() if 'type' in import_: type_.setTextAlignment(Qt.AlignLeft) type_.setText(import_['type']) self.imports_model.appendRow([name, address, module, type_]) def set_exports(self, exports): """ Fills the ExportsList with data """ if self.exports_list is None: return self.exports_list.clear() for export in exports: name = QStandardItem() name.setTextAlignment(Qt.AlignLeft) if 'name' in export: name.setText(export['name']) address = QStandardItem() address.setTextAlignment(Qt.AlignCenter) str_fmt = '0x{0:X}' if not self.uppercase_hex: str_fmt = '0x{0:x}' if 'address' in export: address.setText(str_fmt.format(int(export['address'], 16))) type_ = QStandardItem() type_.setTextAlignment(Qt.AlignLeft) if 'type' in export: type_.setText(export['type']) self.exports_model.appendRow([name, address, type_]) def set_symbols(self, symbols): """ Fills the SymbolsList with data """ if self.symbols_list is None: return self.symbols_list.clear() for symbol in symbols: name = QStandardItem() name.setTextAlignment(Qt.AlignLeft) if 'name' in symbol: name.setText(symbol['name']) address = QStandardItem() address.setTextAlignment(Qt.AlignCenter) str_fmt = '0x{0:X}' if not self.uppercase_hex: str_fmt = '0x{0:x}' if 'address' in symbol: address.setText(str_fmt.format(int(symbol['address'], 16))) type_ = QStandardItem() type_.setTextAlignment(Qt.AlignLeft) if 'type' in symbol: type_.setText(symbol['type']) self.symbols_model.appendRow([name, address, type_]) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _module_clicked(self): """ Module Clicked updates imports/exports/symbols """ if not self.modules_list.hasFocus(): return module_index = self.modules_list.selectionModel().currentIndex().row() module_name = self.modules_model.item(module_index, 0) if module_name is None: return module_name = module_name.text() module_address = self.modules_model.item(module_index, 1).text() module_info = self._app_window.dwarf.database.get_module_info(module_address) if module_info is not None: if not module_info.have_details: module_info = ModuleInfo.build_module_info(self._app_window.dwarf, module_name, fill_ied=True) else: module_info = ModuleInfo.build_module_info(self._app_window.dwarf, module_name, fill_ied=True) if module_info is not None: self.update_module_ui(module_info) if not self._sized: self.setSizes([100, 100]) self._sized = True def update_module_ui(self, module_info): if module_info.imports: self.set_imports(module_info.imports) self.imports_list.setVisible(True) self.imports_list.resizeColumnToContents(0) self.imports_list.resizeColumnToContents(1) self.imports_list.resizeColumnToContents(2) else: self.imports_list.setVisible(False) if module_info.exports: self.set_exports(module_info.exports) self.exports_list.setVisible(True) self.exports_list.resizeColumnToContents(0) self.exports_list.resizeColumnToContents(1) else: self.exports_list.setVisible(False) if module_info.symbols: self.set_symbols(module_info.symbols) self.symbols_list.setVisible(True) self.symbols_list.resizeColumnToContents(0) self.symbols_list.resizeColumnToContents(1) else: self.symbols_list.setVisible(False) def _module_dblclicked(self): """ Module DoubleClicked """ module_index = self.modules_list.selectionModel().currentIndex().row() base = self.modules_model.item(module_index, 1).text() size = self.modules_model.item(module_index, 2).text().replace(',', '') self.onModuleSelected.emit([base, size]) def _import_dblclicked(self): """ ImportFunction DoubleClicked """ index = self.imports_list.selectionModel().currentIndex().row() addr = self.imports_model.item(index, 1).text() self.onModuleFuncSelected.emit(addr) def _export_dblclicked(self): """ ExportFunction DoubleClicked """ index = self.exports_list.selectionModel().currentIndex().row() addr = self.exports_model.item(index, 1).text() self.onModuleFuncSelected.emit(addr) def _symbol_dblclicked(self): """ Symbol DoubleClicked """ index = self.symbols_list.selectionModel().currentIndex().row() addr = self.symbols_model.item(index, 1).text() self.onModuleFuncSelected.emit(addr) def _on_modules_contextmenu(self, pos): """ Modules ContextMenu """ index = self.modules_list.indexAt(pos).row() glbl_pt = self.modules_list.mapToGlobal(pos) context_menu = QMenu(self) if index != -1: context_menu.addAction( 'Dump Binary', lambda: self._on_dumpmodule( self.modules_model.item(index, 1).text(), self.modules_model.item(index, 2).text())) context_menu.addSeparator() context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self.modules_model.item(index, 1).text())) context_menu.addAction( 'Copy Name', lambda: utils.copy_str_to_clipboard( self.modules_model.item(index, 0).text())) context_menu.addAction( 'Copy Path', lambda: utils.copy_str_to_clipboard( self.modules_model.item(index, 3).text())) context_menu.addSeparator() file_path = self.modules_model.item(index, 3).text() if self._app_window.dwarf._platform == 'linux': context_menu.addAction( 'Show ELF Info', lambda: self._on_parse_elf(file_path)) context_menu.addSeparator() # elif file_path and (file_path.endswith('.dll') or file_path.endswith('.exe')): # context_menu.addAction('Show PE Info', lambda: self._on_parse_pe(file_path)) # context_menu.addSeparator() if self.modules_list.search_enabled: context_menu.addSeparator() context_menu.addAction( 'Search', self.modules_list._on_cm_search) context_menu.addSeparator() context_menu.addAction('Refresh', self.update_modules) context_menu.exec_(glbl_pt) def _on_imports_contextmenu(self, pos): """ ImportList ContextMenu """ index = self.imports_list.indexAt(pos).row() if index != -1: context_menu = QMenu(self) func_name = self.imports_model.item(index, 0).text() addr = self.imports_model.item(index, 1).text() context_menu.addAction( 'Add Breakpoint', lambda: self._add_breakpoint(addr, func_name)) context_menu.addSeparator() context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self.imports_model.item(index, 1).text())) context_menu.addSeparator() context_menu.addAction( 'Copy FunctionName', lambda: utils.copy_str_to_clipboard( func_name)) context_menu.addAction( 'Copy ModuleName', lambda: utils.copy_str_to_clipboard( self.imports_model.item(index, 2).text())) if self.imports_list.search_enabled: context_menu.addSeparator() context_menu.addAction( 'Search', self.imports_list._on_cm_search) # show context menu glbl_pt = self.imports_list.mapToGlobal(pos) context_menu.exec_(glbl_pt) def _on_exports_contextmenu(self, pos): """ ExportsList ContextMenu """ index = self.exports_list.indexAt(pos).row() if index != -1: context_menu = QMenu(self) func_name = self.exports_model.item(index, 0).text() addr = self.exports_model.item(index, 1).text() context_menu.addAction( 'Add Breakpoint', lambda: self._add_breakpoint(addr, func_name)) context_menu.addSeparator() context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self.exports_model.item(index, 1).text())) context_menu.addSeparator() context_menu.addAction( 'Copy FunctionName', lambda: utils.copy_str_to_clipboard( func_name)) if self.exports_list.search_enabled: context_menu.addSeparator() context_menu.addAction( 'Search', self.exports_list._on_cm_search) # show contextmenu glbl_pt = self.exports_list.mapToGlobal(pos) context_menu.exec_(glbl_pt) def _on_dumpmodule(self, ptr, size): """ MenuItem DumpBinary """ if isinstance(ptr, int): str_fmt = '0x{0:X}' if not self.uppercase_hex: str_fmt = '0x{0:x}' ptr = str_fmt.format(ptr) size = size.replace(',', '') self.onDumpBinary.emit([ptr, size]) def _add_breakpoint(self, ptr, name=None): """ MenuItem AddBreakpoint """ if name is None: name = ptr if isinstance(ptr, str): if ptr.startswith('0x') or ptr.startswith('#'): self.onAddBreakpoint.emit([ptr, name]) elif isinstance(ptr, int): str_fmt = '0x{0:x}' self.onAddBreakpoint.emit(str_fmt.format([ptr, name])) def _on_parse_elf(self, elf_path): from dwarf_debugger.ui.dialogs.elf_info_dlg import ElfInfo parsed_infos = self._app_window.dwarf.dwarf_api('parseElf', elf_path) if parsed_infos: elf_dlg = ElfInfo(self._app_window, elf_path) elf_dlg.onShowMemoryRequest.connect(self.onModuleFuncSelected) elf_dlg.set_parsed_data(parsed_infos) elf_dlg.show()
class SearchPanel(QWidget): """ SearchPanel """ def __init__(self, parent=None, show_progress_dlg=False): super(SearchPanel, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('SearchPanel created before Dwarf exists') return self._app_window.dwarf.onMemoryScanResult.connect( self._on_search_result) self._app_window.dwarf.onSearchableRanges.connect(self._on_setranges) self._ranges_model = None self._result_model = None self._blocking_search = show_progress_dlg self.progress = None self._pattern_length = 0 self._search_results = [] self.setContentsMargins(0, 0, 0, 0) main_wrap = QVBoxLayout() main_wrap.setContentsMargins(1, 1, 1, 1) wrapping_wdgt = QWidget() wrapping_wdgt.setContentsMargins(10, 10, 10, 10) v_box = QVBoxLayout(wrapping_wdgt) v_box.setContentsMargins(0, 0, 0, 0) self.input = QLineEdit() self.input.setPlaceholderText( 'search for a sequence of bytes in hex format: deadbeef123456aabbccddeeff...' ) v_box.addWidget(self.input) self.check_all_btn = QPushButton('check all') self.check_all_btn.clicked.connect(self._on_click_check_all) self.uncheck_all_btn = QPushButton('uncheck all') self.uncheck_all_btn.clicked.connect(self._on_click_uncheck_all) self.search_btn = QPushButton('search') self.search_btn.clicked.connect(self._on_click_search) h_box = QHBoxLayout() h_box.addWidget(self.check_all_btn) h_box.addWidget(self.uncheck_all_btn) h_box.addWidget(self.search_btn) v_box.addLayout(h_box) main_wrap.addWidget(wrapping_wdgt) self.ranges = DwarfListView(self) self.ranges.clicked.connect(self._on_show_results) self.results = DwarfListView(self) self.results.setVisible(False) h_box = QHBoxLayout() h_box.setContentsMargins(0, 0, 0, 0) h_box.addWidget(self.ranges) h_box.addWidget(self.results) main_wrap.addLayout(h_box) main_wrap.setSpacing(0) self.setLayout(main_wrap) self._setup_models() self._app_window.dwarf.dwarf_api('updateSearchableRanges') # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def _setup_models(self): self._ranges_model = QStandardItemModel(0, 7) # just replicate ranges panel model self._ranges_model.setHeaderData( 0, Qt.Horizontal, 'x' ) # TODO: replace with checkbox in header - remove checkall btns self._ranges_model.setHeaderData(0, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._ranges_model.setHeaderData(1, Qt.Horizontal, 'Address') self._ranges_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._ranges_model.setHeaderData(2, Qt.Horizontal, 'Size') self._ranges_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._ranges_model.setHeaderData(3, Qt.Horizontal, 'Protection') self._ranges_model.setHeaderData(3, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._ranges_model.setHeaderData(4, Qt.Horizontal, 'FileOffset') self._ranges_model.setHeaderData(4, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._ranges_model.setHeaderData(5, Qt.Horizontal, 'FileSize') self._ranges_model.setHeaderData(5, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._ranges_model.setHeaderData(6, Qt.Horizontal, 'FilePath') self.ranges.setModel(self._ranges_model) self.ranges.header().setSectionResizeMode(0, QHeaderView.ResizeToContents) self.ranges.header().setSectionResizeMode(1, QHeaderView.ResizeToContents) self.ranges.header().setSectionResizeMode(2, QHeaderView.ResizeToContents) self.ranges.header().setSectionResizeMode(3, QHeaderView.ResizeToContents) self.ranges.header().setSectionResizeMode(4, QHeaderView.ResizeToContents) self.ranges.header().setSectionResizeMode(5, QHeaderView.ResizeToContents) self.ranges.doubleClicked.connect(self._on_range_dblclick) # setup results model self._result_model = QStandardItemModel(0, 1) self._result_model.setHeaderData(0, Qt.Horizontal, 'Address') self.results.setModel(self._result_model) self.results.doubleClicked.connect(self._on_double_clicked) def _on_setranges(self, ranges): """ Fills Rangelist with Data """ if self._ranges_model.rowCount(): return self.ranges.header().setSectionResizeMode(0, QHeaderView.Fixed) if isinstance(ranges, list): self._ranges_model.removeRows(0, self._ranges_model.rowCount()) for range_entry in ranges: if 'protection' in range_entry and isinstance( range_entry['protection'], str): if 'r' not in range_entry['protection']: # skip not readable range continue else: continue # create items to add str_frmt = '' if self.ranges._uppercase_hex: str_frmt = '0x{0:X}' else: str_frmt = '0x{0:x}' addr = QStandardItem() addr.setTextAlignment(Qt.AlignCenter) addr.setText(str_frmt.format(int(range_entry['base'], 16))) size = QStandardItem() size.setTextAlignment(Qt.AlignRight) size.setText("{0:,d}".format(int(range_entry['size']))) protection = QStandardItem() protection.setTextAlignment(Qt.AlignCenter) protection.setText(range_entry['protection']) file_path = None file_addr = None file_size = None if len(range_entry) > 3: if range_entry['file']['path']: file_path = QStandardItem() file_path.setText(range_entry['file']['path']) if range_entry['file']['offset']: file_addr = QStandardItem() file_addr.setTextAlignment(Qt.AlignCenter) file_addr.setText( str_frmt.format(range_entry['file']['offset'])) if range_entry['file']['size']: file_size = QStandardItem() file_size.setTextAlignment(Qt.AlignRight) file_size.setText("{0:,d}".format( int(range_entry['file']['size']))) checkbox = QStandardItem() checkbox.setCheckable(True) self._ranges_model.appendRow([ checkbox, addr, size, protection, file_addr, file_size, file_path ]) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _on_range_dblclick(self, model_index): item = self._ranges_model.itemFromIndex(model_index) if item: if self._ranges_model.item(model_index.row(), 0).checkState() != Qt.Checked: self._ranges_model.item(model_index.row(), 0).setCheckState(Qt.Checked) else: self._ranges_model.item(model_index.row(), 0).setCheckState(Qt.Unchecked) def _on_click_check_all(self): for i in range(self._ranges_model.rowCount()): self._ranges_model.item(i, 0).setCheckState(Qt.Checked) def _on_click_uncheck_all(self): for i in range(self._ranges_model.rowCount()): self._ranges_model.item(i, 0).setCheckState(Qt.Unchecked) def _on_double_clicked(self, model_index): item = self._result_model.itemFromIndex(model_index) if item: self._app_window.jump_to_address( self._result_model.item(model_index.row(), 0).text()) def _on_click_search(self): pattern = self.input.text() if pattern == '': return 1 # check if we already provide a hex string as input try: test = pattern.replace(' ', '') int(test, 16) pattern = test except ValueError: # search for string pattern = binascii.hexlify(pattern.encode('utf8')).decode('utf8') ranges = [] self._search_results = [] for i in range(self._ranges_model.rowCount()): item = self._ranges_model.item(i, 0) if item.checkState() == Qt.Checked: addr = self._ranges_model.item(i, 1) size = self._ranges_model.item(i, 2) ranges.append([addr.text(), size.text()]) if len(ranges) == 0: return 1 status_message = 'searching...' if self._blocking_search: self.progress = utils.progress_dialog(status_message) self.progress.forceShow() self._app_window.show_progress(status_message) self.input.setEnabled(False) self.search_btn.setEnabled(False) self.check_all_btn.setEnabled(False) self.uncheck_all_btn.setEnabled(False) self._pattern_length = len(pattern) * .5 search_thread = SearchThread(self._app_window.dwarf, self) search_thread.onCmdCompleted.connect(self._on_search_complete) search_thread.onError.connect(self._on_search_error) search_thread.pattern = pattern search_thread.ranges = ranges search_thread.start() def _on_search_result(self, data): self._search_results.append(data) def _on_search_complete(self): self.input.setEnabled(True) self.search_btn.setEnabled(True) self.check_all_btn.setEnabled(True) self.uncheck_all_btn.setEnabled(True) self._app_window.hide_progress() if self._blocking_search: self.progress.cancel() self._ranges_model.removeColumns(4, 3) self._ranges_model.setHeaderData(3, Qt.Horizontal, 'Search Results') self._ranges_model.setHeaderData(3, Qt.Horizontal, None, Qt.TextAlignmentRole) results_count = 0 is_selected = False for i in range(self._ranges_model.rowCount()): item = self._ranges_model.item(i, 0) if item.checkState() == Qt.Checked: item.setCheckState(Qt.Unchecked) if not is_selected: is_selected = True self.ranges.setCurrentIndex(self._ranges_model.index(i, 0)) else: self._search_results.insert(i, None) self._ranges_model.item(i, 3).setText('') self._ranges_model.item(i, 3).setTextAlignment(Qt.AlignLeft) continue if len(self._search_results[i]): results_count += len(self._search_results[i]) self._ranges_model.item(i, 3).setText('Matches: {0}'.format( len(self._search_results[i]))) self._ranges_model.item(i, 3).setTextAlignment(Qt.AlignLeft) else: self._ranges_model.item(i, 3).setText('') self._ranges_model.item(i, 3).setTextAlignment(Qt.AlignLeft) self._app_window.set_status_text( 'Search complete: {0} matches'.format(results_count)) if results_count: for i in self._search_results: if i and len(i): self.results.setVisible(True) for result in i: self._result_model.appendRow( QStandardItem(result['address'])) break def _on_search_error(self, msg): utils.show_message_box(msg) def _on_show_results(self): if self._search_results: self.results.clear() if self._app_window.debug_panel.memory_panel: self._app_window.debug_panel.memory_panel.remove_highlights('search') selected_index = self.ranges.selectionModel().currentIndex().row() if selected_index is not None: item_txt = self._ranges_model.item(selected_index, 3).text() if item_txt == '': return for result in self._search_results[selected_index]: self._result_model.appendRow( QStandardItem(result['address'])) # TODO: fix hexview highlights performance """
class BreakpointsWidget(QWidget): """ BreakpointsWidget Signals: onBreakpointChanged(str) - ptr onBreakpointRemoved(str) - ptr """ onBreakpointChanged = pyqtSignal(str, name='onBreakpointChanged') onBreakpointsRemoved = pyqtSignal(str, name='onBreakpointRemoved') def __init__(self, parent=None): # pylint: disable=too-many-statements super(BreakpointsWidget, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('BreakpointsWidget created before Dwarf exists') return # connect to dwarf self._app_window.dwarf.onApplyContext.connect(self._on_apply_context) self._app_window.dwarf.onAddJavaBreakpoint.connect( self._on_add_breakpoint) self._app_window.dwarf.onAddObjCBreakpoint.connect( self._on_add_breakpoint) self._app_window.dwarf.onAddNativeBreakpoint.connect( self._on_add_breakpoint) self._app_window.dwarf.onAddModuleInitializationBreakpoint.connect( self._on_add_breakpoint) self._app_window.dwarf.onAddJavaClassInitializationBreakpoint.connect( self._on_add_breakpoint) self._app_window.dwarf.onHitModuleInitializationBreakpoint.connect( self._on_hit_module_initialization_breakpoint) self._app_window.dwarf.onHitJavaClassInitializationBreakpoint.connect( self._on_hit_java_class_initialization_breakpoint) self._app_window.dwarf.onDeleteBreakpoint.connect( self._on_breakpoint_deleted) self._breakpoints_list = DwarfListView() self._breakpoints_list.doubleClicked.connect(self._on_double_clicked) self._breakpoints_list.setContextMenuPolicy(Qt.CustomContextMenu) self._breakpoints_list.customContextMenuRequested.connect( self._on_context_menu) self._breakpoints_model = QStandardItemModel(0, 3) self._breakpoints_model.setHeaderData(0, Qt.Horizontal, 'Address') self._breakpoints_model.setHeaderData(1, Qt.Horizontal, 'T') self._breakpoints_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._breakpoints_model.setHeaderData(2, Qt.Horizontal, '<>') self._breakpoints_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._breakpoints_list.setModel(self._breakpoints_model) self._breakpoints_list.header().setStretchLastSection(False) self._breakpoints_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents | QHeaderView.Interactive) self._breakpoints_list.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents) self._breakpoints_list.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents) v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) v_box.addWidget(self._breakpoints_list) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) self.btn1 = QPushButton( QIcon(utils.resource_path('assets/icons/plus.svg')), '') self.btn1.setFixedSize(20, 20) self.btn1.clicked.connect(self._on_add_item_clicked) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(self.btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) self.setLayout(v_box) self._bold_font = QFont(self._breakpoints_list.font()) self._bold_font.setBold(True) shortcut_addnative = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_N), self._app_window, self._on_add_native_breakpoint) shortcut_addnative.setAutoRepeat(False) shortcut_addjava = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_J), self._app_window, self._on_add_java_breakpoint) shortcut_addjava.setAutoRepeat(False) shortcut_add_native_onload = QShortcut( QKeySequence(Qt.CTRL + Qt.Key_O), self._app_window, self._on_add_module_initialization_breakpoint) shortcut_add_native_onload.setAutoRepeat(False) # new menu self.new_menu = QMenu('New') self.new_menu.addAction('Native', self._on_add_native_breakpoint) self.new_menu.addAction('Module initialization', self._on_add_module_initialization_breakpoint) # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def delete_items(self): """ Delete selected Items """ index = self._breakpoints_list.selectionModel().currentIndex().row() if index != -1: self._on_delete_breakpoint(index) self._breakpoints_model.removeRow(index) def clear_list(self): """ Clear the List """ # go through all items and tell it gets removed for item in range(self._breakpoints_model.rowCount()): self._on_delete_breakpoint(item) if self._breakpoints_model.rowCount() > 0: # something was wrong it should be empty self._breakpoints_model.removeRows( 0, self._breakpoints_model.rowCount()) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _on_apply_context(self, context): if context['reason'] == -1: if self._app_window.dwarf.java_available: self.new_menu.addAction('Java', self._on_add_java_breakpoint) self.new_menu.addAction( 'Java class initialization', self._on_add_java_class_initialization_breakpoint) def _on_add_breakpoint(self, breakpoint): type_ = QStandardItem() type_.setFont(self._bold_font) type_.setTextAlignment(Qt.AlignCenter) if breakpoint.breakpoint_type == BREAKPOINT_NATIVE: type_.setText('N') type_.setToolTip('Native breakpoint') elif breakpoint.breakpoint_type == BREAKPOINT_JAVA: type_.setText('J') type_.setToolTip('Java breakpoint') elif breakpoint.breakpoint_type == BREAKPOINT_INITIALIZATION: type_.setText('C') type_.setToolTip('Initialization breakpoint') elif breakpoint.breakpoint_type == BREAKPOINT_OBJC: type_.setText('O') type_.setToolTip('ObjC breakpoint') else: type_.setText('U') type_.setToolTip('Unknown Type') addr = QStandardItem() if breakpoint.breakpoint_type == BREAKPOINT_JAVA: addr.setText(breakpoint.get_target()) elif breakpoint.breakpoint_type == BREAKPOINT_OBJC: addr.setText(breakpoint.get_target()) elif breakpoint.breakpoint_type == BREAKPOINT_INITIALIZATION: addr.setText(breakpoint.get_target()) addr.setData(breakpoint.debug_symbol, Qt.UserRole + 2) else: str_fmt = '0x{0:x}' if self._breakpoints_list.uppercase_hex: str_fmt = '0x{0:X}' # addr.setTextAlignment(Qt.AlignCenter) addr.setText(str_fmt.format(breakpoint.get_target())) condition = QStandardItem() condition.setTextAlignment(Qt.AlignCenter) condition.setFont(self._bold_font) if breakpoint.condition and breakpoint.condition != 'null' and breakpoint.condition != 'undefined': condition.setText('ƒ') condition.setToolTip(breakpoint.condition) condition.setData(breakpoint.condition, Qt.UserRole + 2) self._breakpoints_model.appendRow([addr, type_, condition]) self._breakpoints_list.resizeColumnToContents(0) def _on_hit_module_initialization_breakpoint(self, data): items = self._breakpoints_model.findItems(data[1]['module'], Qt.MatchExactly, 2) if len(items) > 0: self._breakpoints_model.item(items[0].row(), 0).setText(data[1]['moduleBase']) def _on_hit_java_class_initialization_breakpoint(self, data): items = self._breakpoints_model.findItems(data[0], Qt.MatchExactly, 2) if len(items) > 0: pass def _on_double_clicked(self, model_index): item = self._breakpoints_model.itemFromIndex(model_index) if model_index.column() == 2 and item.text() == 'ƒ': self._on_modify_condition(model_index.row()) else: self._app_window.jump_to_address(self._breakpoints_model.item( model_index.row(), 0).text(), view=1) def _on_context_menu(self, pos): context_menu = QMenu(self) context_menu.addMenu(self.new_menu) context_menu.addSeparator() index = self._breakpoints_list.indexAt(pos).row() if index != -1: context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self._breakpoints_model.item(index, 0).text())) context_menu.addAction( 'Jump to address', lambda: self._app_window.jump_to_address( self._breakpoints_model.item(index, 0).text())) context_menu.addSeparator() context_menu.addAction('Edit Condition', lambda: self._on_modify_condition(index)) context_menu.addSeparator() context_menu.addAction('Delete Breakpoint', lambda: self._on_delete_breakpoint(index)) if self._breakpoints_list.search_enabled: context_menu.addSeparator() context_menu.addAction('Search', self._breakpoints_list._on_cm_search) # show context menu global_pt = self._breakpoints_list.mapToGlobal(pos) context_menu.exec(global_pt) def _on_modify_condition(self, num_row): item = self._breakpoints_model.item(num_row, 2) data = item.data(Qt.UserRole + 2) if data is None: data = '' ptr = self._breakpoints_model.item(num_row, 0).text() accept, input_ = InputMultilineDialog().input( 'Condition for breakpoint %s' % ptr, input_content=data) if accept: what = utils.parse_ptr(ptr) if what == 0: what = self._breakpoints_model.item(num_row, 2).data(Qt.UserRole + 2) if self._app_window.dwarf.dwarf_api( 'setBreakpointCondition', [what, input_.replace('\n', '')]): item.setData(input_, Qt.UserRole + 2) if not item.text(): item.setText('ƒ') item.setToolTip(input_) self.onBreakpointChanged.emit(ptr) # + button def _on_add_item_clicked(self): self.new_menu.exec_(QCursor.pos()) # shortcuts/menu def _on_add_native_breakpoint(self): self._app_window.dwarf.breakpoint_native() def _on_add_java_breakpoint(self): self._app_window.dwarf.breakpoint_java() def _on_add_module_initialization_breakpoint(self): self._app_window.dwarf.breakpoint_module_initialization() def _on_add_java_class_initialization_breakpoint(self): self._app_window.dwarf.breakpoint_java_class_initialization() def _on_delete_breakpoint(self, num_row): breakpoint_type = self._breakpoints_model.item(num_row, 1).text() if breakpoint_type == 'N': ptr = self._breakpoints_model.item(num_row, 0).text() ptr = utils.parse_ptr(ptr) self._app_window.dwarf.dwarf_api('removeBreakpoint', ptr) self.onBreakpointRemoved.emit(str(ptr)) elif breakpoint_type == 'J': target = self._breakpoints_model.item(num_row, 0).text() self._app_window.dwarf.dwarf_api('removeBreakpoint', target) elif breakpoint_type == 'O': target = self._breakpoints_model.item(num_row, 0).text() self._app_window.dwarf.dwarf_api('removeBreakpoint', target) elif breakpoint_type == 'C': item = self._breakpoints_model.item(num_row, 0) target = item.text() is_native = item.data(Qt.UserRole + 2) is None if is_native: self._app_window.dwarf.dwarf_api( 'removeModuleInitializationBreakpoint', target) else: self._app_window.dwarf.dwarf_api( 'removeJavaClassInitializationBreakpoint', target) elif breakpoint_type == 'U': ptr = self._breakpoints_model.item(num_row, 0).text() ptr = utils.parse_ptr(ptr) self._app_window.dwarf.dwarf_api('removeBreakpoint', ptr) self.onBreakpointRemoved.emit(str(ptr)) def _on_breakpoint_deleted(self, parts): _msg, _type, _val = parts additional = None if _type == 'objc' or _type == 'java' or _type == 'java_class_initialization': str_frmt = _val item_index = 0 elif _type == 'module_initialization': str_frmt = _val item_index = 0 else: _ptr = utils.parse_ptr(_val) if self._breakpoints_list._uppercase_hex: str_frmt = '0x{0:X}'.format(_ptr) else: str_frmt = '0x{0:x}'.format(_ptr) item_index = 0 for _item in range(self._breakpoints_model.rowCount()): item = self._breakpoints_model.item(_item, item_index) if item is None: continue if str_frmt == item.text(): if additional is not None: if additional == self._breakpoints_model.item(_item, 2).text(): self._breakpoints_model.removeRow(_item) else: self._breakpoints_model.removeRow(_item)
class WatchpointsWidget(QWidget): """ WatchpointsWidget Signals: onItemSelected(addr_str) - item dblclicked onItemAddClick Constants: MEMORY_ACCESS_READ = 1 MEMORY_ACCESS_WRITE = 2 MEMORY_ACCESS_EXECUTE = 4 MEMORY_WATCH_SINGLESHOT = 8 """ MEMORY_ACCESS_READ = 1 MEMORY_ACCESS_WRITE = 2 MEMORY_ACCESS_EXECUTE = 4 MEMORY_WATCH_SINGLESHOT = 8 onItemDoubleClicked = pyqtSignal(int, name='onItemDoubleClicked') onItemAdded = pyqtSignal(int, name='onItemAdded') onItemRemoved = pyqtSignal(int, name='onItemRemoved') def __init__(self, parent=None): # pylint: disable=too-many-statements super(WatchpointsWidget, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('WatchpointsWidget created before Dwarf exists') return self._uppercase_hex = True self.setAutoFillBackground(True) # connect to dwarf self._app_window.dwarf.onWatchpointAdded.connect( self._on_watchpoint_added) self._app_window.dwarf.onWatchpointRemoved.connect( self._on_watchpoint_removed) # setup our model self._watchpoints_model = QStandardItemModel(0, 5) self._watchpoints_model.setHeaderData(0, Qt.Horizontal, 'Address') self._watchpoints_model.setHeaderData(1, Qt.Horizontal, 'R') self._watchpoints_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchpoints_model.setHeaderData(2, Qt.Horizontal, 'W') self._watchpoints_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchpoints_model.setHeaderData(3, Qt.Horizontal, 'X') self._watchpoints_model.setHeaderData(3, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self._watchpoints_model.setHeaderData(4, Qt.Horizontal, 'S') self._watchpoints_model.setHeaderData(4, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) # setup ui v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) self.list_view = DwarfListView() self.list_view.setModel(self._watchpoints_model) self.list_view.header().setSectionResizeMode(0, QHeaderView.Stretch) self.list_view.header().setSectionResizeMode( 1, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 2, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 3, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setSectionResizeMode( 4, QHeaderView.ResizeToContents | QHeaderView.Fixed) self.list_view.header().setStretchLastSection(False) self.list_view.doubleClicked.connect(self._on_item_dblclick) self.list_view.setContextMenuPolicy(Qt.CustomContextMenu) self.list_view.customContextMenuRequested.connect(self._on_contextmenu) v_box.addWidget(self.list_view) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) btn1 = QPushButton(QIcon(utils.resource_path('assets/icons/plus.svg')), '') btn1.setFixedSize(20, 20) btn1.clicked.connect(self._on_additem_clicked) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) # create a centered dot icon _section_width = self.list_view.header().sectionSize(2) self._new_pixmap = QPixmap(_section_width, 20) self._new_pixmap.fill(Qt.transparent) painter = QPainter(self._new_pixmap) rect = QRect(int(_section_width * 0.5), 0, 20, 20) painter.setBrush(QColor('#666')) painter.setPen(QColor('#666')) painter.drawEllipse(rect) self._dot_icon = QIcon(self._new_pixmap) # shortcuts shortcut_add = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_W), self._app_window, self._on_additem_clicked) shortcut_add.setAutoRepeat(False) self.setLayout(v_box) # ************************************************************************ # **************************** Properties ******************************** # ************************************************************************ @property def uppercase_hex(self): """ Addresses displayed lower/upper-case """ return self._uppercase_hex @uppercase_hex.setter def uppercase_hex(self, value): """ Addresses displayed lower/upper-case value - bool or str 'upper', 'lower' """ if isinstance(value, bool): self._uppercase_hex = value elif isinstance(value, str): self._uppercase_hex = (value == 'upper') # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def do_addwatchpoint_dlg(self, ptr=None): # pylint: disable=too-many-branches """ Shows AddWatchpointDialog """ watchpoint_dlg = AddWatchpointDialog(self, ptr) if watchpoint_dlg.exec_() == QDialog.Accepted: mem_r = watchpoint_dlg.acc_read.isChecked() mem_w = watchpoint_dlg.acc_write.isChecked() mem_x = watchpoint_dlg.acc_execute.isChecked() mem_s = watchpoint_dlg.singleshot.isChecked() ptr = watchpoint_dlg.text_field.toPlainText() if ptr: if isinstance(ptr, str): if ptr.startswith('0x') or ptr.startswith('#'): ptr = utils.parse_ptr(ptr) else: try: ptr = int(ptr, 10) except ValueError: pass # int now? if not isinstance(ptr, int): try: ptr = int( self._app_window.dwarf.dwarf_api( 'evaluatePtr', ptr), 16) except ValueError: ptr = 0 if ptr == 0: return if not self._app_window.dwarf.dwarf_api( 'isValidPointer', ptr): return else: return mem_val = 0 if mem_r: mem_val |= self.MEMORY_ACCESS_READ if mem_w: mem_val |= self.MEMORY_ACCESS_WRITE if mem_x: mem_val |= self.MEMORY_ACCESS_EXECUTE if mem_s: mem_val |= self.MEMORY_WATCH_SINGLESHOT self.add_address(ptr, mem_val, from_api=False) # return [ptr, mem_val] def add_address(self, ptr, flags, from_api=False): """ Adds Address to display ptr - str or int flags - int """ if isinstance(ptr, str): ptr = utils.parse_ptr(ptr) if not isinstance(flags, int): try: flags = int(flags, 10) except ValueError: flags = 3 if not from_api: # function was called directly so add it to dwarf if not self._app_window.dwarf.is_address_watched(ptr): self._app_window.dwarf.dwarf_api('putWatchpoint', [ptr, flags]) return # show header self.list_view.setHeaderHidden(False) # create items to add if self._uppercase_hex: str_frmt = '0x{0:X}' else: str_frmt = '0x{0:x}' addr = QStandardItem() addr.setText(str_frmt.format(ptr)) read = QStandardItem() write = QStandardItem() execute = QStandardItem() singleshot = QStandardItem() if flags & self.MEMORY_ACCESS_READ: read.setIcon(self._dot_icon) if flags & self.MEMORY_ACCESS_WRITE: write.setIcon(self._dot_icon) if flags & self.MEMORY_ACCESS_EXECUTE: execute.setIcon(self._dot_icon) if flags & self.MEMORY_WATCH_SINGLESHOT: singleshot.setIcon(self._dot_icon) # add items as new row on top self._watchpoints_model.insertRow( 0, [addr, read, write, execute, singleshot]) def remove_address(self, ptr, from_api=False): """ Remove Address from List """ if isinstance(ptr, str): ptr = utils.parse_ptr(ptr) if not from_api: # called somewhere so remove watchpoint in dwarf too self._app_window.dwarf.dwarf_api('removeWatchpoint', ptr) return str_frmt = '' if self._uppercase_hex: str_frmt = '0x{0:X}'.format(ptr) else: str_frmt = '0x{0:x}'.format(ptr) model = self.list_view.model() for item in range(model.rowCount()): if str_frmt == model.item(item).text(): model.removeRow(item) def delete_items(self): """ Delete selected Items """ model = self.list_view.model() index = self.list_view.selectionModel().currentIndex().row() if index != -1: ptr = model.item(index, 0).text() self.remove_address(ptr) def clear_list(self): """ Clear the List """ model = self.list_view.model() # go through all items and tell it gets removed for item in range(model.rowCount()): ptr = model.item(item, 0).text() self.remove_address(ptr) if model.rowCount() > 0: # something was wrong it should be empty model.removeRows(0, model.rowCount()) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _on_contextmenu(self, pos): index = self.list_view.indexAt(pos).row() glbl_pt = self.list_view.mapToGlobal(pos) context_menu = QMenu(self) context_menu.addAction('Add watchpoint', self._on_additem_clicked) if index != -1: context_menu.addSeparator() context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self._watchpoints_model.item(index, 0).text())) context_menu.addAction( 'Jump to address', lambda: self._app_window.jump_to_address( self._watchpoints_model.item(index, 0).text())) context_menu.addAction( 'Delete watchpoint', lambda: self.remove_address( self._watchpoints_model.item(index, 0).text())) if self.list_view.search_enabled: context_menu.addSeparator() context_menu.addAction('Search', self.list_view._on_cm_search) context_menu.exec_(glbl_pt) def _on_item_dblclick(self, model_index): row = self._watchpoints_model.itemFromIndex(model_index).row() if row != -1: ptr = self._watchpoints_model.item(row, 0).text() self.onItemDoubleClicked.emit(ptr) def _on_additem_clicked(self): if self._app_window.dwarf.pid == 0: return self.do_addwatchpoint_dlg() def _on_watchpoint_added(self, watchpoint): """ Callback from Dwarf after Watchpoint is added """ # add to watchpointslist self.add_address(watchpoint.address, watchpoint.flags, from_api=True) self.onItemAdded.emit(watchpoint.address) def _on_watchpoint_removed(self, ptr): """ Callback from Dwarf after watchpoint is removed """ ptr = utils.parse_ptr(ptr) # remove from list self.remove_address(ptr, from_api=True) self.onItemRemoved.emit(ptr)
class BookmarksWidget(QWidget): def __init__(self, parent=None): # pylint: disable=too-many-statements super(BookmarksWidget, self).__init__(parent=parent) self._app_window = parent if self._app_window.dwarf is None: print('BookmarksPanel created before Dwarf exists') return self.bookmarks = {} self._bookmarks_list = DwarfListView() self._bookmarks_list.doubleClicked.connect(self._on_double_clicked) self._bookmarks_list.setContextMenuPolicy(Qt.CustomContextMenu) self._bookmarks_list.customContextMenuRequested.connect( self._on_contextmenu) self._bookmarks_model = QStandardItemModel(0, 2) self._bookmarks_model.setHeaderData(0, Qt.Horizontal, 'Address') self._bookmarks_model.setHeaderData(1, Qt.Horizontal, 'Notes') self._bookmarks_list.setModel(self._bookmarks_model) self._bookmarks_list.header().setStretchLastSection(False) self._bookmarks_list.header().setSectionResizeMode( 0, QHeaderView.ResizeToContents | QHeaderView.Interactive) self._bookmarks_list.header().setSectionResizeMode( 1, QHeaderView.Stretch | QHeaderView.Interactive) v_box = QVBoxLayout(self) v_box.setContentsMargins(0, 0, 0, 0) v_box.addWidget(self._bookmarks_list) #header = QHeaderView(Qt.Horizontal, self) h_box = QHBoxLayout() h_box.setContentsMargins(5, 2, 5, 5) self.btn1 = QPushButton( QIcon(utils.resource_path('assets/icons/plus.svg')), '') self.btn1.setFixedSize(20, 20) self.btn1.clicked.connect(lambda: self._create_bookmark(-1)) btn2 = QPushButton(QIcon(utils.resource_path('assets/icons/dash.svg')), '') btn2.setFixedSize(20, 20) btn2.clicked.connect(self.delete_items) btn3 = QPushButton( QIcon(utils.resource_path('assets/icons/trashcan.svg')), '') btn3.setFixedSize(20, 20) btn3.clicked.connect(self.clear_list) h_box.addWidget(self.btn1) h_box.addWidget(btn2) h_box.addSpacerItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred)) h_box.addWidget(btn3) # header.setLayout(h_box) # header.setFixedHeight(25) # v_box.addWidget(header) v_box.addLayout(h_box) self.setLayout(v_box) self._bold_font = QFont(self._bookmarks_list.font()) self._bold_font.setBold(True) shortcut_addnative = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_B), self._app_window, self._create_bookmark) shortcut_addnative.setAutoRepeat(False) # ************************************************************************ # **************************** Functions ********************************* # ************************************************************************ def delete_items(self): """ Delete selected Items """ index = self._bookmarks_list.selectionModel().currentIndex().row() if index != -1: self._on_delete_bookmark(index) self._bookmarks_model.removeRow(index) def clear_list(self): """ Clear the List """ # go through all items and tell it gets removed for item in range(self._bookmarks_model.rowCount()): self._on_delete_bookmark(item) if self._bookmarks_model.rowCount() > 0: # something was wrong it should be empty self._bookmarks_model.removeRows(0, self._bookmarks_model.rowCount()) # ************************************************************************ # **************************** Handlers ********************************** # ************************************************************************ def _on_double_clicked(self, index): index = self._bookmarks_list.selectionModel().currentIndex().row() if index != -1: addr = self._bookmarks_model.item(index, 0).text() if addr: self._app_window.jump_to_address(addr, view=1) def _on_contextmenu(self, pos): context_menu = QMenu(self) index = self._bookmarks_list.indexAt(pos).row() if index != -1: context_menu.addAction( 'Copy address', lambda: utils.copy_hex_to_clipboard( self._bookmarks_model.item(index, 0).text())) context_menu.addAction( 'Jump to address', lambda: self._app_window.jump_to_address( self._bookmarks_model.item(index, 0).text())) # todo: add breakpoint address menu context_menu.addSeparator() context_menu.addAction('Edit', lambda: self._create_bookmark(index=index)) context_menu.addAction('Delete', lambda: self._on_delete_bookmark(index)) context_menu.addSeparator() if self._bookmarks_list.search_enabled: context_menu.addSeparator() context_menu.addAction('Search', self._bookmarks_list._on_cm_search) context_menu.addSeparator() context_menu.addAction('New', self._create_bookmark) global_pt = self._bookmarks_list.mapToGlobal(pos) context_menu.exec(global_pt) # + button def _create_bookmark(self, index=-1, ptr='', note=''): if ptr == '': if isinstance(index, int) and index >= 0: ptr = self._bookmarks_model.item(index, 0).text() note = self._bookmarks_model.item(index, 1).text() ptr, _ = InputDialog.input_pointer(parent=self._app_window, input_content=ptr) else: ptr = utils.parse_ptr(ptr) if ptr > 0: ptr = hex(ptr) if self._bookmarks_list.uppercase_hex: ptr = ptr.upper().replace('0X', '0x') index = self._bookmarks_model.findItems(ptr, Qt.MatchExactly) if len(index) > 0: index = index[0].row() note = self._bookmarks_model.item(index, 1).text() else: index = -1 accept = note != '' if note == '': accept, note = InputDialog.input(hint='Insert notes for %s' % ptr, input_content=note) if accept: if index < 0: self.insert_bookmark(ptr, note) else: item = self._bookmarks_model.item(index, 0) item.setText(ptr) item = self._bookmarks_model.item(index, 1) item.setText(note) self.bookmarks[ptr] = note def insert_bookmark(self, ptr_as_hex, note): if self._bookmarks_list.uppercase_hex: ptr_as_hex = ptr_as_hex.upper().replace('0X', '0x') self._bookmarks_model.appendRow( [QStandardItem(ptr_as_hex), QStandardItem(note)]) self._bookmarks_list.resizeColumnToContents(0) def is_address_bookmarked(self, ptr): return utils.parse_ptr(ptr) in self.bookmarks # shortcuts/menu def _on_delete_bookmark(self, index): ptr = self._bookmarks_model.item(index, 0).text() del self.bookmarks[ptr] self._bookmarks_model.removeRow(index)