├── gui
├── __init__.py
├── gui.pyproject
├── inferior_state.py
├── context_data_role.py
├── custom_widgets
│ ├── code_context_widget.py
│ ├── disasm_context_widget.py
│ ├── backtrace_context_widget.py
│ ├── context_text_widget.py
│ ├── info_message_box.py
│ ├── context_text_edit.py
│ ├── register_context_widget.py
│ ├── stack_context_widget.py
│ ├── heap_context_widget.py
│ ├── context_list_widget.py
│ ├── main_context_widget.py
│ └── watches_context_widget.py
├── .gitignore
├── TODO.txt
├── tokens.py
├── html_style_delegate.py
├── form.ui
├── inferior_handler.py
├── ui_form.py
├── parser.py
├── gdb_handler.py
├── constants.py
├── gdb_reader.py
└── pwndbg_gui.py
├── requirements.txt
├── doc
├── Overview.png
└── Overview.drawio
├── screenshots
├── OverviewRunning.png
└── OverviewInferiorInput.png
├── start.py
├── .gitignore
├── Proposal
├── Proposal.md
└── Submission.md
├── README.md
└── LICENSE
/gui/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | PySide6~=6.5.1.1
2 | pygdbmi~=0.11.0.0
3 | psutil~=5.9.5
--------------------------------------------------------------------------------
/gui/gui.pyproject:
--------------------------------------------------------------------------------
1 | {
2 | "files": ["pwndbg_gui.py", "form.ui"]
3 | }
4 |
--------------------------------------------------------------------------------
/doc/Overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlEscher/pwndbg-gui/HEAD/doc/Overview.png
--------------------------------------------------------------------------------
/screenshots/OverviewRunning.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlEscher/pwndbg-gui/HEAD/screenshots/OverviewRunning.png
--------------------------------------------------------------------------------
/screenshots/OverviewInferiorInput.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlEscher/pwndbg-gui/HEAD/screenshots/OverviewInferiorInput.png
--------------------------------------------------------------------------------
/gui/inferior_state.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 |
3 |
4 | class InferiorState(Enum):
5 | # Inferior exited
6 | EXITED = 0
7 | # Inferior is running, GDB input is blocked during this time
8 | RUNNING = 1
9 | # Inferior is stopped, e.g. by a breakpoint
10 | STOPPED = 2
11 | # Inferior is loaded, but not started
12 | QUEUED = 3
13 |
--------------------------------------------------------------------------------
/gui/context_data_role.py:
--------------------------------------------------------------------------------
1 | from enum import auto, IntEnum
2 |
3 | from PySide6.QtCore import Qt
4 |
5 |
6 | class ContextDataRole(IntEnum):
7 | """Custom data role for ContextListWidgets"""
8 | @staticmethod
9 | def _generate_next_value_(name, start, count, last_values):
10 | # Default offset value: https://doc.qt.io/qt-6/qt.html#ItemDataRole-enum
11 | return Qt.ItemDataRole.UserRole + count
12 |
13 | # Represents an address, e.g. the stack address in a stack context
14 | ADDRESS = auto()
15 | # Represents a value, e.g. the value pointed to by a stack address
16 | VALUE = auto()
17 |
--------------------------------------------------------------------------------
/gui/custom_widgets/code_context_widget.py:
--------------------------------------------------------------------------------
1 | from typing import TYPE_CHECKING
2 |
3 | from PySide6.QtWidgets import QSplitter
4 |
5 | from gui.custom_widgets.context_text_widget import ContextTextWidget
6 |
7 | # Prevent circular import error
8 | if TYPE_CHECKING:
9 | from gui.pwndbg_gui import PwnDbgGui
10 |
11 |
12 | class CodeContextWidget(ContextTextWidget):
13 | def __init__(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
14 | super().__init__(parent, title, splitter, index)
15 | self.setObjectName("code")
16 | self.setup_widget_layout(parent, title, splitter, index)
17 |
--------------------------------------------------------------------------------
/gui/custom_widgets/disasm_context_widget.py:
--------------------------------------------------------------------------------
1 | from typing import TYPE_CHECKING
2 |
3 | from PySide6.QtWidgets import QSplitter
4 |
5 | from gui.custom_widgets.context_text_widget import ContextTextWidget
6 |
7 | # Prevent circular import error
8 | if TYPE_CHECKING:
9 | from gui.pwndbg_gui import PwnDbgGui
10 |
11 |
12 | class DisasmContextWidget(ContextTextWidget):
13 | def __init__(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
14 | super().__init__(parent, title, splitter, index)
15 | self.setObjectName("disasm")
16 | self.setup_widget_layout(parent, title, splitter, index)
17 |
--------------------------------------------------------------------------------
/gui/custom_widgets/backtrace_context_widget.py:
--------------------------------------------------------------------------------
1 | from typing import TYPE_CHECKING
2 |
3 | from PySide6.QtWidgets import QSplitter
4 |
5 | from gui.custom_widgets.context_text_widget import ContextTextWidget
6 |
7 | # Prevent circular import error
8 | if TYPE_CHECKING:
9 | from gui.pwndbg_gui import PwnDbgGui
10 |
11 |
12 | class BacktraceContextWidget(ContextTextWidget):
13 | def __init__(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
14 | super().__init__(parent, title, splitter, index)
15 | self.setObjectName("backtrace")
16 | self.setup_widget_layout(parent, title, splitter, index)
17 |
--------------------------------------------------------------------------------
/gui/.gitignore:
--------------------------------------------------------------------------------
1 | # This file is used to ignore files which are generated
2 | # ----------------------------------------------------------------------------
3 |
4 | *~
5 | *.autosave
6 | *.a
7 | *.core
8 | *.moc
9 | *.o
10 | *.obj
11 | *.orig
12 | *.rej
13 | *.so
14 | *.so.*
15 | *_pch.h.cpp
16 | *_resource.rc
17 | *.qm
18 | .#*
19 | *.*#
20 | core
21 | !core/
22 | tags
23 | .DS_Store
24 | .directory
25 | *.debug
26 | Makefile*
27 | *.prl
28 | *.app
29 | moc_*.cpp
30 | ui_*.h
31 | qrc_*.cpp
32 | Thumbs.db
33 | *.res
34 | *.rc
35 | /.qmake.cache
36 | /.qmake.stash
37 |
38 | # qtcreator generated files
39 | *.pro.user*
40 | CMakeLists.txt.user*
41 |
42 | # xemacs temporary files
43 | *.flc
44 |
45 | # Vim temporary files
46 | .*.swp
47 |
48 | # Visual Studio generated files
49 | *.ib_pdb_index
50 | *.idb
51 | *.ilk
52 | *.pdb
53 | *.sln
54 | *.suo
55 | *.vcproj
56 | *vcproj.*.*.user
57 | *.ncb
58 | *.sdf
59 | *.opensdf
60 | *.vcxproj
61 | *vcxproj.*
62 |
63 | # MinGW generated files
64 | *.Debug
65 | *.Release
66 |
67 | # Python byte code
68 | *.pyc
69 |
70 | # Binaries
71 | # --------
72 | *.dll
73 | *.exe
74 |
75 |
--------------------------------------------------------------------------------
/gui/TODO.txt:
--------------------------------------------------------------------------------
1 | Test:
2 | -Shell spawn / multiple threads
3 | -Docker setup + attach
4 | -step through more challanges
5 | -payload insert test (run < payload)
6 | -Shell spawn in local execution (inferior working?)
7 | -clean install (gdb -> pwndbg -> pwndbg-gui)
8 | -final test on Laptop
9 |
10 | Future Features:
11 | -Window for got command
12 | -Window for elf command (one execution is enough)
13 | -Window for checksec command (one execution is enough)
14 | -Search command in main window
15 | - Easier inputting of payloads (e.g. via files)
16 | - Setting breakpoint in source or disassembly via GUI
17 | - Customize contexts arrangement
18 | - Pop out contexts into separate windows
19 | - Rearrange and move contexts around in the GUI
20 | - Editing of memory (e.g. registers, stack, heap) via UI (e.g. double-click on stack line)
21 |
22 | Known Limitations (and facts):
23 | -User can not start/attach process via the main command window -> only GUI buttons
24 | -Stack lines update on startup
25 | -pwndbg next instructions (e.g. nextret, nextcall, ...) will output the entire pwndbg context WITHOUT RESULT DONE! which will send it to our regs context ¯\_(ツ)_/¯
26 | -when attaching the source code dir must be specified manually when not in docker
27 |
28 |
--------------------------------------------------------------------------------
/gui/custom_widgets/context_text_widget.py:
--------------------------------------------------------------------------------
1 | from typing import TYPE_CHECKING
2 |
3 | from PySide6.QtCore import Qt
4 | from PySide6.QtWidgets import QSplitter, QGroupBox, QVBoxLayout
5 |
6 | from gui.custom_widgets.context_text_edit import ContextTextEdit
7 |
8 | # Prevent circular import error
9 | if TYPE_CHECKING:
10 | from gui.pwndbg_gui import PwnDbgGui
11 |
12 |
13 | class ContextTextWidget(ContextTextEdit):
14 | """Wrap the ContextTextEdit in a Groupbox with a header"""
15 | def __init__(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
16 | super().__init__(parent)
17 | self.setReadOnly(True)
18 | self.setup_widget_layout(parent, title, splitter, index)
19 |
20 | def setup_widget_layout(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
21 | # GroupBox needs to have parent before being added to splitter (see SO below)
22 | context_box = QGroupBox(title, parent)
23 | context_box.setAlignment(Qt.AlignmentFlag.AlignCenter)
24 | context_box.setFlat(True)
25 | context_layout = QVBoxLayout()
26 | context_layout.addWidget(self)
27 | context_box.setLayout(context_layout)
28 | splitter.replaceWidget(index, context_box)
29 | # https://stackoverflow.com/a/66067630
30 | context_box.show()
31 |
--------------------------------------------------------------------------------
/gui/custom_widgets/info_message_box.py:
--------------------------------------------------------------------------------
1 | from PySide6.QtCore import Qt, QUrl
2 | from PySide6.QtGui import QIcon, QDesktopServices
3 | from PySide6.QtWidgets import QVBoxLayout, QDialog, QPushButton, QDialogButtonBox, QWidget
4 |
5 | from gui.custom_widgets.context_text_edit import ContextTextEdit
6 |
7 |
8 | class InfoMessageBox(QDialog):
9 | def __init__(self, parent: QWidget, title: str, content: str, url: str):
10 | super().__init__(parent)
11 | layout = QVBoxLayout()
12 | self.content = ContextTextEdit(self)
13 | self.content.add_content(content)
14 | self.content.setMinimumSize(800, 600)
15 |
16 | button_box = QDialogButtonBox(Qt.Orientation.Horizontal)
17 | ok_button = QPushButton("Ok")
18 | info_button = QPushButton("Info")
19 |
20 | ok_button.setIcon(QIcon.fromTheme("dialog-ok"))
21 | ok_button.clicked.connect(self.close)
22 | info_button.setIcon(QIcon.fromTheme("dialog-information"))
23 | info_button.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(url)))
24 |
25 | button_box.addButton(ok_button, QDialogButtonBox.ButtonRole.AcceptRole)
26 | button_box.addButton(info_button, QDialogButtonBox.ButtonRole.HelpRole)
27 |
28 | layout.addWidget(self.content)
29 | layout.addWidget(button_box)
30 |
31 | self.setLayout(layout)
32 | self.setWindowTitle(title)
33 |
--------------------------------------------------------------------------------
/gui/tokens.py:
--------------------------------------------------------------------------------
1 | from enum import IntEnum
2 |
3 |
4 | class ResponseToken(IntEnum):
5 | """Tokens used to identify commands given to the GDB Machine Interface and decide what to do with the result.
6 | The first part of the token name shows who triggered the command, the second part denotes its destination"""
7 | # Discard result
8 | DELETE = 0
9 | # Command originated by user, add to main output widget
10 | USER_MAIN = 1
11 | # Command originated by us, add to main output widget
12 | GUI_MAIN_CONTEXT = 2
13 | GUI_DISASM_CONTEXT = 3
14 | GUI_CODE_CONTEXT = 4
15 | GUI_REGS_CONTEXT = 5
16 | GUI_STACK_CONTEXT = 6
17 | GUI_BACKTRACE_CONTEXT = 7
18 | GUI_HEAP_HEAP = 8
19 | GUI_HEAP_BINS = 9
20 | GUI_HEAP_TRY_MALLOC = 10
21 | GUI_HEAP_TRY_FREE = 11
22 | GUI_REGS_FS_BASE = 12
23 | GUI_PWNDBG_ABOUT = 13
24 | GUI_XINFO = 14
25 | GUI_WATCHES_HEXDUMP = 1000
26 |
27 | def __str__(self):
28 | return str(self.value)
29 |
30 |
31 | Token_to_Context = {
32 | ResponseToken.USER_MAIN: "main",
33 | ResponseToken.GUI_MAIN_CONTEXT: "main",
34 | ResponseToken.GUI_DISASM_CONTEXT: "disasm",
35 | ResponseToken.GUI_CODE_CONTEXT: "code",
36 | ResponseToken.GUI_REGS_CONTEXT: "regs",
37 | ResponseToken.GUI_BACKTRACE_CONTEXT: "backtrace",
38 | ResponseToken.GUI_STACK_CONTEXT: "stack",
39 | }
40 |
41 | Context_to_Token = dict(map(reversed, Token_to_Context.items()))
42 |
--------------------------------------------------------------------------------
/gui/custom_widgets/context_text_edit.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from PySide6.QtGui import QTextCursor
4 | from PySide6.QtWidgets import QTextEdit, QWidget
5 |
6 | logger = logging.getLogger(__file__)
7 |
8 |
9 | class ContextTextEdit(QTextEdit):
10 | def __init__(self, parent: QWidget):
11 | super().__init__(parent)
12 | self.setReadOnly(True)
13 |
14 | def add_content(self, content: str):
15 | self.setHtml(content)
16 | cursor = self.textCursor()
17 | # Move cursor to the end, so that the subsequent ensureCursorVisible will scroll UP
18 | cursor.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.MoveAnchor)
19 | self.setTextCursor(cursor)
20 | # Scroll so that the current line in "code" and "disasm" contexts is in view
21 | self.find_and_set_cursor("►")
22 |
23 |
24 | def find_and_set_cursor(self, character: str):
25 | cursor = self.textCursor()
26 | content = self.toPlainText()
27 | char_index = content.find(character)
28 | if char_index != -1:
29 | cursor.setPosition(char_index)
30 | self.setTextCursor(cursor)
31 | self.ensureCursorVisible()
32 | else:
33 | # Otherwise scroll to the top
34 | self.verticalScrollBar().setValue(0)
35 |
36 | def set_maxheight_to_lines(self, lines: int):
37 | font_metrics = self.fontMetrics()
38 | line_height = font_metrics.lineSpacing()
39 | extra_height = font_metrics.leading()
40 | self.setMaximumHeight((line_height + extra_height) * lines)
41 |
--------------------------------------------------------------------------------
/gui/custom_widgets/register_context_widget.py:
--------------------------------------------------------------------------------
1 | from typing import TYPE_CHECKING
2 |
3 | from PySide6.QtCore import Qt, Slot
4 | from PySide6.QtWidgets import QSplitter, QListWidgetItem
5 |
6 | from gui.context_data_role import ContextDataRole
7 | from gui.custom_widgets.context_list_widget import ContextListWidget
8 | from gui.html_style_delegate import HTMLDelegate
9 |
10 | # Prevent circular import error
11 | if TYPE_CHECKING:
12 | from gui.pwndbg_gui import PwnDbgGui
13 |
14 |
15 | class RegisterContextWidget(ContextListWidget):
16 | def __init__(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
17 | super().__init__(parent, title, splitter, index)
18 | self.setObjectName("regs")
19 | self.setItemDelegate(HTMLDelegate())
20 |
21 | @Slot(bytes)
22 | def receive_fs_base(self, content: bytes):
23 | """Callback to receive the hex value of the fs register"""
24 | cleaned = self.parser.to_html(b" \x1b[1mFS \x1b[0m \x1b[35m" + content + b"\x1b[0m").splitlines()
25 | # Remove unneeded lines containing only HTML, as "content" will be a full HTML document returned by the parser
26 | body_start = cleaned.index(next(line for line in cleaned if "
2 |
3 | PwnDbgGui
4 |
5 |
6 |
7 | 0
8 | 0
9 | 1367
10 | 1037
11 |
12 |
13 |
14 | PwnDbgGui
15 |
16 |
17 |
18 |
19 | 0
20 | 10
21 | 1361
22 | 1021
23 |
24 |
25 |
26 | Qt::Vertical
27 |
28 |
29 |
30 | Qt::Horizontal
31 |
32 |
33 |
34 | Qt::Vertical
35 |
36 |
37 |
38 | true
39 |
40 |
41 |
42 |
43 | true
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 | Qt::Horizontal
53 |
54 |
55 |
56 |
57 | Qt::Vertical
58 |
59 |
60 |
61 |
62 | true
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/gui/inferior_handler.py:
--------------------------------------------------------------------------------
1 | import fcntl
2 | import logging
3 | import os
4 | import select
5 | import tty
6 |
7 | from PySide6.QtCore import QObject, Slot, Signal, QCoreApplication
8 |
9 | from gui.inferior_state import InferiorState
10 |
11 | logger = logging.getLogger(__file__)
12 |
13 |
14 | class InferiorHandler(QObject):
15 | update_gui = Signal(str, bytes)
16 | INFERIOR_STATE = InferiorState.QUEUED
17 |
18 | def __init__(self):
19 | super().__init__()
20 |
21 | # open a tty for interaction with the inferior process (allows for separation of contexts)
22 | self.master, self.slave = os.openpty()
23 | # Set the master file descriptor to non-blocking mode
24 | flags = fcntl.fcntl(self.master, fcntl.F_GETFL)
25 | fcntl.fcntl(self.master, fcntl.F_SETFL, flags | os.O_NONBLOCK)
26 | # Disable ASCII control character interpretation, so that any byte input by the user doesn't get swallowed
27 | tty.setraw(self.slave)
28 | tty.setraw(self.master)
29 | # execute gdb tty command to forward the inferior to this tty
30 | self.tty = os.ttyname(self.slave)
31 | logger.debug("Opened tty for inferior interaction: %s", self.tty)
32 | self.to_write = b""
33 | self.run = True
34 |
35 | @Slot()
36 | def inferior_runs(self):
37 | """Main entry for inferior thread. Read and Write to tty."""
38 | logger.debug("Starting Inferior Interaction")
39 | while self.run:
40 | can_read, _, _ = select.select([self.master], [], [], 0.2) # Non-blocking check for readability
41 | if can_read:
42 | # read data and send it to main
43 | data = os.read(self.master, 4096)
44 | self.update_gui.emit("main", data)
45 | QCoreApplication.processEvents() # Process pending write events
46 | if self.to_write != b"":
47 | os.write(self.master, self.to_write)
48 | self.to_write = b""
49 |
50 | @Slot(bytes)
51 | def inferior_write(self, inferior_input: bytes):
52 | """Inferior write slot. Will be emitted from gdb_handler.
53 | :param inferior_input: Bytes to write to the inferior
54 | """
55 | self.to_write += inferior_input
56 |
57 | @Slot()
58 | def set_run(self, state: bool) -> object:
59 | """Sets whether the thread should keep working"""
60 | self.run = state
61 |
--------------------------------------------------------------------------------
/start.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import getpass
3 | import logging
4 | import subprocess
5 | import sys
6 | import venv
7 | from pathlib import Path
8 |
9 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s | [%(levelname)s] : %(message)s')
10 | logger = logging.getLogger(__file__)
11 |
12 |
13 | def create_virtual_environment(env_dir: Path):
14 | """Create a new Python virtual environment."""
15 | if not env_dir.exists():
16 | logger.info("Creating virtual environment at %s", str(env_dir))
17 | venv.create(env_dir, with_pip=True)
18 |
19 |
20 | def install_dependencies(env_dir: Path, requirements_file: Path):
21 | """Install dependencies in the virtual environment using pip."""
22 | pip_path = f"{env_dir}/Scripts/pip" if sys.platform == "win32" else f"{env_dir}/bin/pip"
23 | logger.info("Installing requirements from %s for %s", str(requirements_file), str(env_dir))
24 | subprocess.run([pip_path, "install", "-r", requirements_file], check=True)
25 |
26 |
27 | def run_script_in_environment(env_dir: Path, script_path: Path, args: argparse.Namespace):
28 | """Run the Python script within the virtual environment."""
29 | python_path = f"{env_dir}/Scripts/python" if sys.platform == "win32" else f"{env_dir}/bin/python"
30 | logger.info("Starting GUI using %s", python_path)
31 | cmd = [python_path, script_path, args.logging_level]
32 | if args.sudo:
33 | cmd = ["sudo", "-S"] + cmd
34 | password = getpass.getpass("Enter your sudo password: ")
35 | password = password.strip()
36 | process = subprocess.Popen(cmd, stdin=subprocess.PIPE)
37 | process.communicate(password.encode())
38 | else:
39 | subprocess.run(cmd, check=True)
40 |
41 |
42 | def main():
43 | parser = argparse.ArgumentParser()
44 | parser.add_argument("--sudo", action="store_true", help="Run the script with sudo. This is required if you want "
45 | "GDB to attach to a running process")
46 | parser.add_argument("-l", "--logging-level", help="Set the log level of the GUI", default="INFO")
47 | args = parser.parse_args()
48 | root_dir = Path(__file__).parent.resolve()
49 | env_dir = root_dir / "pwndbg-gui-venv"
50 | requirements_file = root_dir / "requirements.txt"
51 | script_path = root_dir / "gui" / "pwndbg_gui.py"
52 |
53 | create_virtual_environment(env_dir)
54 | install_dependencies(env_dir, requirements_file)
55 | run_script_in_environment(env_dir, script_path, args)
56 |
57 |
58 | if __name__ == "__main__":
59 | main()
60 |
--------------------------------------------------------------------------------
/gui/ui_form.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | ################################################################################
4 | ## Form generated from reading UI file 'form.ui'
5 | ##
6 | ## Created by: Qt User Interface Compiler version 6.5.1
7 | ##
8 | ## WARNING! All changes made in this file will be lost when recompiling UI file!
9 | ################################################################################
10 |
11 | from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
12 | QMetaObject, QObject, QPoint, QRect,
13 | QSize, QTime, QUrl, Qt)
14 | from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
15 | QFont, QFontDatabase, QGradient, QIcon,
16 | QImage, QKeySequence, QLinearGradient, QPainter,
17 | QPalette, QPixmap, QRadialGradient, QTransform)
18 | from PySide6.QtWidgets import (QApplication, QListWidget, QListWidgetItem, QSizePolicy,
19 | QSplitter, QTextEdit, QWidget)
20 |
21 | class Ui_PwnDbgGui(object):
22 | def setupUi(self, PwnDbgGui):
23 | if not PwnDbgGui.objectName():
24 | PwnDbgGui.setObjectName(u"PwnDbgGui")
25 | PwnDbgGui.resize(1367, 1037)
26 | self.top_splitter = QSplitter(PwnDbgGui)
27 | self.top_splitter.setObjectName(u"top_splitter")
28 | self.top_splitter.setGeometry(QRect(0, 10, 1361, 1021))
29 | self.top_splitter.setOrientation(Qt.Vertical)
30 | self.splitter_4 = QSplitter(self.top_splitter)
31 | self.splitter_4.setObjectName(u"splitter_4")
32 | self.splitter_4.setOrientation(Qt.Horizontal)
33 | self.code_splitter = QSplitter(self.splitter_4)
34 | self.code_splitter.setObjectName(u"code_splitter")
35 | self.code_splitter.setOrientation(Qt.Vertical)
36 | self.disasm = QTextEdit(self.code_splitter)
37 | self.disasm.setObjectName(u"disasm")
38 | self.disasm.setReadOnly(True)
39 | self.code_splitter.addWidget(self.disasm)
40 | self.code = QTextEdit(self.code_splitter)
41 | self.code.setObjectName(u"code")
42 | self.code.setReadOnly(True)
43 | self.code_splitter.addWidget(self.code)
44 | self.splitter_4.addWidget(self.code_splitter)
45 | self.heap = QTextEdit(self.splitter_4)
46 | self.heap.setObjectName(u"heap")
47 | self.splitter_4.addWidget(self.heap)
48 | self.stack = QListWidget(self.splitter_4)
49 | self.stack.setObjectName(u"stack")
50 | self.splitter_4.addWidget(self.stack)
51 | self.top_splitter.addWidget(self.splitter_4)
52 | self.splitter = QSplitter(self.top_splitter)
53 | self.splitter.setObjectName(u"splitter")
54 | self.splitter.setOrientation(Qt.Horizontal)
55 | self.main = QTextEdit(self.splitter)
56 | self.main.setObjectName(u"main")
57 | self.splitter.addWidget(self.main)
58 | self.splitter_3 = QSplitter(self.splitter)
59 | self.splitter_3.setObjectName(u"splitter_3")
60 | self.splitter_3.setOrientation(Qt.Vertical)
61 | self.regs = QTextEdit(self.splitter_3)
62 | self.regs.setObjectName(u"regs")
63 | self.splitter_3.addWidget(self.regs)
64 | self.backtrace = QTextEdit(self.splitter_3)
65 | self.backtrace.setObjectName(u"backtrace")
66 | self.backtrace.setReadOnly(True)
67 | self.splitter_3.addWidget(self.backtrace)
68 | self.splitter.addWidget(self.splitter_3)
69 | self.watches = QTextEdit(self.splitter)
70 | self.watches.setObjectName(u"watches")
71 | self.splitter.addWidget(self.watches)
72 | self.top_splitter.addWidget(self.splitter)
73 |
74 | self.retranslateUi(PwnDbgGui)
75 |
76 | QMetaObject.connectSlotsByName(PwnDbgGui)
77 | # setupUi
78 |
79 | def retranslateUi(self, PwnDbgGui):
80 | PwnDbgGui.setWindowTitle(QCoreApplication.translate("PwnDbgGui", u"PwnDbgGui", None))
81 | # retranslateUi
82 |
83 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 | /pwndbg-gui-venv/
162 |
--------------------------------------------------------------------------------
/Proposal/Proposal.md:
--------------------------------------------------------------------------------
1 | # Pwndbg GUI
2 |
3 | ## Motivation
4 |
5 | `pwndbg` is a command line utility that enhances `gdb` by allowing the user to more easily view data, as well as by adding various new commands.
6 | However, with it being a command line tool it comes with various restrictions regarding usability.
7 | Especially the multitasking and customizability sufferes in text-based terminal applications since they are by design bound to the limits of terminal representation.
8 |
9 | By default `pwndbg` prints everything to the same terminal, just pushing old output out the top. This makes the space for the different contexts of `pwndbg` extremly limited.
10 | If you want to have a scrolling free experience you need to limit yourself to the screensize or adjust the terminal font-size.
11 | [Splitting contexts](https://github.com/pwndbg/pwndbg/blob/dev/FEATURES.md#splitting--layouting-context) using `tmux` and `splitmind` can help mitigating some headaches by allowing multiple contexts to be displayed at the same time in different terminals, however these tools are still bound by terminal limitations.
12 | Simple things such as copying multiple lines of data, viewing previous states and switching bewteen the context windows to adapt sizes of the contexts are either impossible or cumbersome.
13 |
14 | While `pwndbg` already simplified overused commands in gdb, there are still a lot of commands that need to be typed often and can have complex outputs like heap commands (`heap`, `bins`, etc.) or `vmmap`.
15 | By introducing a GUI layer ontop of `pwndbg` we can filter out, reorder and customize the gdb output.
16 |
17 | Having a GUI application would not only allow using `pwndbg`'s functionality in a simplified, more streamlined way, but also allows for advantages a typical GUI interface has like interacting with the filesystem easily or rich media support.
18 | A GUI is also more intuitive to use, having the user remember less commands and hiding unnecessary output.
19 |
20 | ## Approach
21 |
22 | The idea is to build a wrapper around `pwndbg` using the [Qt](https://doc.qt.io/qtforpython-6/) framework.
23 | The user would need to setup `pwndbg` on their system once and then start the GUI, which invokes `gdb`.
24 | All interaction would then only be done through the GUI, which forwards the specific commands and presents the output accordingly.
25 | This allows us to aggregate and customize output and simplify command input (e.g. buttons).
26 |
27 | ## Features
28 |
29 | - [x] Multi pane setup similar to [Splitting contexts](https://github.com/pwndbg/pwndbg/blob/dev/FEATURES.md#splitting--layouting-context)
30 | - [x] Resizable, scrollable panes
31 | - [x] Allow to start a local executable
32 | - [x] Allow attaching to an already running program
33 | - Functionality is implemented, but requires `sudo` which is problematic for python modules
34 | - Inferior communication may require changes
35 | - [x] Include banners/header for panes
36 | - [x] Add `fs_base` to register section
37 | - [x] Convenience buttons (maybe hotkeys) / fields for `c`, `r`, `n`, `s`, `ni`, `si`
38 | - [x] Add a `search` functionality
39 | - [x] Add a context menu to `stack`/`regs` to allow copy and display information about data (e.g. offsets)
40 | - [x] +/- buttons for adding `pwndbg` context-stack lines
41 | - [x] New context: Heap
42 | - Add a new context to the ones `pwndbg` already offers (stack, backtrace, etc...) for the heap
43 | - Continuously show heap related information (`heap` command, `main_arena`, fastbins, smallbins)
44 | - Also allow to use `pwndbgs`'s `try_free`
45 | - [x] New context: `hexdump`
46 | - Allow the user to actively "Watch" a number of addresses via hexdump
47 | - Increase / Decrease number of lines shown via GUI buttons
48 |
49 | ## Additional (possibly future) Features
50 |
51 | - Easier inputting of payloads (e.g. via files)
52 | - Setting breakpoint in source or disassembly via GUI
53 | - Customize contexts arrangement
54 | - Pop out contexts into separate windows
55 | - Rearrange and move contexts around in the GUI
56 | - Remember layout on startup
57 | - Sizes of splitters
58 | - Arrangement of contexts (custom context layout not yet supported)
59 | - Editing of memory (e.g. registers, stack, heap) via UI (e.g. double-click on stack line)
--------------------------------------------------------------------------------
/gui/custom_widgets/heap_context_widget.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import TYPE_CHECKING
3 |
4 | from PySide6.QtCore import Qt, Signal, Slot
5 | from PySide6.QtWidgets import QGroupBox, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QSplitter, QWidget
6 |
7 | from gui.custom_widgets.context_text_edit import ContextTextEdit
8 | from gui.parser import ContextParser
9 |
10 | # Prevent circular import error
11 | if TYPE_CHECKING:
12 | from gui.pwndbg_gui import PwnDbgGui
13 |
14 | logger = logging.getLogger(__file__)
15 |
16 |
17 | class HeapContextWidget(QGroupBox):
18 | # Execute "try_free" in pwndbg
19 | get_try_free = Signal(str)
20 |
21 | def __init__(self, parent: 'PwnDbgGui'):
22 | super().__init__(parent)
23 | self.parser = ContextParser()
24 | self.bins_output: ContextTextEdit | None = None
25 | self.heap_output: ContextTextEdit | None = None
26 | self.try_free_output: ContextTextEdit | None = None
27 | self.try_free_input: QLineEdit | None = None
28 | # The "top" layout of the whole heap context widget
29 | self.context_layout = QVBoxLayout()
30 | self.context_splitter = QSplitter()
31 | self.context_splitter.setOrientation(Qt.Orientation.Vertical)
32 | self.context_splitter.setObjectName("heap_splitter")
33 | self.setAlignment(Qt.AlignmentFlag.AlignCenter)
34 | self.setFlat(True)
35 | self.setTitle("Heap")
36 | self.get_try_free.connect(parent.gdb_handler.execute_try_free)
37 | # Set up the interior layout of this widget
38 | self.setup_widget_layout()
39 | # Insert this widget into the UI
40 | parent.ui.splitter_4.replaceWidget(1, self)
41 |
42 | def setup_widget_layout(self):
43 | output_splitter = QSplitter()
44 | output_splitter.setOrientation(Qt.Orientation.Horizontal)
45 | output_splitter.setObjectName("heap_output_splitter")
46 |
47 | self.heap_output = ContextTextEdit(self)
48 | output_splitter.addWidget(self.heap_output)
49 | self.bins_output = ContextTextEdit(self)
50 | output_splitter.addWidget(self.bins_output)
51 | self.context_splitter.addWidget(output_splitter)
52 |
53 | # The overall element of the TryFree block, containing the input mask and output box
54 | try_free_layout = QVBoxLayout()
55 | # The layout for the input mask (label and line edit) of the Try Free functionality
56 | try_free_input_layout = QHBoxLayout()
57 | try_free_label = QLabel("Try Free:")
58 | try_free_label.setToolTip("Simulate a free() call on a heap pointer")
59 | try_free_input_layout.addWidget(try_free_label)
60 | self.try_free_input = QLineEdit()
61 | self.try_free_input.setToolTip("Simulate a free() call on a heap pointer")
62 | self.try_free_input.returnPressed.connect(self.try_free_submit)
63 | try_free_input_layout.addWidget(self.try_free_input)
64 | try_free_layout.addLayout(try_free_input_layout)
65 | self.try_free_output = ContextTextEdit(self)
66 | try_free_layout.addWidget(self.try_free_output)
67 | # Package the try_free layout in a widget so that we can add it to the splitter
68 | try_free_widget = QWidget(self)
69 | try_free_widget.setLayout(try_free_layout)
70 | self.context_splitter.addWidget(try_free_widget)
71 |
72 | self.context_layout.addWidget(self.context_splitter)
73 | self.setLayout(self.context_layout)
74 |
75 | @Slot()
76 | def try_free_submit(self):
77 | """Callback for when the user presses Enter in the try_free input mask"""
78 | param = self.try_free_input.text()
79 | self.get_try_free.emit(param)
80 | self.try_free_input.clear()
81 |
82 | @Slot(bytes)
83 | def receive_try_free_result(self, result: bytes):
84 | """Callback for receiving the result of the 'try_free' command from the GDB reader"""
85 | self.try_free_output.add_content(self.parser.to_html(result))
86 |
87 | @Slot(bytes)
88 | def receive_heap_result(self, result: bytes):
89 | """Callback for receiving the result of the 'heap' command from the GDB reader"""
90 | self.heap_output.add_content(self.parser.to_html(result))
91 |
92 | @Slot(bytes)
93 | def receive_bins_result(self, result: bytes):
94 | """Callback for receiving the result of the 'bins' command from the GDB reader"""
95 | self.bins_output.add_content(self.parser.to_html(result))
96 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pwndbg-gui [](https://github.com/AlEscher/pwndbg-gui/actions/workflows/github-code-scanning/codeql)
2 |
3 | An unofficial GUI wrapper around [pwndbg](https://github.com/pwndbg/pwndbg) intended to leverage the UI benefits of a graphical user interface.
4 |
5 | ## Setup
6 |
7 | 1. Install and setup [pwndbg](https://github.com/pwndbg/pwndbg#how)
8 | 2. Optionally add any settings you want in `~/.gdbinit`
9 | 3. Run `python start.py`
10 | - This will create a virtual environment and install the needed dependencies
11 | - On Debian/Ubuntu systems, you may need to previously install `python3-venv`
12 | - If you want to attach to running programs, GDB needs to be started with sudo. To do this, copy `~/.gdbinit` into `/root` and run `python start.py --sudo` and enter your sudo password when prompted
13 |
14 | ## Features
15 |
16 | - Resizable and collapsible panes
17 | - Heap context
18 | - Continuously show heap related information such as allocated chunks and freed bins
19 | - Give easy access to `pwndbg`'s `try_free` command
20 | - Watch context
21 | - Add multiple addresses to a watch context to continuously monitor the data in a hexdump format
22 | - Context menus for Stack and Register contexts, that allow easy lookup via the `xinfo` command.
23 | - Keyboard shortcuts
24 | - Shortcuts for GDB commands as well as GUI features
25 | - Shortcuts are either displayed next to the action in a menu (e.g. `Ctrl + N`) or shown by an underlined letter (pressing `Alt + ` will activate the button / menu)
26 | - Input byte literals
27 | - When inputting to the inferior process (denoted by the label next to the main pane's input field) you can supply a python `bytes` literal
28 | - E.g.: Writing b"Hello\x00World\n" will interpret the input as a `bytes` literal and evaluate it accordingly
29 | - All existing GDB / `pwndbg` commands can still be executed via the Main input widget
30 |
31 | ## Preview
32 |
33 | 
34 |
35 | ## Motivation
36 |
37 | `pwndbg` is a command line utility that greatly enhances `gdb` by allowing the user to more easily view data, as well as by adding many new commands.
38 | As the dominant tools for debugging and pwning, they mostly suffer from the fact that they are bound to the limitations of terminal applications.
39 | To address this we wanted to leverage a modern UI framework to wrap the most essential functionality.
40 | This allows us to filter out, reorder and customize the gdb output, simplifying or highlighting important information.
41 | Our GUI application primarily focuses on usability reducing the number of user commands, displaying information neatly, copying data easily, and providing hotkeys for control-flow.
42 |
43 | ## Approach
44 |
45 | The GUI is written using the [Qt](https://doc.qt.io/qtforpython-6/) framework for python.
46 | GDB is managed as a subprocess in [MI mode](https://ftp.gnu.org/old-gnu/Manuals/gdb/html_chapter/gdb_22.html) and interaction is handled by [pygdbmi](https://pypi.org/project/pygdbmi/).
47 | To make the GUI more fluent and prevent hangups, the application is multithreaded.
48 | The main thread is the GUI thread, which starts other threads that handle input to GDB (`GdbHandler`), collecting output from GDB (`GdbReader`) and interaction with the inferior process (`InferiorHandler`)
49 |
50 | ## Troubleshooting
51 |
52 | - If you are experiencing issues on startup relating to QT plugins not being found or loaded try to set `QT_DEBUG_PLUGINS=1` for the user where the failure is occurring and retry. This will show you more debug output related to QT. Most likely you will have some missing dependencies that can be installed via your favourite package manager. On Ubuntu/Debian it was the `libxcb-cursor0` library. See this [SO post](https://stackoverflow.com/questions/68036484/qt6-qt-qpa-plugin-could-not-load-the-qt-platform-plugin-xcb-in-even-thou).
53 |
54 | ## External dependencies
55 | - [Qt PySide6](https://www.qt.io/download-open-source) as the GUI framework
56 | - [Pygdbmi](https://github.com/cs01/pygdbmi) for interaction with GDB in MI mode
57 | - [psutil](https://pypi.org/project/psutil/) for cross-platform access to process information
58 |
59 | ## Disclaimer
60 | This tool was developed as project for the Binary Exploitation practical course at TUM. All features are targeted to complete the pwning challenges during the course. If you like it, but have a use case that is currently not supported feel free to open a PR or an issue.
--------------------------------------------------------------------------------
/doc/Overview.drawio:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/gui/parser.py:
--------------------------------------------------------------------------------
1 | from PySide6.QtCore import Qt
2 | from PySide6.QtGui import QFont, QColor
3 | from PySide6.QtWidgets import QTextEdit
4 |
5 | from gui.constants import PwndbgGuiConstants
6 |
7 | import logging
8 |
9 | logger = logging.getLogger(__file__)
10 |
11 |
12 | class ContextParser:
13 | """Parses raw output from gdb/pwndbg containing ASCII control characters into equivalent HTML code"""
14 |
15 | def __init__(self):
16 | # Misuse QTextEdit as a HTML parser
17 | self.parser = QTextEdit()
18 |
19 | def reset(self):
20 | """
21 | Reset the internal parser
22 | """
23 | self.parser.clear()
24 | self.reset_font()
25 |
26 | def parse(self, raw_output: bytes, remove_headers=False):
27 | """
28 | Parse program output containing ASCII control characters
29 | :param raw_output: The output as received from e.g. pwndbg
30 | :param remove_headers: Whether to remove the header, e.g. for "context" commands
31 | """
32 | self.reset()
33 | if remove_headers:
34 | lines = raw_output.split(b"\n")
35 | updated_lines = lines[2:][:-2]
36 | raw_output = b"\n".join(updated_lines)
37 |
38 | tokens = raw_output.split(b"\x1b[")
39 | for token in tokens:
40 | self.parse_ascii_control(token)
41 | self.reset_font()
42 |
43 | def to_html(self, raw_output: bytes, remove_headers=False) -> str:
44 | """
45 | Parses output containing ASCII control characters into equivalent HTML code
46 | :param raw_output: The output as received from e.g. pwndbg
47 | :param remove_headers: Whether to remove the header, e.g. for "context" commands
48 | :return:
49 | """
50 | self.parse(raw_output, remove_headers)
51 | return self.parser.toHtml()
52 |
53 | def from_html(self, html: str):
54 | """
55 | Takes HTML and returns the plain text content
56 | :param html: The valid HTML representation of an output
57 | :return:
58 | """
59 | self.reset()
60 | self.parser.setHtml(html)
61 | return self.parser.toPlainText()
62 |
63 | def reset_font(self):
64 | self.parser.setFontWeight(QFont.Weight.Normal)
65 | self.parser.setTextColor(Qt.GlobalColor.white)
66 | self.parser.setFontUnderline(False)
67 | self.parser.setFontItalic(False)
68 |
69 | def parse_ascii_control(self, token: bytes):
70 | """
71 | Parse a single token, if it is an ASCII control character emulate it (e.g. change text color) and
72 | otherwise add any normal plain text to the parser's document
73 | :param token: A single token
74 | """
75 | # Remove weird bytes, e.g. in \x01\x1b[31m\x1b[1m\x02pwndbg> \x01\x1b[0m\x1b[31m\x1b[0m\x02
76 | token = token.replace(b"\x01", b"").replace(b"\x02", b"")
77 | start = token[:3]
78 | # https://stackoverflow.com/a/33206814
79 | # Colors
80 | if start == b"30m":
81 | self.parser.setTextColor(Qt.GlobalColor.black)
82 | self.insert_token(token.replace(start, b"", 1))
83 | elif start == b"31m":
84 | self.parser.setTextColor(PwndbgGuiConstants.RED)
85 | self.insert_token(token.replace(start, b"", 1))
86 | elif start == b"32m":
87 | self.parser.setTextColor(PwndbgGuiConstants.GREEN)
88 | self.insert_token(token.replace(start, b"", 1))
89 | elif start == b"33m":
90 | self.parser.setTextColor(PwndbgGuiConstants.YELLOW)
91 | self.insert_token(token.replace(start, b"", 1))
92 | elif start == b"34m":
93 | self.parser.setTextColor(PwndbgGuiConstants.LIGHT_BLUE)
94 | self.insert_token(token.replace(start, b"", 1))
95 | elif start == b"35m":
96 | self.parser.setTextColor(PwndbgGuiConstants.PURPLE)
97 | self.insert_token(token.replace(start, b"", 1))
98 | elif start == b"36m":
99 | self.parser.setTextColor(PwndbgGuiConstants.CYAN)
100 | self.insert_token(token.replace(start, b"", 1))
101 | elif start == b"37m":
102 | self.parser.setTextColor(Qt.GlobalColor.white)
103 | self.insert_token(token.replace(start, b"", 1))
104 | elif start.startswith(b"38"):
105 | # 256-bit color format: 38;5;m
106 | # RGB format: 38;2;;;m
107 | start = token[:token.index(b"m")]
108 | args = start.split(b";")
109 | if args[1].isdigit() and int(args[1]) == 5:
110 | color = PwndbgGuiConstants.ANSI_COLOR_TO_RGB[int(args[2])]
111 | self.parser.setTextColor(QColor.fromRgb(color[0], color[1], color[2]))
112 | elif args[1].isdigit() and int(args[1]) == 2:
113 | r = int(args[2])
114 | g = int(args[3])
115 | b = int(args[4])
116 | self.parser.setTextColor(QColor.fromRgb(r, g, b, 255))
117 | # Add the "m" into the start for stripping
118 | start = token[:token.index(b"m") + 1]
119 | self.insert_token(token.replace(start, b"", 1))
120 | elif start == b"39m":
121 | self.parser.setTextColor(Qt.GlobalColor.white)
122 | self.insert_token(token.replace(start, b""))
123 | elif start == b"91m":
124 | # Bright red
125 | self.parser.setTextColor(Qt.GlobalColor.red)
126 | self.insert_token(token.replace(start, b""))
127 | # Font
128 | elif start.startswith(b"0m"):
129 | self.reset_font()
130 | self.insert_token(token[2:])
131 | elif start.startswith(b"1m"):
132 | self.parser.setFontWeight(QFont.Weight.Bold)
133 | self.insert_token(token[2:])
134 | elif start.startswith(b"3m"):
135 | self.parser.setFontItalic(not self.parser.fontItalic())
136 | self.insert_token(token[2:])
137 | elif start.startswith(b"4m"):
138 | self.parser.setFontUnderline(not self.parser.fontUnderline())
139 | self.insert_token(token[2:])
140 | else:
141 | self.insert_token(token)
142 |
143 | def insert_token(self, token: bytes):
144 | try:
145 | self.parser.insertPlainText(token.decode())
146 | except UnicodeDecodeError:
147 | self.parser.insertPlainText(repr(token))
148 |
--------------------------------------------------------------------------------
/Proposal/Submission.md:
--------------------------------------------------------------------------------
1 | # Toolsubmission: pwndbg-gui
2 |
3 | We built a GUI wrapper around [pwndbg](https://github.com/pwndbg/pwndbg) intended to leverage the UI benefits of a graphical user interface. It is available via the public [github repository](https://github.com/AlEscher/pwndbg-gui)
4 |
5 |
6 | ## Motivation
7 |
8 | As stated in the proposal we identified multiple ideas to increase usability and approachability of `pwndbg` and `gdb`. As the dominant tools for debugging and pwning, they mostly suffer from the fact that they are bound to the limitations of terminal applications. To address this we wanted to leverage a modern UI framework to wrap the most essential functionality. This allows us to filter out, reorder and customize the gdb output, simplifying or highlighting important information. Our GUI application primarily focuses on usability reducing the number of user commands, displaying information neatly, copying data easily, and providing hotkeys for control-flow.
9 |
10 |
11 | ## Approach
12 |
13 | The GUI is written using the [Qt](https://doc.qt.io/qtforpython-6/) framework for Python. It is an open source framework that allows for easy implementation of custom widgets via inheritance. All our context widgets are tailored for the corresponding `pwndbg` context or custom context.
14 | All displayed information is received from GDB, which is managed as a subprocess in [MI mode](https://ftp.gnu.org/old-gnu/Manuals/gdb/html_chapter/gdb_22.html) and interaction is handled by [pygdbmi](https://pypi.org/project/pygdbmi/). The most important feature of `MI Mode` is the ability to assign tokens to commands. This allows us to filter output and send it to the corresponding widget. The context widgets are updated automatically on user interaction or program advancement.
15 | To make the GUI more fluent and prevent hangups, the application is multithreaded. The threading logic is built on tools from the `Qt` framework which offers a powerful inter-thread communication with [Signal and Slots](https://doc.qt.io/qt-6/signalsandslots.html).
16 | Our Application logic is split into three threads that handle different distinct tasks.
17 | The main thread is the GUI thread, which starts other threads that handle input to GDB (`GdbHandler`), collecting output from GDB (`GdbReader`) and interacting with the inferior process (`InferiorHandler`).
18 |
19 |
20 | ## Features
21 |
22 | - Resizable and collapsible panes
23 | - Allows local executables as well as attaching to a running program (last requires --sudo)
24 | - Buttons to control the inferior control flow
25 | - Search functionality for different data types
26 | - All default `pwndbg` contexts in a separate pane
27 | - Context menus for Stack and Register contexts, that allow easy lookup via the `xinfo` command.
28 | - Heap context
29 | - Continuously show heap-related information such as allocated chunks and freed bins
30 | - Give easy access to `pwndbg's` `try_free` command
31 | - Watch context
32 | - Add multiple addresses to a watch context to continuously monitor the data in a hexdump format
33 | - Individually adjustable watch size
34 | - Keyboard shortcuts
35 | - Shortcuts for GDB commands as well as GUI features
36 | - Shortcuts are either displayed next to the action in a menu (e.g. `Ctrl + N`) or shown by an underlined letter (pressing `Alt + ` will activate the button/menu)
37 | - Input byte literals
38 | - When inputting to the inferior process (denoted by the label next to the main pane's input field) you can supply a Python `bytes` literal
39 | - E.g.: Writing b"Hello\x00World\n" will interpret the input as a `bytes` literal and evaluate it accordingly
40 | - Splitter layout is saved when the application is reopened
41 | - All existing GDB / `pwndbg` commands can still be executed via the Main input widget
42 |
43 | ## Preview
44 |
45 | 
46 |
47 |
48 | ## How to use
49 | The GUI is a wrapper for `GDB`. All functionality is based on its commands or custom commands `pwndbg` adds.
50 |
51 | Since `GDB` is a terminal-based application with tons of use cases we didn't want to limit the user to a subset. Therefore we kept the basic prompt-style interaction as one of the widgets in our application.
52 | The bottom left widget is the so-called "Main" widget which lets the user interact with `GDB` the same way as with the terminal application.
53 | All `GDB` and `pwndbg` commands can be entered here in the bottom left input line.
54 | The corresponding output is shown in the box above.
55 | The "Main" widget also includes buttons for controlling the debugged process, which are essentially wrappers around the usual `n`, `ni`, etc... commands.
56 | Most of them additionally provide keyboard shortcuts via pressing `Alt + ` where `` is the underlined letter in the button.
57 | A search bar wraps the `pwndbg` `search` command that lets the user find data in memory.
58 |
59 | The Disassembly, Code, Registers, Stack, and Backtrace widgets display the corresponding `pwndbg` contexts in scrollable panes.
60 | The lines of the Stack context can be adjusted via the spinbox in its header.
61 | The contexts all update automatically on every stop of the debugged process or user input command.
62 |
63 | The Heap context is a custom-made context that is based on the `heap`, `bins`, and `try_free` commands of `pwndbg`.
64 | It shows the current chunk layout in the main arena and the bins.
65 | In the "Try Free" input the user can give an address to check if a free call on it would succeed or see what checks would fail.
66 |
67 | The Watches context is a custom-made context that is based on the `hexdump` command of `pwndbg`.
68 | It can track addresses and expressions in memory on every context update.
69 | The individual watches can be adjusted in size and collapsed if necessary.
70 | Watch expressions can include some symbols and operations (e.g. `$fs_base+0x30`)
71 |
72 | For the contexts Stack and Registers there is a context menu on right-click that allows for copying of the address or the dereferenced value, as well as a lookup of offset information of both of them via the `xinfo` command.
73 |
74 | Some Nice-to-Knows:
75 | - Most buttons and input fields have a tooltip.
76 | - Keyboard hotkeys are indicated in tooltips or via an underlined letter on the action/button.
77 | - The About -> pwndbg option in the Navbar gives an overview of all pwndbg commands.
78 | - Popup windows are non-blocking and can be moved to a second monitor.
79 |
80 | ## Future (planned) Features
81 | - Easier inputting of payloads (e.g. via gui filesystem)
82 | - Setting breakpoints in source or disassembly via GUI
83 | - Customize contexts arrangement
84 | - Pop-out contexts into separate windows
85 | - Rearrange and move contexts around in the GUI
86 | - Editing of memory (e.g. registers, stack, heap) via UI (e.g. double-click on stack line)
87 | - Extra window for one-time commands like `elf`, `checksec`, and `vmmap`
88 |
89 |
90 | ## Known Limitations
91 | There are some limitations in the current state of the application that the user must be aware of.
92 | - User can not start/attach process via the `GDB` terminal commands (`file` and `attach`), but only via the GUI buttons.
93 | - This is because GDB MI does not inform us properly of such events, so we need to keep track of this information ourselves
94 | - The stack lines box does not update on startup
95 | - This was initially implemented, however resulted in some edge cases where Qt signals would enter an infinite recursive loop :|
96 | - Some specific `Pwndbg's` next instructions (e.g. nextret, nextcall, ...) output the entire pwndbg context twice without indication of the source command which will send it to our regs context
97 | - Nothing we can do here ¯\\\_(ツ)\_/¯
98 | - When attaching the source code dir must be specified manually when the executable runs in a docker
99 | - We could add a button for this in the future
100 | - Loading .gdbinit was only tested with loading `pwndbg` and setting some basic variables. No guarantee for any compatibility with other gdb plugins or custom scripts.
101 | - We could detect when `pwndbg` is successfully loaded and if not load our own basic .gdbinit
102 |
103 |
--------------------------------------------------------------------------------
/gui/gdb_handler.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from pathlib import Path
3 | from typing import List, Dict
4 |
5 | from PySide6.QtCore import QObject, Slot, Signal
6 | from pygdbmi import gdbcontroller
7 |
8 | from gui.constants import PwndbgGuiConstants
9 | from gui.inferior_handler import InferiorHandler
10 | from gui.inferior_state import InferiorState
11 | from gui.tokens import ResponseToken, Context_to_Token
12 |
13 | logger = logging.getLogger(__file__)
14 |
15 |
16 | class GdbHandler(QObject):
17 | """A wrapper to interact with GDB/pwndbg via the GDB Machine Interface"""
18 | update_gui = Signal(str, bytes)
19 |
20 | def __init__(self):
21 | super().__init__()
22 | self.contexts = ['regs', 'stack', 'disasm', 'code', 'backtrace']
23 | self.controller = gdbcontroller.GdbController()
24 | # active watches in the form of {address: [idx , number of lines]}
25 | self.watches: Dict[str, List[int]] = {}
26 |
27 | def write_to_controller(self, token: ResponseToken, command: str):
28 | """
29 | Wrapper for writing a command to GDB MI with the specified token
30 | :param token: The token to prepend to the command
31 | :param command: The command (normal GDB or GDB MI)
32 | """
33 | self.controller.write(str(token) + command, read_response=False)
34 |
35 | def init(self):
36 | """Load the user's .gdbinit, check that pwndbg is loaded"""
37 | # With GDB MI, the .gdbinit file is ignored so we load it ourselves
38 | gdbinit = Path(Path.home() / ".gdbinit").resolve()
39 | if not gdbinit.exists():
40 | logger.warning("Could not find .gdbinit file at %s", str(gdbinit))
41 | return
42 | logger.debug("Loading .gdbinit from %s", str(gdbinit))
43 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, f"source {str(gdbinit)}")
44 | self.write_to_controller(ResponseToken.GUI_PWNDBG_ABOUT, "pwndbg --all")
45 |
46 | @Slot(str)
47 | def send_command(self, cmd: str):
48 | """
49 | Execute the given command as if it came from the user and then update all context panes
50 | :param cmd: The command the user gave
51 | """
52 | try:
53 | self.write_to_controller(ResponseToken.USER_MAIN, cmd)
54 | self.update_contexts()
55 | except Exception as e:
56 | logger.warning("Error while sending command '%s': '%s'", cmd, str(e))
57 |
58 | @Slot(bool)
59 | def update_contexts(self, flush_to_main=False):
60 | """
61 | Send commands to query updates for all context information.
62 | :param flush_to_main: If True, flush all currently buffered GDB output to the main context widget
63 | """
64 | if flush_to_main:
65 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, "")
66 | for context in self.contexts:
67 | self.write_to_controller(Context_to_Token[context], f"context {context}")
68 | # Update heap
69 | self.write_to_controller(ResponseToken.GUI_HEAP_HEAP, "heap")
70 | self.write_to_controller(ResponseToken.GUI_HEAP_BINS, "bins")
71 | self.write_to_controller(ResponseToken.GUI_REGS_FS_BASE, "fsbase")
72 | # Update watches
73 | logger.debug("updating watches: ")
74 | for watch, params in self.watches.items():
75 | logger.debug("updating watch: %s", watch)
76 | self.write_to_controller(ResponseToken.GUI_WATCHES_HEXDUMP + params[0],
77 | " ".join(["hexdump", watch, str(params[1])]))
78 |
79 | @Slot(list)
80 | def execute_cmd(self, arguments: List[str]):
81 | """
82 | Execute the given command in gdb as if it came from us and not the user.
83 | The output of the command will be forwarded to the main context output
84 | :param arguments: The parts of the command
85 | """
86 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, " ".join(arguments))
87 |
88 | @Slot(list)
89 | def set_file_target(self, arguments: List[str]):
90 | """
91 | Load the executable specified by a file path using the "file" command
92 | :param arguments: The arguments to add after "file"
93 | """
94 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, " ".join(["file"] + arguments))
95 | InferiorHandler.INFERIOR_STATE = InferiorState.QUEUED
96 |
97 | @Slot(list)
98 | def set_pid_target(self, arguments: List[str]):
99 | """
100 | Attach to the given PID argument using the "attach" command
101 | :param arguments: The arguments to add after "attach"
102 | """
103 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, " ".join(["attach"] + arguments))
104 | # Attaching to a running process stops it
105 | InferiorHandler.INFERIOR_STATE = InferiorState.STOPPED
106 |
107 | @Slot(list)
108 | def set_source_dir(self, arguments: List[str]):
109 | """
110 | Add a directory where GDB should look for source files using the "dir" command
111 | :param arguments: The arguments to add after "dir"
112 | """
113 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, " ".join(["dir"] + arguments))
114 |
115 | @Slot(list)
116 | def change_setting(self, arguments: List[str]):
117 | """
118 | Change a setting using "set". The resulting output will be discarded.
119 | :param arguments: The setting to change and e.g. the value
120 | """
121 | logging.debug("Changing gdb setting with parameters: %s", arguments)
122 | self.write_to_controller(ResponseToken.DELETE, " ".join(["set"] + arguments))
123 |
124 | @Slot(int)
125 | def update_stack_lines(self, new_value: int):
126 | """
127 | Set pwndbg's context-stack-lines to a new value
128 | :param new_value: The new stack-lines value
129 | """
130 | self.change_setting(["context-stack-lines", str(new_value)])
131 | self.write_to_controller(ResponseToken.GUI_STACK_CONTEXT, "context stack")
132 |
133 | @Slot(str)
134 | def execute_try_free(self, param: str):
135 | """Execute the "try_free" command with the given address"""
136 | self.write_to_controller(ResponseToken.GUI_HEAP_TRY_FREE, " ".join(["try_free", param]))
137 |
138 | @Slot(str, int)
139 | def add_watch(self, param: str, idx: int):
140 | self.watches[param] = [idx, PwndbgGuiConstants.DEFAULT_WATCH_BYTES]
141 | logger.debug("Added to watchlist: %s with index %d", param, idx)
142 | self.write_to_controller(ResponseToken.GUI_WATCHES_HEXDUMP + idx,
143 | " ".join(["hexdump", param, str(PwndbgGuiConstants.DEFAULT_WATCH_BYTES)]))
144 |
145 | @Slot(str)
146 | def del_watch(self, param: str):
147 | logger.debug("Deleted watch %s with index %d", param, self.watches[param][0])
148 | del self.watches[param]
149 |
150 | @Slot(str, int)
151 | def change_watch_lines(self, param: str, lines: int):
152 | self.watches[param][1] = lines
153 | logger.debug("Adapted line count for watch %s to %d", param, lines)
154 | self.write_to_controller(ResponseToken.GUI_WATCHES_HEXDUMP + self.watches[param][0],
155 | " ".join(["hexdump", param, str(lines)]))
156 |
157 | @Slot(bytes)
158 | def execute_xinfo(self, address: str):
159 | """
160 | Execute the "xinfo" command with the given address
161 | :param address: The parameter for xinfo
162 | """
163 | self.write_to_controller(ResponseToken.GUI_XINFO, " ".join(["xinfo", address]))
164 |
165 | @Slot(str)
166 | def set_tty(self, tty: str):
167 | """
168 | Execute the "tty" command with the given tty path. GDB will route future inferiors' I/O via this tty
169 | :param tty: The tty slave
170 | """
171 | self.write_to_controller(ResponseToken.DELETE, " ".join(["tty", tty]))
172 |
173 | @Slot(bytes)
174 | def send_inferior_input(self, user_input: bytes):
175 | """
176 | Send input for the inferior via GDB (e.g. if we attached to the inferior) without any tokens
177 | :param user_input: The user input
178 | """
179 | self.controller.write(user_input.decode(), read_response=False)
180 |
181 | @Slot(list)
182 | def execute_search(self, search_params: List[str]):
183 | """
184 | Execute the "search" command for a given parameter
185 | :param search_params: A list of the search parameters
186 | """
187 | self.write_to_controller(ResponseToken.GUI_MAIN_CONTEXT, " ".join(["search"] + search_params))
188 |
--------------------------------------------------------------------------------
/gui/custom_widgets/context_list_widget.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import re
3 | from typing import TYPE_CHECKING
4 |
5 | from PySide6.QtCore import Qt, Signal, Slot, QKeyCombination
6 | from PySide6.QtGui import QIcon, QKeySequence, QKeyEvent
7 | from PySide6.QtWidgets import QListWidget, QListWidgetItem, QApplication, QMenu, QSplitter, QGroupBox, QVBoxLayout
8 |
9 | from gui.context_data_role import ContextDataRole
10 | from gui.parser import ContextParser
11 |
12 | # Prevent circular import error
13 | if TYPE_CHECKING:
14 | from gui.pwndbg_gui import PwnDbgGui
15 |
16 | logger = logging.getLogger(__file__)
17 |
18 |
19 | class ContextListWidget(QListWidget):
20 | execute_xinfo = Signal(str)
21 | value_xinfo = Signal(str)
22 |
23 | def __init__(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
24 | super().__init__(parent)
25 | self.parser = ContextParser()
26 | self.setup_widget_layout(parent, title, splitter, index)
27 | self.setResizeMode(QListWidget.ResizeMode.Adjust)
28 | self.context_menu = QMenu(self)
29 | self.context_shortcuts = {"copy_address": QKeyCombination(Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier | Qt.Key.Key_C),
30 | "copy_value": QKeyCombination(Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier | Qt.Key.Key_V),
31 | "xinfo_address": QKeyCombination(Qt.KeyboardModifier.ControlModifier | Qt.Key.Key_X),
32 | "xinfo_value": QKeyCombination(Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier | Qt.Key.Key_X)}
33 | self.setup_context_menu()
34 |
35 | def setup_widget_layout(self, parent: 'PwnDbgGui', title: str, splitter: QSplitter, index: int):
36 | # GroupBox needs to have parent before being added to splitter (see SO below)
37 | context_box = QGroupBox(title, parent)
38 | context_box.setAlignment(Qt.AlignmentFlag.AlignCenter)
39 | context_box.setFlat(True)
40 | context_layout = QVBoxLayout()
41 | context_layout.addWidget(self)
42 | context_box.setLayout(context_layout)
43 | splitter.replaceWidget(index, context_box)
44 | # https://stackoverflow.com/a/66067630
45 | context_box.show()
46 |
47 | def setup_context_menu(self):
48 | # Copy the address data, for a stack this is the stack address, for a register this is the register's content
49 | copy_addr_action = self.context_menu.addAction("Copy Address")
50 | copy_addr_action.setIcon(QIcon.fromTheme("edit-copy"))
51 | # Shortcuts don't work for some reason, we still set them to get the text in the context menu
52 | copy_addr_action.setShortcut(self.context_shortcuts["copy_address"])
53 | copy_addr_action.triggered.connect(self.copy_address)
54 | # Copy the value data, for a stack this is the value that the stack address points to,
55 | # for a register this is the value that the address points to if one exists
56 | copy_val_action = self.context_menu.addAction("Copy Value")
57 | copy_val_action.setIcon(QIcon.fromTheme("edit-copy"))
58 | copy_val_action.setShortcut(self.context_shortcuts["copy_value"])
59 | copy_val_action.triggered.connect(self.copy_value)
60 | # Show a dialog with offset information about the address entry
61 | offset_address_action = self.context_menu.addAction("Show Address Offsets")
62 | offset_address_action.setIcon(QIcon.fromTheme("system-search"))
63 | offset_address_action.setShortcut(self.context_shortcuts["xinfo_address"])
64 | offset_address_action.triggered.connect(self.xinfo_address)
65 | # Show a dialog with offset information about the value entry
66 | offset_value_action = self.context_menu.addAction("Show Value Offsets")
67 | offset_value_action.setIcon(QIcon.fromTheme("system-search"))
68 | offset_value_action.setShortcut(self.context_shortcuts["xinfo_value"])
69 | offset_value_action.triggered.connect(self.xinfo_value)
70 |
71 | def add_content(self, content: str):
72 | self.clear()
73 | lines = content.splitlines()
74 | # Remove unneeded lines containing only HTML, as "content" will be a full HTML document returned by the parser
75 | body_start = lines.index(next(line for line in lines if " tag
78 | cleaned = self.delete_first_html_tag(self.delete_last_html_tag(line))
79 | item = QListWidgetItem(self)
80 | item.setData(Qt.ItemDataRole.DisplayRole, cleaned)
81 | plain_text = self.parser.from_html(line)
82 | address, value = self.find_hex_values(plain_text)
83 | item.setData(ContextDataRole.ADDRESS, address)
84 | item.setData(ContextDataRole.VALUE, value)
85 |
86 | def keyPressEvent(self, event: QKeyEvent):
87 | """Event handler for any key presses on this widget"""
88 | if event.matches(QKeySequence.StandardKey.Copy):
89 | # When the user presses Ctrl+C, we copy the selected stack line into his clipboard
90 | selected_items = self.selectedItems()
91 | if selected_items:
92 | item = selected_items[0]
93 | data = self.parser.from_html(item.text())
94 | if data:
95 | QApplication.clipboard().setText(data)
96 | return
97 | # We have to do this garbage here manually because Qt Shortcuts don't work for the context menu actions
98 | elif event.keyCombination().toCombined() == self.context_shortcuts["copy_address"].toCombined():
99 | self.copy_address()
100 | return
101 | elif event.keyCombination().toCombined() == self.context_shortcuts["copy_value"].toCombined():
102 | self.copy_value()
103 | return
104 | elif event.keyCombination().toCombined() == self.context_shortcuts["xinfo_address"].toCombined():
105 | self.xinfo_address()
106 | return
107 | elif event.keyCombination().toCombined() == self.context_shortcuts["xinfo_value"].toCombined():
108 | self.xinfo_value()
109 | return
110 |
111 | super().keyPressEvent(event)
112 |
113 | @Slot()
114 | def copy_value(self):
115 | """Callback for the "Copy Value" action"""
116 | if len(self.selectedItems()) == 0:
117 | return
118 | self.set_data_to_clipboard(self.selectedItems()[0], ContextDataRole.VALUE)
119 |
120 | @Slot()
121 | def copy_address(self):
122 | """Callback for the "Copy Address" action"""
123 | if len(self.selectedItems()) == 0:
124 | return
125 | self.set_data_to_clipboard(self.selectedItems()[0], ContextDataRole.ADDRESS)
126 |
127 | @Slot()
128 | def xinfo_address(self):
129 | """Callback for the "Offset Address" action"""
130 | if len(self.selectedItems()) == 0:
131 | return
132 | self.execute_xinfo.emit(str(self.selectedItems()[0].data(ContextDataRole.ADDRESS)))
133 |
134 | @Slot()
135 | def xinfo_value(self):
136 | """Callback for the "Offset Value" action"""
137 | if len(self.selectedItems()) == 0:
138 | return
139 | self.execute_xinfo.emit(str(self.selectedItems()[0].data(ContextDataRole.VALUE)))
140 |
141 | def contextMenuEvent(self, event):
142 | """Called by Qt when the user opens the context menu (right click) on this widget"""
143 | selected_items = self.selectedItems()
144 | if selected_items is None or len(selected_items) == 0:
145 | super().contextMenuEvent(event)
146 | return
147 | self.context_menu.exec(event.globalPos())
148 |
149 | def delete_first_html_tag(self, string: str):
150 | pattern = r"<[^>]+>" # Regular expression pattern to match HTML tags
151 | return re.sub(pattern, "", string, count=1)
152 |
153 | def delete_last_html_tag(self, string: str):
154 | # Find the last closing HTML tag
155 | pattern = r'[^>]+>$'
156 | match = re.search(pattern, string)
157 |
158 | if match:
159 | last_tag = match.group()
160 | # Remove the last closing HTML tag
161 | modified_string = string.replace(last_tag, '')
162 | return modified_string
163 | else:
164 | return string # No closing HTML tag found
165 |
166 | def find_hex_values(self, line: str):
167 | pattern = re.compile(r"0x[0-9a-fA-F]+", re.UNICODE)
168 | # Filter out empty matches
169 | hex_values = [match for match in pattern.findall(line) if match]
170 | first_value = ""
171 | second_value = ""
172 | if len(hex_values) > 0:
173 | first_value = hex_values[0]
174 | if len(hex_values) > 1:
175 | second_value = hex_values[1]
176 | return first_value, second_value
177 |
178 | def set_data_to_clipboard(self, item: QListWidgetItem, role: ContextDataRole):
179 | data = item.data(role)
180 | if data is not None:
181 | QApplication.clipboard().setText(data)
182 |
183 | def resizeEvent(self, resizeEvent):
184 | """Called by Qt when the Widget is resized by the user"""
185 | self.reset()
186 | super().resizeEvent(resizeEvent)
187 |
--------------------------------------------------------------------------------
/gui/constants.py:
--------------------------------------------------------------------------------
1 | class PwndbgGuiConstants:
2 | DEFAULT_WATCH_BYTES = 64
3 | FONT = "Noto Sans Mono"
4 | BLACK = "#282C34"
5 | RED = "#ED254E"
6 | GREEN = "#71F79F"
7 | YELLOW = "#F9DC5C"
8 | LIGHT_BLUE = "#7CB7FF"
9 | PURPLE = "#C74DED"
10 | CYAN = "#00C1E4"
11 | LIGHT_GRAY = "#DCDFE4"
12 | SETTINGS_FOLDER = "pwndbg-gui"
13 | SETTINGS_FILE = "pwndbg-gui"
14 | # The top level of the settings hierarchy
15 | SETTINGS_TOP_LEVEL = "MainWindow"
16 | SPLITTER_GEOMETRIES = "/".join([SETTINGS_TOP_LEVEL, "Splitters/Geometry"])
17 | SPLITTER_STATES = "/".join([SETTINGS_TOP_LEVEL, "Splitters/State"])
18 | SETTINGS_WINDOW_STATE = "/".join([SETTINGS_TOP_LEVEL, "State"])
19 | SETTINGS_WINDOW_GEOMETRY = "/".join([SETTINGS_TOP_LEVEL, "Geometry"])
20 | # Written by ChatGPT lol
21 | ABOUT_TEXT = """About pwndbg-gui
22 |
23 | Welcome to pwndbg-gui, a graphical user interface (GUI) application designed to enhance your experience with
24 | pwndbg, a powerful command-line tool for exploit development and binary analysis.
25 |
26 | Key Features:
27 |
28 | - Intuitive and user-friendly interface
29 | - Enhanced debugging experience
30 | - Seamless integration with pwndbg
31 |
32 |
33 | For more information, see the Github repo.
34 |
35 | Feedback and Contributions:
You can report issues or contribute to the project.
"""
38 | # Thank you, ChatGPT
39 | ANSI_COLOR_TO_RGB = {
40 | 0: (0, 0, 0),
41 | 1: (128, 0, 0),
42 | 2: (0, 128, 0),
43 | 3: (128, 128, 0),
44 | 4: (0, 0, 128),
45 | 5: (128, 0, 128),
46 | 6: (0, 128, 128),
47 | 7: (192, 192, 192),
48 | 8: (128, 128, 128),
49 | 9: (255, 0, 0),
50 | 10: (0, 255, 0),
51 | 11: (255, 255, 0),
52 | 12: (0, 0, 255),
53 | 13: (255, 0, 255),
54 | 14: (0, 255, 255),
55 | 15: (255, 255, 255),
56 | 16: (0, 0, 0),
57 | 17: (0, 0, 95),
58 | 18: (0, 0, 135),
59 | 19: (0, 0, 175),
60 | 20: (0, 0, 215),
61 | 21: (0, 0, 255),
62 | 22: (0, 95, 0),
63 | 23: (0, 95, 95),
64 | 24: (0, 95, 135),
65 | 25: (0, 95, 175),
66 | 26: (0, 95, 215),
67 | 27: (0, 95, 255),
68 | 28: (0, 135, 0),
69 | 29: (0, 135, 95),
70 | 30: (0, 135, 135),
71 | 31: (0, 135, 175),
72 | 32: (0, 135, 215),
73 | 33: (0, 135, 255),
74 | 34: (0, 175, 0),
75 | 35: (0, 175, 95),
76 | 36: (0, 175, 135),
77 | 37: (0, 175, 175),
78 | 38: (0, 175, 215),
79 | 39: (0, 175, 255),
80 | 40: (0, 215, 0),
81 | 41: (0, 215, 95),
82 | 42: (0, 215, 135),
83 | 43: (0, 215, 175),
84 | 44: (0, 215, 215),
85 | 45: (0, 215, 255),
86 | 46: (0, 255, 0),
87 | 47: (0, 255, 95),
88 | 48: (0, 255, 135),
89 | 49: (0, 255, 175),
90 | 50: (0, 255, 215),
91 | 51: (0, 255, 255),
92 | 52: (95, 0, 0),
93 | 53: (95, 0, 95),
94 | 54: (95, 0, 135),
95 | 55: (95, 0, 175),
96 | 56: (95, 0, 215),
97 | 57: (95, 0, 255),
98 | 58: (95, 95, 0),
99 | 59: (95, 95, 95),
100 | 60: (95, 95, 135),
101 | 61: (95, 95, 175),
102 | 62: (95, 95, 215),
103 | 63: (95, 95, 255),
104 | 64: (95, 135, 0),
105 | 65: (95, 135, 95),
106 | 66: (95, 135, 135),
107 | 67: (95, 135, 175),
108 | 68: (95, 135, 215),
109 | 69: (95, 135, 255),
110 | 70: (95, 175, 0),
111 | 71: (95, 175, 95),
112 | 72: (95, 175, 135),
113 | 73: (95, 175, 175),
114 | 74: (95, 175, 215),
115 | 75: (95, 175, 255),
116 | 76: (95, 215, 0),
117 | 77: (95, 215, 95),
118 | 78: (95, 215, 135),
119 | 79: (95, 215, 175),
120 | 80: (95, 215, 215),
121 | 81: (95, 215, 255),
122 | 82: (95, 255, 0),
123 | 83: (95, 255, 95),
124 | 84: (95, 255, 135),
125 | 85: (95, 255, 175),
126 | 86: (95, 255, 215),
127 | 87: (95, 255, 255),
128 | 88: (135, 0, 0),
129 | 89: (135, 0, 95),
130 | 90: (135, 0, 135),
131 | 91: (135, 0, 175),
132 | 92: (135, 0, 215),
133 | 93: (135, 0, 255),
134 | 94: (135, 95, 0),
135 | 95: (135, 95, 95),
136 | 96: (135, 95, 135),
137 | 97: (135, 95, 175),
138 | 98: (135, 95, 215),
139 | 99: (135, 95, 255),
140 | 100: (135, 135, 0),
141 | 101: (135, 135, 95),
142 | 102: (135, 135, 135),
143 | 103: (135, 135, 175),
144 | 104: (135, 135, 215),
145 | 105: (135, 135, 255),
146 | 106: (135, 175, 0),
147 | 107: (135, 175, 95),
148 | 108: (135, 175, 135),
149 | 109: (135, 175, 175),
150 | 110: (135, 175, 215),
151 | 111: (135, 175, 255),
152 | 112: (135, 215, 0),
153 | 113: (135, 215, 95),
154 | 114: (135, 215, 135),
155 | 115: (135, 215, 175),
156 | 116: (135, 215, 215),
157 | 117: (135, 215, 255),
158 | 118: (135, 255, 0),
159 | 119: (135, 255, 95),
160 | 120: (135, 255, 135),
161 | 121: (135, 255, 175),
162 | 122: (135, 255, 215),
163 | 123: (135, 255, 255),
164 | 124: (175, 0, 0),
165 | 125: (175, 0, 95),
166 | 126: (175, 0, 135),
167 | 127: (175, 0, 175),
168 | 128: (175, 0, 215),
169 | 129: (175, 0, 255),
170 | 130: (175, 95, 0),
171 | 131: (175, 95, 95),
172 | 132: (175, 95, 135),
173 | 133: (175, 95, 175),
174 | 134: (175, 95, 215),
175 | 135: (175, 95, 255),
176 | 136: (175, 135, 0),
177 | 137: (175, 135, 95),
178 | 138: (175, 135, 135),
179 | 139: (175, 135, 175),
180 | 140: (175, 135, 215),
181 | 141: (175, 135, 255),
182 | 142: (175, 175, 0),
183 | 143: (175, 175, 95),
184 | 144: (175, 175, 135),
185 | 145: (175, 175, 175),
186 | 146: (175, 175, 215),
187 | 147: (175, 175, 255),
188 | 148: (175, 215, 0),
189 | 149: (175, 215, 95),
190 | 150: (175, 215, 135),
191 | 151: (175, 215, 175),
192 | 152: (175, 215, 215),
193 | 153: (175, 215, 255),
194 | 154: (175, 255, 0),
195 | 155: (175, 255, 95),
196 | 156: (175, 255, 135),
197 | 157: (175, 255, 175),
198 | 158: (175, 255, 215),
199 | 159: (175, 255, 255),
200 | 160: (215, 0, 0),
201 | 161: (215, 0, 95),
202 | 162: (215, 0, 135),
203 | 163: (215, 0, 175),
204 | 164: (215, 0, 215),
205 | 165: (215, 0, 255),
206 | 166: (215, 95, 0),
207 | 167: (215, 95, 95),
208 | 168: (215, 95, 135),
209 | 169: (215, 95, 175),
210 | 170: (215, 95, 215),
211 | 171: (215, 95, 255),
212 | 172: (215, 135, 0),
213 | 173: (215, 135, 95),
214 | 174: (215, 135, 135),
215 | 175: (215, 135, 175),
216 | 176: (215, 135, 215),
217 | 177: (215, 135, 255),
218 | 178: (215, 175, 0),
219 | 179: (215, 175, 95),
220 | 180: (215, 175, 135),
221 | 181: (215, 175, 175),
222 | 182: (215, 175, 215),
223 | 183: (215, 175, 255),
224 | 184: (215, 215, 0),
225 | 185: (215, 215, 95),
226 | 186: (215, 215, 135),
227 | 187: (215, 215, 175),
228 | 188: (215, 215, 215),
229 | 189: (215, 215, 255),
230 | 190: (215, 255, 0),
231 | 191: (215, 255, 95),
232 | 192: (215, 255, 135),
233 | 193: (215, 255, 175),
234 | 194: (215, 255, 215),
235 | 195: (215, 255, 255),
236 | 196: (255, 0, 0),
237 | 197: (255, 0, 95),
238 | 198: (255, 0, 135),
239 | 199: (255, 0, 175),
240 | 200: (255, 0, 215),
241 | 201: (255, 0, 255),
242 | 202: (255, 95, 0),
243 | 203: (255, 95, 95),
244 | 204: (255, 95, 135),
245 | 205: (255, 95, 175),
246 | 206: (255, 95, 215),
247 | 207: (255, 95, 255),
248 | 208: (255, 135, 0),
249 | 209: (255, 135, 95),
250 | 210: (255, 135, 135),
251 | 211: (255, 135, 175),
252 | 212: (255, 135, 215),
253 | 213: (255, 135, 255),
254 | 214: (255, 175, 0),
255 | 215: (255, 175, 95),
256 | 216: (255, 175, 135),
257 | 217: (255, 175, 175),
258 | 218: (255, 175, 215),
259 | 219: (255, 175, 255),
260 | 220: (255, 215, 0),
261 | 221: (255, 215, 95),
262 | 222: (255, 215, 135),
263 | 223: (255, 215, 175),
264 | 224: (255, 215, 215),
265 | 225: (255, 215, 255),
266 | 226: (255, 255, 0),
267 | 227: (255, 255, 95),
268 | 228: (255, 255, 135),
269 | 229: (255, 255, 175),
270 | 230: (255, 255, 215),
271 | 231: (255, 255, 255),
272 | 232: (8, 8, 8),
273 | 233: (18, 18, 18),
274 | 234: (28, 28, 28),
275 | 235: (38, 38, 38),
276 | 236: (48, 48, 48),
277 | 237: (58, 58, 58),
278 | 238: (68, 68, 68),
279 | 239: (78, 78, 78),
280 | 240: (88, 88, 88),
281 | 241: (98, 98, 98),
282 | 242: (108, 108, 108),
283 | 243: (118, 118, 118),
284 | 244: (128, 128, 128),
285 | 245: (138, 138, 138),
286 | 246: (148, 148, 148),
287 | 247: (158, 158, 158),
288 | 248: (168, 168, 168),
289 | 249: (178, 178, 178),
290 | 250: (188, 188, 188),
291 | 251: (198, 198, 198),
292 | 252: (208, 208, 208),
293 | 253: (218, 218, 218),
294 | 254: (228, 228, 228),
295 | 255: (238, 238, 238)
296 | }
297 |
298 |
299 |
--------------------------------------------------------------------------------
/gui/gdb_reader.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import List
3 |
4 | from PySide6.QtCore import QObject, Slot, Signal, QCoreApplication
5 | from pygdbmi import gdbcontroller
6 |
7 | import gui.tokens as tokens
8 | from gui.inferior_handler import InferiorHandler
9 | from gui.inferior_state import InferiorState
10 |
11 | logger = logging.getLogger(__file__)
12 |
13 |
14 | class GdbReader(QObject):
15 | """Reader object to continuously check for data from gdb and handle the parsed responses"""
16 | # Update a context pane in the GUI with data
17 | update_gui = Signal(str, bytes)
18 | # Send the result of a try_free command to the Heap widget
19 | send_heap_try_free_response = Signal(bytes)
20 | # Send the result of a heap command to the Heap widget
21 | send_heap_heap_response = Signal(bytes)
22 | # Send the result of a bins command to the Heap widget
23 | send_heap_bins_response = Signal(bytes)
24 | # Send the result of the hexdump output of a watch to the Watches widget
25 | send_watches_hexdump_response = Signal(int, bytes)
26 | # Send the fs base to the "regs" context
27 | send_fs_base_response = Signal(bytes)
28 | # Send the overview of all pwndbg commands to the GUI
29 | send_pwndbg_about = Signal(bytes)
30 | # Send the result of an xinfo command to a list widget
31 | send_xinfo = Signal(bytes)
32 | # Emitted when the inferior state changes. True for Stopped and False for Running
33 | inferior_state_changed = Signal(bool)
34 |
35 | def __init__(self, controller: gdbcontroller.GdbController):
36 | super().__init__()
37 | self.controller = controller
38 | self.result = []
39 | # Whether the thread should keep working
40 | self.run = True
41 | # Some import information like error output of pwndbg commands or even GDB's own commands is only outputted
42 | # as "log" elements. However, since also all inputted commands are echoed back as logs, we capture logs
43 | # separately and decide on a "result" element whether we want to forward the logs or not
44 | self.logs: List[str] = []
45 |
46 | @Slot()
47 | def read_with_timeout(self):
48 | """Start continuously reading output from GDB MI"""
49 | while self.run:
50 | QCoreApplication.processEvents()
51 | response = self.controller.get_gdb_response(raise_error_on_timeout=False)
52 | if response is not None:
53 | self.parse_response(response)
54 |
55 | @Slot()
56 | def set_run(self, state: bool):
57 | """
58 | Sets whether the thread should keep working
59 | :param state: True if the thread should keep working
60 | """
61 | self.run = state
62 |
63 | def send_update_gui(self, token: int):
64 | """
65 | Flushes all collected outputs to the destination specified by token
66 | :param token: Token of the context pane
67 | """
68 | if len(self.result) and len(self.logs) == 0:
69 | return
70 | context = tokens.Token_to_Context[token]
71 | # If we want to send an update but have no results and only logs, it means something went wrong,
72 | # and we want to forward the output to the user. If we do have results, prioritize them over the logs
73 | if len(self.result) > 0:
74 | content = "".join(self.result).encode()
75 | else:
76 | # We skip the first log as it is (always?) just the inputted command echoed back
77 | content = "".join(self.logs[1:]).encode()
78 | # When the program is not stopped we cannot send commands to gdb, so any context output produced that was not
79 | # destined to main should not be shown
80 | if context == tokens.Token_to_Context[tokens.ResponseToken.GUI_MAIN_CONTEXT.value]:
81 | self.update_gui.emit(context, content)
82 | elif InferiorHandler.INFERIOR_STATE == InferiorState.STOPPED:
83 | self.update_gui.emit(context, content)
84 | self.result = []
85 |
86 | def send_main_update(self):
87 | """Flushes all collected outputs to the main output window"""
88 | self.update_gui.emit("main", "".join(self.result).encode())
89 | self.result = []
90 |
91 | def send_context_update(self, signal: Signal, send_on_stop=True):
92 | """
93 | Emit a supplied signal with the collected output
94 | :param signal: The signal that will handle the data
95 | :param send_on_stop: Whether to send data only when the inferior is stopped
96 | """
97 | if not send_on_stop:
98 | # Send this signal even if the inferior is not started yet or running
99 | signal.emit("".join(self.result).encode())
100 | elif InferiorHandler.INFERIOR_STATE == InferiorState.STOPPED:
101 | signal.emit("".join(self.result).encode())
102 | self.result = []
103 |
104 | def parse_response(self, gdbmi_response: list[dict]):
105 | """
106 | Parse a response received from GDB MI and decide how to handle it
107 | :param gdbmi_response: The parsed response from pygdbmi
108 | """
109 | for response in gdbmi_response:
110 | if response["type"] == "console" and response["payload"] is not None and response["stream"] == "stdout":
111 | self.result.append(response["payload"])
112 | # When a subprocess is spawned, we get no proper notify/result event from GDB, so we check manually
113 | if response["payload"].startswith("[Detaching"):
114 | self.send_main_update()
115 | elif response["type"] == "output":
116 | # We always append "output": If the process is started by GDB, our inferior handler will capture all
117 | # inferior output in his tty, so this code will never be triggered. If the user attaches to a
118 | # process, the TTY approach does not work, so we will collect the output here instead. The output is
119 | # sometimes broken, i.e. it contains data that was printed by pwndbg/gdb, however this is a
120 | # limitation with GDB/Pygdbmi which we cannot fix
121 | self.result.append(response["payload"])
122 | elif response["type"] == "result":
123 | self.handle_result(response)
124 | elif response["type"] == "notify":
125 | self.handle_notify(response)
126 | elif response["type"] == "log":
127 | self.logs.append(response["payload"])
128 |
129 | def handle_result(self, response: dict):
130 | """
131 | Handle messages of the result type, which are emitted after a command/action has finished producing output
132 | :param response: GDB-MI response with ["type"] == result
133 | """
134 | if response["token"] is None:
135 | self.result = []
136 | return
137 | if response["message"] == "error" and response["payload"] is not None:
138 | self.result.append(response["payload"]["msg"])
139 | token = response["token"]
140 | if token == tokens.ResponseToken.GUI_HEAP_TRY_FREE:
141 | self.send_context_update(self.send_heap_try_free_response)
142 | elif token == tokens.ResponseToken.GUI_HEAP_HEAP:
143 | self.send_context_update(self.send_heap_heap_response)
144 | elif token == tokens.ResponseToken.GUI_HEAP_BINS:
145 | self.send_context_update(self.send_heap_bins_response)
146 | elif token == tokens.ResponseToken.GUI_REGS_FS_BASE:
147 | self.send_context_update(self.send_fs_base_response)
148 | elif token == tokens.ResponseToken.GUI_PWNDBG_ABOUT:
149 | self.send_context_update(self.send_pwndbg_about, send_on_stop=False)
150 | elif token == tokens.ResponseToken.GUI_XINFO:
151 | self.send_context_update(self.send_xinfo)
152 | elif token >= tokens.ResponseToken.GUI_WATCHES_HEXDUMP:
153 | if InferiorHandler.INFERIOR_STATE == InferiorState.STOPPED:
154 | ''' Here we send the result of the hexdump, the signal differs from the rest here since we need to send
155 | the token as well so that the watch-widget knows to which watch the result belongs. If we have logs then
156 | something was wrong with the hexdump command. In this case the logs that describe the error will always
157 | be from the third log line onwards.'''
158 | self.send_watches_hexdump_response.emit(token, "".join(self.result + self.logs[2:]).encode())
159 | self.result = []
160 | elif token != tokens.ResponseToken.DELETE:
161 | # We found a context token -> send it to the corresponding context
162 | self.send_update_gui(token)
163 | else:
164 | # no token in result -> dropping all previous messages
165 | self.result = []
166 | self.logs = []
167 |
168 | def handle_notify(self, response: dict):
169 | """
170 | Handle the notify events, which are emitted for different occasions
171 | :param response: GDB-MI response with ["type"] == notify
172 | """
173 | if response["message"] == "running":
174 | logger.debug("Setting inferior state to %s", InferiorState.RUNNING.name)
175 | InferiorHandler.INFERIOR_STATE = InferiorState.RUNNING
176 | # When we start the inferior we should flush everything we have to main
177 | self.send_main_update()
178 | self.inferior_state_changed.emit(False)
179 | elif response["message"] == "stopped":
180 | # Don't go from EXITED->STOPPED state
181 | self.inferior_state_changed.emit(True)
182 | if InferiorHandler.INFERIOR_STATE != InferiorState.EXITED:
183 | logger.debug("Setting inferior state to %s", InferiorState.STOPPED.name)
184 | InferiorHandler.INFERIOR_STATE = InferiorState.STOPPED
185 | # If we get a stop we don't get a result type done, which is why we trigger a main context update manually
186 | self.send_main_update()
187 | elif response["message"] == "thread-group-exited":
188 | logger.debug("Setting inferior state to %s", InferiorState.EXITED.name)
189 | InferiorHandler.INFERIOR_STATE = InferiorState.EXITED
190 | # If we attach while having a process open we will get a thread-group-exited to indicate the exit of the current
191 | # process. However, we don't get a running message when attaching for the second time, but only a stopped
192 | # message. Since we don't switch from exited -> stopped our contexts will not update although they got new
193 | # information. Solution: interpret thread-group-started notify as running state change.
194 | elif response["message"] == "thread-group-started":
195 | logger.debug("Setting inferior state to %s", InferiorState.RUNNING.name)
196 | InferiorHandler.INFERIOR_STATE = InferiorState.RUNNING
197 |
--------------------------------------------------------------------------------
/gui/custom_widgets/main_context_widget.py:
--------------------------------------------------------------------------------
1 | import ast
2 | import logging
3 | import re
4 | from typing import TYPE_CHECKING, List
5 |
6 | from PySide6.QtCore import Qt, Signal, Slot, QEvent
7 | from PySide6.QtGui import QIcon, QTextCursor
8 | from PySide6.QtWidgets import QGroupBox, QVBoxLayout, QLineEdit, QHBoxLayout, QPushButton, QLabel, QWidget, QComboBox, \
9 | QFrame
10 | from gui.constants import PwndbgGuiConstants
11 | from gui.custom_widgets.context_text_edit import ContextTextEdit
12 | from gui.inferior_handler import InferiorHandler
13 | from gui.inferior_state import InferiorState
14 |
15 | # Prevent circular import error
16 | if TYPE_CHECKING:
17 | from gui.pwndbg_gui import PwnDbgGui
18 |
19 | logger = logging.getLogger(__file__)
20 |
21 |
22 | class MainContextOutput(ContextTextEdit):
23 | def __init__(self, parent: QWidget):
24 | super().__init__(parent)
25 | self.setObjectName("main")
26 |
27 | def add_content(self, content: str):
28 | """Appends content instead of replacing it like other normal ContextTextEdit widgets"""
29 | # Prevent selected text from being overwritten
30 | cursor = self.textCursor()
31 | cursor.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.MoveAnchor)
32 | self.setTextCursor(cursor)
33 | self.insertHtml(content)
34 | # Scroll to the bottom
35 | self.ensureCursorVisible()
36 |
37 |
38 | class MainContextWidget(QGroupBox):
39 | """The main context widget with which the user can interact with GDB and receive data"""
40 | # Signal to send a command to GDB MI
41 | gdb_write = Signal(str)
42 | # Signal to send inferior input via GDB
43 | gdb_write_input = Signal(bytes)
44 | # Signal to send inferior input via InferiorHandler's TTY
45 | inferior_write = Signal(bytes)
46 | # Signal to update data in the GUI
47 | update_gui = Signal(str, bytes)
48 | # Send a search request to GDB
49 | gdb_search = Signal(list)
50 |
51 | def __init__(self, parent: 'PwnDbgGui'):
52 | super().__init__(parent)
53 | self.update_gui.connect(parent.update_pane)
54 | self.buttons_data = {'s&tart': (self.start, "media-record"), '&r': (self.run, "media-playback-start"), '&c': (self.continue_execution, "media-skip-forward"), '&n': (self.next, "media-seek-forward"),
55 | '&s': (self.step, "go-bottom"), 'ni': (self.next_instruction, "go-next"), 'si': (self.step_into, "go-down")}
56 | # Whether the inferior was attached or started by GDB. If attached, we cannot divert I/O of the inferior via
57 | # GDB to the tty, so we need to send input via the GdbHandler.
58 | self.inferior_attached = False
59 | self.setup_worker_signals(parent)
60 | self.input_label = QLabel(f"pwndbg>")
61 | self.output_widget = MainContextOutput(self)
62 | self.input_widget = QLineEdit(self)
63 | self.search_input_widget = QLineEdit(self)
64 | self.search_input_widget.returnPressed.connect(self.handle_search_submit)
65 | self.search_input_widget.setPlaceholderText("Search data...")
66 | self.search_drop_down = QComboBox(self)
67 | self.search_drop_down.addItems(["byte", "word", "dword", "qword", "pointer", "string", "bytes"])
68 | self.search_drop_down.setCurrentText("bytes")
69 | self.search_drop_down.setToolTip("Select the type of data you want to search for")
70 | self.input_widget.returnPressed.connect(self.handle_submit)
71 | self.input_widget.installEventFilter(self)
72 | # The currently selected command in the command history, for when the user presses ↑ and ↓
73 | self.current_cmd_index = 0
74 | self.buttons = QHBoxLayout()
75 | self.setup_buttons()
76 | self.setup_widget_layout()
77 | self.command_history: List[str] = [""]
78 |
79 | def setup_widget_layout(self):
80 | """Create the layout of this widget and its sub widgets"""
81 | self.setAlignment(Qt.AlignmentFlag.AlignCenter)
82 | self.setFlat(True)
83 | context_layout = QVBoxLayout()
84 | # The layout containing the search field and buttons
85 | top_line_layout = QHBoxLayout()
86 | top_line_layout.addWidget(self.search_input_widget)
87 | top_line_layout.addWidget(self.search_drop_down)
88 | separator_line = QFrame(self)
89 | separator_line.setFrameShape(QFrame.Shape.VLine)
90 | separator_line.setFrameShadow(QFrame.Shadow.Sunken)
91 | top_line_layout.addWidget(separator_line)
92 | top_line_layout.addLayout(self.buttons)
93 | context_layout.addLayout(top_line_layout)
94 | context_layout.addWidget(self.output_widget)
95 | input_layout = QHBoxLayout()
96 | input_layout.addWidget(self.input_label)
97 | input_layout.addWidget(self.input_widget)
98 | context_layout.addLayout(input_layout)
99 | self.setLayout(context_layout)
100 |
101 | def setup_buttons(self):
102 | """Setup the convenience buttons (Run, Continue, Step, etc...)"""
103 | self.buttons.setAlignment(Qt.AlignmentFlag.AlignRight)
104 | for label, data in self.buttons_data.items():
105 | callback, icon = data
106 | button = QPushButton(label)
107 | button.clicked.connect(callback)
108 | if icon is not None:
109 | button.setIcon(QIcon.fromTheme(icon))
110 | if button.shortcut() is not None:
111 | button.setToolTip(button.shortcut().toString())
112 | self.buttons.addWidget(button)
113 |
114 | def setup_worker_signals(self, parent: 'PwnDbgGui'):
115 | """Connect signals to the GDB and Inferior writer to allow this widget to forward commands/input"""
116 | # Allow giving the thread work from outside
117 | self.gdb_write.connect(parent.gdb_handler.send_command)
118 | self.inferior_write.connect(parent.inferior_handler.inferior_write)
119 |
120 | @Slot()
121 | def handle_submit(self):
122 | """Callback for when the user presses Enter in the main widget's input field"""
123 | if InferiorHandler.INFERIOR_STATE == InferiorState.RUNNING:
124 | # Inferior is running, send to inferior
125 | self.submit_input()
126 | else:
127 | # Enter was pressed, send command to pwndbg
128 | self.submit_cmd()
129 |
130 | @Slot()
131 | def start(self):
132 | """Callback of the start button"""
133 | logger.debug("Executing start callback")
134 | self.gdb_write.emit("start")
135 |
136 | @Slot()
137 | def run(self):
138 | """Callback of the Run button"""
139 | logger.debug("Executing r callback")
140 | self.gdb_write.emit("r")
141 |
142 | @Slot()
143 | def continue_execution(self):
144 | """Callback of the Continue button"""
145 | logger.debug("Executing c callback")
146 | self.gdb_write.emit("c")
147 |
148 | @Slot()
149 | def next(self):
150 | """Callback of the Next button"""
151 | logger.debug("Executing n callback")
152 | self.gdb_write.emit("n")
153 |
154 | @Slot()
155 | def step(self):
156 | """Callback of the Step button"""
157 | logger.debug("Executing s callback")
158 | self.gdb_write.emit("s")
159 |
160 | @Slot()
161 | def next_instruction(self):
162 | """Callback of the Next Instruction button"""
163 | logger.debug("Executing ni callback")
164 | self.gdb_write.emit("ni")
165 |
166 | @Slot()
167 | def step_into(self):
168 | """Callback of the Step Instruction button"""
169 | logger.debug("Executing si callback")
170 | self.gdb_write.emit("si")
171 |
172 | @Slot(bool)
173 | def change_input_label(self, is_pwndbg: bool):
174 | """Update the input label's text"""
175 | if is_pwndbg:
176 | self.input_label.setText(f"pwndbg>")
177 | else:
178 | self.input_label.setText(f"target>")
179 |
180 | @Slot()
181 | def handle_search_submit(self):
182 | search_value = self.search_input_widget.text()
183 | value_type = self.search_drop_down.currentText()
184 | if value_type == "bytes":
185 | # Wrap the user input with "", otherwise characters like "'" and " " cause problems
186 | search_value = f'"{search_value}"'
187 | params = ["-t", value_type, search_value]
188 | logger.debug("Executing search with %s", params)
189 | self.gdb_search.emit(params)
190 | self.search_input_widget.clear()
191 |
192 | def submit_cmd(self):
193 | """Submit a command to GDB"""
194 | user_line = self.input_widget.text()
195 | if self.command_history[-1] != user_line:
196 | self.command_history.insert(-1, user_line)
197 | self.current_cmd_index = len(self.command_history) - 1
198 | logger.debug("Sending command '%s' to gdb", user_line)
199 | self.update_gui.emit("main", f"> {user_line}\n".encode())
200 | self.gdb_write.emit(user_line)
201 | self.input_widget.clear()
202 |
203 | def submit_input(self):
204 | """Submit an input to the inferior process"""
205 | user_line = self.input_widget.text()
206 | logger.debug("Sending input '%s' to inferior", user_line)
207 | user_input = b""
208 | user_echo = b""
209 | # Check if the user wants to input a byte string literal, i.e. the input is in the form: 'b"MyInput \x12\x34"'
210 | if re.match(r'^b["\'].*["\']$', user_line):
211 | # Parse the str as if it were a bytes object
212 | # literal_eval is safer than eval(), however it still poses security risks regarding DoS, which we don't care about
213 | logger.debug("Trying to evaluate literal '%s'", user_line)
214 | byte_string = ast.literal_eval(user_line)
215 | logger.debug("Parsed input as bytes string, final input: %s", byte_string)
216 | # Don't pass a newline here, the user needs to specify this himself by writing '\n' at the end of his input
217 | user_input = byte_string
218 | # We want the user to get the evaluated string echoed back
219 | # However without leading b' and ending ' to avoid confusion with regular string insert
220 | user_echo = repr(byte_string)[2:][:-1].encode()
221 | else:
222 | user_echo = user_line.encode() + b"\n"
223 | user_input = user_line.encode() + b"\n"
224 | if self.inferior_attached:
225 | self.gdb_write_input.emit(user_input)
226 | else:
227 | self.update_gui.emit("main", user_echo)
228 | self.inferior_write.emit(user_input)
229 | self.input_widget.clear()
230 |
231 | def eventFilter(self, source: QWidget, event: QEvent):
232 | """Callback for Qt events. Handles the navigation of the user's command history"""
233 | # https://stackoverflow.com/a/46506129
234 | if event.type() != QEvent.Type.KeyPress or source is not self.input_widget:
235 | return super().eventFilter(source, event)
236 | if event.key() == Qt.Key.Key_Down:
237 | self.current_cmd_index = min(len(self.command_history) - 1, self.current_cmd_index + 1)
238 | self.input_widget.setText(self.command_history[self.current_cmd_index])
239 | elif event.key() == Qt.Key.Key_Up:
240 | self.current_cmd_index = max(0, self.current_cmd_index - 1)
241 | self.input_widget.setText(self.command_history[self.current_cmd_index])
242 | return super().eventFilter(source, event)
243 |
--------------------------------------------------------------------------------
/gui/custom_widgets/watches_context_widget.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import TYPE_CHECKING, List
3 |
4 | from PySide6.QtCore import Qt, Signal, Slot, QParallelAnimationGroup, QPropertyAnimation, QAbstractAnimation, QSize
5 | from PySide6.QtGui import QIcon
6 | from PySide6.QtWidgets import QGroupBox, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QWidget, \
7 | QFrame, QScrollArea, QToolButton, QGridLayout, QSizePolicy, QBoxLayout, QSpinBox, QTextEdit, \
8 | QApplication
9 |
10 | from gui.constants import PwndbgGuiConstants
11 | from gui.custom_widgets.context_text_edit import ContextTextEdit
12 | from gui.parser import ContextParser
13 | from gui.tokens import ResponseToken
14 |
15 | # Prevent circular import error
16 | if TYPE_CHECKING:
17 | from gui.pwndbg_gui import PwnDbgGui
18 |
19 | logger = logging.getLogger(__file__)
20 |
21 |
22 | class Spoiler(QWidget):
23 | def __init__(self, content_layout: QBoxLayout, parent=None, title='', animationDuration=300):
24 | """
25 | References:
26 | # Adapted from c++ version
27 | http://stackoverflow.com/questions/32476006/how-to-make-an-expandable-collapsable-section-widget-in-qt
28 | """
29 | super(Spoiler, self).__init__(parent=parent)
30 |
31 | self.animationDuration = animationDuration
32 | self.toggleAnimation = QParallelAnimationGroup()
33 | self.contentArea = QScrollArea(parent=self)
34 | self.headerLine = QFrame(parent=self)
35 | self.toggleButton = QToolButton(parent=self)
36 | self.mainLayout = QGridLayout()
37 |
38 | toggle_button = self.toggleButton
39 | toggle_button.setStyleSheet("QToolButton { border: none; }")
40 | toggle_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
41 | toggle_button.setArrowType(Qt.RightArrow)
42 | toggle_button.setText(str(title))
43 | toggle_button.setCheckable(True)
44 | toggle_button.setChecked(False)
45 |
46 | header_line = self.headerLine
47 | header_line.setFrameShape(QFrame.Shape.HLine)
48 | header_line.setFrameShadow(QFrame.Shadow.Sunken)
49 | header_line.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
50 |
51 | self.contentArea.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
52 | # start out collapsed
53 | self.contentArea.setMaximumHeight(0)
54 | self.contentArea.setMinimumHeight(0)
55 |
56 | # let the entire widget grow and shrink with its content
57 | toggle_animation = self.toggleAnimation
58 | toggle_animation.addAnimation(QPropertyAnimation(self, b"minimumHeight"))
59 | toggle_animation.addAnimation(QPropertyAnimation(self, b"maximumHeight"))
60 | toggle_animation.addAnimation(QPropertyAnimation(self.contentArea, b"maximumHeight"))
61 | # don't waste space
62 | main_layout = self.mainLayout
63 | main_layout.setVerticalSpacing(0)
64 | main_layout.setContentsMargins(0, 0, 0, 0)
65 | row = 0
66 | main_layout.addWidget(self.toggleButton, row, 0, 1, 1, Qt.AlignLeft)
67 | main_layout.addWidget(self.headerLine, row, 2, 1, 1)
68 | row += 1
69 | main_layout.addWidget(self.contentArea, row, 0, 1, 3)
70 | self.setLayout(self.mainLayout)
71 | self.setContentLayout(content_layout)
72 |
73 | def start_animation(checked):
74 | arrow_type = Qt.DownArrow if checked else Qt.RightArrow
75 | direction = QAbstractAnimation.Forward if checked else QAbstractAnimation.Backward
76 | toggle_button.setArrowType(arrow_type)
77 | self.toggleAnimation.setDirection(direction)
78 | self.toggleAnimation.start()
79 |
80 | # Connect button and animation and finally toggle animation to be in the expanded state
81 | self.toggleButton.clicked.connect(start_animation)
82 | self.toggleButton.click()
83 |
84 | def setContentLayout(self, content_layout):
85 | self.contentArea.destroy()
86 | self.contentArea.setLayout(content_layout)
87 | self.update_content_height()
88 |
89 | def update_content_height(self):
90 | collapsed_height = self.sizeHint().height() - self.contentArea.maximumHeight()
91 | content_height = self.contentArea.layout().sizeHint().height()
92 | for i in range(self.toggleAnimation.animationCount() - 1):
93 | spoiler_animation = self.toggleAnimation.animationAt(i)
94 | spoiler_animation.setDuration(self.animationDuration)
95 | spoiler_animation.setStartValue(collapsed_height)
96 | spoiler_animation.setEndValue(collapsed_height + content_height)
97 | content_animation = self.toggleAnimation.animationAt(self.toggleAnimation.animationCount() - 1)
98 | content_animation.setDuration(self.animationDuration)
99 | content_animation.setStartValue(0)
100 | content_animation.setEndValue(content_height)
101 |
102 | def instant_update(self):
103 | # Lord have mercy on my soul for that I have sinned
104 | for i in range(self.toggleAnimation.animationCount() - 1):
105 | spoiler_animation = self.toggleAnimation.animationAt(i)
106 | spoiler_animation.setDuration(0)
107 | content_animation = self.toggleAnimation.animationAt(self.toggleAnimation.animationCount() - 1)
108 | content_animation.setDuration(0)
109 | self.toggleButton.click()
110 | self.toggleButton.click()
111 | for i in range(self.toggleAnimation.animationCount() - 1):
112 | spoiler_animation = self.toggleAnimation.animationAt(i)
113 | spoiler_animation.setDuration(self.animationDuration)
114 | content_animation = self.toggleAnimation.animationAt(self.toggleAnimation.animationCount() - 1)
115 | content_animation.setDuration(self.animationDuration)
116 |
117 |
118 | class ActiveWatch:
119 | """Class that holds information for an active watch widget"""
120 | def __init__(self, address: str, index: int, spoiler: Spoiler, output: ContextTextEdit, numbytes: int):
121 | self.address = address
122 | self.index = index
123 | self.spoiler = spoiler
124 | self.output = output
125 | self.numbytes = numbytes
126 |
127 |
128 | class HDumpContextWidget(QGroupBox):
129 | # Execute "hexdump" in pwndbg and add watch in controller
130 | add_watch = Signal(str, int)
131 | # Delete watch in controller
132 | del_watch = Signal(str)
133 | # Change num of watch lines in controller
134 | change_lines_watch = Signal(str, int)
135 | # Number of lines that the hexdump command will output for the Default number of bytes
136 | default_lines = (PwndbgGuiConstants.DEFAULT_WATCH_BYTES / 16 + 1)
137 |
138 | def __init__(self, parent: 'PwnDbgGui'):
139 | super().__init__(parent)
140 | self.parser = ContextParser()
141 | # Currently watched addresses as list of ActiveWatches
142 | self.watches: List[ActiveWatch] = []
143 | self.idx = 0
144 | # UI init
145 | self.active_watches_layout = QVBoxLayout()
146 | self.new_watch_input: QLineEdit | None = None
147 | # The watch context
148 | self.context_layout = QVBoxLayout()
149 | self.setAlignment(Qt.AlignmentFlag.AlignCenter)
150 | self.setFlat(True)
151 | self.setTitle("Watches")
152 | # Connect signals for gdb_handler communication
153 | self.add_watch.connect(parent.gdb_handler.add_watch)
154 | self.del_watch.connect(parent.gdb_handler.del_watch)
155 | self.change_lines_watch.connect(parent.gdb_handler.change_watch_lines)
156 | # Set up the interior layout of this widget
157 | self.setup_widget_layout()
158 | # Insert this widget into the UI
159 | parent.ui.splitter.replaceWidget(2, self)
160 |
161 | def setup_widget_layout(self):
162 | # The layout for the input mask (label and line edit) of the New Watch functionality
163 | new_watch_input_layout = QHBoxLayout()
164 | new_watch_input_label = QLabel("New Watch:", parent=self)
165 | new_watch_input_label.setToolTip("Add an address to be watched every context update via 'hexdump'")
166 | new_watch_input_layout.addWidget(new_watch_input_label)
167 | self.new_watch_input = QLineEdit()
168 | self.new_watch_input.setToolTip("New address to watch")
169 | self.new_watch_input.returnPressed.connect(self.new_watch_submit)
170 | new_watch_input_layout.addWidget(self.new_watch_input)
171 | # Package the new_watch layout in a widget so that we can add it to the overall widget
172 | new_watch_widget = QWidget(self)
173 | new_watch_widget.setLayout(new_watch_input_layout)
174 | self.context_layout.addWidget(new_watch_widget)
175 |
176 | # Wrapper for QScrollArea widget for added watches
177 | watches_scroll_area = QScrollArea(self)
178 | watches_scroll_area.setWidgetResizable(True)
179 | # Widget for the QScrollArea
180 | vertical_scroll_widget = QWidget(self)
181 | self.active_watches_layout = QVBoxLayout(vertical_scroll_widget)
182 | watches_scroll_area.setWidget(vertical_scroll_widget)
183 | self.context_layout.addWidget(watches_scroll_area)
184 |
185 | self.setLayout(self.context_layout)
186 |
187 | def setup_new_watch_widget(self, address: str):
188 | """
189 | Adds a new Spoiler widget to the active watches.
190 | :param address: address or expression to watch
191 | """
192 | # Setup inter Spoiler layout
193 | inter_spoiler_layout = QVBoxLayout()
194 | # First setup HBoxLayout for delete and lines
195 | watch_interact_layout = QHBoxLayout()
196 | watch_interact_layout.setAlignment(Qt.AlignmentFlag.AlignLeft)
197 |
198 | # Bytes Spinbox
199 | watch_lines_label = QLabel("Bytes:", parent=self)
200 | watch_interact_layout.addWidget(watch_lines_label)
201 | watch_lines_incrementor = QSpinBox()
202 | watch_lines_incrementor.setRange(1, 999)
203 | watch_lines_incrementor.setValue(PwndbgGuiConstants.DEFAULT_WATCH_BYTES)
204 | watch_lines_incrementor.valueChanged.connect(lambda value: self.change_lines_watch.emit(address, value))
205 | watch_lines_incrementor.setFixedHeight(QApplication.font().pointSize() * 2.5)
206 | watch_lines_incrementor.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
207 | watch_interact_layout.addWidget(watch_lines_incrementor)
208 |
209 | # Delete button
210 | delete_watch_button = QToolButton()
211 | delete_watch_button.setIcon(QIcon.fromTheme("edit-delete"))
212 | delete_watch_button.setIconSize(QSize(QApplication.font().pointSize() * 2, QApplication.font().pointSize() * 2))
213 | delete_watch_button.setFixedSize(
214 | QSize(QApplication.font().pointSize() * 2.5, QApplication.font().pointSize() * 2.5))
215 | delete_watch_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
216 | delete_watch_button.clicked.connect(lambda: self.delete_watch_submit(address))
217 | watch_interact_layout.addWidget(delete_watch_button)
218 |
219 | spoiler_interact_widget = QWidget(self)
220 | spoiler_interact_widget.setLayout(watch_interact_layout)
221 | inter_spoiler_layout.addWidget(spoiler_interact_widget)
222 | # Second setup hexdump output
223 | hexdump_output = ContextTextEdit(self)
224 | # Setting maximum height
225 | hexdump_output.set_maxheight_to_lines(self.default_lines)
226 | hexdump_output.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
227 | inter_spoiler_layout.addWidget(hexdump_output)
228 | # Setup Spoiler
229 | spoiler = Spoiler(inter_spoiler_layout, parent=self, title=address)
230 | # Add watch to outer context
231 | self.watches.append(ActiveWatch(address, self.idx, spoiler, hexdump_output, PwndbgGuiConstants.DEFAULT_WATCH_BYTES))
232 | self.idx += 1
233 | self.active_watches_layout.insertWidget(0, spoiler)
234 |
235 | def find_watch_by_id(self, index: id) -> ActiveWatch:
236 | """
237 | Finds active ActiveWatch object by index.
238 | :param index: Index to search for.
239 | :return: ActiveWatch object with specified index.
240 | """
241 | found_watch = next((watch for watch in self.watches if watch.index == index), None)
242 | return found_watch
243 |
244 | def find_watch_by_address(self, address: str) -> ActiveWatch:
245 | """
246 | Finds active ActiveWatch object by address.
247 | :param address: Address to search for.
248 | :return: ActiveWatch object with specified address.
249 | """
250 | found_watch = next((watch for watch in self.watches if watch.address == address), None)
251 | return found_watch
252 |
253 | @Slot()
254 | def new_watch_submit(self):
255 | """Callback for when the user presses Enter in the new_watch input mask"""
256 | param = self.new_watch_input.text()
257 | if self.find_watch_by_address(param) is not None:
258 | self.new_watch_input.clear()
259 | return
260 | self.setup_new_watch_widget(param)
261 | self.add_watch.emit(param, self.find_watch_by_address(param).index)
262 | self.new_watch_input.clear()
263 |
264 | @Slot(str)
265 | def delete_watch_submit(self, address: str):
266 | """Callback for when the user presses Delete in one of the watch spoilers
267 | :param address: Address to delete
268 | """
269 | watch = self.find_watch_by_address(address)
270 | self.context_layout.removeWidget(watch.spoiler)
271 | watch.spoiler.deleteLater()
272 | self.watches.remove(watch)
273 | self.del_watch.emit(address)
274 |
275 | @Slot(int, bytes)
276 | def receive_hexdump_result(self, token: int, result: bytes):
277 | """Slot for receiving the result of the 'hexdump' command from the GDB reader
278 | :param token: Token that identifies the answer from pygdbmi.
279 | :param result: Content to update the watch with.
280 | """
281 | index = token - ResponseToken.GUI_WATCHES_HEXDUMP
282 | watch = self.find_watch_by_id(index)
283 | if watch is not None:
284 | # First trim the first column if necessary
285 | lines = result.split(b'\n')
286 | non_empty_lines = [line for line in lines if line]
287 | # Throwaway the first column if it is an offset column
288 | trimmed_lines = [line.split(b' ', 1)[1] if line.startswith(b"+0") else line for line in non_empty_lines]
289 | content = b'\n'.join(trimmed_lines)
290 |
291 | # Second add content to the watch and reset scrollbars
292 | watch.output.add_content(self.parser.to_html(content))
293 | watch.output.verticalScrollBar().setValue(0)
294 | watch.output.horizontalScrollBar().setValue(0)
295 |
296 | # Adapt output size if content now is less than before
297 | line_count = len(result.split(b"\n"))
298 | if line_count < self.default_lines:
299 | watch.output.set_maxheight_to_lines(line_count)
300 | else:
301 | watch.output.set_maxheight_to_lines(self.default_lines)
302 |
303 | # Last update spoiler size
304 | watch.spoiler.update_content_height()
305 | watch.spoiler.instant_update()
306 |
--------------------------------------------------------------------------------
/gui/pwndbg_gui.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import sys
3 | from pathlib import Path
4 | from typing import List
5 | from os import path
6 |
7 | import psutil
8 |
9 | sys.path.extend([path.join(path.dirname(__file__), path.pardir)])
10 | from gui.custom_widgets.backtrace_context_widget import BacktraceContextWidget
11 | from gui.custom_widgets.code_context_widget import CodeContextWidget
12 | from gui.custom_widgets.disasm_context_widget import DisasmContextWidget
13 | from gui.custom_widgets.info_message_box import InfoMessageBox
14 | from gui.custom_widgets.register_context_widget import RegisterContextWidget
15 | from gui.custom_widgets.stack_context_widget import StackContextWidget
16 |
17 | import PySide6
18 | from PySide6.QtCore import Slot, Qt, Signal, QThread, QSettings, QByteArray
19 | from PySide6.QtGui import QTextOption, QAction, QKeySequence, QFont, QPalette, QColor
20 | from PySide6.QtWidgets import QApplication, QFileDialog, QMainWindow, QInputDialog, \
21 | QLineEdit, QMessageBox, QSpinBox, QSplitter
22 |
23 | from gui.constants import PwndbgGuiConstants
24 | from gui.custom_widgets.context_list_widget import ContextListWidget
25 | from gui.custom_widgets.context_text_edit import ContextTextEdit
26 | from gui.custom_widgets.main_context_widget import MainContextWidget
27 | from gui.gdb_handler import GdbHandler
28 | from gui.custom_widgets.heap_context_widget import HeapContextWidget
29 | from gui.custom_widgets.watches_context_widget import HDumpContextWidget
30 | from gui.gdb_reader import GdbReader
31 | from gui.inferior_handler import InferiorHandler
32 | from gui.parser import ContextParser
33 | # Important:
34 | # You need to run the following command to generate the ui_form.py file
35 | # pyside6-uic form.ui -o ui_form.py, or
36 | # pyside2-uic form.ui -o ui_form.py
37 | from gui.ui_form import Ui_PwnDbgGui
38 |
39 |
40 | logging.basicConfig(level=sys.argv[1] if len(sys.argv) > 1 else logging.INFO, format='%(asctime)s - %(name)s | [%('
41 | 'levelname)s] : %(message)s')
42 | logger = logging.getLogger(__file__)
43 |
44 |
45 | class PwnDbgGui(QMainWindow):
46 | change_gdb_setting = Signal(list)
47 | stop_gdb_threads = Signal()
48 | set_gdb_file_target_signal = Signal(list)
49 | set_gdb_pid_target_signal = Signal(list)
50 | set_gdb_source_dir_signal = Signal(list)
51 | set_gdb_tty = Signal(str)
52 | # Signal to request a context update for all contexts from the GdbHandler
53 | update_contexts = Signal(bool)
54 |
55 | def __init__(self, parent=None):
56 | super().__init__(parent)
57 | # An overview of all pwndbg commands
58 | self.pwndbg_cmds = ""
59 | self.main_context: MainContextWidget | None = None
60 | # Thread that will handle all writing to GDB
61 | self.gdb_handler_thread: QThread | None = None
62 | # Thread that will continuously read from GDB
63 | self.gdb_reader_thread: QThread | None = None
64 | # Thread that will continuously read and write to inferior
65 | self.inferior_thread: QThread | None = None
66 | self.gdb_handler = GdbHandler()
67 | self.gdb_reader = GdbReader(self.gdb_handler.controller)
68 | self.inferior_handler = InferiorHandler()
69 | self.menu_bar = None
70 | self.ui = Ui_PwnDbgGui()
71 | self.ui.setupUi(self)
72 | # Make all widgets resizable with the window
73 | self.setCentralWidget(self.ui.top_splitter)
74 | self.setup_custom_widgets()
75 | self.seg_to_widget = dict(stack=self.ui.stack, code=self.ui.code, disasm=self.ui.disasm,
76 | backtrace=self.ui.backtrace, regs=self.ui.regs,
77 | main=self.main_context.output_widget)
78 | self.parser = ContextParser()
79 | self.setup_gdb_workers()
80 | self.setup_menu()
81 | self.gdb_handler.init()
82 | self.setup_inferior()
83 | self.load_state()
84 |
85 | def setup_custom_widgets(self):
86 | """
87 | Ugly workaround to allow to use custom widgets. Using custom widgets in Qt Designer seems to only work for C++
88 | """
89 | logger.debug("Replacing widgets with custom implementations")
90 | # Widget index depends on the order they were added in ui_form.py
91 | self.ui.stack = StackContextWidget(self, title="Stack", splitter=self.ui.splitter_4, index=2)
92 | self.ui.regs = RegisterContextWidget(self, title="Registers", splitter=self.ui.splitter_3, index=0)
93 | self.ui.backtrace = BacktraceContextWidget(self, title="Backtrace", splitter=self.ui.splitter_3, index=1)
94 | self.ui.disasm = DisasmContextWidget(self, title="Disassembly", splitter=self.ui.code_splitter, index=0)
95 | self.ui.code = CodeContextWidget(self, title="Code", splitter=self.ui.code_splitter, index=1)
96 | self.ui.heap = HeapContextWidget(self)
97 | self.ui.watches = HDumpContextWidget(self)
98 | self.main_context = MainContextWidget(parent=self)
99 | self.ui.splitter.replaceWidget(0, self.main_context)
100 |
101 | def setup_menu(self):
102 | """Create the menu and toolbar at the top of the window"""
103 | self.menu_bar = self.menuBar()
104 | debug_menu = self.menu_bar.addMenu("&Debug")
105 | debug_toolbar = self.addToolBar("Debug")
106 | debug_toolbar.setObjectName("debugToolbar")
107 |
108 | start_action = QAction("Start Program", self)
109 | start_action.setToolTip("Start the program to debug")
110 | start_action.setShortcut(QKeySequence.StandardKey.New)
111 | start_action.triggered.connect(self.select_file)
112 | debug_menu.addAction(start_action)
113 | debug_toolbar.addAction(start_action)
114 |
115 | attach_name_action = QAction("Attach Via Name", self)
116 | attach_name_action.setToolTip("Attach to a running program via its name (requires sudo)")
117 | attach_name_action.triggered.connect(self.query_process_name)
118 | debug_menu.addAction(attach_name_action)
119 | debug_toolbar.addAction(attach_name_action)
120 |
121 | attach_pid_action = QAction("Attach Via PID", self)
122 | attach_pid_action.setToolTip("Attach to a running program via its pid (requires sudo)")
123 | attach_pid_action.triggered.connect(self.query_process_pid)
124 | debug_menu.addAction(attach_pid_action)
125 | debug_toolbar.addAction(attach_pid_action)
126 |
127 | debug_menu.addSeparator()
128 | exit_action = QAction("E&xit", self)
129 | exit_action.setShortcut(QKeySequence.StandardKey.Quit)
130 | exit_action.setToolTip("Exit the application")
131 | exit_action.triggered.connect(self.close)
132 | debug_menu.addAction(exit_action)
133 |
134 | about_menu = self.menu_bar.addMenu("About")
135 | about_action = QAction("About", self)
136 | about_action.triggered.connect(self.about)
137 | about_menu.addAction(about_action)
138 | about_pwndbg_action = QAction("About Pwndbg", self)
139 | about_pwndbg_action.triggered.connect(self.about_pwndbg)
140 | about_menu.addAction(about_pwndbg_action)
141 | about_qt_action = QAction("About Qt", self)
142 | about_qt_action.triggered.connect(QApplication.aboutQt)
143 | about_menu.addAction(about_qt_action)
144 |
145 | def setup_gdb_workers(self):
146 | """Setup our worker threads and connect all required signals with their slots"""
147 | self.gdb_handler_thread = QThread()
148 | self.gdb_reader_thread = QThread()
149 | self.gdb_handler.moveToThread(self.gdb_handler_thread)
150 | self.gdb_reader.moveToThread(self.gdb_reader_thread)
151 | # Allow widgets to send signals that interact with GDB
152 | self.set_gdb_file_target_signal.connect(self.gdb_handler.set_file_target)
153 | self.set_gdb_pid_target_signal.connect(self.gdb_handler.set_pid_target)
154 | self.set_gdb_source_dir_signal.connect(self.gdb_handler.set_source_dir)
155 | self.set_gdb_tty.connect(self.gdb_handler.set_tty)
156 | self.update_contexts.connect(self.gdb_handler.update_contexts)
157 | self.main_context.gdb_write_input.connect(self.gdb_handler.send_inferior_input)
158 | self.main_context.gdb_search.connect(self.gdb_handler.execute_search)
159 | self.ui.stack.stack_lines_incrementor.valueChanged.connect(self.gdb_handler.update_stack_lines)
160 | self.ui.stack.execute_xinfo.connect(self.gdb_handler.execute_xinfo)
161 | self.ui.regs.execute_xinfo.connect(self.gdb_handler.execute_xinfo)
162 | # Allow the worker to update contexts in the GUI thread
163 | self.gdb_handler.update_gui.connect(self.update_pane)
164 | self.gdb_reader.update_gui.connect(self.update_pane)
165 | self.gdb_reader.inferior_state_changed.connect(self.main_context.change_input_label)
166 | self.gdb_reader.send_pwndbg_about.connect(self.receive_pwndbg_about)
167 | self.gdb_reader.send_xinfo.connect(self.display_xinfo_result)
168 | # Allow the heap context to receive the results it requests
169 | self.gdb_reader.send_heap_try_free_response.connect(self.ui.heap.receive_try_free_result)
170 | self.gdb_reader.send_heap_heap_response.connect(self.ui.heap.receive_heap_result)
171 | self.gdb_reader.send_heap_bins_response.connect(self.ui.heap.receive_bins_result)
172 | # Allow the watches context to receive the hexdump results
173 | self.gdb_reader.send_watches_hexdump_response.connect(self.ui.watches.receive_hexdump_result)
174 | # Allow the "regs" context to receive information about the fs register
175 | self.gdb_reader.send_fs_base_response.connect(self.ui.regs.receive_fs_base)
176 | # Thread cleanup
177 | self.gdb_handler_thread.finished.connect(self.gdb_handler.deleteLater)
178 | self.gdb_reader_thread.finished.connect(self.gdb_reader.deleteLater)
179 | self.stop_gdb_threads.connect(lambda: self.gdb_reader.set_run(False))
180 | self.stop_gdb_threads.connect(self.gdb_handler_thread.quit)
181 | self.stop_gdb_threads.connect(self.gdb_reader_thread.quit)
182 | logger.debug("Starting new worker threads")
183 | self.gdb_reader_thread.started.connect(self.gdb_reader.read_with_timeout)
184 | self.gdb_handler_thread.start()
185 | self.gdb_reader_thread.start()
186 | logger.info("Started worker threads")
187 |
188 | def setup_inferior(self):
189 | # Thread setup
190 | self.inferior_thread = QThread()
191 | self.inferior_handler.moveToThread(self.inferior_thread)
192 | # Connect signals from inferior_handler
193 | self.inferior_handler.update_gui.connect(self.update_pane)
194 | # execute gdb command to redirect inferior to tty
195 | self.set_gdb_tty.emit(self.inferior_handler.tty)
196 | # Thread cleanup
197 | self.inferior_thread.finished.connect(self.inferior_handler.deleteLater())
198 | self.stop_gdb_threads.connect(lambda: self.inferior_handler.set_run(False))
199 | self.stop_gdb_threads.connect(self.inferior_thread.quit)
200 | # Thread start
201 | self.inferior_thread.started.connect(self.inferior_handler.inferior_runs)
202 | self.inferior_thread.start()
203 |
204 | def closeEvent(self, event: PySide6.QtGui.QCloseEvent) -> None:
205 | """
206 | Called when window is closed. Stop our worker threads
207 | :param event: The event forwarded by Qt
208 | """
209 | logger.debug("Stopping GDB threads")
210 | self.stop_gdb_threads.emit()
211 | self.save_state()
212 | logger.debug("Waiting for GDB Handler thread")
213 | self.gdb_handler_thread.wait()
214 | logger.debug("Waiting for GDB Reader thread")
215 | self.gdb_reader_thread.wait()
216 | logger.debug("Waiting for Inferior thread")
217 | self.inferior_thread.wait()
218 | event.accept()
219 |
220 | @Slot()
221 | def select_file(self):
222 | """Query the user for the path to an executable with a file dialog in order to start it"""
223 | dialog = QFileDialog(self)
224 | dialog.setFileMode(QFileDialog.FileMode.ExistingFile)
225 | dialog.setViewMode(QFileDialog.ViewMode.Detail)
226 | if dialog.exec() and len(dialog.selectedFiles()) > 0:
227 | file_name = dialog.selectedFiles()[0]
228 | # Before loading the file we want to set the correct tty for the inferior
229 | self.set_gdb_tty.emit(self.inferior_handler.tty)
230 | self.set_gdb_file_target_signal.emit([file_name])
231 | # Reset dir so that GDB doesn't get confused when we load multiple programs with the same name / source
232 | # file name
233 | # TODO: Allow user to supply dir via GUI, differentiate between user supplied dirs and automatically added by us
234 | #self.set_gdb_source_dir_signal.emit([""])
235 | # GDB only looks for source files in the cwd, so we additionally add the directory of the executable
236 | self.set_gdb_source_dir_signal.emit([str(Path(file_name).parent)])
237 | self.main_context.inferior_attached = False
238 |
239 | @Slot()
240 | def query_process_name(self):
241 | """Query the user for a process name in order to attach to it"""
242 | name, ok = QInputDialog.getText(self, "Enter a running process name", "Name:", QLineEdit.EchoMode.Normal,
243 | "vuln")
244 | if ok and name:
245 | pid = None
246 | for process in psutil.process_iter(['pid', 'name']):
247 | if process.name() == name:
248 | pid = process.pid
249 | if pid is None:
250 | logger.error("Could not find PID for process %s", name)
251 | self.update_pane("main", f"Could not find PID for process {name}".encode())
252 | return
253 | self.attach_to_pid(pid)
254 |
255 | @Slot()
256 | def query_process_pid(self):
257 | """Query the user for process ID in order to attach to it"""
258 | pid, ok = QInputDialog.getInt(self, "Enter a running process pid", "PID:", minValue=0)
259 | if ok and pid > 0:
260 | self.attach_to_pid(pid)
261 |
262 | @Slot(str, bytes)
263 | def update_pane(self, context: str, content: bytes):
264 | """
265 | Used by other threads to update widgets in the GUI. Updates to the GUI have to be made in the GUI's thread
266 | :param context: The context to update
267 | :param content: The collected output from GDB
268 | """
269 | widget: ContextTextEdit | ContextListWidget = self.seg_to_widget[context]
270 | logger.debug("Updating context %s", widget.objectName())
271 | remove_header = True
272 | if context == "main":
273 | remove_header = False
274 | # Main should end with newline
275 | if content != b"" and not content.endswith(b"\n"):
276 | content += b"\n"
277 | html = self.parser.to_html(content, remove_header)
278 | widget.add_content(html)
279 |
280 | @Slot()
281 | def about(self):
282 | """Display the About section for our GUI"""
283 | QMessageBox.about(self, "About PwndbgGui", PwndbgGuiConstants.ABOUT_TEXT)
284 |
285 | @Slot(bytes)
286 | def receive_pwndbg_about(self, content: bytes):
287 | """
288 | Receive the output of the command overview for pwndbg
289 | :param content: The output of "pwndbg --all" command
290 | """
291 | self.pwndbg_cmds = self.parser.to_html(content)
292 |
293 | @Slot()
294 | def about_pwndbg(self):
295 | """Display the About section for pwndbg"""
296 | popup = InfoMessageBox(self, "About Pwndbg", self.pwndbg_cmds, "https://github.com/pwndbg/pwndbg#pwndbg")
297 | popup.exec()
298 |
299 | @Slot(bytes)
300 | def display_xinfo_result(self, content: bytes):
301 | """
302 | Create a PopUp that displays the offset information the user requested.
303 | :param content: The output of a "xinfo" command
304 | """
305 | message = self.parser.to_html(content)
306 | # pwndbg doesn't seem to have documentation on commands, so we link to code ¯\_(ツ)_/¯
307 | popup = InfoMessageBox(self, "xinfo", message, "https://github.com/pwndbg/pwndbg/blob/dev/pwndbg/commands"
308 | "/xinfo.py#L102")
309 | popup.show()
310 |
311 | def save_state(self):
312 | """Save the state of the current session (e.g. in ~/.config folder on Linux)"""
313 | settings = QSettings(PwndbgGuiConstants.SETTINGS_FOLDER, PwndbgGuiConstants.SETTINGS_FILE)
314 | logger.info("Saving GUI layout state to %s", settings.fileName())
315 | settings.setValue(PwndbgGuiConstants.SETTINGS_WINDOW_STATE, self.saveState())
316 | settings.setValue(PwndbgGuiConstants.SETTINGS_WINDOW_GEOMETRY, self.saveGeometry())
317 | settings = QSettings(PwndbgGuiConstants.SETTINGS_FOLDER, PwndbgGuiConstants.SETTINGS_FILE)
318 | splitters = self.findChildren(QSplitter)
319 | splitter_sizes: List[QByteArray] = [splitter.saveGeometry() for splitter in splitters]
320 | splitter_states: List[QByteArray] = [splitter.saveState() for splitter in splitters]
321 | settings.setValue(PwndbgGuiConstants.SPLITTER_GEOMETRIES, b','.join(map(QByteArray.toBase64, splitter_sizes)))
322 | settings.setValue(PwndbgGuiConstants.SPLITTER_STATES, b','.join(map(QByteArray.toBase64, splitter_states)))
323 |
324 | def load_state(self):
325 | """Load the state of the previous session"""
326 | settings = QSettings(PwndbgGuiConstants.SETTINGS_FOLDER, PwndbgGuiConstants.SETTINGS_FILE)
327 | state = settings.value(PwndbgGuiConstants.SETTINGS_WINDOW_STATE)
328 | if state:
329 | self.restoreState(state)
330 | geometry = settings.value(PwndbgGuiConstants.SETTINGS_WINDOW_GEOMETRY)
331 | if geometry:
332 | self.restoreGeometry(geometry)
333 | splitter_sizes = settings.value(PwndbgGuiConstants.SPLITTER_GEOMETRIES)
334 | splitter_states = settings.value(PwndbgGuiConstants.SPLITTER_STATES)
335 | if splitter_sizes is not None and splitter_states is not None:
336 | logger.info("Loading existing GUI layout state from %s", settings.fileName())
337 | splitter_sizes = [QByteArray.fromBase64(size) for size in splitter_sizes.split(b',')]
338 | splitter_states = [QByteArray.fromBase64(size) for size in splitter_states.split(b',')]
339 | splitters = self.findChildren(QSplitter)
340 | for splitter, size, state in zip(splitters, splitter_sizes, splitter_states):
341 | splitter.restoreGeometry(size)
342 | splitter.restoreState(state)
343 |
344 | def attach_to_pid(self, pid: int):
345 | """
346 | Attach to the given (valid) PID. Also sets the search directories and updates the contexts after attaching
347 | :param pid: The PID of a running program
348 | """
349 | # Reset dir so that GDB doesn't get confused when we load multiple programs with the same name / source
350 | # file name
351 | # TODO: Allow user to supply dir via GUI, differentiate between user supplied dirs and automatically added by us
352 | #self.set_gdb_source_dir_signal.emit([""])
353 | # Add the directory of the executable as a search directory for source files for GDB
354 | process_path = Path(psutil.Process(pid).exe()).parent.resolve()
355 | self.set_gdb_source_dir_signal.emit([str(process_path)])
356 | # If we attach we don't want gdb to have any weired tty configs that would interfere with the inferior
357 | self.set_gdb_tty.emit("")
358 | self.set_gdb_pid_target_signal.emit([str(pid)])
359 | # When attaching to a process, GDB will immediately stop it for us allowing us to execute commands
360 | self.update_contexts.emit(True)
361 | self.main_context.inferior_attached = True
362 |
363 |
364 | def run_gui():
365 | """Start our GUI with the specified font and theme"""
366 | # Set font where characters are all equally wide (monospace) to help with formatting and alignment
367 | font = QFont(PwndbgGuiConstants.FONT)
368 | font.setStyleHint(QFont.StyleHint.Monospace)
369 | QApplication.setFont(font)
370 | app = QApplication(sys.argv)
371 |
372 | app.setStyle("Fusion")
373 | # Create a dark palette: https://stackoverflow.com/a/45634644 (Change: Fix tooltip color)
374 | dark_palette = QPalette()
375 | dark_palette.setColor(QPalette.ColorRole.Window, QColor(53, 53, 53))
376 | dark_palette.setColor(QPalette.ColorRole.WindowText, Qt.GlobalColor.white)
377 | dark_palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.WindowText, QColor(127, 127, 127))
378 | dark_palette.setColor(QPalette.ColorRole.Base, QColor(42, 42, 42))
379 | dark_palette.setColor(QPalette.ColorRole.AlternateBase, QColor(66, 66, 66))
380 | dark_palette.setColor(QPalette.ColorRole.ToolTipBase, Qt.GlobalColor.black)
381 | dark_palette.setColor(QPalette.ColorRole.ToolTipText, Qt.GlobalColor.white)
382 | dark_palette.setColor(QPalette.ColorRole.Text, Qt.GlobalColor.white)
383 | dark_palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Text, QColor(127, 127, 127))
384 | dark_palette.setColor(QPalette.ColorRole.PlaceholderText, Qt.GlobalColor.white)
385 | dark_palette.setColor(QPalette.ColorRole.Dark, QColor(35, 35, 35))
386 | dark_palette.setColor(QPalette.ColorRole.Shadow, QColor(20, 20, 20))
387 | dark_palette.setColor(QPalette.ColorRole.Button, QColor(53, 53, 53))
388 | dark_palette.setColor(QPalette.ColorRole.ButtonText, Qt.GlobalColor.white)
389 | dark_palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.ButtonText, QColor(127, 127, 127))
390 | dark_palette.setColor(QPalette.ColorRole.BrightText, Qt.GlobalColor.red)
391 | dark_palette.setColor(QPalette.ColorRole.Link, QColor(42, 130, 218))
392 | dark_palette.setColor(QPalette.ColorRole.Highlight, QColor(42, 130, 218))
393 | dark_palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Highlight, QColor(80, 80, 80))
394 | dark_palette.setColor(QPalette.ColorRole.HighlightedText, Qt.GlobalColor.white)
395 | dark_palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.HighlightedText, QColor(127, 127, 127))
396 | # Set the dark palette
397 | app.setPalette(dark_palette)
398 | # fix for Tooltip colors
399 | app.setStyleSheet("""
400 | QToolTip {
401 | background-color: #303030;
402 | color: white;
403 | }
404 | """)
405 |
406 | window = PwnDbgGui()
407 | window.showMaximized()
408 | sys.exit(app.exec())
409 |
410 |
411 | def main():
412 | logger.info("Starting GUI")
413 | run_gui()
414 |
415 |
416 | if __name__ == "__main__":
417 | main()
418 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------