diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 1f9ccf6e..00000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,108 +0,0 @@ -name: Bug Report -description: Report a bug or issue with PINCE -title: "[Bug] " -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to report a bug! Please fill out the information below to help us diagnose and fix the issue. - - - type: checkboxes - id: prerequisites - attributes: - label: Prerequisites - description: Please confirm the following before submitting your bug report - options: - - label: I have searched existing issues (both open and closed) to ensure this hasn't been reported before - required: true - - label: I have looked through the Wiki and asked (either in Discord or GitHub discussions) for topics related to my issue - required: true - - label: I have tried replicating this issue on the latest AppImage and will mention the results in description - required: true - - - type: textarea - id: description - attributes: - label: Description - description: A clear and concise description of the bug - placeholder: Tell us what happened - validations: - required: true - - - type: textarea - id: steps-to-reproduce - attributes: - label: Steps to Reproduce - description: Detailed steps to reproduce the behavior - placeholder: | - 1. Launch PINCE with 'sh PINCE.sh' - 2. Attach to process '...' - 3. Click on '...' - 4. See error - validations: - required: true - - - type: textarea - id: expected-behavior - attributes: - label: Expected Behavior - description: What you expected to happen - placeholder: Describe what should have happened - validations: - required: true - - - type: textarea - id: actual-behavior - attributes: - label: Actual Behavior - description: What actually happened - placeholder: Describe what actually happened - validations: - required: true - - - type: input - id: os - attributes: - label: Operating System - description: Distribution and version - placeholder: "e.g., Kubuntu 22.04, Arch Linux" - validations: - required: true - - - type: dropdown - id: pince-build-type - attributes: - label: PINCE Build Type - description: How did you run PINCE? - options: - - Latest AppImage - - Local dev (PINCE.sh) - - Other (not supported) - validations: - required: true - - - type: dropdown - id: target-application - attributes: - label: Target Application - description: If issue happened while attached, what type of application were you debugging? - options: - - Native (Linux x86 ELF) - - WINE/Proton - - N/A - validations: - required: true - - - type: textarea - id: logs - attributes: - label: Error Messages / Logs - description: Terminal output or /var/log/pince.log file of the session where the error happened - placeholder: Paste error messages or logs here - render: shell - - - type: textarea - id: screenshots - attributes: - label: Screenshots - description: If applicable, add screenshots to help explain the problem diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 2fe2ac82..00000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,11 +0,0 @@ -blank_issues_enabled: false -contact_links: - - name: FAQ - url: https://github.com/korcankaraokcu/PINCE/wiki/Frequently-Asked-Questions - about: Frequently Asked Questions - - name: Troubleshooting - url: https://github.com/korcankaraokcu/PINCE/wiki/Troubleshooting - about: Find solutions to known problems - - name: Discord Community - url: https://discord.gg/jVt3BzTSpz - about: Ask questions and discuss PINCE with the community diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index 50ac9e05..00000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Feature Request -description: Suggest a new feature or enhancement for PINCE -title: "[Feature Request] " -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to suggest a new feature! Please fill out the information below to help us understand your request. - - - type: checkboxes - id: prerequisites - attributes: - label: Prerequisites - description: Please confirm the following before submitting your feature request - options: - - label: I have looked through the Wiki and asked (either in Discord or GitHub discussions) to confirm this feature doesn't already exist - required: true - - label: I have searched existing issues (both open and closed) to ensure this hasn't been requested before - required: true - - - type: textarea - id: description - attributes: - label: Feature Description - description: A clear and concise description of the feature you'd like to see - placeholder: Describe the feature - validations: - required: true - - - type: textarea - id: use-case - attributes: - label: Use Case / Motivation - description: Explain why this feature would be useful and what problem it solves - placeholder: | - What problem does this solve? How would you use this feature? - Example: "When debugging games with dynamic memory allocation, it would be helpful to..." - validations: - required: true - - - type: textarea - id: examples - attributes: - label: Examples / References - description: Are there similar features in other tools (Cheat Engine, x64dbg, etc.) or examples that illustrate this feature? - placeholder: Link to documentation, screenshots, or describe similar implementations diff --git a/.github/workflows/build_docs.yml b/.github/workflows/build_docs.yml deleted file mode 100644 index c2c202a8..00000000 --- a/.github/workflows/build_docs.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: Deploy Sphinx Docs to GitHub Pages - -on: - push: - tags: - - "v*.*" - - "v*.*.*" - workflow_dispatch: - -jobs: - deploy: - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@v3 - - - name: Set up Python - uses: actions/setup-python@v3 - with: - python-version: '3.12' - - - name: Install dependencies - run: | - sudo apt install libegl1 libgirepository1.0-dev libcairo2-dev - python3 -m venv .venv - . .venv/bin/activate - pip3 install --upgrade pip - pip3 install -r requirements.txt - - - name: Install Sphinx - run: | - cd docs - ./install_sphinx.sh - - - name: Build docs - run: | - cd docs - ./build_html.sh - - - name: Deploy to GitHub Pages - uses: peaceiris/actions-gh-pages@v4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./docs/build/html - publish_branch: gh-pages - force_orphan: true - keep_files: false diff --git a/.github/workflows/release_appimage.yml b/.github/workflows/release_appimage.yml deleted file mode 100644 index 4aed085b..00000000 --- a/.github/workflows/release_appimage.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Release AppImage - -on: - push: - tags: - - "v*.*" - - "v*.*.*" - -jobs: - build: - runs-on: ubuntu-22.04 - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Install Dependencies - run: sudo apt install -y fuse3 qt6-l10n-tools patchelf - - name: Build - run: ./ci/package.sh - - name: Release - uses: softprops/action-gh-release@v2 - with: - make_latest: true - files: | - ci/PINCE-x86_64.AppImage - ci/PINCE-x86_64.AppImage.zsync diff --git a/.gitignore b/.gitignore index 65d5f239..b716a15d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,6 @@ __pycache__/ .idea/* -.vscode/* -!.vscode/launch.json -!.vscode/settings.json -libpince/libmemscan/* -libpince/libmono_collector/* -mono_collector/* -!mono_collector/*.zig -docs/build/* -*.directory -*.lprof -*.qm +.directory *.py[cod] *$py.class -gdb_pince/* -*.gnbs.conf -.venv/* -*.AppImage -*.zsync +gdb_pince/* \ No newline at end of file diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 1af2785a..00000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "libmemscan"] - path = libmemscan - url = https://github.com/brkzlr/libmemscan - ignore = dirty diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index ad488ba4..00000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Debug PINCE", - "type": "debugpy", - "request": "launch", - "cwd": "${workspaceFolder}", - "stopOnEntry": false, - "justMyCode": false, - "sudo": true, - "console": "integratedTerminal", - "program": "${workspaceFolder}/PINCE.py", - "python": "${workspaceFolder}/.venv/bin/python3" - } - ] -} diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 878f6027..00000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "[python]": { - "diffEditor.ignoreTrimWhitespace": false, - "editor.formatOnType": true, - "editor.wordBasedSuggestions": "off", - "editor.defaultFormatter": "ms-python.black-formatter", - "editor.formatOnSave": true, - "editor.formatOnSaveTimeout": 2000 - }, - "black-formatter.args": [ - "--line-length=150" - ], - "editor.tabSize": 4 -} diff --git a/AUTHORS b/AUTHORS index 10f2a9f8..b51b6a35 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,11 +1,7 @@ -Copyright (C) 2016-2020 Korcan Karaokçu -Copyright (C) 2016-2020 Çağrı Ulaş -Copyright (C) 2016-2020 Jakob Kreuze -Copyright (C) 2020 Viktor Horsmanheimo -Copyright (C) 2018 user202729 -Copyright (C) 2018 Özgür Özbek [media/logo/ozgurozbek] +Copyright (C) 2016 Korcan Karaokçu [Almost everything] +Copyright (C) 2016 Çağrı Ulaş [GUI] Copyright (C) Mark James 2005, 2006 Silk Icons [media/icons/] -Silk Icons are licensed under Creative Commons Attribution 3.0 -Unported License. See COPYING.CC-BY for conditions. +Silk Icons are licensed under a Creative Commons Attribution 3.0 +Unported License. See COPYING.CC-BY for conditions. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 10f1d72f..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,238 +0,0 @@ -# Code Structure -- [PINCE.py](./PINCE.py) - The main file, it sets up the application along with its translations and launches the [MainWindow](./GUI/Widgets/MainWindow) -- [PINCE.sh](./PINCE.sh) - Launch script -- [install.sh](./install.sh) - Installation script -- [compile_ts.sh](./compile_ts.sh) - Gathers translation information from various sources and compiles them into ts files -- [fix_ts.py](./fix_ts.py) - Fixes line information issue, used within [compile_ts.sh](./compile_ts.sh) -- [GUI](./GUI) - Contains Qt Designer forms and their respective codes along with utility functions and custom Qt classes -- [media](./media) - Contains media files such as logos and icons -- [tr](./tr) - Contains translation constants -- [docs](./docs) - Contains Sphinx documentation. The build files are automatically generated in the `gh-pages` branch. -- [i18n](./i18n) - Contains translation files. `ts` files are created with Qt Linguist and [compile_ts.sh](./compile_ts.sh), `qm` files are created within the last section of [install.sh](./install.sh) -- [mono_collector](./mono_collector) - Zig source for the collector libraries that PINCE injects into Mono/IL2CPP processes to dissect their managed runtime. Built (Linux native and WINE, x86 and x64) into `libpince/libmono_collector` by the installation script -- ### **[libpince](./libpince)** - - [debugcore.py](./libpince/debugcore.py) - Everything related to communicating with GDB and debugging - - [scancore.py](./libpince/scancore.py) - Everything related to the variable scanning backend - - [monocore.py](./libpince/monocore.py) - Everything related to dissecting the Mono/IL2CPP managed runtime - - [speedhack.py](./libpince/speedhack.py) - Everything related to speedhack functionality for Linux native and WINE/Proton processes - - [utils.py](./libpince/utils.py) - Contains generic utility functions such as parsing, file creation, process querying etc - - [typedefs.py](./libpince/typedefs.py) - Contains shared constants and data types, including the self-contained value type classes and their serialization - - [regexes.py](./libpince/regexes.py) - Contains regexes for parsing GDB output and other things - - ### **[gdb_python_scripts](./libpince/gdb_python_scripts)** - - [gdbextensions.py](./libpince/gdb_python_scripts/gdbextensions.py) - Contains custom GDB commands - - [gdbutils.py](./libpince/gdb_python_scripts/gdbutils.py) - Contains utility functions for GDB commands - -**About GUI file structure**: All GUI logic is kept in its respective folder and the GUI folder follows this structure: -``` -GUI/ -|-- AbstractTableModels/ (QAbstractTableModel classes, used by views that hold large amounts of data) -|-- ItemDelegates/ (QStyledItemDelegate classes) -|-- Labels/ (QLabel classes) -|-- Overlays/ (Classes that paint on top of existing widgets) -|-- Session/ (Session saving, loading and its data structures) -|-- Settings/ (Settings and theme handling) -|-- States/ (Globally shared GUI state such as signals and thread pools) -|-- TableViews/ (QTableView classes) -|-- TreeWidgets/ (QTreeWidget classes) -|-- Utils/ (Utility functions, shared types and custom Qt classes) -|-- Validators/ (QValidator classes) -|-- Widgets/ -| |-- Example/ -| | |-- Form/ -| | | |-- ExampleWidget.ui (Designer UI file) -| | | |-- ExampleWidget.py (Auto-generated from the UI file) -| | |-- Example.py (Form logic) -| | |-- CustomClass.py (Helper class) -``` -A good example of the structure above can be seen in [ManageScanRegions](./GUI/Widgets/ManageScanRegions) - -# AI -Using AI tools is permitted as long as all contributors fully understand all the code that they're submitting and claiming full responsibility/ownership of everything that was written and generated. - -***You must also disclose the use of AI if it has been used in any capacity and detail the extent of AI intervention***. - -Any discussions, whether it's to explain code, other PR interaction and/or anything else on the repository should be done by a person and not an AI agent. - -Failure to respect any of the rules laid above will result in an instant PR closure, no exceptions. Repeated offences will result in a repository ban. - -# Code Checking -Make good use of `python -m compileall -q .` to ensure all of the Python files do not have syntax or parsing errors before you submit a commit or PR that contains Python files changes. - -Same goes for shell scripts: run `sh -n yourscript.sh` to catch syntax errors and `shellcheck -s sh yourscript.sh` to catch portability problems before you submit. Keep in mind that `shellcheck` only sees the file you hand it, so scripts that get generated inside heredocs (such as the gdb wrapper and `AppRun.sh` in [ci/package.sh](./ci/package.sh)) need to be extracted and checked separately. - -# Code Style -***Make sure that you add type hints to all of the functions that you add or modify in .py files.*** You can follow the rest of the codebase as an example of how they should look like. - -Formatting style is [Black](https://github.com/psf/black) defaults, except line length is 150. You can use Black without parameters since we already use `pyproject.toml` for this setting. - -***You must format the files you changed using Black before you open a PR!*** Please do not format automatically generated files under GUI folder. Your changes will be overwritten by Qt Designer. More info at [UI Files](#ui-files) -- Max characters per line: 150 -- Variable naming for libpince: - - Classes: PascalCase - - Class members: snake_case - - Variables: snake_case - - Functions: snake_case - - Constants: SCREAMING_SNAKE_CASE - - Modules: flatcase - - Standalone scripts: snake_case -- Variable naming for Qt: - - Classes: PascalCase - - Class members: - - non-Qt: snake_case - - Qt: objectType + PascalCase - For example: `lineEdit_Hotkey` in [Settings.py](./GUI/Widgets/Settings/Settings.py) - - Variables: snake_case - - Functions: - - non-Qt: snake_case - - Qt: objectName + snake_case - Here's an example: `lineEdit_Hotkey_key_pressed_event` in [Settings.py](./GUI/Widgets/Settings/Settings.py) - - Constants: SCREAMING_SNAKE_CASE - - Modules: PascalCase - - Standalone scripts: snake_case - -For convenience, I'm using auto-format tool of vscode. Any modern IDE will most likely have an auto-formatting tool. -Readability and being clear is the most important aspect, so if you decide to not follow the rules, make sure that your code still reads nice and plays well with others. -If you feel unsure to which naming convention you should use, try to check out similar patterns in the code or just ask away in the PINCE discord server! - -The reason behind Qt class member naming convention is that when this project first started, supported python version didn't have type hints. -So, to have an idea about the type of the variable we are working with, I've come up with that naming idea. It's an old habit if anything. -It could maybe replaced with something else after a refactorization - -# Shell Scripts -***All `.sh` files must be POSIX shell compatible.*** Every script in the repository uses `#!/bin/sh`, which is not guaranteed to be bash. It's [dash](https://wiki.ubuntu.com/DashAsBinSh) on Debian and Ubuntu and busybox `ash` on some minimal systems, so bash-only syntax will break PINCE for those users even when it runs fine on your machine. - -These do not work in a POSIX shell, so don't use them: -- `mapfile`/`readarray`, arrays and `"${array[@]}"` -- `read -d`, here-strings (`<<< word`), `${var^^}`/`${var,,}`, `var+=value` -- `[[ ]]` tests, `==` inside `[ ]`, `function name {}` -- Process substitution (`< <(...)`), and `source` (use `.` instead) - -Watch out for these in particular, because they fail *silently* rather than erroring out: -- `&>` - dash parses it as `command &` followed by `> file`, so the command gets backgrounded and its output isn't redirected at all -- `echo -e` - dash's `echo` has no `-e` flag and prints it as part of the output. It already expands escapes, so just drop the flag -- `$'...'` - dash prints the string literally instead of expanding the escapes - -Utilities matter too, not just syntax. Not every system ships GNU coreutils, so prefer POSIX utilities and options. For example, use `env` instead of `printenv` and avoid non-POSIX flags such as `env -0`. - -# Documentation -We use Google style documentation and type hints. A good example would be `get_breakpoints_in_range` function in [debugcore.py](./libpince/debugcore.py). Root folder of libpince has 100% documentation coverage so a pull request regarding libpince has to be documented. For other places, it's enough to document the parts you think that'd be confusing to read later on. You are not obliged to document everything in other places as we are also quite lax with it - -We use Sphinx to automatically generate html files from the docs and napoleon extension to convert Google style docs to reStructuredText. To test locally, `cd` into the [docs](./docs) directory and execute `sh install_sphinx.sh`. This will install Sphinx and its extensions within the venv. After this, You can modify [source files](./docs/source) and then build html files with `sh build_html.sh` to test your changes. To create source files for multiple modules automatically, `sphinx-apidoc` can be used. For single modules, you can edit the source files manually - -[build_docs.yml](.github/workflows/build_docs.yml) workflow is responsible for automatic html generation, it gets triggered automatically whenever there's a new release or manually whenever necessary. The workflow generates files within the `gh-pages` branch. It's an orphaned branch so it can be deleted without affecting the history - -# UI Files -You need to have [Qt6 Designer](https://pkgs.org/search/?q=designer&on=files) installed. If there are no available packages for your distro, install [pyqt6-tools](https://pypi.org/project/pyqt6-tools/) instead - -Follow the steps below: -- Edit or create ui files with the designer and save them -- After saving ui files, run `sh ui_to_py.sh` within GUI folder to convert them into py files - -The py files that contains the same name with the ui files are auto-generated, please edit the ui files with designer instead of messing with the py files - -# Translation -You need to have [Qt6 Linguist](https://pkgs.org/search/?q=linguist&on=files) installed. If there are no available packages for your distro, install [pyqt6-tools](https://pypi.org/project/pyqt6-tools/) instead - -Follow the steps below: -- To create a new translation file, use [compile_ts.sh](./compile_ts.sh) with the locale as the parameter, such as `sh compile_ts.sh ja_JP`. This will create a ts file with the locale you entered. -You can skip this step if you only want to edit already existing files -- Edit ts files in [/i18n/ts](./i18n/ts) with the linguist and then save them. After saving the files, run the [compile_ts.sh](./compile_ts.sh) script. -This script fixes inconsistencies between Qt6 Linguist and pylupdate6, also removes line information so the git history stays cleaner -- To test your translations, use [install.sh](./install.sh). The last part of the installation script also compiles ts files to qm files so PINCE can process them. -When asked to recompile libmemscan, enter no - -Make sure that you read the comments in [tr.py](./tr/tr.py). Some of the translations have caveats that might interest you - -About the untranslated parts of the code, such as context menus of libpince reference widget. You'll see that some of the code serves as a placeholder that'll be -removed or replaced in the future. These are not marked as translatable as translating them would be a waste of time - -**ATTENTION:** Make sure you read this part even if you aren't a translator: -If you create or delete any Qt related string (for example, ui forms or translation constants in [tr.py](./tr/tr.py)), you must run [compile_ts.sh](./compile_ts.sh) so it updates the translations. -Not every string has to be translatable, if it's only printed on console, it can stay as is, in English. If it's shown to the user within a form, it should be translatable - -# Logo -All logo requests should be posted in `/media/logo/your_username`. Instead of opening a new issue, pull request your logo files to that folder. -Your PR must include at least one png file named pince_small, pince_medium or pince_big, according to its size. So, a minimal PR will look like this: - -`/media/logo/your_username/pince_big.png` - -pince_big is interchangeable with pince_medium and pince_small -A full PR will look like this: -``` -/media/logo/your_username/pince_big.png -/media/logo/your_username/pince_medium.png -/media/logo/your_username/pince_small.png -``` - -# Notes -Here are some notes that explains some of the caveats and hacks, they also include a timestamp. As we upgrade the libraries and the methods we are working with, -some of these notes might become obsolete. You are free to test and provide solutions to these tricks - -- 28/08/2018 - All QMessageBoxes that's called from outside of their classes(via parent() etc.) must use 'QApplication.focusWidget()' instead of 'self' in their first parameter. -Refer to issue #57 for more information - -- 23/11/2018 - Don't use get_current_item or get_current_row within currentItemChanged or currentChanged signals. -Qt doesn't update selected rows on first currentChanged or currentItemChanged calls - -- 22/05/2023 - For QTableWidget and QTableView, disabling wordWrap and using ScrollPerPixel as the horizontal scroll mode can help the user experience. -Consider doing these when creating a new QTableWidget or QTableView - -- 15/02/2024 - Don't always trust the "Adjust Size" button of the Qt Designer, it might expand widgets much more than needed, especially for smaller widgets. Consider the use cases -and adjust manually. This also helps functions like `guiutils.center_to_parent` work properly - -- 13/05/2024 - Monospace font and `utils.upper_hex` function greatly improve readability if the text area includes hex data, consider using those when creating new text areas. Memory Viewer is a good example for this - -- 13/10/2024 - Using big integers as a `pyqtSignal` param will cause them to overflow and turn into different numbers because of the type mismatch between python and cpp. Use `object` instead of `int` as param in this case. An example for this case can be seen in [BookmarkWidget](./GUI/Widgets/Bookmark/Bookmark.py) - -- 02/09/2018 - Seek methods of all file handles that read directly from the memory(/proc/pid/mem etc.) should be wrapped in a try/except block that catches both -OSError and ValueError exceptions. For instance: -```python - try: - self.memory.seek(start_addr) - except (OSError, ValueError): - break -``` -OSError handles I/O related errors and ValueError handles the off_t limit error that prints "cannot fit 'int' into an offset-sized integer" - -- 12/09/2018 - All namedtuples must have the same field name with their variable names. This makes the namedtuple transferable via pickle. For instance: -```python - tuple_examine_expression = collections.namedtuple("tuple_examine_expression", "all address symbol") -``` -- 06/10/2016 - HexView section of MemoryViewWindow.ui: Changed listWidget_HexView_Address to tableWidget_HexView_Address in order to prevent possible future visual bugs. -Logically, it should stay as a listwidget considering its functionality. But it doesn't play nice with the other neighboring tablewidgets in different pyqt versions, -forcing me to use magic numbers for adjusting, which is a bit hackish - -# Roadmap -So, after learning how to contribute, you are wondering where to start now. You can either search for `TODO` within the code or pick up any task from the roadmap below. -These tasks are ordered by importance but feel free to pick any of them. Further details can be discussed in the PINCE discord server -- Libpince support for Java (symbol recognition, calling functions, dissect obj tree etc.) -- Extend documentation to GUI parts. Libpince has 100% documentation coverage but GUI doesn't -- Flowcharts based on disassembled output -- Consider implementing a GUI for catchpoints(syscall, fork, exec etc.). Signal handling already has a GUI(HandleSignals widget), but the remaining catchpoint types are still done via the GDB Console -- Implement unrandomizer -- Automatic function bypassing(make it return the desired value, hook specific parts etc.) -- Implement auto-ESP&aimbot -- Implement thread info widget -- Write at least one test for each function in libpince -- Refactorize memory write/read functions - - ReferencedStringsWidget refreshes the cache every time the comboBox_ValueType changes, this creates serious performance issues if total results are more than 800k. - Only update the visible rows to prevent this(check ```disassemble_check_viewport``` for an example) - - Implement same system for the TrackBreakpointWidget if necessary. Do performance tests - - Put a warning for users about replacement bytes for non UTF-8 types -- Implement "Investigate Registers" button to gather information about the addresses registers point to -- Add the ability to track down registers and addresses in tracer(unsure) -- Implement CE's Ultimap-like feature for tracing data, dissect code data and raw instruction list. -Search for calls and store their hit counts to filter out the functions that haven't or have executed specific number of times. -Implement a flexible input field for the execution count. For instance, 2^x only searches for hit counts 2, 4, 8 and so on, 3x only searches for 3, 6, 9 etc. -([CE#358](https://github.com/cheat-engine/cheat-engine/issues/358)) -- Extend search_referenced_strings with relative search -- Consider adding type guessing for the StackView -- Implement a pseudo-terminal for the inferior like edb does(idk if necessary, we don't usually target CLI games, up to debate) -- Try to optimize TrackBreakpoint and TrackWatchpoint return data structures further, adding an id field might simplify traversing of the tree, performance tests are required -- Implement extra MemoryViewWindow tabs(not really critical right now, up to debate) -- ~~Consider removing the command file layer of IPC system for debugcore.send_command to speed up things~~ -[Update-29/04/2018 : Delaying this until GDB/MI implements a native multiline command feature or improves ```interpreter-exec``` command to cover every single multiline command type(including ```define``` commands)] -- Implement developer mode in settings. Developer mode will include features like dissection of GUI elements on events such as mouse-over -- Add ability to include non-absolute calls for dissect code feature(i.e call rax). Should be considered after the first version release. Might be useful for multi-breakpoint related features -- Provide information about absolute addresses in disassemble screen -- All tables that hold large amount of data should only update the visible rows(check ```disassemble_check_viewport``` for an example diff --git a/GUI/.directory b/GUI/.directory new file mode 100644 index 00000000..7240e84b --- /dev/null +++ b/GUI/.directory @@ -0,0 +1,3 @@ +[Dolphin] +Timestamp=2016,5,14,1,40,54 +Version=3 diff --git a/GUI/Widgets/About/Form/AboutWidget.py b/GUI/AboutWidget.py similarity index 75% rename from GUI/Widgets/About/Form/AboutWidget.py rename to GUI/AboutWidget.py index 8ecc8b62..4ff0ea25 100644 --- a/GUI/Widgets/About/Form/AboutWidget.py +++ b/GUI/AboutWidget.py @@ -1,13 +1,13 @@ -# Form implementation generated from reading ui file 'Widgets/About/Form/AboutWidget.ui' +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'aboutwidget.ui' # -# Created by: PyQt6 UI code generator 6.11.0 +# Created: Wed Jun 29 16:34:26 2016 +# by: PyQt5 UI code generator 5.2.1 # -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets +# WARNING! All changes made in this file will be lost! +from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TabWidget(object): def setupUi(self, TabWidget): @@ -17,7 +17,7 @@ def setupUi(self, TabWidget): self.tab_Contributors.setObjectName("tab_Contributors") self.gridLayout_2 = QtWidgets.QGridLayout(self.tab_Contributors) self.gridLayout_2.setObjectName("gridLayout_2") - self.textBrowser_Contributors = QtWidgets.QTextBrowser(parent=self.tab_Contributors) + self.textBrowser_Contributors = QtWidgets.QTextBrowser(self.tab_Contributors) self.textBrowser_Contributors.setObjectName("textBrowser_Contributors") self.gridLayout_2.addWidget(self.textBrowser_Contributors, 0, 0, 1, 1) TabWidget.addTab(self.tab_Contributors, "") @@ -25,7 +25,7 @@ def setupUi(self, TabWidget): self.tab_License.setObjectName("tab_License") self.gridLayout = QtWidgets.QGridLayout(self.tab_License) self.gridLayout.setObjectName("gridLayout") - self.textBrowser_License = QtWidgets.QTextBrowser(parent=self.tab_License) + self.textBrowser_License = QtWidgets.QTextBrowser(self.tab_License) self.textBrowser_License.setObjectName("textBrowser_License") self.gridLayout.addWidget(self.textBrowser_License, 0, 0, 1, 1) TabWidget.addTab(self.tab_License, "") @@ -39,3 +39,4 @@ def retranslateUi(self, TabWidget): TabWidget.setWindowTitle(_translate("TabWidget", "About PINCE")) TabWidget.setTabText(TabWidget.indexOf(self.tab_Contributors), _translate("TabWidget", "Contributors")) TabWidget.setTabText(TabWidget.indexOf(self.tab_License), _translate("TabWidget", "License")) + diff --git a/GUI/Widgets/About/Form/AboutWidget.ui b/GUI/AboutWidget.ui similarity index 100% rename from GUI/Widgets/About/Form/AboutWidget.ui rename to GUI/AboutWidget.ui diff --git a/GUI/AbstractTableModels/AsciiModel.py b/GUI/AbstractTableModels/AsciiModel.py deleted file mode 100644 index cae3db54..00000000 --- a/GUI/AbstractTableModels/AsciiModel.py +++ /dev/null @@ -1,31 +0,0 @@ -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtCore import QObject -from GUI.AbstractTableModels.HexModel import HexModel -from libpince import utils - - -class AsciiModel(HexModel): - def __init__(self, row_count: int, column_count: int, parent: QObject | None = None) -> None: - super().__init__(row_count, column_count, parent) - - def display_data(self, index: int) -> str: - return utils.aob_to_str(self.data_array[index]) - - def translate_data(self, data: str) -> str: - return utils.str_to_aob(data) diff --git a/GUI/AbstractTableModels/HexModel.py b/GUI/AbstractTableModels/HexModel.py deleted file mode 100644 index 83a25f87..00000000 --- a/GUI/AbstractTableModels/HexModel.py +++ /dev/null @@ -1,118 +0,0 @@ -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtCore import QAbstractTableModel, QModelIndex, QObject, Qt -from PyQt6.QtGui import QColor, QColorConstants -from libpince import utils, debugcore, typedefs -from typing import Any - - -class HexModel(QAbstractTableModel): - def __init__(self, row_count: int, column_count: int, parent: QObject | None = None) -> None: - super().__init__(parent) - self.breakpoint_list: set[int] = set() - self.row_count = row_count - self.column_count = column_count - self.current_address = 0 - offset = row_count * column_count - self.data_array = ["??"] * offset - self.cell_animation = [0] * offset - self.cell_change_color = QColor(QColorConstants.Red) - self.breakpoint_color = QColor(QColorConstants.Green) - self.breakpoint_color.setAlpha(96) - - def rowCount(self, QModelIndex_parent: QModelIndex | None = None, *args: Any, **kwargs: Any) -> int: - return self.row_count - - def set_row_count(self, row_count: int) -> None: - # Resize the model to a new row count (e.g. when the hex view is resized). - # Caller is expected to repopulate data_array by calling refresh()/update_loop(). - if row_count < 1 or row_count == self.row_count: - return - self.beginResetModel() - self.row_count = row_count - offset = row_count * self.column_count - self.data_array = ["??"] * offset - self.cell_animation = [0] * offset - self.endResetModel() - - def columnCount(self, QModelIndex_parent: QModelIndex | None = None, *args: Any, **kwargs: Any) -> int: - return self.column_count - - def flags(self, index: QModelIndex) -> Qt.ItemFlag: - return super().flags(index) | Qt.ItemFlag.ItemIsEditable - - def data(self, model_index: QModelIndex, int_role: int | None = None) -> Any: - if self.data_array and model_index.isValid(): - index = model_index.row() * self.column_count + model_index.column() - if int_role == Qt.ItemDataRole.BackgroundRole: - address = self.current_address + index - if utils.modulo_address(address, debugcore.inferior_arch) in self.breakpoint_list: - return self.breakpoint_color - self.cell_change_color.setAlpha(20 * self.cell_animation[index]) - return self.cell_change_color - elif int_role == Qt.ItemDataRole.DisplayRole: - return self.display_data(index) - - def display_data(self, index: int) -> str: - return self.data_array[index] - - def translate_data(self, data: str) -> str: - return data - - def refresh( - self, - int_address: int, - offset: int, - data_array: list[str] | None = None, - breakpoint_info: list[typedefs.tuple_breakpoint_info] | None = None, - ) -> None: - int_address = utils.modulo_address(int_address, debugcore.inferior_arch) - self.breakpoint_list.clear() - if data_array is None: - self.data_array = debugcore.hex_dump(int_address, offset) - else: - self.data_array = data_array - if breakpoint_info is None: - breakpoint_info = debugcore.get_breakpoint_info() - for bp in breakpoint_info: - if type(bp.address) != str: - continue - breakpoint_address = utils.safe_str_to_int(bp.address, 16) - for i in range(bp.size): - self.breakpoint_list.add(utils.modulo_address(breakpoint_address + i, debugcore.inferior_arch)) - self.current_address = int_address - self.cell_animation = [0] * offset - self.dataChanged.emit(self.index(0, 0), self.index(self.row_count - 1, self.column_count - 1)) - - def update_loop(self, updated_array: list[str]) -> None: - for index, item in enumerate(self.cell_animation): - if item > 0: - self.cell_animation[index] = item - 1 - for index, item in enumerate(updated_array): - if item != self.data_array[index]: - self.cell_animation[index] = 6 - self.data_array = updated_array - self.dataChanged.emit(self.index(0, 0), self.index(self.row_count - 1, self.column_count - 1)) - - def update_index(self, index: int, data: str) -> None: - data = self.translate_data(data) - if self.data_array[index] != data: - self.cell_animation[index] = 6 - self.data_array[index] = data - model_index = self.index(index // self.column_count, index % self.column_count) - self.dataChanged.emit(model_index, model_index) diff --git a/GUI/AbstractTableModels/PointerScanModel.py b/GUI/AbstractTableModels/PointerScanModel.py deleted file mode 100644 index dfebe907..00000000 --- a/GUI/AbstractTableModels/PointerScanModel.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -Copyright (C) 2026 brkzlr - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtCore import QAbstractTableModel, QModelIndex, QObject, Qt -from libpince import typedefs -from tr.tr import TranslationConstants as tr - - -def _base_sort_key(row: tuple[str, list[int]]) -> tuple[str, int]: - base = row[0] - try: - return ("", int(base, 16)) # absolute address: sorted numerically, grouped ahead of module-relative bases - except ValueError: - pass - split = max(base.rfind("+0x"), base.rfind("-0x")) # "module+/-0xHEX": group by module, then numeric offset - if split <= 0: - return (base, 0) - try: - return (base[:split], int(base[split:], 16)) - except ValueError: - return (base, 0) - - -class PointerScanModel(QAbstractTableModel): - def __init__(self, parent: QObject | None = None) -> None: - super().__init__(parent) - self.rows: list[tuple[str, list[int]]] = [] - self.offset_columns = 0 - - def set_data(self, rows: list[tuple[str, list[int]]], offset_columns: int) -> None: - self.beginResetModel() - self.rows = rows - self.offset_columns = offset_columns - self.endResetModel() - - def clear(self) -> None: - self.set_data([], 0) - - def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: - return len(self.rows) - - def columnCount(self, parent: QModelIndex = QModelIndex()) -> int: - return 1 + self.offset_columns if self.rows else 0 # 0 columns hides the header while empty - - def data(self, index: QModelIndex, role: Qt.ItemDataRole = Qt.ItemDataRole.DisplayRole) -> str | None: - if not index.isValid() or role != Qt.ItemDataRole.DisplayRole: - return None - base, offsets = self.rows[index.row()] - column = index.column() - if column == 0: - return base - return hex(offsets[column - 1]) if column - 1 < len(offsets) else "" - - def headerData(self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole = Qt.ItemDataRole.DisplayRole) -> str | None: - if role != Qt.ItemDataRole.DisplayRole or orientation != Qt.Orientation.Horizontal: - return None - return tr.BASE_ADDRESS if section == 0 else f"{tr.OFFSET} {section}" - - def sort(self, column: int, order: Qt.SortOrder = Qt.SortOrder.AscendingOrder) -> None: - if not self.rows or column < 0: - return - if column == 0: - key = _base_sort_key - else: - offset_index = column - 1 - key = lambda row: row[1][offset_index] if offset_index < len(row[1]) else float("inf") - self.beginResetModel() - self.rows.sort(key=key, reverse=order == Qt.SortOrder.DescendingOrder) - self.endResetModel() - - def pointer_chain_request(self, row: int) -> typedefs.PointerChainRequest: - base, offsets = self.rows[row] - return typedefs.PointerChainRequest(base, list(offsets)) - - def format_row(self, row: int) -> str: - base, offsets = self.rows[row] - return " -> ".join([base, *map(hex, offsets)]) diff --git a/GUI/AddAddressManuallyDialog.py b/GUI/AddAddressManuallyDialog.py new file mode 100644 index 00000000..3fc7bfc9 --- /dev/null +++ b/GUI/AddAddressManuallyDialog.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'addaddressmanuallydialog.ui' +# +# Created: Fri Jun 10 16:09:42 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_Dialog(object): + def setupUi(self, Dialog): + Dialog.setObjectName("Dialog") + Dialog.resize(374, 222) + Dialog.setMaximumSize(QtCore.QSize(374, 222)) + Dialog.setWindowTitle("") + self.verticalLayout_5 = QtWidgets.QVBoxLayout(Dialog) + self.verticalLayout_5.setObjectName("verticalLayout_5") + self.verticalLayout_2 = QtWidgets.QVBoxLayout() + self.verticalLayout_2.setObjectName("verticalLayout_2") + self.label = QtWidgets.QLabel(Dialog) + self.label.setObjectName("label") + self.verticalLayout_2.addWidget(self.label) + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setObjectName("horizontalLayout") + self.lineEdit_address = QtWidgets.QLineEdit(Dialog) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.lineEdit_address.sizePolicy().hasHeightForWidth()) + self.lineEdit_address.setSizePolicy(sizePolicy) + self.lineEdit_address.setMinimumSize(QtCore.QSize(100, 0)) + self.lineEdit_address.setText("") + self.lineEdit_address.setObjectName("lineEdit_address") + self.horizontalLayout.addWidget(self.lineEdit_address) + self.label_2 = QtWidgets.QLabel(Dialog) + self.label_2.setObjectName("label_2") + self.horizontalLayout.addWidget(self.label_2) + self.label_valueofaddress = QtWidgets.QLabel(Dialog) + self.label_valueofaddress.setObjectName("label_valueofaddress") + self.horizontalLayout.addWidget(self.label_valueofaddress) + spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout.addItem(spacerItem) + self.verticalLayout_2.addLayout(self.horizontalLayout) + self.verticalLayout_5.addLayout(self.verticalLayout_2) + self.verticalLayout = QtWidgets.QVBoxLayout() + self.verticalLayout.setObjectName("verticalLayout") + self.label_4 = QtWidgets.QLabel(Dialog) + self.label_4.setObjectName("label_4") + self.verticalLayout.addWidget(self.label_4) + self.lineEdit_description = QtWidgets.QLineEdit(Dialog) + self.lineEdit_description.setText("") + self.lineEdit_description.setObjectName("lineEdit_description") + self.verticalLayout.addWidget(self.lineEdit_description) + self.verticalLayout_5.addLayout(self.verticalLayout) + self.horizontalLayout_3 = QtWidgets.QHBoxLayout() + self.horizontalLayout_3.setObjectName("horizontalLayout_3") + self.verticalLayout_4 = QtWidgets.QVBoxLayout() + self.verticalLayout_4.setObjectName("verticalLayout_4") + self.label_5 = QtWidgets.QLabel(Dialog) + self.label_5.setObjectName("label_5") + self.verticalLayout_4.addWidget(self.label_5) + self.horizontalLayout_2 = QtWidgets.QHBoxLayout() + self.horizontalLayout_2.setObjectName("horizontalLayout_2") + self.comboBox_ValueType = QtWidgets.QComboBox(Dialog) + self.comboBox_ValueType.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) + self.comboBox_ValueType.setObjectName("comboBox_ValueType") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.horizontalLayout_2.addWidget(self.comboBox_ValueType) + self.label_length = QtWidgets.QLabel(Dialog) + self.label_length.setObjectName("label_length") + self.horizontalLayout_2.addWidget(self.label_length) + self.lineEdit_length = QtWidgets.QLineEdit(Dialog) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.lineEdit_length.sizePolicy().hasHeightForWidth()) + self.lineEdit_length.setSizePolicy(sizePolicy) + self.lineEdit_length.setInputMask("") + self.lineEdit_length.setObjectName("lineEdit_length") + self.horizontalLayout_2.addWidget(self.lineEdit_length) + spacerItem1 = QtWidgets.QSpacerItem(13, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_2.addItem(spacerItem1) + self.verticalLayout_4.addLayout(self.horizontalLayout_2) + self.horizontalLayout_3.addLayout(self.verticalLayout_4) + self.verticalLayout_3 = QtWidgets.QVBoxLayout() + self.verticalLayout_3.setObjectName("verticalLayout_3") + self.checkBox_zeroterminate = QtWidgets.QCheckBox(Dialog) + self.checkBox_zeroterminate.setChecked(True) + self.checkBox_zeroterminate.setObjectName("checkBox_zeroterminate") + self.verticalLayout_3.addWidget(self.checkBox_zeroterminate) + self.checkBox_Unicode = QtWidgets.QCheckBox(Dialog) + self.checkBox_Unicode.setObjectName("checkBox_Unicode") + self.verticalLayout_3.addWidget(self.checkBox_Unicode) + self.horizontalLayout_3.addLayout(self.verticalLayout_3) + self.verticalLayout_5.addLayout(self.horizontalLayout_3) + self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) + self.buttonBox.setObjectName("buttonBox") + self.verticalLayout_5.addWidget(self.buttonBox) + + self.retranslateUi(Dialog) + self.comboBox_ValueType.setCurrentIndex(2) + self.buttonBox.accepted.connect(Dialog.accept) + self.buttonBox.rejected.connect(Dialog.reject) + QtCore.QMetaObject.connectSlotsByName(Dialog) + + def retranslateUi(self, Dialog): + _translate = QtCore.QCoreApplication.translate + self.label.setText(_translate("Dialog", "Address:")) + self.label_2.setText(_translate("Dialog", "=")) + self.label_valueofaddress.setText(_translate("Dialog", "??")) + self.label_4.setText(_translate("Dialog", "Description:")) + self.label_5.setText(_translate("Dialog", "Type:")) + self.comboBox_ValueType.setItemText(0, _translate("Dialog", "Byte")) + self.comboBox_ValueType.setItemText(1, _translate("Dialog", "2 Bytes")) + self.comboBox_ValueType.setItemText(2, _translate("Dialog", "4 Bytes")) + self.comboBox_ValueType.setItemText(3, _translate("Dialog", "8 Bytes")) + self.comboBox_ValueType.setItemText(4, _translate("Dialog", "Float")) + self.comboBox_ValueType.setItemText(5, _translate("Dialog", "Double")) + self.comboBox_ValueType.setItemText(6, _translate("Dialog", "String")) + self.comboBox_ValueType.setItemText(7, _translate("Dialog", "Array of bytes")) + self.label_length.setText(_translate("Dialog", "Length")) + self.lineEdit_length.setText(_translate("Dialog", "10")) + self.checkBox_zeroterminate.setText(_translate("Dialog", "Zero-Terminated")) + self.checkBox_Unicode.setText(_translate("Dialog", "Unicode")) + diff --git a/GUI/AddAddressManuallyDialog.ui b/GUI/AddAddressManuallyDialog.ui new file mode 100644 index 00000000..c436ccfd --- /dev/null +++ b/GUI/AddAddressManuallyDialog.ui @@ -0,0 +1,275 @@ + + + Dialog + + + + 0 + 0 + 374 + 222 + + + + + 374 + 222 + + + + + + + + + + + + Address: + + + + + + + + + + 0 + 0 + + + + + 100 + 0 + + + + + + + + + + + = + + + + + + + ?? + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + Description: + + + + + + + + + + + + + + + + + + + + Type: + + + + + + + + + 2 + + + QComboBox::AdjustToContents + + + + Byte + + + + + 2 Bytes + + + + + 4 Bytes + + + + + 8 Bytes + + + + + Float + + + + + Double + + + + + String + + + + + Array of bytes + + + + + + + + Length + + + + + + + + 0 + 0 + + + + + + + 10 + + + + + + + Qt::Horizontal + + + + 13 + 20 + + + + + + + + + + + + + + Zero-Terminated + + + true + + + + + + + Unicode + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + Dialog + accept() + + + 280 + 371 + + + 157 + 274 + + + + + buttonBox + rejected() + Dialog + reject() + + + 280 + 371 + + + 283 + 274 + + + + + diff --git a/GUI/Widgets/Bookmark/Form/BookmarkWidget.py b/GUI/BookmarkWidget.py similarity index 70% rename from GUI/Widgets/Bookmark/Form/BookmarkWidget.py rename to GUI/BookmarkWidget.py index a3cc7cc3..72164235 100644 --- a/GUI/Widgets/Bookmark/Form/BookmarkWidget.py +++ b/GUI/BookmarkWidget.py @@ -1,13 +1,13 @@ -# Form implementation generated from reading ui file 'Widgets/Bookmark/Form/BookmarkWidget.ui' +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'bookmarkwidget.ui' # -# Created by: PyQt6 UI code generator 6.11.0 +# Created: Sat Jul 9 16:03:34 2016 +# by: PyQt5 UI code generator 5.2.1 # -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets +# WARNING! All changes made in this file will be lost! +from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): @@ -19,33 +19,30 @@ def setupUi(self, Form): self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") - self.label = QtWidgets.QLabel(parent=Form) + self.label = QtWidgets.QLabel(Form) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) - self.listWidget = QtWidgets.QListWidget(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.listWidget.setFont(font) + self.listWidget = QtWidgets.QListWidget(Form) self.listWidget.setObjectName("listWidget") self.verticalLayout.addWidget(self.listWidget) self.horizontalLayout.addLayout(self.verticalLayout) self.verticalLayout_2 = QtWidgets.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") - self.label_2 = QtWidgets.QLabel(parent=Form) + self.label_2 = QtWidgets.QLabel(Form) self.label_2.setObjectName("label_2") self.verticalLayout_2.addWidget(self.label_2) - self.lineEdit_Info = QtWidgets.QLineEdit(parent=Form) + self.lineEdit_Info = QtWidgets.QLineEdit(Form) self.lineEdit_Info.setReadOnly(True) self.lineEdit_Info.setObjectName("lineEdit_Info") self.verticalLayout_2.addWidget(self.lineEdit_Info) - self.label_3 = QtWidgets.QLabel(parent=Form) + self.label_3 = QtWidgets.QLabel(Form) self.label_3.setObjectName("label_3") self.verticalLayout_2.addWidget(self.label_3) - self.lineEdit_Comment = QtWidgets.QLineEdit(parent=Form) + self.lineEdit_Comment = QtWidgets.QLineEdit(Form) self.lineEdit_Comment.setReadOnly(True) self.lineEdit_Comment.setObjectName("lineEdit_Comment") self.verticalLayout_2.addWidget(self.lineEdit_Comment) - spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) + spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem) self.horizontalLayout.addLayout(self.verticalLayout_2) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) @@ -59,3 +56,4 @@ def retranslateUi(self, Form): self.label.setText(_translate("Form", "Bookmarked Addresses")) self.label_2.setText(_translate("Form", "Info")) self.label_3.setText(_translate("Form", "Comment")) + diff --git a/GUI/Widgets/Bookmark/Form/BookmarkWidget.ui b/GUI/BookmarkWidget.ui similarity index 91% rename from GUI/Widgets/Bookmark/Form/BookmarkWidget.ui rename to GUI/BookmarkWidget.ui index 09cbfecc..a0b7a9be 100644 --- a/GUI/Widgets/Bookmark/Form/BookmarkWidget.ui +++ b/GUI/BookmarkWidget.ui @@ -26,13 +26,7 @@ - - - - Monospace - - - + diff --git a/GUI/Widgets/Console/Form/ConsoleWidget.py b/GUI/ConsoleWidget.py similarity index 52% rename from GUI/Widgets/Console/Form/ConsoleWidget.py rename to GUI/ConsoleWidget.py index bafefa4b..29c6e48e 100644 --- a/GUI/Widgets/Console/Form/ConsoleWidget.py +++ b/GUI/ConsoleWidget.py @@ -1,19 +1,19 @@ -# Form implementation generated from reading ui file 'Widgets/Console/Form/ConsoleWidget.ui' +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'consolewidget.ui' # -# Created by: PyQt6 UI code generator 6.11.0 +# Created: Thu Jul 21 18:11:36 2016 +# by: PyQt5 UI code generator 5.2.1 # -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets +# WARNING! All changes made in this file will be lost! +from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(850, 500) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) @@ -23,55 +23,50 @@ def setupUi(self, Form): self.verticalLayout_2.setObjectName("verticalLayout_2") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") - self.textBrowser = QtWidgets.QTextBrowser(parent=Form) + self.textBrowser = QtWidgets.QTextBrowser(Form) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 255, 0)) - brush.setStyle(QtCore.Qt.BrushStyle.SolidPattern) - palette.setBrush(QtGui.QPalette.ColorGroup.Active, QtGui.QPalette.ColorRole.Text, brush) + brush.setStyle(QtCore.Qt.SolidPattern) + palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) - brush.setStyle(QtCore.Qt.BrushStyle.SolidPattern) - palette.setBrush(QtGui.QPalette.ColorGroup.Active, QtGui.QPalette.ColorRole.Base, brush) - brush = QtGui.QBrush(QtGui.QColor(0, 255, 0, 128)) - brush.setStyle(QtCore.Qt.BrushStyle.NoBrush) - palette.setBrush(QtGui.QPalette.ColorGroup.Active, QtGui.QPalette.ColorRole.PlaceholderText, brush) + brush.setStyle(QtCore.Qt.SolidPattern) + palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 255, 0)) - brush.setStyle(QtCore.Qt.BrushStyle.SolidPattern) - palette.setBrush(QtGui.QPalette.ColorGroup.Inactive, QtGui.QPalette.ColorRole.Text, brush) + brush.setStyle(QtCore.Qt.SolidPattern) + palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) - brush.setStyle(QtCore.Qt.BrushStyle.SolidPattern) - palette.setBrush(QtGui.QPalette.ColorGroup.Inactive, QtGui.QPalette.ColorRole.Base, brush) - brush = QtGui.QBrush(QtGui.QColor(0, 255, 0, 128)) - brush.setStyle(QtCore.Qt.BrushStyle.NoBrush) - palette.setBrush(QtGui.QPalette.ColorGroup.Inactive, QtGui.QPalette.ColorRole.PlaceholderText, brush) + brush.setStyle(QtCore.Qt.SolidPattern) + palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(128, 128, 128)) - brush.setStyle(QtCore.Qt.BrushStyle.SolidPattern) - palette.setBrush(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.Text, brush) + brush.setStyle(QtCore.Qt.SolidPattern) + palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) - brush.setStyle(QtCore.Qt.BrushStyle.SolidPattern) - palette.setBrush(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.Base, brush) - brush = QtGui.QBrush(QtGui.QColor(0, 255, 0, 128)) - brush.setStyle(QtCore.Qt.BrushStyle.NoBrush) - palette.setBrush(QtGui.QPalette.ColorGroup.Disabled, QtGui.QPalette.ColorRole.PlaceholderText, brush) + brush.setStyle(QtCore.Qt.SolidPattern) + palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) self.textBrowser.setPalette(palette) font = QtGui.QFont() font.setFamily("Monospace") font.setBold(False) font.setItalic(False) + font.setWeight(50) self.textBrowser.setFont(font) self.textBrowser.setObjectName("textBrowser") self.verticalLayout.addWidget(self.textBrowser) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") - self.lineEdit = QtWidgets.QLineEdit(parent=Form) + self.lineEdit = QtWidgets.QLineEdit(Form) self.lineEdit.setObjectName("lineEdit") self.horizontalLayout.addWidget(self.lineEdit) - self.pushButton_Send = QtWidgets.QPushButton(parent=Form) + self.pushButton_Send = QtWidgets.QPushButton(Form) self.pushButton_Send.setObjectName("pushButton_Send") self.horizontalLayout.addWidget(self.pushButton_Send) - self.radioButton_CLI = QtWidgets.QRadioButton(parent=Form) + self.pushButton_SendCtrl = QtWidgets.QPushButton(Form) + self.pushButton_SendCtrl.setObjectName("pushButton_SendCtrl") + self.horizontalLayout.addWidget(self.pushButton_SendCtrl) + self.radioButton_CLI = QtWidgets.QRadioButton(Form) self.radioButton_CLI.setObjectName("radioButton_CLI") self.horizontalLayout.addWidget(self.radioButton_CLI) - self.radioButton_MI = QtWidgets.QRadioButton(parent=Form) + self.radioButton_MI = QtWidgets.QRadioButton(Form) self.radioButton_MI.setChecked(True) self.radioButton_MI.setObjectName("radioButton_MI") self.horizontalLayout.addWidget(self.radioButton_MI) @@ -84,6 +79,13 @@ def setupUi(self, Form): def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "GDB Console")) + self.textBrowser.setHtml(_translate("Form", "\n" +"\n" +"


")) self.pushButton_Send.setText(_translate("Form", "Send")) + self.pushButton_SendCtrl.setText(_translate("Form", "Send ctrl+c")) self.radioButton_CLI.setText(_translate("Form", "CLI")) self.radioButton_MI.setText(_translate("Form", "MI")) + diff --git a/GUI/Widgets/Console/Form/ConsoleWidget.ui b/GUI/ConsoleWidget.ui similarity index 79% rename from GUI/Widgets/Console/Form/ConsoleWidget.ui rename to GUI/ConsoleWidget.ui index f4b589dd..51b3eba2 100644 --- a/GUI/Widgets/Console/Form/ConsoleWidget.ui +++ b/GUI/ConsoleWidget.ui @@ -51,15 +51,6 @@ - - - - 0 - 255 - 0 - - - @@ -80,15 +71,6 @@ - - - - 0 - 255 - 0 - - - @@ -109,25 +91,24 @@ - - - - 0 - 255 - 0 - - - Monospace + 50 false false + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Monospace'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + @@ -142,6 +123,13 @@ + + + + Send ctrl+c + + + diff --git a/GUI/CustomAbstractTableModels/AsciiModel.py b/GUI/CustomAbstractTableModels/AsciiModel.py new file mode 100644 index 00000000..f807f9aa --- /dev/null +++ b/GUI/CustomAbstractTableModels/AsciiModel.py @@ -0,0 +1,20 @@ +from PyQt5.QtCore import QVariant, Qt +from GUI.CustomAbstractTableModels.HexModel import QHexModel + +from libPINCE import SysUtils + + +class QAsciiModel(QHexModel): + # data_array is returned from GDB_Engine.hex_dump() + def __init__(self, row_count, column_count, data_array=None, parent=None): + super().__init__(row_count, column_count, data_array, parent) + + def data(self, QModelIndex, int_role=None): + if not QModelIndex.isValid(): + return QVariant() + elif int_role != Qt.DisplayRole: + return QVariant() + if self.data_array is None: + return QVariant() + return QVariant( + SysUtils.aob_to_ascii(self.data_array[QModelIndex.row() * self.column_count + QModelIndex.column()])) diff --git a/GUI/CustomAbstractTableModels/HexModel.py b/GUI/CustomAbstractTableModels/HexModel.py new file mode 100644 index 00000000..8f7be9e0 --- /dev/null +++ b/GUI/CustomAbstractTableModels/HexModel.py @@ -0,0 +1,29 @@ +from PyQt5.QtCore import QAbstractTableModel, QVariant, Qt + + +class QHexModel(QAbstractTableModel): + # data_array is returned from GDB_Engine.hex_dump() + def __init__(self, row_count, column_count, data_array=None, parent=None): + super().__init__(parent) + self.data_array = data_array + self.row_count = row_count + self.column_count = column_count + + def rowCount(self, QModelIndex_parent=None, *args, **kwargs): + return self.row_count + + def columnCount(self, QModelIndex_parent=None, *args, **kwargs): + return self.column_count + + def data(self, QModelIndex, int_role=None): + if not QModelIndex.isValid(): + return QVariant() + elif int_role != Qt.DisplayRole: + return QVariant() + if self.data_array is None: + return QVariant() + return QVariant(self.data_array[QModelIndex.row() * self.column_count + QModelIndex.column()]) + + def refresh(self, new_data_array): + self.data_array = new_data_array + self.layoutChanged.emit() diff --git a/GUI/CustomLabels/FlagRegisterLabel.py b/GUI/CustomLabels/FlagRegisterLabel.py new file mode 100644 index 00000000..ec178b5e --- /dev/null +++ b/GUI/CustomLabels/FlagRegisterLabel.py @@ -0,0 +1,37 @@ +from PyQt5.QtWidgets import QLabel, QMessageBox +from PyQt5.QtGui import QCursor +from PyQt5.QtCore import Qt +from libPINCE import GDB_Engine +from PINCE import DialogWithButtonsForm + + +class QFlagRegisterLabel(QLabel): + def __init__(self, parent=None): + super().__init__(parent) + + def set_value(self, value): + new = value + old = self.text() + if old != new: + self.setStyleSheet("color: red") + else: + self.setStyleSheet("color: black") + self.setText(new) + + def enterEvent(self, QEvent): + self.setCursor(QCursor(Qt.PointingHandCursor)) + + def mouseDoubleClickEvent(self, QMouseEvent): + registers = GDB_Engine.read_registers() + current_flag = self.objectName().lower() + label_text = "Enter the new value of flag " + self.objectName() + "(0 or 1)" + register_dialog = DialogWithButtonsForm(label_text=label_text, + hide_line_edit=False, line_edit_text=registers[current_flag]) + if register_dialog.exec_(): + result = register_dialog.get_values().strip() + if result == "0" or result == "1": + GDB_Engine.set_register_flag(current_flag, register_dialog.get_values()) + self.set_value(GDB_Engine.read_registers()[current_flag]) + else: + QMessageBox.information(self, "Error", "That's clearly not 0 or 1") + return diff --git a/GUI/CustomLabels/RegisterLabel.py b/GUI/CustomLabels/RegisterLabel.py new file mode 100644 index 00000000..e95b00a5 --- /dev/null +++ b/GUI/CustomLabels/RegisterLabel.py @@ -0,0 +1,31 @@ +from PyQt5.QtWidgets import QLabel +from PyQt5.QtGui import QCursor +from PyQt5.QtCore import Qt +from libPINCE import GDB_Engine +from PINCE import DialogWithButtonsForm + + +class QRegisterLabel(QLabel): + def __init__(self, parent=None): + super().__init__(parent) + + def set_value(self, value): + new = self.objectName() + "=" + value + old = self.text() + if old != new: + self.setStyleSheet("color: red") + else: + self.setStyleSheet("color: black") + self.setText(new) + + def enterEvent(self, QEvent): + self.setCursor(QCursor(Qt.PointingHandCursor)) + + def mouseDoubleClickEvent(self, QMouseEvent): + registers = GDB_Engine.read_registers() + current_register = self.objectName().lower() + register_dialog = DialogWithButtonsForm(label_text="Enter the new value of register " + self.objectName(), + hide_line_edit=False, line_edit_text=registers[current_register]) + if register_dialog.exec_(): + GDB_Engine.set_convenience_variable(current_register, register_dialog.get_values()) + self.set_value(GDB_Engine.read_registers()[current_register]) diff --git a/GUI/CustomTableViews/AsciiView.py b/GUI/CustomTableViews/AsciiView.py new file mode 100644 index 00000000..d88dfae7 --- /dev/null +++ b/GUI/CustomTableViews/AsciiView.py @@ -0,0 +1,7 @@ +from GUI.CustomTableViews.HexView import QHexView + +class QAsciiView(QHexView): + # data_array is returned from GDB_Engine.hex_dump() + def __init__(self, parent=None): + super().__init__(parent) + self.horizontalHeader().setDefaultSectionSize(15) diff --git a/GUI/CustomTableViews/HexView.py b/GUI/CustomTableViews/HexView.py new file mode 100644 index 00000000..c4bd6caa --- /dev/null +++ b/GUI/CustomTableViews/HexView.py @@ -0,0 +1,31 @@ +from PyQt5.QtWidgets import QTableView, QAbstractItemView +from PyQt5.QtCore import Qt + + +class QHexView(QTableView): + def __init__(self, parent=None): + super().__init__(parent) + self.horizontalHeader().setVisible(False) + self.verticalHeader().setVisible(False) + + # TODO: 15 is a magic number, it makes the entries in address listwidget and hexview be in the same height + # TODO: Change design of the hexview group if any display problems occur in different pyqt versions + self.verticalHeader().setDefaultSectionSize(15) + self.horizontalHeader().setDefaultSectionSize(23) + self.setStyleSheet("QTableView {background-color: transparent;}") + self.setShowGrid(False) + self.setSelectionMode(QAbstractItemView.SingleSelection) + self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.setAutoScroll(False) + + def wheelEvent(self, QWheelEvent): + QWheelEvent.ignore() + + def resize_to_contents(self): + size = self.sizeHintForColumn(0) * (self.model().columnCount() + 1) + self.setMinimumWidth(size) + self.setMaximumWidth(size) + + def get_current_offset(self): + return self.currentIndex().row() * self.model().columnCount() + self.currentIndex().column() diff --git a/GUI/DialogWithButtons.py b/GUI/DialogWithButtons.py new file mode 100644 index 00000000..fc1b2dbb --- /dev/null +++ b/GUI/DialogWithButtons.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'dialogwithbuttons.ui' +# +# Created: Sun Jun 12 15:22:56 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_Dialog(object): + def setupUi(self, Dialog): + Dialog.setObjectName("Dialog") + Dialog.resize(186, 99) + Dialog.setWindowTitle("") + self.horizontalLayout = QtWidgets.QHBoxLayout(Dialog) + self.horizontalLayout.setObjectName("horizontalLayout") + self.verticalLayout = QtWidgets.QVBoxLayout() + self.verticalLayout.setObjectName("verticalLayout") + self.label = QtWidgets.QLabel(Dialog) + self.label.setAlignment(QtCore.Qt.AlignCenter) + self.label.setObjectName("label") + self.verticalLayout.addWidget(self.label) + self.lineEdit = QtWidgets.QLineEdit(Dialog) + self.lineEdit.setObjectName("lineEdit") + self.verticalLayout.addWidget(self.lineEdit) + self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) + self.buttonBox.setCenterButtons(True) + self.buttonBox.setObjectName("buttonBox") + self.verticalLayout.addWidget(self.buttonBox) + self.horizontalLayout.addLayout(self.verticalLayout) + + self.retranslateUi(Dialog) + self.buttonBox.accepted.connect(Dialog.accept) + self.buttonBox.rejected.connect(Dialog.reject) + QtCore.QMetaObject.connectSlotsByName(Dialog) + + def retranslateUi(self, Dialog): + _translate = QtCore.QCoreApplication.translate + self.label.setText(_translate("Dialog", "TextLabel")) + diff --git a/GUI/Widgets/TextEdit/Form/TextEditDialog.ui b/GUI/DialogWithButtons.ui similarity index 51% rename from GUI/Widgets/TextEdit/Form/TextEditDialog.ui rename to GUI/DialogWithButtons.ui index b25f7653..15440d82 100644 --- a/GUI/Widgets/TextEdit/Form/TextEditDialog.ui +++ b/GUI/DialogWithButtons.ui @@ -6,30 +6,43 @@ 0 0 - 568 - 529 + 186 + 99 - Dialog + - - - - - Hit Esc to cancel and Ctrl+Enter to accept - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - + + + + + + + TextLabel + + + Qt::AlignCenter + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + true + + + + diff --git a/GUI/Widgets/FloatRegister/Form/FloatRegisterWidget.py b/GUI/FloatRegisterWidget.py similarity index 75% rename from GUI/Widgets/FloatRegister/Form/FloatRegisterWidget.py rename to GUI/FloatRegisterWidget.py index 874c316e..35aa8a46 100644 --- a/GUI/Widgets/FloatRegister/Form/FloatRegisterWidget.py +++ b/GUI/FloatRegisterWidget.py @@ -1,27 +1,26 @@ -# Form implementation generated from reading ui file 'Widgets/FloatRegister/Form/FloatRegisterWidget.ui' +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'floatregisterwidget.ui' # -# Created by: PyQt6 UI code generator 6.11.0 +# Created: Tue Jul 19 01:12:53 2016 +# by: PyQt5 UI code generator 5.2.1 # -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets +# WARNING! All changes made in this file will be lost! +from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TabWidget(object): def setupUi(self, TabWidget): TabWidget.setObjectName("TabWidget") - TabWidget.resize(400, 316) + TabWidget.resize(400, 300) self.FPU = QtWidgets.QWidget() self.FPU.setObjectName("FPU") self.gridLayout = QtWidgets.QGridLayout(self.FPU) self.gridLayout.setObjectName("gridLayout") - self.tableWidget_FPU = QtWidgets.QTableWidget(parent=self.FPU) - self.tableWidget_FPU.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_FPU.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_FPU.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_FPU.setWordWrap(False) + self.tableWidget_FPU = QtWidgets.QTableWidget(self.FPU) + self.tableWidget_FPU.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.tableWidget_FPU.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) + self.tableWidget_FPU.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.tableWidget_FPU.setObjectName("tableWidget_FPU") self.tableWidget_FPU.setColumnCount(2) self.tableWidget_FPU.setRowCount(0) @@ -32,15 +31,15 @@ def setupUi(self, TabWidget): self.tableWidget_FPU.horizontalHeader().setStretchLastSection(True) self.tableWidget_FPU.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tableWidget_FPU, 0, 0, 1, 1) - TabWidget.addTab(self.FPU, "FPU") + TabWidget.addTab(self.FPU, "") self.XMM = QtWidgets.QWidget() self.XMM.setObjectName("XMM") self.gridLayout_2 = QtWidgets.QGridLayout(self.XMM) self.gridLayout_2.setObjectName("gridLayout_2") - self.tableWidget_XMM = QtWidgets.QTableWidget(parent=self.XMM) - self.tableWidget_XMM.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_XMM.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_XMM.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) + self.tableWidget_XMM = QtWidgets.QTableWidget(self.XMM) + self.tableWidget_XMM.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.tableWidget_XMM.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) + self.tableWidget_XMM.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.tableWidget_XMM.setObjectName("tableWidget_XMM") self.tableWidget_XMM.setColumnCount(2) self.tableWidget_XMM.setRowCount(0) @@ -51,7 +50,7 @@ def setupUi(self, TabWidget): self.tableWidget_XMM.horizontalHeader().setStretchLastSection(True) self.tableWidget_XMM.verticalHeader().setVisible(False) self.gridLayout_2.addWidget(self.tableWidget_XMM, 0, 0, 1, 1) - TabWidget.addTab(self.XMM, "XMM") + TabWidget.addTab(self.XMM, "") self.retranslateUi(TabWidget) TabWidget.setCurrentIndex(0) @@ -64,7 +63,10 @@ def retranslateUi(self, TabWidget): item.setText(_translate("TabWidget", "Register")) item = self.tableWidget_FPU.horizontalHeaderItem(1) item.setText(_translate("TabWidget", "Value")) + TabWidget.setTabText(TabWidget.indexOf(self.FPU), _translate("TabWidget", "FPU")) item = self.tableWidget_XMM.horizontalHeaderItem(0) item.setText(_translate("TabWidget", "Register")) item = self.tableWidget_XMM.horizontalHeaderItem(1) item.setText(_translate("TabWidget", "Value")) + TabWidget.setTabText(TabWidget.indexOf(self.XMM), _translate("TabWidget", "XMM")) + diff --git a/GUI/Widgets/FloatRegister/Form/FloatRegisterWidget.ui b/GUI/FloatRegisterWidget.ui similarity index 93% rename from GUI/Widgets/FloatRegister/Form/FloatRegisterWidget.ui rename to GUI/FloatRegisterWidget.ui index 3719368e..3bd78037 100644 --- a/GUI/Widgets/FloatRegister/Form/FloatRegisterWidget.ui +++ b/GUI/FloatRegisterWidget.ui @@ -7,7 +7,7 @@ 0 0 400 - 316 + 300 @@ -18,7 +18,7 @@ - FPU + FPU @@ -32,9 +32,6 @@ QAbstractItemView::SelectRows - - false - true @@ -57,7 +54,7 @@ - XMM + XMM diff --git a/GUI/ItemDelegates/HexDelegate.py b/GUI/ItemDelegates/HexDelegate.py deleted file mode 100644 index da53af40..00000000 --- a/GUI/ItemDelegates/HexDelegate.py +++ /dev/null @@ -1,44 +0,0 @@ -""" -Copyright (C) Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtWidgets import QStyledItemDelegate, QLineEdit, QWidget, QStyleOptionViewItem -from PyQt6.QtGui import QRegularExpressionValidator -from PyQt6.QtCore import QModelIndex, QObject, Qt, QRegularExpression - - -class HexDelegate(QStyledItemDelegate): - def __init__(self, max_length: int = 2, regexp: str = "[0-9a-fA-F]+", parent: QObject | None = None) -> None: - super().__init__(parent) - self.max_length = max_length - self.regexp = regexp - - def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QLineEdit: - self.editor = QLineEdit(parent) - self.editor.setMaxLength(self.max_length) - hex_validator = QRegularExpressionValidator(QRegularExpression(self.regexp), self.editor) - self.editor.setValidator(hex_validator) - self.editor.setText(index.model().data(index, Qt.ItemDataRole.DisplayRole)) - self.editor.textChanged.connect(self.check_text) - return self.editor - - def setEditorData(self, editor: QWidget, index: QModelIndex) -> None: - # Initial text was set in createEditor, this is a trick to dodge the textChanged signal - return - - def check_text(self) -> None: - if len(self.editor.text()) >= self.max_length: - self.closeEditor.emit(self.editor, QStyledItemDelegate.EndEditHint.EditNextItem) diff --git a/GUI/Labels/FlagRegisterLabel.py b/GUI/Labels/FlagRegisterLabel.py deleted file mode 100644 index bcf745b6..00000000 --- a/GUI/Labels/FlagRegisterLabel.py +++ /dev/null @@ -1,59 +0,0 @@ -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtWidgets import QLabel, QMessageBox, QWidget -from PyQt6.QtGui import QCursor, QMouseEvent, QEnterEvent -from PyQt6.QtCore import Qt -from libpince import debugcore, typedefs -from GUI.Utils import guiutils, utilwidgets -from tr.tr import TranslationConstants as tr - - -class FlagRegisterLabel(QLabel): - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - - def set_value(self, value: str) -> None: - new = value - old = self.text() - if old != new: - self.setStyleSheet("color: red") - else: - self.setStyleSheet("") - self.setText(new) - - def enterEvent(self, event: QEnterEvent) -> None: - self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) - super().enterEvent(event) - - def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: - if event.button() != Qt.MouseButton.LeftButton: - return - if debugcore.currentpid == -1 or debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - # self.window() is needed to fix messagebox text color being red - QMessageBox.information(self.window(), tr.ERROR, tr.REQUIRE_PROCESS_STOP) - return - registers = debugcore.read_registers() - current_flag = self.objectName().lower() - label_text = tr.ENTER_FLAG_VALUE.format(self.objectName()) - register_dialog = utilwidgets.ComboBoxDialog(self.window(), label_text, ["0", "1"], int(registers[current_flag])) - if register_dialog.exec(): - # self.window() is needed to fix messagebox text color being red - if guiutils.check_inferior_running(self.window()): - return - debugcore.set_register_flag(current_flag, register_dialog.get_values()) - self.set_value(debugcore.read_registers()[current_flag]) diff --git a/GUI/Labels/RegisterLabel.py b/GUI/Labels/RegisterLabel.py deleted file mode 100644 index c5b251b3..00000000 --- a/GUI/Labels/RegisterLabel.py +++ /dev/null @@ -1,80 +0,0 @@ -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtWidgets import QLabel, QMenu, QApplication, QMessageBox, QWidget -from PyQt6.QtGui import QCursor, QMouseEvent, QEnterEvent, QContextMenuEvent -from PyQt6.QtCore import Qt, pyqtSignal -from libpince import debugcore, typedefs -from GUI.Utils import guiutils, utilwidgets -from tr.tr import TranslationConstants as tr - - -class RegisterLabel(QLabel): - hex_view_requested = pyqtSignal(str) - disassemble_requested = pyqtSignal(str) - - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - - def set_value(self, value: str | None) -> None: - if value is None: - value = "??" - new = self.objectName() + "=" + value - old = self.text() - if old != new: - self.setStyleSheet("color: red") - else: - self.setStyleSheet("") - self.setText(new) - - def enterEvent(self, event: QEnterEvent) -> None: - self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) - super().enterEvent(event) - - def mouseDoubleClickEvent(self, event: QMouseEvent) -> None: - if event.button() != Qt.MouseButton.LeftButton: - return - if debugcore.currentpid == -1 or debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - # self.window() is needed to fix messagebox text color being red - QMessageBox.information(self.window(), tr.ERROR, tr.REQUIRE_PROCESS_STOP) - return - registers = debugcore.read_registers() - current_register = self.objectName().lower() - items = [(tr.ENTER_REGISTER_VALUE.format(self.objectName()), registers[current_register])] - register_dialog = utilwidgets.InputDialog(self.window(), items) - if register_dialog.exec(): - # self.window() is needed to fix messagebox text color being red - if guiutils.check_inferior_running(self.window()): - return - debugcore.set_convenience_variable(current_register, register_dialog.get_values()[0]) - self.set_value(debugcore.read_registers()[current_register]) - - def contextMenuEvent(self, event: QContextMenuEvent) -> None: - menu = QMenu() - copy = menu.addAction(tr.COPY) - menu.addSeparator() - show_in_hex_view = menu.addAction(tr.SHOW_HEXVIEW) - show_in_disassembler = menu.addAction(tr.SHOW_DISASSEMBLER) - font_size = self.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - if action == show_in_hex_view: - self.hex_view_requested.emit(self.text().split("=")[-1]) - elif action == show_in_disassembler: - self.disassemble_requested.emit(self.text().split("=")[-1]) - elif action == copy: - QApplication.clipboard().setText(self.text().split("=")[1]) diff --git a/GUI/LoadingWidget.py b/GUI/LoadingWidget.py new file mode 100644 index 00000000..c0317316 --- /dev/null +++ b/GUI/LoadingWidget.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'loadingwidget.ui' +# +# Created: Fri May 13 03:12:03 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_Form(object): + def setupUi(self, Form): + Form.setObjectName("Form") + Form.setWindowModality(QtCore.Qt.WindowModal) + Form.resize(447, 300) + Form.setCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) + Form.setWindowTitle("") + Form.setAutoFillBackground(True) + self.horizontalLayout_2 = QtWidgets.QHBoxLayout(Form) + self.horizontalLayout_2.setObjectName("horizontalLayout_2") + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setObjectName("horizontalLayout") + spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout.addItem(spacerItem) + self.label_Animated = QtWidgets.QLabel(Form) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.label_Animated.sizePolicy().hasHeightForWidth()) + self.label_Animated.setSizePolicy(sizePolicy) + self.label_Animated.setText("") + self.label_Animated.setScaledContents(False) + self.label_Animated.setObjectName("label_Animated") + self.horizontalLayout.addWidget(self.label_Animated) + self.label_StatusText = QtWidgets.QLabel(Form) + self.label_StatusText.setObjectName("label_StatusText") + self.horizontalLayout.addWidget(self.label_StatusText) + spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout.addItem(spacerItem1) + self.horizontalLayout_2.addLayout(self.horizontalLayout) + + self.retranslateUi(Form) + QtCore.QMetaObject.connectSlotsByName(Form) + + def retranslateUi(self, Form): + _translate = QtCore.QCoreApplication.translate + self.label_StatusText.setText(_translate("Form", "Processing")) + diff --git a/GUI/Widgets/LoadingDialog/Form/LoadingDialog.ui b/GUI/LoadingWidget.ui similarity index 77% rename from GUI/Widgets/LoadingDialog/Form/LoadingDialog.ui rename to GUI/LoadingWidget.ui index 2c02b567..7592947d 100644 --- a/GUI/Widgets/LoadingDialog/Form/LoadingDialog.ui +++ b/GUI/LoadingWidget.ui @@ -1,17 +1,29 @@ - Dialog - + Form + + + Qt::WindowModal + 0 0 - 107 - 71 + 447 + 300 - - + + WaitCursor + + + + + + true + + + @@ -64,13 +76,6 @@ - - - - Cancel - - - diff --git a/GUI/MainWindow.py b/GUI/MainWindow.py new file mode 100644 index 00000000..c586dc41 --- /dev/null +++ b/GUI/MainWindow.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'mainwindow.ui' +# +# Created: Wed Jun 29 14:12:48 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_MainWindow(object): + def setupUi(self, MainWindow): + MainWindow.setObjectName("MainWindow") + MainWindow.resize(751, 659) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) + MainWindow.setSizePolicy(sizePolicy) + MainWindow.setMinimumSize(QtCore.QSize(751, 659)) + MainWindow.setMaximumSize(QtCore.QSize(751, 659)) + self.centralwidget = QtWidgets.QWidget(MainWindow) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) + self.centralwidget.setSizePolicy(sizePolicy) + self.centralwidget.setObjectName("centralwidget") + self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.centralwidget) + self.verticalLayout_6.setObjectName("verticalLayout_6") + self.horizontalLayout_5 = QtWidgets.QHBoxLayout() + self.horizontalLayout_5.setSizeConstraint(QtWidgets.QLayout.SetFixedSize) + self.horizontalLayout_5.setObjectName("horizontalLayout_5") + self.processbutton = QtWidgets.QPushButton(self.centralwidget) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.processbutton.sizePolicy().hasHeightForWidth()) + self.processbutton.setSizePolicy(sizePolicy) + self.processbutton.setText("") + self.processbutton.setObjectName("processbutton") + self.horizontalLayout_5.addWidget(self.processbutton) + self.pushButton_Open = QtWidgets.QPushButton(self.centralwidget) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.pushButton_Open.sizePolicy().hasHeightForWidth()) + self.pushButton_Open.setSizePolicy(sizePolicy) + self.pushButton_Open.setText("") + self.pushButton_Open.setObjectName("pushButton_Open") + self.horizontalLayout_5.addWidget(self.pushButton_Open) + self.pushButton_Save = QtWidgets.QPushButton(self.centralwidget) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.pushButton_Save.sizePolicy().hasHeightForWidth()) + self.pushButton_Save.setSizePolicy(sizePolicy) + self.pushButton_Save.setText("") + self.pushButton_Save.setObjectName("pushButton_Save") + self.horizontalLayout_5.addWidget(self.pushButton_Save) + self.pushButton_Wiki = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_Wiki.setText("") + self.pushButton_Wiki.setObjectName("pushButton_Wiki") + self.horizontalLayout_5.addWidget(self.pushButton_Wiki) + self.pushButton_About = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_About.setText("") + self.pushButton_About.setObjectName("pushButton_About") + self.horizontalLayout_5.addWidget(self.pushButton_About) + spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_5.addItem(spacerItem) + self.label_SelectedProcess = QtWidgets.QLabel(self.centralwidget) + self.label_SelectedProcess.setObjectName("label_SelectedProcess") + self.horizontalLayout_5.addWidget(self.label_SelectedProcess) + self.label_InferiorStatus = QtWidgets.QLabel(self.centralwidget) + self.label_InferiorStatus.setText("") + self.label_InferiorStatus.setObjectName("label_InferiorStatus") + self.horizontalLayout_5.addWidget(self.label_InferiorStatus) + spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_5.addItem(spacerItem1) + self.pushButton_Console = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_Console.setText("") + self.pushButton_Console.setObjectName("pushButton_Console") + self.horizontalLayout_5.addWidget(self.pushButton_Console) + self.pushButton_Settings = QtWidgets.QPushButton(self.centralwidget) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.pushButton_Settings.sizePolicy().hasHeightForWidth()) + self.pushButton_Settings.setSizePolicy(sizePolicy) + self.pushButton_Settings.setText("") + self.pushButton_Settings.setObjectName("pushButton_Settings") + self.horizontalLayout_5.addWidget(self.pushButton_Settings) + self.verticalLayout_6.addLayout(self.horizontalLayout_5) + self.horizontalLayout_9 = QtWidgets.QHBoxLayout() + self.horizontalLayout_9.setObjectName("horizontalLayout_9") + self.tableWidget_valuesearchtable = QtWidgets.QTableWidget(self.centralwidget) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.tableWidget_valuesearchtable.sizePolicy().hasHeightForWidth()) + self.tableWidget_valuesearchtable.setSizePolicy(sizePolicy) + self.tableWidget_valuesearchtable.setMinimumSize(QtCore.QSize(330, 0)) + self.tableWidget_valuesearchtable.setObjectName("tableWidget_valuesearchtable") + self.tableWidget_valuesearchtable.setColumnCount(3) + self.tableWidget_valuesearchtable.setRowCount(0) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_valuesearchtable.setHorizontalHeaderItem(0, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_valuesearchtable.setHorizontalHeaderItem(1, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_valuesearchtable.setHorizontalHeaderItem(2, item) + self.horizontalLayout_9.addWidget(self.tableWidget_valuesearchtable) + self.QWidget_Toolbox = QtWidgets.QWidget(self.centralwidget) + self.QWidget_Toolbox.setEnabled(False) + self.QWidget_Toolbox.setObjectName("QWidget_Toolbox") + self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.QWidget_Toolbox) + self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) + self.verticalLayout_5.setObjectName("verticalLayout_5") + self.horizontalLayout_6 = QtWidgets.QHBoxLayout() + self.horizontalLayout_6.setObjectName("horizontalLayout_6") + self.pushButton_NewFirstScan = QtWidgets.QPushButton(self.QWidget_Toolbox) + self.pushButton_NewFirstScan.setObjectName("pushButton_NewFirstScan") + self.horizontalLayout_6.addWidget(self.pushButton_NewFirstScan) + self.pushButton_NextScan = QtWidgets.QPushButton(self.QWidget_Toolbox) + self.pushButton_NextScan.setObjectName("pushButton_NextScan") + self.horizontalLayout_6.addWidget(self.pushButton_NextScan) + spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_6.addItem(spacerItem2) + self.pushButton_UndoScan = QtWidgets.QPushButton(self.QWidget_Toolbox) + self.pushButton_UndoScan.setObjectName("pushButton_UndoScan") + self.horizontalLayout_6.addWidget(self.pushButton_UndoScan) + self.verticalLayout_5.addLayout(self.horizontalLayout_6) + self.horizontalLayout_7 = QtWidgets.QHBoxLayout() + self.horizontalLayout_7.setObjectName("horizontalLayout_7") + self.widget = QtWidgets.QWidget(self.QWidget_Toolbox) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth()) + self.widget.setSizePolicy(sizePolicy) + self.widget.setObjectName("widget") + self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget) + self.verticalLayout_2.setSpacing(0) + self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) + self.verticalLayout_2.setObjectName("verticalLayout_2") + self.radioButton_Bits = QtWidgets.QRadioButton(self.widget) + self.radioButton_Bits.setObjectName("radioButton_Bits") + self.verticalLayout_2.addWidget(self.radioButton_Bits) + self.radioButton_Decimal = QtWidgets.QRadioButton(self.widget) + self.radioButton_Decimal.setObjectName("radioButton_Decimal") + self.verticalLayout_2.addWidget(self.radioButton_Decimal) + self.checkBox_Hex = QtWidgets.QCheckBox(self.widget) + self.checkBox_Hex.setObjectName("checkBox_Hex") + self.verticalLayout_2.addWidget(self.checkBox_Hex) + self.horizontalLayout_7.addWidget(self.widget) + self.lineEdit_Scan = QtWidgets.QLineEdit(self.QWidget_Toolbox) + self.lineEdit_Scan.setObjectName("lineEdit_Scan") + self.horizontalLayout_7.addWidget(self.lineEdit_Scan) + self.verticalLayout_5.addLayout(self.horizontalLayout_7) + self.horizontalLayout_4 = QtWidgets.QHBoxLayout() + self.horizontalLayout_4.setObjectName("horizontalLayout_4") + self.widget1 = QtWidgets.QWidget(self.QWidget_Toolbox) + self.widget1.setObjectName("widget1") + self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.widget1) + self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) + self.verticalLayout_4.setObjectName("verticalLayout_4") + self.horizontalLayout_2 = QtWidgets.QHBoxLayout() + self.horizontalLayout_2.setObjectName("horizontalLayout_2") + self.label = QtWidgets.QLabel(self.widget1) + self.label.setObjectName("label") + self.horizontalLayout_2.addWidget(self.label) + self.comboBox_ScanType = QtWidgets.QComboBox(self.widget1) + self.comboBox_ScanType.setObjectName("comboBox_ScanType") + self.horizontalLayout_2.addWidget(self.comboBox_ScanType) + self.verticalLayout_4.addLayout(self.horizontalLayout_2) + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setObjectName("horizontalLayout") + self.label_2 = QtWidgets.QLabel(self.widget1) + self.label_2.setObjectName("label_2") + self.horizontalLayout.addWidget(self.label_2) + self.comboBox_ValueType = QtWidgets.QComboBox(self.widget1) + self.comboBox_ValueType.setObjectName("comboBox_ValueType") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.comboBox_ValueType.addItem("") + self.horizontalLayout.addWidget(self.comboBox_ValueType) + self.verticalLayout_4.addLayout(self.horizontalLayout) + self.pushButton_ShowMemoryRegions = QtWidgets.QPushButton(self.widget1) + self.pushButton_ShowMemoryRegions.setObjectName("pushButton_ShowMemoryRegions") + self.verticalLayout_4.addWidget(self.pushButton_ShowMemoryRegions) + spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_4.addItem(spacerItem3) + self.horizontalLayout_4.addWidget(self.widget1) + self.widget_2 = QtWidgets.QWidget(self.QWidget_Toolbox) + self.widget_2.setObjectName("widget_2") + self.verticalLayout = QtWidgets.QVBoxLayout(self.widget_2) + self.verticalLayout.setSpacing(0) + self.verticalLayout.setContentsMargins(0, 0, 0, 0) + self.verticalLayout.setObjectName("verticalLayout") + self.radioButton_RoundedDefault = QtWidgets.QRadioButton(self.widget_2) + self.radioButton_RoundedDefault.setObjectName("radioButton_RoundedDefault") + self.verticalLayout.addWidget(self.radioButton_RoundedDefault) + self.radioButton_RoundedExtreme = QtWidgets.QRadioButton(self.widget_2) + self.radioButton_RoundedExtreme.setObjectName("radioButton_RoundedExtreme") + self.verticalLayout.addWidget(self.radioButton_RoundedExtreme) + self.radioButton_Truncated = QtWidgets.QRadioButton(self.widget_2) + self.radioButton_Truncated.setObjectName("radioButton_Truncated") + self.verticalLayout.addWidget(self.radioButton_Truncated) + self.checkBox_Unicode = QtWidgets.QCheckBox(self.widget_2) + self.checkBox_Unicode.setObjectName("checkBox_Unicode") + self.verticalLayout.addWidget(self.checkBox_Unicode) + self.checkBox_CaseSensitive = QtWidgets.QCheckBox(self.widget_2) + self.checkBox_CaseSensitive.setObjectName("checkBox_CaseSensitive") + self.verticalLayout.addWidget(self.checkBox_CaseSensitive) + self.verticalLayout_3 = QtWidgets.QVBoxLayout() + self.verticalLayout_3.setObjectName("verticalLayout_3") + spacerItem4 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_3.addItem(spacerItem4) + self.checkBox_Unrandomizer = QtWidgets.QCheckBox(self.widget_2) + self.checkBox_Unrandomizer.setObjectName("checkBox_Unrandomizer") + self.verticalLayout_3.addWidget(self.checkBox_Unrandomizer) + self.verticalLayout.addLayout(self.verticalLayout_3) + self.horizontalLayout_4.addWidget(self.widget_2) + self.verticalLayout_5.addLayout(self.horizontalLayout_4) + self.horizontalLayout_3 = QtWidgets.QHBoxLayout() + self.horizontalLayout_3.setObjectName("horizontalLayout_3") + self.verticalLayout_5.addLayout(self.horizontalLayout_3) + self.horizontalLayout_9.addWidget(self.QWidget_Toolbox) + self.verticalLayout_6.addLayout(self.horizontalLayout_9) + self.horizontalLayout_8 = QtWidgets.QHBoxLayout() + self.horizontalLayout_8.setSizeConstraint(QtWidgets.QLayout.SetMinAndMaxSize) + self.horizontalLayout_8.setObjectName("horizontalLayout_8") + self.pushButton_MemoryView = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_MemoryView.setObjectName("pushButton_MemoryView") + self.horizontalLayout_8.addWidget(self.pushButton_MemoryView) + spacerItem5 = QtWidgets.QSpacerItem(120, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_8.addItem(spacerItem5) + self.pushButton_CopyToAddressTable = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_CopyToAddressTable.setText("") + self.pushButton_CopyToAddressTable.setObjectName("pushButton_CopyToAddressTable") + self.horizontalLayout_8.addWidget(self.pushButton_CopyToAddressTable) + self.pushButton_CleanAddressTable = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_CleanAddressTable.setText("") + self.pushButton_CleanAddressTable.setObjectName("pushButton_CleanAddressTable") + self.horizontalLayout_8.addWidget(self.pushButton_CleanAddressTable) + spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_8.addItem(spacerItem6) + self.pushButton_RefreshAdressTable = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_RefreshAdressTable.setText("") + self.pushButton_RefreshAdressTable.setObjectName("pushButton_RefreshAdressTable") + self.horizontalLayout_8.addWidget(self.pushButton_RefreshAdressTable) + spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_8.addItem(spacerItem7) + self.pushButton_AddAddressManually = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_AddAddressManually.setObjectName("pushButton_AddAddressManually") + self.horizontalLayout_8.addWidget(self.pushButton_AddAddressManually) + self.verticalLayout_6.addLayout(self.horizontalLayout_8) + self.tableWidget_addresstable = QtWidgets.QTableWidget(self.centralwidget) + self.tableWidget_addresstable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.tableWidget_addresstable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) + self.tableWidget_addresstable.setObjectName("tableWidget_addresstable") + self.tableWidget_addresstable.setColumnCount(5) + self.tableWidget_addresstable.setRowCount(0) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_addresstable.setHorizontalHeaderItem(0, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_addresstable.setHorizontalHeaderItem(1, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_addresstable.setHorizontalHeaderItem(2, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_addresstable.setHorizontalHeaderItem(3, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_addresstable.setHorizontalHeaderItem(4, item) + self.tableWidget_addresstable.horizontalHeader().setStretchLastSection(True) + self.verticalLayout_6.addWidget(self.tableWidget_addresstable) + self.horizontalLayout_10 = QtWidgets.QHBoxLayout() + self.horizontalLayout_10.setObjectName("horizontalLayout_10") + self.pushButton_AdvancedOptions = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_AdvancedOptions.setObjectName("pushButton_AdvancedOptions") + self.horizontalLayout_10.addWidget(self.pushButton_AdvancedOptions) + spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_10.addItem(spacerItem8) + self.pushButton_TableExtras = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_TableExtras.setObjectName("pushButton_TableExtras") + self.horizontalLayout_10.addWidget(self.pushButton_TableExtras) + self.verticalLayout_6.addLayout(self.horizontalLayout_10) + MainWindow.setCentralWidget(self.centralwidget) + self.menubar = QtWidgets.QMenuBar(MainWindow) + self.menubar.setGeometry(QtCore.QRect(0, 0, 751, 22)) + self.menubar.setObjectName("menubar") + MainWindow.setMenuBar(self.menubar) + + self.retranslateUi(MainWindow) + self.comboBox_ValueType.setCurrentIndex(2) + QtCore.QMetaObject.connectSlotsByName(MainWindow) + + def retranslateUi(self, MainWindow): + _translate = QtCore.QCoreApplication.translate + MainWindow.setWindowTitle(_translate("MainWindow", "PINCE")) + self.processbutton.setToolTip(_translate("MainWindow", "Create or attach to a process")) + self.pushButton_Open.setToolTip(_translate("MainWindow", "Open a file, script or a cheat table")) + self.pushButton_Save.setToolTip(_translate("MainWindow", "Save current tables to a file")) + self.pushButton_Wiki.setToolTip(_translate("MainWindow", "Wiki")) + self.pushButton_About.setToolTip(_translate("MainWindow", "About")) + self.label_SelectedProcess.setText(_translate("MainWindow", "No Process Selected")) + self.pushButton_Console.setToolTip(_translate("MainWindow", "Open a gdb console")) + self.pushButton_Settings.setToolTip(_translate("MainWindow", "Configure options")) + item = self.tableWidget_valuesearchtable.horizontalHeaderItem(0) + item.setText(_translate("MainWindow", "Address")) + item = self.tableWidget_valuesearchtable.horizontalHeaderItem(1) + item.setText(_translate("MainWindow", "Value")) + item = self.tableWidget_valuesearchtable.horizontalHeaderItem(2) + item.setText(_translate("MainWindow", "Previous")) + self.pushButton_NewFirstScan.setText(_translate("MainWindow", "First Scan")) + self.pushButton_NextScan.setText(_translate("MainWindow", "Next Scan")) + self.pushButton_UndoScan.setText(_translate("MainWindow", "Undo Scan")) + self.radioButton_Bits.setText(_translate("MainWindow", "Bits")) + self.radioButton_Decimal.setText(_translate("MainWindow", "Decimal")) + self.checkBox_Hex.setText(_translate("MainWindow", "Hex")) + self.label.setText(_translate("MainWindow", "Scan Type:")) + self.label_2.setText(_translate("MainWindow", "Value Type:")) + self.comboBox_ValueType.setItemText(0, _translate("MainWindow", "Byte")) + self.comboBox_ValueType.setItemText(1, _translate("MainWindow", "2 Bytes")) + self.comboBox_ValueType.setItemText(2, _translate("MainWindow", "4 Bytes")) + self.comboBox_ValueType.setItemText(3, _translate("MainWindow", "8 Bytes")) + self.comboBox_ValueType.setItemText(4, _translate("MainWindow", "Float")) + self.comboBox_ValueType.setItemText(5, _translate("MainWindow", "Double")) + self.comboBox_ValueType.setItemText(6, _translate("MainWindow", "String")) + self.comboBox_ValueType.setItemText(7, _translate("MainWindow", "Array of bytes")) + self.pushButton_ShowMemoryRegions.setText(_translate("MainWindow", "Show Memory Regions")) + self.radioButton_RoundedDefault.setText(_translate("MainWindow", "Rounded (Default)")) + self.radioButton_RoundedExtreme.setText(_translate("MainWindow", "Rounded (Extreme)")) + self.radioButton_Truncated.setText(_translate("MainWindow", "Truncated")) + self.checkBox_Unicode.setText(_translate("MainWindow", "Unicode")) + self.checkBox_CaseSensitive.setText(_translate("MainWindow", "Case Sensitive")) + self.checkBox_Unrandomizer.setText(_translate("MainWindow", "Unrandomizer")) + self.pushButton_MemoryView.setText(_translate("MainWindow", "Memory View")) + self.pushButton_CopyToAddressTable.setToolTip(_translate("MainWindow", "Copy selected items to the address table")) + self.pushButton_CleanAddressTable.setToolTip(_translate("MainWindow", "Erase all the table contents")) + self.pushButton_RefreshAdressTable.setToolTip(_translate("MainWindow", "Refresh the address table")) + self.pushButton_AddAddressManually.setText(_translate("MainWindow", "Add Address Manually")) + item = self.tableWidget_addresstable.horizontalHeaderItem(0) + item.setText(_translate("MainWindow", "F")) + item.setToolTip(_translate("MainWindow", "Freeze the value")) + item = self.tableWidget_addresstable.horizontalHeaderItem(1) + item.setText(_translate("MainWindow", "Description")) + item = self.tableWidget_addresstable.horizontalHeaderItem(2) + item.setText(_translate("MainWindow", "Address")) + item = self.tableWidget_addresstable.horizontalHeaderItem(3) + item.setText(_translate("MainWindow", "Type")) + item = self.tableWidget_addresstable.horizontalHeaderItem(4) + item.setText(_translate("MainWindow", "Value")) + self.pushButton_AdvancedOptions.setText(_translate("MainWindow", "Advanced Options")) + self.pushButton_TableExtras.setText(_translate("MainWindow", "Table Extras")) + diff --git a/GUI/Widgets/MainWindow/Form/MainWindow.ui b/GUI/MainWindow.ui similarity index 55% rename from GUI/Widgets/MainWindow/Form/MainWindow.ui rename to GUI/MainWindow.ui index 7c991e59..16d89ec6 100644 --- a/GUI/Widgets/MainWindow/Form/MainWindow.ui +++ b/GUI/MainWindow.ui @@ -6,50 +6,86 @@ 0 0 - 768 - 664 + 751 + 659 + + + 0 + 0 + + + + + 751 + 659 + + + + + 751 + 659 + + - PINCE + PINCE - - - + + + 0 + 0 + + + + + - QLayout::SizeConstraint::SetMinAndMaxSize + QLayout::SetFixedSize - - - false + + + + 0 + 0 + + + + Create or attach to a process - Memory View + - - - Qt::Orientation::Horizontal + + + + 0 + 0 + - - QSizePolicy::Policy::Fixed + + Open a file, script or a cheat table - - - 120 - 20 - + + - + - + + + + 0 + 0 + + - Copy selected items to the address table + Save current tables to a file @@ -57,9 +93,9 @@ - + - Erase all the table contents + Wiki @@ -67,9 +103,19 @@ - + + + About + + + + + + + + - Qt::Orientation::Horizontal + Qt::Horizontal @@ -80,19 +126,23 @@ - - - Refresh the address table[R] + + + No Process Selected + + + + - + - Qt::Orientation::Horizontal + Qt::Horizontal @@ -103,155 +153,74 @@ - - - false + + + Open a gdb console - Add Address Manually + + + + + + + + + 0 + 0 + + + + Configure options + + + - - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - QAbstractItemView::DragDropMode::DragDrop - - - Qt::DropAction::MoveAction - - - QAbstractItemView::SelectionMode::ExtendedSelection - - - 12 - - - true - - - false - - - - Freeze - - - Freeze the value. Click just to the right of checkbox to cycle between freeze types: -- No arrow: Frozen at current value -- ▲: Allow increments only -- ▼: Allow decrements only - - - - - Description - - - - - Address - - - - - Type - - - - - Value - - - - - + - - - - - Match count: 0 - - - - - - - true - - - false - - - Qt::ScrollBarPolicy::ScrollBarAlwaysOff - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - true - - - QAbstractItemView::SelectionBehavior::SelectRows - - - false - - - true - - - false - - - true - - - true - - - false - - - 20 - - - 23 - - - - Address - - - - - Value - - - - - Previous - - - - - + + + + 0 + 0 + + + + + 330 + 0 + + + + + Address + + + + + Value + + + + + Previous + + + - + false - + @@ -269,7 +238,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -279,13 +248,6 @@ - - - - Cancel Scan - - - @@ -296,49 +258,69 @@ - - - - 0 - - - 0 - - - 0 - - - - - Hex + + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 - - - - - - - - - <-> + + 0 - - - - - - - + + + + Bits + + + + + + + Decimal + + + + + + + Hex + + + + + + + + + + - + - + - + - + Scan Type: @@ -350,72 +332,74 @@ - + - + Value Type: - - - - - - - - - - Scan Scope: - - - - - - - - - - - - - - Endianness: + + + 2 + + + Byte + + + + + 2 Bytes + + + + + 4 Bytes + + + + + 8 Bytes + + + + + Float + + + + + Double + + + + + String + + + + + Array of bytes + + - - - - - - - - Alignment: - - - - - - - - - - + - Manage Scan Regions + Show Memory Regions - + - Qt::Orientation::Vertical + Qt::Vertical @@ -429,7 +413,7 @@ - + 0 @@ -446,41 +430,47 @@ 0 + + + + Rounded (Default) + + + + + + + Rounded (Extreme) + + + + + + + Truncated + + + + + + + Unicode + + + + + + + Case Sensitive + + + - - - - Enable Speedhack - - - - - - - false - - - 1 - - - 0.200000000000000 - - - 10.000000000000000 - - - 0.100000000000000 - - - 1.000000000000000 - - - - Qt::Orientation::Vertical + Qt::Vertical @@ -490,6 +480,13 @@ + + + + Unrandomizer + + + @@ -497,53 +494,46 @@ + + + - - + + + + QLayout::SetMinAndMaxSize + - + + + Memory View + + + + + - Qt::Orientation::Horizontal + Qt::Horizontal + + + QSizePolicy::Fixed - 40 + 120 20 - - - Open session notes - - - Notes - - - - - - - - - QLayout::SizeConstraint::SetFixedSize - - - - - - 0 - 0 - - + - Create or attach to a process + Copy selected items to the address table @@ -551,15 +541,9 @@ - - - - 0 - 0 - - + - Open a cheat table + Erase all the table contents @@ -567,25 +551,22 @@ - - - - 0 - 0 - - - - Save current table to a file + + + Qt::Horizontal - - + + + 40 + 20 + - + - + - Wiki + Refresh the address table @@ -593,75 +574,94 @@ - - - About + + + Qt::Horizontal - - + + + 40 + 20 + - + - + - No Process Selected + Add Address Manually + + + + + + QAbstractItemView::NoEditTriggers + + + QAbstractItemView::SelectRows + + + true + + + + F + + + Freeze the value + + + + + Description + + + + + Address + + + + + Type + + + + + Value + + + + + + - + - + Advanced Options - - - 0 - + - Qt::Orientation::Horizontal - - - - - - - Open a gdb console - - - - - - - - - - false + Qt::Horizontal - - Check for updates - - - + + + 40 + 20 + - + - - - - 0 - 0 - - - - Configure options - + - + Table Extras @@ -674,19 +674,12 @@ 0 0 - 768 - 32 + 751 + 22 - - - AddressTree - QTreeWidget -
GUI.TreeWidgets.AddressTree
-
-
diff --git a/GUI/MemoryViewerWindow.py b/GUI/MemoryViewerWindow.py new file mode 100644 index 00000000..1c464535 --- /dev/null +++ b/GUI/MemoryViewerWindow.py @@ -0,0 +1,783 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'MemoryViewerWindow.ui' +# +# Created: Tue Sep 13 20:06:27 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_MainWindow(object): + def setupUi(self, MainWindow): + MainWindow.setObjectName("MainWindow") + MainWindow.resize(800, 600) + self.centralwidget = QtWidgets.QWidget(MainWindow) + self.centralwidget.setObjectName("centralwidget") + self.gridLayout_5 = QtWidgets.QGridLayout(self.centralwidget) + self.gridLayout_5.setObjectName("gridLayout_5") + self.splitter_MainMiddle = QtWidgets.QSplitter(self.centralwidget) + self.splitter_MainMiddle.setLineWidth(1) + self.splitter_MainMiddle.setOrientation(QtCore.Qt.Vertical) + self.splitter_MainMiddle.setOpaqueResize(True) + self.splitter_MainMiddle.setHandleWidth(10) + self.splitter_MainMiddle.setChildrenCollapsible(True) + self.splitter_MainMiddle.setObjectName("splitter_MainMiddle") + self.splitter_Disassemble_Registers = QtWidgets.QSplitter(self.splitter_MainMiddle) + self.splitter_Disassemble_Registers.setOrientation(QtCore.Qt.Horizontal) + self.splitter_Disassemble_Registers.setHandleWidth(10) + self.splitter_Disassemble_Registers.setObjectName("splitter_Disassemble_Registers") + self.widget_Disassemble = QtWidgets.QWidget(self.splitter_Disassemble_Registers) + self.widget_Disassemble.setObjectName("widget_Disassemble") + self.gridLayout_2 = QtWidgets.QGridLayout(self.widget_Disassemble) + self.gridLayout_2.setContentsMargins(0, 0, 0, 0) + self.gridLayout_2.setObjectName("gridLayout_2") + self.tableWidget_Disassemble = QtWidgets.QTableWidget(self.widget_Disassemble) + font = QtGui.QFont() + font.setPointSize(9) + self.tableWidget_Disassemble.setFont(font) + self.tableWidget_Disassemble.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) + self.tableWidget_Disassemble.setAutoScroll(False) + self.tableWidget_Disassemble.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.tableWidget_Disassemble.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) + self.tableWidget_Disassemble.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) + self.tableWidget_Disassemble.setObjectName("tableWidget_Disassemble") + self.tableWidget_Disassemble.setColumnCount(4) + self.tableWidget_Disassemble.setRowCount(0) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Disassemble.setHorizontalHeaderItem(0, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Disassemble.setHorizontalHeaderItem(1, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Disassemble.setHorizontalHeaderItem(2, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Disassemble.setHorizontalHeaderItem(3, item) + self.tableWidget_Disassemble.horizontalHeader().setStretchLastSection(True) + self.tableWidget_Disassemble.verticalHeader().setVisible(False) + self.tableWidget_Disassemble.verticalHeader().setDefaultSectionSize(15) + self.tableWidget_Disassemble.verticalHeader().setStretchLastSection(False) + self.gridLayout_2.addWidget(self.tableWidget_Disassemble, 0, 0, 1, 1) + self.verticalScrollBar_Disassemble = QtWidgets.QScrollBar(self.widget_Disassemble) + self.verticalScrollBar_Disassemble.setOrientation(QtCore.Qt.Vertical) + self.verticalScrollBar_Disassemble.setObjectName("verticalScrollBar_Disassemble") + self.gridLayout_2.addWidget(self.verticalScrollBar_Disassemble, 0, 1, 1, 1) + self.widget_Registers = QtWidgets.QWidget(self.splitter_Disassemble_Registers) + self.widget_Registers.setMinimumSize(QtCore.QSize(0, 0)) + self.widget_Registers.setObjectName("widget_Registers") + self.gridLayout_4 = QtWidgets.QGridLayout(self.widget_Registers) + self.gridLayout_4.setContentsMargins(0, 0, 0, 0) + self.gridLayout_4.setObjectName("gridLayout_4") + self.scrollArea_Registers = QtWidgets.QScrollArea(self.widget_Registers) + self.scrollArea_Registers.setWidgetResizable(True) + self.scrollArea_Registers.setObjectName("scrollArea_Registers") + self.scrollAreaWidgetContents_Registers = QtWidgets.QWidget() + self.scrollAreaWidgetContents_Registers.setGeometry(QtCore.QRect(0, 0, 352, 439)) + self.scrollAreaWidgetContents_Registers.setObjectName("scrollAreaWidgetContents_Registers") + self.gridLayout_8 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_Registers) + self.gridLayout_8.setObjectName("gridLayout_8") + self.horizontalLayout_4 = QtWidgets.QHBoxLayout() + self.horizontalLayout_4.setObjectName("horizontalLayout_4") + self.verticalLayout_19 = QtWidgets.QVBoxLayout() + self.verticalLayout_19.setObjectName("verticalLayout_19") + self.label_3 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_3.setFont(font) + self.label_3.setObjectName("label_3") + self.verticalLayout_19.addWidget(self.label_3) + self.line = QtWidgets.QFrame(self.scrollAreaWidgetContents_Registers) + self.line.setFrameShape(QtWidgets.QFrame.HLine) + self.line.setFrameShadow(QtWidgets.QFrame.Sunken) + self.line.setObjectName("line") + self.verticalLayout_19.addWidget(self.line) + self.stackedWidget = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents_Registers) + self.stackedWidget.setMaximumSize(QtCore.QSize(16777215, 200)) + self.stackedWidget.setObjectName("stackedWidget") + self.registers_64 = QtWidgets.QWidget() + self.registers_64.setObjectName("registers_64") + self.gridLayout_7 = QtWidgets.QGridLayout(self.registers_64) + self.gridLayout_7.setObjectName("gridLayout_7") + self.verticalLayout_17 = QtWidgets.QVBoxLayout() + self.verticalLayout_17.setObjectName("verticalLayout_17") + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setObjectName("horizontalLayout") + self.verticalLayout_16 = QtWidgets.QVBoxLayout() + self.verticalLayout_16.setObjectName("verticalLayout_16") + self.RAX = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RAX.setFont(font) + self.RAX.setObjectName("RAX") + self.verticalLayout_16.addWidget(self.RAX) + self.RBX = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RBX.setFont(font) + self.RBX.setObjectName("RBX") + self.verticalLayout_16.addWidget(self.RBX) + self.RCX = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RCX.setFont(font) + self.RCX.setObjectName("RCX") + self.verticalLayout_16.addWidget(self.RCX) + self.RDX = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RDX.setFont(font) + self.RDX.setObjectName("RDX") + self.verticalLayout_16.addWidget(self.RDX) + self.RSI = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RSI.setFont(font) + self.RSI.setObjectName("RSI") + self.verticalLayout_16.addWidget(self.RSI) + self.RDI = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RDI.setFont(font) + self.RDI.setObjectName("RDI") + self.verticalLayout_16.addWidget(self.RDI) + self.RBP = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RBP.setFont(font) + self.RBP.setObjectName("RBP") + self.verticalLayout_16.addWidget(self.RBP) + self.RSP = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RSP.setFont(font) + self.RSP.setObjectName("RSP") + self.verticalLayout_16.addWidget(self.RSP) + self.horizontalLayout.addLayout(self.verticalLayout_16) + spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout.addItem(spacerItem) + self.verticalLayout_3 = QtWidgets.QVBoxLayout() + self.verticalLayout_3.setObjectName("verticalLayout_3") + self.R8 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R8.setFont(font) + self.R8.setObjectName("R8") + self.verticalLayout_3.addWidget(self.R8) + self.R9 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R9.setFont(font) + self.R9.setObjectName("R9") + self.verticalLayout_3.addWidget(self.R9) + self.R10 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R10.setFont(font) + self.R10.setObjectName("R10") + self.verticalLayout_3.addWidget(self.R10) + self.R11 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R11.setFont(font) + self.R11.setObjectName("R11") + self.verticalLayout_3.addWidget(self.R11) + self.R12 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R12.setFont(font) + self.R12.setObjectName("R12") + self.verticalLayout_3.addWidget(self.R12) + self.R13 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R13.setFont(font) + self.R13.setObjectName("R13") + self.verticalLayout_3.addWidget(self.R13) + self.R14 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R14.setFont(font) + self.R14.setObjectName("R14") + self.verticalLayout_3.addWidget(self.R14) + self.R15 = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.R15.setFont(font) + self.R15.setObjectName("R15") + self.verticalLayout_3.addWidget(self.R15) + self.horizontalLayout.addLayout(self.verticalLayout_3) + self.verticalLayout_17.addLayout(self.horizontalLayout) + self.horizontalLayout_18 = QtWidgets.QHBoxLayout() + self.horizontalLayout_18.setObjectName("horizontalLayout_18") + self.RIP = QRegisterLabel(self.registers_64) + font = QtGui.QFont() + font.setPointSize(9) + self.RIP.setFont(font) + self.RIP.setObjectName("RIP") + self.horizontalLayout_18.addWidget(self.RIP) + spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_18.addItem(spacerItem1) + self.verticalLayout_17.addLayout(self.horizontalLayout_18) + spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_17.addItem(spacerItem2) + self.gridLayout_7.addLayout(self.verticalLayout_17, 0, 0, 1, 1) + self.stackedWidget.addWidget(self.registers_64) + self.registers_32 = QtWidgets.QWidget() + self.registers_32.setObjectName("registers_32") + self.gridLayout_6 = QtWidgets.QGridLayout(self.registers_32) + self.gridLayout_6.setObjectName("gridLayout_6") + self.verticalLayout_14 = QtWidgets.QVBoxLayout() + self.verticalLayout_14.setObjectName("verticalLayout_14") + self.horizontalLayout_3 = QtWidgets.QHBoxLayout() + self.horizontalLayout_3.setObjectName("horizontalLayout_3") + self.verticalLayout_2 = QtWidgets.QVBoxLayout() + self.verticalLayout_2.setObjectName("verticalLayout_2") + self.EAX = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.EAX.setFont(font) + self.EAX.setObjectName("EAX") + self.verticalLayout_2.addWidget(self.EAX) + self.EBX = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.EBX.setFont(font) + self.EBX.setObjectName("EBX") + self.verticalLayout_2.addWidget(self.EBX) + self.ECX = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.ECX.setFont(font) + self.ECX.setObjectName("ECX") + self.verticalLayout_2.addWidget(self.ECX) + self.EDX = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.EDX.setFont(font) + self.EDX.setObjectName("EDX") + self.verticalLayout_2.addWidget(self.EDX) + self.ESI = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.ESI.setFont(font) + self.ESI.setObjectName("ESI") + self.verticalLayout_2.addWidget(self.ESI) + self.EDI = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.EDI.setFont(font) + self.EDI.setObjectName("EDI") + self.verticalLayout_2.addWidget(self.EDI) + self.EBP = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.EBP.setFont(font) + self.EBP.setObjectName("EBP") + self.verticalLayout_2.addWidget(self.EBP) + self.ESP = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.ESP.setFont(font) + self.ESP.setObjectName("ESP") + self.verticalLayout_2.addWidget(self.ESP) + self.EIP = QRegisterLabel(self.registers_32) + font = QtGui.QFont() + font.setPointSize(9) + self.EIP.setFont(font) + self.EIP.setObjectName("EIP") + self.verticalLayout_2.addWidget(self.EIP) + self.horizontalLayout_3.addLayout(self.verticalLayout_2) + spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_3.addItem(spacerItem3) + self.verticalLayout_14.addLayout(self.horizontalLayout_3) + spacerItem4 = QtWidgets.QSpacerItem(156, 16, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_14.addItem(spacerItem4) + self.gridLayout_6.addLayout(self.verticalLayout_14, 0, 0, 1, 1) + self.stackedWidget.addWidget(self.registers_32) + self.verticalLayout_19.addWidget(self.stackedWidget) + self.label_29 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_29.setFont(font) + self.label_29.setObjectName("label_29") + self.verticalLayout_19.addWidget(self.label_29) + self.line_2 = QtWidgets.QFrame(self.scrollAreaWidgetContents_Registers) + self.line_2.setFrameShape(QtWidgets.QFrame.HLine) + self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) + self.line_2.setObjectName("line_2") + self.verticalLayout_19.addWidget(self.line_2) + self.horizontalLayout_21 = QtWidgets.QHBoxLayout() + self.horizontalLayout_21.setObjectName("horizontalLayout_21") + self.verticalLayout_5 = QtWidgets.QVBoxLayout() + self.verticalLayout_5.setObjectName("verticalLayout_5") + self.label_31 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_31.setFont(font) + self.label_31.setObjectName("label_31") + self.verticalLayout_5.addWidget(self.label_31) + self.CF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.CF.setFont(font) + self.CF.setObjectName("CF") + self.verticalLayout_5.addWidget(self.CF) + self.horizontalLayout_21.addLayout(self.verticalLayout_5) + self.verticalLayout_6 = QtWidgets.QVBoxLayout() + self.verticalLayout_6.setObjectName("verticalLayout_6") + self.label_35 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_35.setFont(font) + self.label_35.setObjectName("label_35") + self.verticalLayout_6.addWidget(self.label_35) + self.PF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.PF.setFont(font) + self.PF.setObjectName("PF") + self.verticalLayout_6.addWidget(self.PF) + self.horizontalLayout_21.addLayout(self.verticalLayout_6) + self.verticalLayout_7 = QtWidgets.QVBoxLayout() + self.verticalLayout_7.setObjectName("verticalLayout_7") + self.label_37 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_37.setFont(font) + self.label_37.setObjectName("label_37") + self.verticalLayout_7.addWidget(self.label_37) + self.AF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.AF.setFont(font) + self.AF.setObjectName("AF") + self.verticalLayout_7.addWidget(self.AF) + self.horizontalLayout_21.addLayout(self.verticalLayout_7) + self.verticalLayout_8 = QtWidgets.QVBoxLayout() + self.verticalLayout_8.setObjectName("verticalLayout_8") + self.label_39 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_39.setFont(font) + self.label_39.setObjectName("label_39") + self.verticalLayout_8.addWidget(self.label_39) + self.ZF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.ZF.setFont(font) + self.ZF.setObjectName("ZF") + self.verticalLayout_8.addWidget(self.ZF) + self.horizontalLayout_21.addLayout(self.verticalLayout_8) + self.verticalLayout_9 = QtWidgets.QVBoxLayout() + self.verticalLayout_9.setObjectName("verticalLayout_9") + self.label_41 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_41.setFont(font) + self.label_41.setObjectName("label_41") + self.verticalLayout_9.addWidget(self.label_41) + self.SF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.SF.setFont(font) + self.SF.setObjectName("SF") + self.verticalLayout_9.addWidget(self.SF) + self.horizontalLayout_21.addLayout(self.verticalLayout_9) + self.verticalLayout_10 = QtWidgets.QVBoxLayout() + self.verticalLayout_10.setObjectName("verticalLayout_10") + self.label_43 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_43.setFont(font) + self.label_43.setObjectName("label_43") + self.verticalLayout_10.addWidget(self.label_43) + self.TF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.TF.setFont(font) + self.TF.setObjectName("TF") + self.verticalLayout_10.addWidget(self.TF) + self.horizontalLayout_21.addLayout(self.verticalLayout_10) + self.verticalLayout_11 = QtWidgets.QVBoxLayout() + self.verticalLayout_11.setObjectName("verticalLayout_11") + self.label_45 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_45.setFont(font) + self.label_45.setObjectName("label_45") + self.verticalLayout_11.addWidget(self.label_45) + self.IF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.IF.setFont(font) + self.IF.setObjectName("IF") + self.verticalLayout_11.addWidget(self.IF) + self.horizontalLayout_21.addLayout(self.verticalLayout_11) + self.verticalLayout_12 = QtWidgets.QVBoxLayout() + self.verticalLayout_12.setObjectName("verticalLayout_12") + self.label_47 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_47.setFont(font) + self.label_47.setObjectName("label_47") + self.verticalLayout_12.addWidget(self.label_47) + self.DF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.DF.setFont(font) + self.DF.setObjectName("DF") + self.verticalLayout_12.addWidget(self.DF) + self.horizontalLayout_21.addLayout(self.verticalLayout_12) + self.verticalLayout_13 = QtWidgets.QVBoxLayout() + self.verticalLayout_13.setObjectName("verticalLayout_13") + self.label_49 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_49.setFont(font) + self.label_49.setObjectName("label_49") + self.verticalLayout_13.addWidget(self.label_49) + self.OF = QFlagRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.OF.setFont(font) + self.OF.setObjectName("OF") + self.verticalLayout_13.addWidget(self.OF) + self.horizontalLayout_21.addLayout(self.verticalLayout_13) + self.verticalLayout_19.addLayout(self.horizontalLayout_21) + self.label_30 = QtWidgets.QLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.label_30.setFont(font) + self.label_30.setObjectName("label_30") + self.verticalLayout_19.addWidget(self.label_30) + self.line_3 = QtWidgets.QFrame(self.scrollAreaWidgetContents_Registers) + self.line_3.setFrameShape(QtWidgets.QFrame.HLine) + self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken) + self.line_3.setObjectName("line_3") + self.verticalLayout_19.addWidget(self.line_3) + self.horizontalLayout_2 = QtWidgets.QHBoxLayout() + self.horizontalLayout_2.setObjectName("horizontalLayout_2") + self.verticalLayout_4 = QtWidgets.QVBoxLayout() + self.verticalLayout_4.setObjectName("verticalLayout_4") + self.CS = QRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.CS.setFont(font) + self.CS.setObjectName("CS") + self.verticalLayout_4.addWidget(self.CS) + self.ES = QRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.ES.setFont(font) + self.ES.setObjectName("ES") + self.verticalLayout_4.addWidget(self.ES) + self.horizontalLayout_2.addLayout(self.verticalLayout_4) + spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_2.addItem(spacerItem5) + self.verticalLayout_15 = QtWidgets.QVBoxLayout() + self.verticalLayout_15.setObjectName("verticalLayout_15") + self.SS = QRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.SS.setFont(font) + self.SS.setObjectName("SS") + self.verticalLayout_15.addWidget(self.SS) + self.GS = QRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.GS.setFont(font) + self.GS.setObjectName("GS") + self.verticalLayout_15.addWidget(self.GS) + self.horizontalLayout_2.addLayout(self.verticalLayout_15) + spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_2.addItem(spacerItem6) + self.verticalLayout_18 = QtWidgets.QVBoxLayout() + self.verticalLayout_18.setObjectName("verticalLayout_18") + self.DS = QRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.DS.setFont(font) + self.DS.setObjectName("DS") + self.verticalLayout_18.addWidget(self.DS) + self.FS = QRegisterLabel(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.FS.setFont(font) + self.FS.setObjectName("FS") + self.verticalLayout_18.addWidget(self.FS) + self.horizontalLayout_2.addLayout(self.verticalLayout_18) + self.verticalLayout_19.addLayout(self.horizontalLayout_2) + self.pushButton_ShowFloatRegisters = QtWidgets.QPushButton(self.scrollAreaWidgetContents_Registers) + font = QtGui.QFont() + font.setPointSize(9) + self.pushButton_ShowFloatRegisters.setFont(font) + self.pushButton_ShowFloatRegisters.setObjectName("pushButton_ShowFloatRegisters") + self.verticalLayout_19.addWidget(self.pushButton_ShowFloatRegisters) + spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_19.addItem(spacerItem7) + self.horizontalLayout_4.addLayout(self.verticalLayout_19) + spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_4.addItem(spacerItem8) + self.gridLayout_8.addLayout(self.horizontalLayout_4, 0, 0, 1, 1) + self.scrollArea_Registers.setWidget(self.scrollAreaWidgetContents_Registers) + self.gridLayout_4.addWidget(self.scrollArea_Registers, 0, 0, 1, 1) + self.splitter_HexView_StackView = QtWidgets.QSplitter(self.splitter_MainMiddle) + self.splitter_HexView_StackView.setOrientation(QtCore.Qt.Horizontal) + self.splitter_HexView_StackView.setHandleWidth(10) + self.splitter_HexView_StackView.setObjectName("splitter_HexView_StackView") + self.widget_HexView = QtWidgets.QWidget(self.splitter_HexView_StackView) + self.widget_HexView.setObjectName("widget_HexView") + self.gridLayout = QtWidgets.QGridLayout(self.widget_HexView) + self.gridLayout.setContentsMargins(0, 0, 0, 0) + self.gridLayout.setObjectName("gridLayout") + self.scrollArea_Hex = QtWidgets.QScrollArea(self.widget_HexView) + self.scrollArea_Hex.setWidgetResizable(True) + self.scrollArea_Hex.setObjectName("scrollArea_Hex") + self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() + self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 473, 196)) + self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2") + self.gridLayout_11 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_2) + self.gridLayout_11.setObjectName("gridLayout_11") + self.horizontalLayout_5 = QtWidgets.QHBoxLayout() + self.horizontalLayout_5.setObjectName("horizontalLayout_5") + self.listWidget_HexView_Address = QtWidgets.QListWidget(self.scrollAreaWidgetContents_2) + self.listWidget_HexView_Address.setObjectName("listWidget_HexView_Address") + self.horizontalLayout_5.addWidget(self.listWidget_HexView_Address) + self.line_5 = QtWidgets.QFrame(self.scrollAreaWidgetContents_2) + self.line_5.setFrameShape(QtWidgets.QFrame.VLine) + self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken) + self.line_5.setObjectName("line_5") + self.horizontalLayout_5.addWidget(self.line_5) + self.tableView_HexView_Hex = QHexView(self.scrollAreaWidgetContents_2) + self.tableView_HexView_Hex.setObjectName("tableView_HexView_Hex") + self.horizontalLayout_5.addWidget(self.tableView_HexView_Hex) + self.line_4 = QtWidgets.QFrame(self.scrollAreaWidgetContents_2) + self.line_4.setFrameShape(QtWidgets.QFrame.VLine) + self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken) + self.line_4.setObjectName("line_4") + self.horizontalLayout_5.addWidget(self.line_4) + self.tableView_HexView_Ascii = QAsciiView(self.scrollAreaWidgetContents_2) + self.tableView_HexView_Ascii.setObjectName("tableView_HexView_Ascii") + self.horizontalLayout_5.addWidget(self.tableView_HexView_Ascii) + spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_5.addItem(spacerItem9) + self.gridLayout_11.addLayout(self.horizontalLayout_5, 2, 0, 1, 1) + self.label_HexView_Information = QtWidgets.QLabel(self.scrollAreaWidgetContents_2) + self.label_HexView_Information.setText("") + self.label_HexView_Information.setObjectName("label_HexView_Information") + self.gridLayout_11.addWidget(self.label_HexView_Information, 0, 0, 1, 1) + self.line_6 = QtWidgets.QFrame(self.scrollAreaWidgetContents_2) + self.line_6.setFrameShape(QtWidgets.QFrame.HLine) + self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken) + self.line_6.setObjectName("line_6") + self.gridLayout_11.addWidget(self.line_6, 1, 0, 1, 1) + self.scrollArea_Hex.setWidget(self.scrollAreaWidgetContents_2) + self.gridLayout.addWidget(self.scrollArea_Hex, 0, 0, 1, 1) + self.verticalScrollBar_HexView = QtWidgets.QScrollBar(self.widget_HexView) + self.verticalScrollBar_HexView.setOrientation(QtCore.Qt.Vertical) + self.verticalScrollBar_HexView.setObjectName("verticalScrollBar_HexView") + self.gridLayout.addWidget(self.verticalScrollBar_HexView, 0, 1, 1, 1) + self.widget_StackView = QtWidgets.QWidget(self.splitter_HexView_StackView) + self.widget_StackView.setObjectName("widget_StackView") + self.gridLayout_3 = QtWidgets.QGridLayout(self.widget_StackView) + self.gridLayout_3.setContentsMargins(0, 0, 0, 0) + self.gridLayout_3.setObjectName("gridLayout_3") + self.stackedWidget_StackScreens = QtWidgets.QStackedWidget(self.widget_StackView) + self.stackedWidget_StackScreens.setObjectName("stackedWidget_StackScreens") + self.StackTrace = QtWidgets.QWidget() + self.StackTrace.setObjectName("StackTrace") + self.gridLayout_9 = QtWidgets.QGridLayout(self.StackTrace) + self.gridLayout_9.setObjectName("gridLayout_9") + self.tableWidget_StackTrace = QtWidgets.QTableWidget(self.StackTrace) + font = QtGui.QFont() + font.setPointSize(9) + self.tableWidget_StackTrace.setFont(font) + self.tableWidget_StackTrace.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.tableWidget_StackTrace.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) + self.tableWidget_StackTrace.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) + self.tableWidget_StackTrace.setObjectName("tableWidget_StackTrace") + self.tableWidget_StackTrace.setColumnCount(2) + self.tableWidget_StackTrace.setRowCount(0) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_StackTrace.setHorizontalHeaderItem(0, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_StackTrace.setHorizontalHeaderItem(1, item) + self.tableWidget_StackTrace.horizontalHeader().setStretchLastSection(True) + self.tableWidget_StackTrace.verticalHeader().setVisible(False) + self.tableWidget_StackTrace.verticalHeader().setDefaultSectionSize(15) + self.gridLayout_9.addWidget(self.tableWidget_StackTrace, 0, 0, 1, 1) + self.stackedWidget_StackScreens.addWidget(self.StackTrace) + self.Stack = QtWidgets.QWidget() + self.Stack.setObjectName("Stack") + self.gridLayout_10 = QtWidgets.QGridLayout(self.Stack) + self.gridLayout_10.setObjectName("gridLayout_10") + self.tableWidget_Stack = QtWidgets.QTableWidget(self.Stack) + font = QtGui.QFont() + font.setPointSize(9) + self.tableWidget_Stack.setFont(font) + self.tableWidget_Stack.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.tableWidget_Stack.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) + self.tableWidget_Stack.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) + self.tableWidget_Stack.setObjectName("tableWidget_Stack") + self.tableWidget_Stack.setColumnCount(4) + self.tableWidget_Stack.setRowCount(0) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Stack.setHorizontalHeaderItem(0, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Stack.setHorizontalHeaderItem(1, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Stack.setHorizontalHeaderItem(2, item) + item = QtWidgets.QTableWidgetItem() + self.tableWidget_Stack.setHorizontalHeaderItem(3, item) + self.tableWidget_Stack.horizontalHeader().setStretchLastSection(True) + self.tableWidget_Stack.verticalHeader().setVisible(False) + self.tableWidget_Stack.verticalHeader().setDefaultSectionSize(15) + self.gridLayout_10.addWidget(self.tableWidget_Stack, 0, 0, 1, 1) + self.stackedWidget_StackScreens.addWidget(self.Stack) + self.gridLayout_3.addWidget(self.stackedWidget_StackScreens, 0, 0, 1, 1) + self.gridLayout_5.addWidget(self.splitter_MainMiddle, 0, 0, 1, 1) + MainWindow.setCentralWidget(self.centralwidget) + self.menubar = QtWidgets.QMenuBar(MainWindow) + self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 20)) + self.menubar.setObjectName("menubar") + self.menuView = QtWidgets.QMenu(self.menubar) + self.menuView.setObjectName("menuView") + self.menuDebug = QtWidgets.QMenu(self.menubar) + self.menuDebug.setObjectName("menuDebug") + self.menuTools = QtWidgets.QMenu(self.menubar) + self.menuTools.setObjectName("menuTools") + MainWindow.setMenuBar(self.menubar) + self.statusbar = QtWidgets.QStatusBar(MainWindow) + self.statusbar.setObjectName("statusbar") + MainWindow.setStatusBar(self.statusbar) + self.actionBookmarks = QtWidgets.QAction(MainWindow) + self.actionBookmarks.setObjectName("actionBookmarks") + self.actionStackTrace_Info = QtWidgets.QAction(MainWindow) + self.actionStackTrace_Info.setObjectName("actionStackTrace_Info") + self.actionInject_so_file = QtWidgets.QAction(MainWindow) + self.actionInject_so_file.setObjectName("actionInject_so_file") + self.actionRun = QtWidgets.QAction(MainWindow) + self.actionRun.setObjectName("actionRun") + self.actionBreak = QtWidgets.QAction(MainWindow) + self.actionBreak.setObjectName("actionBreak") + self.actionStep = QtWidgets.QAction(MainWindow) + self.actionStep.setObjectName("actionStep") + self.actionStep_Over = QtWidgets.QAction(MainWindow) + self.actionStep_Over.setObjectName("actionStep_Over") + self.actionExecute_Till_Return = QtWidgets.QAction(MainWindow) + self.actionExecute_Till_Return.setObjectName("actionExecute_Till_Return") + self.actionToggle_Breakpoint = QtWidgets.QAction(MainWindow) + self.actionToggle_Breakpoint.setObjectName("actionToggle_Breakpoint") + self.menuView.addAction(self.actionBookmarks) + self.menuView.addAction(self.actionStackTrace_Info) + self.menuDebug.addAction(self.actionRun) + self.menuDebug.addAction(self.actionBreak) + self.menuDebug.addSeparator() + self.menuDebug.addAction(self.actionStep) + self.menuDebug.addAction(self.actionStep_Over) + self.menuDebug.addAction(self.actionExecute_Till_Return) + self.menuDebug.addAction(self.actionToggle_Breakpoint) + self.menuTools.addAction(self.actionInject_so_file) + self.menubar.addAction(self.menuView.menuAction()) + self.menubar.addAction(self.menuDebug.menuAction()) + self.menubar.addAction(self.menuTools.menuAction()) + + self.retranslateUi(MainWindow) + self.stackedWidget.setCurrentIndex(0) + self.stackedWidget_StackScreens.setCurrentIndex(0) + QtCore.QMetaObject.connectSlotsByName(MainWindow) + + def retranslateUi(self, MainWindow): + _translate = QtCore.QCoreApplication.translate + MainWindow.setWindowTitle(_translate("MainWindow", "Memory Viewer")) + item = self.tableWidget_Disassemble.horizontalHeaderItem(0) + item.setText(_translate("MainWindow", "Address")) + item = self.tableWidget_Disassemble.horizontalHeaderItem(1) + item.setText(_translate("MainWindow", "Bytes")) + item = self.tableWidget_Disassemble.horizontalHeaderItem(2) + item.setText(_translate("MainWindow", "Opcodes")) + item = self.tableWidget_Disassemble.horizontalHeaderItem(3) + item.setText(_translate("MainWindow", "Comment")) + self.label_3.setText(_translate("MainWindow", "Registers")) + self.RAX.setText(_translate("MainWindow", "RAX=")) + self.RBX.setText(_translate("MainWindow", "RBX=")) + self.RCX.setText(_translate("MainWindow", "RCX=")) + self.RDX.setText(_translate("MainWindow", "RDX=")) + self.RSI.setText(_translate("MainWindow", "RSI=")) + self.RDI.setText(_translate("MainWindow", "RDI=")) + self.RBP.setText(_translate("MainWindow", "RBP=")) + self.RSP.setText(_translate("MainWindow", "RSP=")) + self.R8.setText(_translate("MainWindow", "R8=")) + self.R9.setText(_translate("MainWindow", "R9=")) + self.R10.setText(_translate("MainWindow", "R10=")) + self.R11.setText(_translate("MainWindow", "R11=")) + self.R12.setText(_translate("MainWindow", "R12=")) + self.R13.setText(_translate("MainWindow", "R13=")) + self.R14.setText(_translate("MainWindow", "R14=")) + self.R15.setText(_translate("MainWindow", "R15=")) + self.RIP.setText(_translate("MainWindow", "RIP=")) + self.EAX.setText(_translate("MainWindow", "EAX=")) + self.EBX.setText(_translate("MainWindow", "EBX=")) + self.ECX.setText(_translate("MainWindow", "ECX=")) + self.EDX.setText(_translate("MainWindow", "EDX=")) + self.ESI.setText(_translate("MainWindow", "ESI=")) + self.EDI.setText(_translate("MainWindow", "EDI=")) + self.EBP.setText(_translate("MainWindow", "EBP=")) + self.ESP.setText(_translate("MainWindow", "ESP=")) + self.EIP.setText(_translate("MainWindow", "EIP=")) + self.label_29.setText(_translate("MainWindow", "Flags")) + self.label_31.setText(_translate("MainWindow", "CF")) + self.CF.setText(_translate("MainWindow", "0")) + self.label_35.setText(_translate("MainWindow", "PF")) + self.PF.setText(_translate("MainWindow", "0")) + self.label_37.setText(_translate("MainWindow", "AF")) + self.AF.setText(_translate("MainWindow", "0")) + self.label_39.setText(_translate("MainWindow", "ZF")) + self.ZF.setText(_translate("MainWindow", "0")) + self.label_41.setText(_translate("MainWindow", "SF")) + self.SF.setText(_translate("MainWindow", "0")) + self.label_43.setText(_translate("MainWindow", "TF")) + self.TF.setText(_translate("MainWindow", "0")) + self.label_45.setText(_translate("MainWindow", "IF")) + self.IF.setText(_translate("MainWindow", "0")) + self.label_47.setText(_translate("MainWindow", "DF")) + self.DF.setText(_translate("MainWindow", "0")) + self.label_49.setText(_translate("MainWindow", "OF")) + self.OF.setText(_translate("MainWindow", "0")) + self.label_30.setText(_translate("MainWindow", "Segment Registers")) + self.CS.setText(_translate("MainWindow", "CS=")) + self.ES.setText(_translate("MainWindow", "ES=")) + self.SS.setText(_translate("MainWindow", "SS=")) + self.GS.setText(_translate("MainWindow", "GS=")) + self.DS.setText(_translate("MainWindow", "DS=")) + self.FS.setText(_translate("MainWindow", "FS=")) + self.pushButton_ShowFloatRegisters.setText(_translate("MainWindow", "Show Float Registers")) + item = self.tableWidget_StackTrace.horizontalHeaderItem(0) + item.setText(_translate("MainWindow", "Return Address")) + item = self.tableWidget_StackTrace.horizontalHeaderItem(1) + item.setText(_translate("MainWindow", "Frame Address")) + item = self.tableWidget_Stack.horizontalHeaderItem(0) + item.setText(_translate("MainWindow", "Address")) + item = self.tableWidget_Stack.horizontalHeaderItem(1) + item.setText(_translate("MainWindow", "Value")) + item = self.tableWidget_Stack.horizontalHeaderItem(2) + item.setText(_translate("MainWindow", "Int Repr")) + item = self.tableWidget_Stack.horizontalHeaderItem(3) + item.setText(_translate("MainWindow", "Float Repr")) + self.menuView.setTitle(_translate("MainWindow", "View")) + self.menuDebug.setTitle(_translate("MainWindow", "Debug")) + self.menuTools.setTitle(_translate("MainWindow", "Tools")) + self.actionBookmarks.setText(_translate("MainWindow", "Bookmarks")) + self.actionStackTrace_Info.setText(_translate("MainWindow", "StackTrace Info")) + self.actionInject_so_file.setText(_translate("MainWindow", "Inject .so file")) + self.actionRun.setText(_translate("MainWindow", "Break")) + self.actionBreak.setText(_translate("MainWindow", "Run")) + self.actionStep.setText(_translate("MainWindow", "Step[F7]")) + self.actionStep_Over.setText(_translate("MainWindow", "Step Over[F8]")) + self.actionExecute_Till_Return.setText(_translate("MainWindow", "Execute Till Return[Shift+F8]")) + self.actionToggle_Breakpoint.setText(_translate("MainWindow", "Toggle Breakpoint[F5]")) + +from GUI.CustomTableViews.AsciiView import QAsciiView +from GUI.CustomLabels.FlagRegisterLabel import QFlagRegisterLabel +from GUI.CustomTableViews.HexView import QHexView +from GUI.CustomLabels.RegisterLabel import QRegisterLabel diff --git a/GUI/Widgets/MemoryView/Form/MemoryViewWindow.ui b/GUI/MemoryViewerWindow.ui similarity index 58% rename from GUI/Widgets/MemoryView/Form/MemoryViewWindow.ui rename to GUI/MemoryViewerWindow.ui index 48ce5387..78054a4c 100644 --- a/GUI/Widgets/MemoryView/Form/MemoryViewWindow.ui +++ b/GUI/MemoryViewerWindow.ui @@ -1,7 +1,7 @@ - MainWindow_MemoryView - + MainWindow + 0 @@ -15,28 +15,13 @@ - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - 1 - Qt::Orientation::Vertical + Qt::Vertical true @@ -49,61 +34,34 @@ - Qt::Orientation::Horizontal + Qt::Horizontal 10 - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - Monospace + 9 - Qt::ScrollBarPolicy::ScrollBarAlwaysOff + Qt::ScrollBarAlwaysOff false - QAbstractItemView::EditTrigger::NoEditTriggers - - - true + QAbstractItemView::NoEditTriggers - QAbstractItemView::SelectionMode::ExtendedSelection + QAbstractItemView::SingleSelection - QAbstractItemView::SelectionBehavior::SelectRows - - - QAbstractItemView::ScrollMode::ScrollPerPixel - - - false - - - false + QAbstractItemView::SelectRows true @@ -111,11 +69,8 @@ false - - 16 - - 16 + 15 false @@ -127,12 +82,12 @@ - Opcodes + Bytes - Instruction + Opcodes @@ -145,34 +100,20 @@ - Qt::Orientation::Vertical + Qt::Vertical - - - Monospace - + + + 0 + 0 + - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - @@ -183,41 +124,20 @@ 0 0 - 373 - 373 + 352 + 439 - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - Monospace + 9 @@ -228,158 +148,122 @@ - Qt::Orientation::Horizontal + Qt::Horizontal - - - 0 - 0 - - - - - 0 - 145 - - 16777215 - 145 + 200 - 1 + 0 - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - + - Monospace + 9 - RAX= + RAX= - + - Monospace + 9 - RBX= + RBX= - + - Monospace + 9 - RCX= + RCX= - + - Monospace + 9 - RDX= + RDX= - + - Monospace + 9 - RSI= + RSI= - + - Monospace + 9 - RDI= + RDI= - + - Monospace + 9 - RBP= + RBP= - + - Monospace + 9 - RSP= + RSP= @@ -388,7 +272,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -400,102 +284,99 @@ - - 0 - - + - Monospace + 9 - R8= + R8= - + - Monospace + 9 - R9= + R9= - + - Monospace + 9 - R10= + R10= - + - Monospace + 9 - R11= + R11= - + - Monospace + 9 - R12= + R12= - + - Monospace + 9 - R13= + R13= - + - Monospace + 9 - R14= + R14= - + - Monospace + 9 - R15= + R15= @@ -505,25 +386,22 @@ - - 0 - - + - Monospace + 9 - RIP= + RIP= - Qt::Orientation::Horizontal + Qt::Horizontal @@ -538,7 +416,7 @@ - Qt::Orientation::Vertical + Qt::Vertical @@ -554,141 +432,117 @@ - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - + - Monospace + 9 - EAX= + EAX= - + - Monospace + 9 - EBX= + EBX= - + - Monospace + 9 - ECX= + ECX= - + - Monospace + 9 - EDX= + EDX= - + - Monospace + 9 - ESI= + ESI= - + - Monospace + 9 - EDI= + EDI= - + - Monospace + 9 - EBP= + EBP= - + - Monospace + 9 - ESP= + ESP= - + - Monospace + 9 - EIP= + EIP= @@ -697,7 +551,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -709,6 +563,19 @@ + + + + Qt::Vertical + + + + 156 + 16 + + + + @@ -719,7 +586,7 @@ - Monospace + 9 @@ -730,41 +597,35 @@ - Qt::Orientation::Horizontal + Qt::Horizontal - - 0 - - - 0 - - Monospace + 9 - CF + CF - + - Monospace + 9 - 0 + 0 @@ -772,30 +633,27 @@ - - 0 - - Monospace + 9 - PF + PF - + - Monospace + 9 - 0 + 0 @@ -803,30 +661,27 @@ - - 0 - - Monospace + 9 - AF + AF - + - Monospace + 9 - 0 + 0 @@ -834,30 +689,27 @@ - - 0 - - Monospace + 9 - ZF + ZF - + - Monospace + 9 - 0 + 0 @@ -865,30 +717,27 @@ - - 0 - - Monospace + 9 - SF + SF - + - Monospace + 9 - 0 + 0 @@ -896,30 +745,27 @@ - - 0 - - Monospace + 9 - TF + TF - + - Monospace + 9 - 0 + 0 @@ -927,30 +773,27 @@ - - 0 - - Monospace + 9 - IF + IF - + - Monospace + 9 - 0 + 0 @@ -958,30 +801,27 @@ - - 0 - - Monospace + 9 - DF + DF - + - Monospace + 9 - 0 + 0 @@ -989,30 +829,27 @@ - - 0 - - Monospace + 9 - OF + OF - + - Monospace + 9 - 0 + 0 @@ -1020,27 +857,11 @@ - - - - Qt::Orientation::Vertical - - - QSizePolicy::Policy::Fixed - - - - 20 - 15 - - - - - Monospace + 9 @@ -1051,41 +872,35 @@ - Qt::Orientation::Horizontal + Qt::Horizontal - - 0 - - - 0 - - + - Monospace + 9 - CS= + CS= - + - Monospace + 9 - ES= + ES= @@ -1094,7 +909,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -1106,30 +921,27 @@ - - 0 - - + - Monospace + 9 - SS= + SS= - + - Monospace + 9 - GS= + GS= @@ -1138,7 +950,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -1150,30 +962,27 @@ - - 0 - - + - Monospace + 9 - DS= + DS= - + - Monospace + 9 - FS= + FS= @@ -1185,7 +994,7 @@ - Monospace + 9 @@ -1196,7 +1005,7 @@ - Qt::Orientation::Vertical + Qt::Vertical @@ -1211,7 +1020,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -1232,31 +1041,13 @@ - Qt::Orientation::Horizontal + Qt::Horizontal 10 - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 4 - @@ -1267,105 +1058,40 @@ 0 0 - 490 - 181 + 473 + 196 - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Monospace - - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - QAbstractItemView::SelectionBehavior::SelectRows - - - false - - - false - - - false - - - false - - - - Address - - - + - Qt::Orientation::Vertical + Qt::Vertical - - - - Monospace - - - - QAbstractScrollArea::SizeAdjustPolicy::AdjustToContents - - + - Qt::Orientation::Vertical + Qt::Vertical - - - - Monospace - - - - QAbstractScrollArea::SizeAdjustPolicy::AdjustToContents - - + - Qt::Orientation::Horizontal + Qt::Horizontal @@ -1387,7 +1113,7 @@ - Qt::Orientation::Horizontal + Qt::Horizontal @@ -1401,7 +1127,7 @@ - Qt::Orientation::Vertical + Qt::Vertical @@ -1409,21 +1135,6 @@ - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - @@ -1431,39 +1142,21 @@ - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - Monospace + 9 - QAbstractItemView::EditTrigger::NoEditTriggers + QAbstractItemView::NoEditTriggers - QAbstractItemView::SelectionMode::SingleSelection + QAbstractItemView::SingleSelection - QAbstractItemView::SelectionBehavior::SelectRows - - - false + QAbstractItemView::SelectRows true @@ -1471,11 +1164,8 @@ false - - 16 - - 16 + 15 @@ -1493,36 +1183,21 @@ - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - Monospace + 9 - QAbstractItemView::EditTrigger::NoEditTriggers + QAbstractItemView::NoEditTriggers - QAbstractItemView::SelectionMode::SingleSelection + QAbstractItemView::SingleSelection - QAbstractItemView::SelectionBehavior::SelectRows + QAbstractItemView::SelectRows true @@ -1530,11 +1205,8 @@ false - - 16 - - 16 + 15 @@ -1548,7 +1220,12 @@ - Points to + Int Repr + + + + + Float Repr @@ -1570,27 +1247,19 @@ 0 0 800 - 32 + 20 - V&iew + View - - - - - - - - - &Debug + Debug @@ -1599,198 +1268,84 @@ - - - - &Tools + Tools - - - - - - - - - - - Fi&le - - - - - - Help - - - - - &Bookmarks + Bookmarks - &StackTrace Info + StackTrace Info - &Inject .so file - - - - - Inject D&LL file + Inject .so file - &Break + Break - &Run + Run - &Step[F7] + Step[F7] - Step &Over[F8] + Step Over[F8] - &Execute Till Return[Shift+F8] + Execute Till Return[Shift+F8] - &Toggle Breakpoint[F5] - - - - - B&reakpoints - - - - - &Functions - - - - - Set Address[Shift+F4] - - - - - &Call Function - - - - - &Load Trace - - - - - &Libpince - - - - - &GDB Log File - - - - - &Search Instructions - - - - - &Memory Regions - - - - - &Dissect Code - - - - - Dissect &Mono/IL2CPP - - - - - R&eferenced Strings - - - - - Referenced &Calls - - - - - To&ggle Attach - - - - - Restore Instructions - - - - - Libpince Engine - - - - - Structures + Toggle Breakpoint[F5] - RegisterLabel + QRegisterLabel QLabel -
GUI.Labels.RegisterLabel
+
GUI.CustomLabels.RegisterLabel
- FlagRegisterLabel + QFlagRegisterLabel QLabel -
GUI.Labels.FlagRegisterLabel
+
GUI.CustomLabels.FlagRegisterLabel
- HexView + QHexView QTableView -
GUI.TableViews.HexView
+
GUI.CustomTableViews.HexView
- AsciiView + QAsciiView QTableView -
GUI.TableViews.AsciiView
+
GUI.CustomTableViews.AsciiView
diff --git a/GUI/Notes.txt b/GUI/Notes.txt new file mode 100644 index 00000000..824a9b98 --- /dev/null +++ b/GUI/Notes.txt @@ -0,0 +1 @@ +IMPORTANT: Don't try to add a QKeySequenceEdit to the 2nd widget of stacked widget in settingsdialog.ui, pyuic5 gives error when QKeySequenceEdit is used. I had to implement it in PINCE.py because of this unfortunately. Check SettingsDialogForm class for the usage. \ No newline at end of file diff --git a/GUI/Overlays/DisassembleArrowOverlay.py b/GUI/Overlays/DisassembleArrowOverlay.py deleted file mode 100644 index f0426aa8..00000000 --- a/GUI/Overlays/DisassembleArrowOverlay.py +++ /dev/null @@ -1,414 +0,0 @@ -""" -This file is part of PINCE. - -PINCE is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -PINCE is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with PINCE. If not, see . -""" - -import math - -from PyQt6.QtCore import QEvent, QObject, QPointF, QRect, Qt, pyqtSignal -from PyQt6.QtGui import QColor, QMouseEvent, QPainter, QPainterPath, QPaintEvent, QPalette, QPen, QPolygonF -from PyQt6.QtWidgets import QTableWidget, QToolTip - -# How an arrow endpoint is anchored. -# _ROW is a real disassembled row, drawn at its own position and clipped by the viewport. -# _ABOVE and _BELOW are addresses with no displayed row, pinned to an edge. -_ROW = 0 -_ABOVE = -1 -_BELOW = 1 - -# Geometry of the arrows, in pixels. -# They are anchored to the left edge of the instruction column and fan out leftwards over the opcodes column, -# putting the arrowheads right next to the instruction text. -_RIGHT_GAP = 2 # gap between the arrowheads and the instruction text -_FIRST_LANE_OFFSET = 6 # distance between the instruction column and the innermost (closest) lane -_LANE_SPACING = 7 # horizontal distance between two neighbouring lanes -_MAX_LANES = 8 # lanes beyond this reuse the outermost column instead of fanning out further -_PEN_WIDTH = 1.6 -_HEAD = 5 # arrowhead size -_HOVER_THRESHOLD = 5 # how close (px) the cursor must be to an arrow to hover it -_TOOLTIP_MSEC = 2147483647 # effectively indefinite display time so the tooltip stays up while hovering an arrow - -# Categorical palette. -# Overlapping arrows are still separated by their lane's x offset if hues repeat. -_HUES = [210, 145, 32, 280, 190, 340, 55, 0] # blue, green, orange, purple, teal, pink, yellow, red - -# The Wong (colorblind-friendly) theme paints on an orange base (#E69F00, see GUI/Settings/themes.py). -# On that background the palette above is both low-contrast and confusable under red-green colour blindness. -# This replacement is dark enough to clear WCAG 3:1 against the orange and stays distinct under deuteranopia, protanopia and tritanopia. -_WONG_BASE = "#e69f00" # lower-cased QColor.name() of the Wong theme's Base role -_WONG_COLORS = ["#005A8B", "#903E00", "#006246", "#843D66", "#101014"] # blue, vermillion, green, purple, near-black - - -class DisassembleArrowOverlay(QObject): - """Draws jmp/call references as arrows overlaid on the disassemble table, left of the instructions. - - Each arrow starts at the referrer (caller) address and ends, with an arrowhead, at the referenced - (called/jumped-to) address. An arrow is drawn as long as at least one of its two instructions is on - screen, so it stays visible even when its caller or target has scrolled out of view. An endpoint with - no displayed row of its own is pinned to the nearest edge. Hovering an arrow highlights it and dims - the rest so its destination is easy to follow, and clicking an arrow asks to follow one of its - endpoints (see follow_requested). - - Rather than living in its own widget, the arrows are painted straight onto the table's viewport - after the cells (by wrapping the table's paintEvent) so they hug the instruction column. Mouse - interaction is handled through an event filter on the viewport. - """ - - # Emitted when an arrow is clicked, carrying its (source_address, target_address). - # object is used instead of int because a large address overflows the C++ int a pyqtSignal would marshal it through. - follow_requested = pyqtSignal(object, object) - - def __init__(self, table: QTableWidget, instruction_column: int) -> None: - """ - Args: - table (QTableWidget): The disassemble table the arrows are drawn over - instruction_column (int): Index of the instruction column the arrows are anchored to - """ - super().__init__(table) - self.table = table - self.viewport = table.viewport() - self.instruction_column = instruction_column - self.arrows: list[tuple[int, int, str]] = [] # [(source_address, target_address, kind), ...] - self.address_to_row: dict[int, int] = {} # displayed address -> table row index - self.window_first = 0 # address of the first displayed instruction - self.window_last = 0 # address of the last displayed instruction - self._dark = False # whether the current theme is dark, refreshed on every paint - self._wong = False # whether the colorblind-friendly Wong theme is active, refreshed on every paint - # Geometry of the arrows drawn in the last paint, used for hover hit-testing without recomputing. - self._geometry: list[dict] = [] - self._hovered: tuple[int, int, str] | None = None # (source, target, kind) of the hovered arrow - # Lane (x offset) chosen for each arrow last paint, keyed by (source, target, kind). - # An arrow already on screen keeps this column when new arrows appear rather than being fanned wider. - self._lane_memory: dict[tuple[int, int, str], int] = {} - - # Wrap the table's paintEvent to draw on top of the freshly painted cells. - # Follow its mouse and resize events through an event filter on the viewport. - self._table_paint_event = table.paintEvent - table.paintEvent = self._paint_event - self.viewport.setMouseTracking(True) - self.viewport.installEventFilter(self) - - def set_arrows( - self, - arrows: list[tuple[int, int, str]], - address_to_row: dict[int, int], - window_first: int, - window_last: int, - ) -> None: - """Replaces the arrows currently shown and repaints them - - Args: - arrows (list): [(source_address, target_address, kind), ...] where kind is "jmp" or "call" - address_to_row (dict): Maps every displayed instruction address to its table row index - window_first (int): Address of the first displayed instruction - window_last (int): Address of the last displayed instruction - """ - self.arrows = arrows - self.address_to_row = address_to_row - self.window_first = window_first - self.window_last = window_last - self._set_hovered(None) # the previous hover no longer maps to anything, so clear it and restore the cursor - self.viewport.update() - - def _paint_event(self, event: QPaintEvent) -> None: - """Paints the table cells (original handler) and then the arrows on top of them""" - self._table_paint_event(event) - painter = QPainter(self.viewport) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - self._draw(painter) - painter.end() - - def _endpoint(self, address: int, vp_bottom: int) -> tuple[int, int]: - """Resolves an address to a y coordinate - - Displayed rows keep their real position even when it falls outside the viewport, so the arrow is - drawn in full and the painter simply clips whatever hangs off the top or bottom edge. An address - that isn't displayed at all has no row to anchor to, so it is clamped to the nearest edge. - - Returns: - tuple: (y coordinate, direction) where direction is _ROW, _ABOVE or _BELOW - """ - row = self.address_to_row.get(address) - if row is not None: - return self.table.rowViewportPosition(row) + self.table.rowHeight(row) // 2, _ROW - # Not part of the disassembled range at all, decide the edge from its address. - return (0, _ABOVE) if address < self.window_first else (vp_bottom, _BELOW) - - def _arrow_color(self, key: int) -> QColor: - """Picks an arrow's colour from the palette using a stable per-arrow key, so its colour stays the - same when other arrows scroll into or out of view""" - if self._wong: - return QColor(_WONG_COLORS[key % len(_WONG_COLORS)]) - hue = _HUES[key % len(_HUES)] - return QColor.fromHsv(hue, 180, 235) if self._dark else QColor.fromHsv(hue, 235, 175) - - @staticmethod - def _palette_key(source: int, target: int) -> int: - """A stable value derived only from the arrow's own addresses, so its palette slot never changes - as other arrows scroll in or out. Hashing the pair mixes the bits so neighbouring aligned - addresses still spread across the palette. Deterministic here since both parts are ints""" - return hash((source, target)) - - def _assign_lanes(self, resolved: list[tuple]) -> list[int]: - """Packs arrows into vertical lanes, keeping every arrow already on screen in the lane it first got - - A surviving arrow reclaims its previous lane and only brand-new arrows are placed fresh, shortest - first, into the lanes the survivors leave open. Shortest first puts nested branches on the inner - lanes (closest to the code) the way IDA/Cheat Engine lay them out. - - Args: - resolved (list): Arrow geometry tuples of (y0, y1, src_dir, tgt_dir, kind, source, target) - - Returns: - list: The lane index chosen for each arrow, in the same order as resolved - """ - intervals = [(min(item[0], item[1]), max(item[0], item[1])) for item in resolved] - keys = [(item[5], item[6], item[4]) for item in resolved] - lanes: list[list[tuple[int, int]]] = [] # each lane holds the y intervals already occupying it - result = [0] * len(resolved) - - def lane_is_free(lane_index: int, top: int, bottom: int) -> bool: - return lane_index >= len(lanes) or all(bottom < lo or top > hi for lo, hi in lanes[lane_index]) - - def occupy(index: int, lane_index: int) -> None: - while len(lanes) <= lane_index: - lanes.append([]) - lanes[lane_index].append(intervals[index]) - result[index] = lane_index - - def lowest_free(top: int, bottom: int) -> int: - lane_index = 0 - while not lane_is_free(lane_index, top, bottom): - lane_index += 1 - return lane_index - - # Reclaim remembered lanes first, innermost outwards, so a surviving arrow holds its column. - remembered = sorted((i for i in range(len(resolved)) if keys[i] in self._lane_memory), key=lambda i: self._lane_memory[keys[i]]) - for i in remembered: - top, bottom = intervals[i] - desired = self._lane_memory[keys[i]] - occupy(i, desired if lane_is_free(desired, top, bottom) else lowest_free(top, bottom)) - - # Place the arrows that just appeared, shortest first, into whatever lanes the survivors left open. - fresh = sorted( - (i for i in range(len(resolved)) if keys[i] not in self._lane_memory), - key=lambda i: intervals[i][1] - intervals[i][0], - ) - for i in fresh: - top, bottom = intervals[i] - occupy(i, lowest_free(top, bottom)) - - # Keep only the arrows on screen now so the map can't grow, while a returning arrow still finds its lane. - # An empty frame (every arrow off the same edge) is left alone so a brief full scroll-off keeps the columns. - if resolved: - self._lane_memory = {keys[i]: result[i] for i in range(len(resolved))} - return result - - def _arrow_points(self, y0: int, y1: int, src_dir: int, tgt_dir: int, lane_x: int, anchor_x: int) -> list[QPointF]: - """Builds the polyline the arrow follows: source stub, vertical run through the lane, target stub""" - points = [] - if src_dir == _ROW: - points.append(QPointF(anchor_x, y0)) - points.append(QPointF(lane_x, y0)) # corner where the line turns down into its lane - points.append(QPointF(lane_x, y1)) - if tgt_dir == _ROW: - points.append(QPointF(anchor_x, y1)) - return points - - def _draw(self, painter: QPainter) -> None: - """Resolves the arrows to on-screen geometry and paints them, hovered one on top""" - self._geometry = [] - if not self.arrows or not self.address_to_row: - return - # Detect the mode from the actual background to also track live theme changes and previews. - base = self.viewport.palette().color(QPalette.ColorRole.Base) - self._wong = base.name().lower() == _WONG_BASE - self._dark = base.lightness() < 128 - vp_bottom = self.viewport.height() - anchor_x = self.table.columnViewportPosition(self.instruction_column) - _RIGHT_GAP - innermost_x = anchor_x - _FIRST_LANE_OFFSET - - # Resolve each arrow to on-screen geometry, keeping the arrow whenever any part of its vertical span falls - # inside the viewport while the painter clips whatever runs off an edge. - # An arrow is dropped only when both endpoints sit past the same edge. - # One crossing the viewport is still drawn even when neither endpoint is on screen. - resolved = [] - for source, target, kind in self.arrows: - y0, src_dir = self._endpoint(source, vp_bottom) - y1, tgt_dir = self._endpoint(target, vp_bottom) - src_above = src_dir == _ABOVE or (src_dir == _ROW and y0 < 0) - src_below = src_dir == _BELOW or (src_dir == _ROW and y0 > vp_bottom) - tgt_above = tgt_dir == _ABOVE or (tgt_dir == _ROW and y1 < 0) - tgt_below = tgt_dir == _BELOW or (tgt_dir == _ROW and y1 > vp_bottom) - if (src_above and tgt_above) or (src_below and tgt_below): - continue - resolved.append((y0, y1, src_dir, tgt_dir, kind, source, target)) - - lanes = self._assign_lanes(resolved) - for i, (y0, y1, src_dir, tgt_dir, kind, source, target) in enumerate(resolved): - lane_x = max(1, innermost_x - min(lanes[i], _MAX_LANES - 1) * _LANE_SPACING) - self._geometry.append( - { - "key": (source, target, kind), - "kind": kind, - "color": self._arrow_color(self._palette_key(source, target)), - "points": self._arrow_points(y0, y1, src_dir, tgt_dir, lane_x, anchor_x), - "tgt_dir": tgt_dir, - "lane_x": lane_x, - "y1": y1, - "anchor_x": anchor_x, - } - ) - - hovering = any(geometry["key"] == self._hovered for geometry in self._geometry) - # Draw the non-hovered arrows first (dimmed while hovering), then the hovered one on top. - for geometry in self._geometry: - if geometry["key"] != self._hovered: - self._draw_arrow(painter, geometry, dim=hovering) - for geometry in self._geometry: - if geometry["key"] == self._hovered: - self._draw_arrow(painter, geometry, highlight=True) - - def _draw_arrow(self, painter: QPainter, geometry: dict, dim: bool = False, highlight: bool = False) -> None: - """Draws a single arrow, optionally dimmed (a sibling of the hovered one) or highlighted""" - color = QColor(geometry["color"]) - width = _PEN_WIDTH - if highlight: - width = _PEN_WIDTH + 1.5 - if self._wong: - color = color.darker(125) # deepen against the orange background rather than lighten - elif self._dark: - color = color.lighter(125) - else: - color = color.darker(115) - elif dim: - color.setAlpha(50) - - path = QPainterPath(geometry["points"][0]) - for point in geometry["points"][1:]: - path.lineTo(point) - - if highlight: - # A soft, wide halo underneath makes the hovered path pop out from the dimmed ones. - halo = QColor(color) - halo.setAlpha(70) - painter.strokePath(path, self._make_pen(halo, width + 4, geometry["kind"])) - painter.strokePath(path, self._make_pen(color, width, geometry["kind"])) - self._draw_head(painter, color, geometry, big=highlight) - - def _make_pen(self, color: QColor, width: float, kind: str) -> QPen: - """Creates the pen for an arrow, dashed for calls and solid for jumps""" - pen = QPen(color, width) - pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) - if kind == "call": - pen.setStyle(Qt.PenStyle.CustomDashLine) - pen.setDashPattern([4, 3]) - pen.setCapStyle(Qt.PenCapStyle.FlatCap) - else: - pen.setCapStyle(Qt.PenCapStyle.RoundCap) - return pen - - def _draw_head(self, painter: QPainter, color: QColor, geometry: dict, big: bool) -> None: - """Draws the filled triangular arrowhead at the target end of the arrow""" - size = _HEAD + (2 if big else 0) - y = geometry["y1"] - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(color) - if geometry["tgt_dir"] == _ROW: # points right, into the code - x = geometry["anchor_x"] - head = QPolygonF([QPointF(x, y), QPointF(x - size, y - size + 1), QPointF(x - size, y + size - 1)]) - else: - x = geometry["lane_x"] - direction = -1 if geometry["tgt_dir"] == _ABOVE else 1 # points up or down, off-screen target - base_y = y - direction * size - head = QPolygonF([QPointF(x, y), QPointF(x - size + 1, base_y), QPointF(x + size - 1, base_y)]) - painter.drawPolygon(head) - - def eventFilter(self, obj: QObject, event: QEvent) -> bool: - if obj is not self.viewport: - return False - event_type = event.type() - if event_type == QEvent.Type.Resize: - self.viewport.update() # visible rows changed, redraw the arrows - elif event_type == QEvent.Type.MouseMove: - self._update_hover(event) - elif event_type == QEvent.Type.MouseButtonPress and event.button() == Qt.MouseButton.LeftButton: - geometry = self._arrow_at(event.position().x(), event.position().y()) - if geometry: - source, target, _ = geometry["key"] - self.follow_requested.emit(source, target) - return True # consume to keep the click from also changing the row selection - elif event_type == QEvent.Type.ToolTip: - geometry = self._arrow_at(event.pos().x(), event.pos().y()) - if geometry: - # Show our own tooltip and swallow the event to stop the view replacing it with the cell's (usually empty) tooltip, - # which is what made it vanish after the hover delay. - QToolTip.showText(event.globalPos(), self._tooltip_text(geometry["key"]), self.viewport, QRect(), _TOOLTIP_MSEC) - return True - elif event_type == QEvent.Type.Leave: - self._set_hovered(None) - QToolTip.hideText() - return False - - def _arrow_at(self, x: float, y: float) -> dict | None: - """Returns the arrow geometry closest to (x, y) within the hover threshold, or None""" - nearest = None - nearest_distance = _HOVER_THRESHOLD + 1 - for geometry in self._geometry: - points = geometry["points"] - for start, end in zip(points, points[1:]): - distance = self._distance_to_segment(x, y, start, end) - if distance < nearest_distance: - nearest_distance = distance - nearest = geometry - return nearest if nearest_distance <= _HOVER_THRESHOLD else None - - def _update_hover(self, event: QMouseEvent) -> None: - position = event.position() - geometry = self._arrow_at(position.x(), position.y()) - hovered = geometry["key"] if geometry else None - # Only touch the tooltip when the hovered arrow actually changes. - # Calling showText on every mouse move (even over the same arrow) thrashed the shared tooltip window into half-drawn or flickering states, - # especially while switching between arrows. - if hovered == self._hovered: - return - self._set_hovered(hovered) # updates the cursor and repaints - if hovered: - QToolTip.showText(event.globalPosition().toPoint(), self._tooltip_text(hovered), self.viewport, QRect(), _TOOLTIP_MSEC) - else: - QToolTip.hideText() - - @staticmethod - def _tooltip_text(key: tuple[int, int, str]) -> str: - """Builds the 'source -> target (kind)' label shown when hovering an arrow""" - source, target, kind = key - return f"{hex(source)} → {hex(target)} ({kind})" - - def _set_hovered(self, hovered: tuple[int, int, str] | None) -> None: - if hovered != self._hovered: - self._hovered = hovered - self.viewport.setCursor(Qt.CursorShape.PointingHandCursor if hovered else Qt.CursorShape.ArrowCursor) - self.viewport.update() # repaint the cells and arrows so the highlight/dim is correct - - @staticmethod - def _distance_to_segment(px: float, py: float, start: QPointF, end: QPointF) -> float: - """Returns the shortest distance from point (px, py) to the line segment start-end""" - dx = end.x() - start.x() - dy = end.y() - start.y() - if dx == 0 and dy == 0: - return math.hypot(px - start.x(), py - start.y()) - t = ((px - start.x()) * dx + (py - start.y()) * dy) / (dx * dx + dy * dy) - t = max(0.0, min(1.0, t)) - return math.hypot(px - (start.x() + t * dx), py - (start.y() + t * dy)) diff --git a/GUI/SelectProcess.py b/GUI/SelectProcess.py new file mode 100644 index 00000000..072acb2d --- /dev/null +++ b/GUI/SelectProcess.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'selectprocess.ui' +# +# Created: Thu May 19 03:10:46 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_MainWindow(object): + def setupUi(self, MainWindow): + MainWindow.setObjectName("MainWindow") + MainWindow.setWindowModality(QtCore.Qt.WindowModal) + MainWindow.resize(443, 420) + self.centralwidget = QtWidgets.QWidget(MainWindow) + self.centralwidget.setObjectName("centralwidget") + self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) + self.verticalLayout.setObjectName("verticalLayout") + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setObjectName("horizontalLayout") + self.label = QtWidgets.QLabel(self.centralwidget) + self.label.setObjectName("label") + self.horizontalLayout.addWidget(self.label) + self.lineEdit_searchprocess = QtWidgets.QLineEdit(self.centralwidget) + self.lineEdit_searchprocess.setObjectName("lineEdit_searchprocess") + self.horizontalLayout.addWidget(self.lineEdit_searchprocess) + self.verticalLayout.addLayout(self.horizontalLayout) + self.processtable = QtWidgets.QTableWidget(self.centralwidget) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.processtable.sizePolicy().hasHeightForWidth()) + self.processtable.setSizePolicy(sizePolicy) + self.processtable.setAutoFillBackground(False) + self.processtable.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustIgnored) + self.processtable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) + self.processtable.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) + self.processtable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) + self.processtable.setObjectName("processtable") + self.processtable.setColumnCount(3) + self.processtable.setRowCount(0) + item = QtWidgets.QTableWidgetItem() + self.processtable.setHorizontalHeaderItem(0, item) + item = QtWidgets.QTableWidgetItem() + self.processtable.setHorizontalHeaderItem(1, item) + item = QtWidgets.QTableWidgetItem() + item.setTextAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) + self.processtable.setHorizontalHeaderItem(2, item) + self.processtable.horizontalHeader().setDefaultSectionSize(70) + self.processtable.horizontalHeader().setStretchLastSection(True) + self.processtable.verticalHeader().setVisible(False) + self.processtable.verticalHeader().setStretchLastSection(False) + self.verticalLayout.addWidget(self.processtable) + self.horizontalLayout_2 = QtWidgets.QHBoxLayout() + self.horizontalLayout_2.setObjectName("horizontalLayout_2") + spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_2.addItem(spacerItem) + self.pushButton_Open = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_Open.setObjectName("pushButton_Open") + self.horizontalLayout_2.addWidget(self.pushButton_Open) + self.pushButton_Close = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_Close.setObjectName("pushButton_Close") + self.horizontalLayout_2.addWidget(self.pushButton_Close) + spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_2.addItem(spacerItem1) + self.verticalLayout.addLayout(self.horizontalLayout_2) + self.horizontalLayout_3 = QtWidgets.QHBoxLayout() + self.horizontalLayout_3.setObjectName("horizontalLayout_3") + spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_3.addItem(spacerItem2) + self.pushButton_CreateProcess = QtWidgets.QPushButton(self.centralwidget) + self.pushButton_CreateProcess.setObjectName("pushButton_CreateProcess") + self.horizontalLayout_3.addWidget(self.pushButton_CreateProcess) + spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_3.addItem(spacerItem3) + self.verticalLayout.addLayout(self.horizontalLayout_3) + MainWindow.setCentralWidget(self.centralwidget) + + self.retranslateUi(MainWindow) + QtCore.QMetaObject.connectSlotsByName(MainWindow) + + def retranslateUi(self, MainWindow): + _translate = QtCore.QCoreApplication.translate + MainWindow.setWindowTitle(_translate("MainWindow", "Please select a Process")) + self.label.setText(_translate("MainWindow", "Name of the Process:")) + self.processtable.setSortingEnabled(True) + item = self.processtable.horizontalHeaderItem(0) + item.setText(_translate("MainWindow", "PID")) + item = self.processtable.horizontalHeaderItem(1) + item.setText(_translate("MainWindow", "Username")) + item = self.processtable.horizontalHeaderItem(2) + item.setText(_translate("MainWindow", "Process Name")) + self.pushButton_Open.setToolTip(_translate("MainWindow", "Attach to the selected process")) + self.pushButton_Open.setText(_translate("MainWindow", "Open")) + self.pushButton_Close.setText(_translate("MainWindow", "Cancel")) + self.pushButton_CreateProcess.setToolTip(_translate("MainWindow", "Open an executable")) + self.pushButton_CreateProcess.setText(_translate("MainWindow", "Create Process")) + diff --git a/GUI/Widgets/SelectProcess/Form/SelectProcess.ui b/GUI/SelectProcess.ui similarity index 93% rename from GUI/Widgets/SelectProcess/Form/SelectProcess.ui rename to GUI/SelectProcess.ui index 9e5e81e8..0f78c58c 100644 --- a/GUI/Widgets/SelectProcess/Form/SelectProcess.ui +++ b/GUI/SelectProcess.ui @@ -23,17 +23,17 @@ - Name or PID of the Process: + Name of the Process: - +
- + 0 @@ -58,9 +58,6 @@ true - - false - 70 @@ -88,7 +85,7 @@ Process Name - AlignLeading|AlignVCenter + AlignLeft|AlignVCenter @@ -161,7 +158,7 @@ Open an executable
- Create Process[F1] + Create Process
diff --git a/GUI/Session/session.py b/GUI/Session/session.py deleted file mode 100644 index da24ae0f..00000000 --- a/GUI/Session/session.py +++ /dev/null @@ -1,537 +0,0 @@ -import os -from enum import IntFlag, auto -from typing import Any - -from PyQt6.QtCore import QSettings -from PyQt6.QtGui import QCloseEvent -from PyQt6.QtWidgets import QCheckBox, QFileDialog, QMessageBox - -from GUI.Settings import settings -from GUI.States import states -from GUI.Utils import guiutils -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - - -class SessionDataChanged(IntFlag): - NONE = 0 - ADDRESS_TREE = auto() - BOOKMARKS = auto() - NOTES = auto() - PROCESS_NAME = auto() - STRUCTURES = auto() - - -# The PCT-archive repo (https://github.com/PINCE-org/PCT-archive) validates submitted -# .pct files against this format. If you change the session structure or bump the version, -# update its validation too (.github/scripts/common.py in that repo) -LATEST_VERSION = 3 - - -def _legacy_to_v1(content: list) -> dict[str, Any]: - utils.logger.info("Migrating legacy session data to version 1") - return {"version": 1, "notes": "", "bookmarks": {}, "address_tree": content, "process_name": ""} - - -def _v1_to_v2(content: dict[str, Any]) -> dict[str, Any]: - # v2 added script entry rows which are told apart by length so no row transform is needed - utils.logger.info("Migrating version 1 session data to version 2") - content["version"] = 2 - return content - - -def _v2_to_v3(content: dict[str, Any]) -> dict[str, Any]: - # v3 added saved structures - utils.logger.info("Migrating version 2 session data to version 3") - content["version"] = 3 - content.setdefault("structures", {}) - return content - - -def migrate_version(content: Any) -> dict[str, Any]: - if type(content) is list: - content = _legacy_to_v1(content) - if isinstance(content, dict) and type(content.get("version")) is int and content["version"] == 1: - content = _v1_to_v2(content) - if isinstance(content, dict) and type(content.get("version")) is int and content["version"] == 2: - content = _v2_to_v3(content) - return content - - -def _valid_value_type(data: Any) -> bool: - if not isinstance(data, list) or len(data) not in (4, 5): - return False - try: - if isinstance(typedefs.ValueType.deserialize(data), typedefs.BitFieldValueType): - return True - except (KeyError, TypeError, ValueError): - return False - type_id, length, zero_terminate, value_repr = data[:4] - return ( - all(type(value) is int for value in (type_id, length, value_repr, *data[4:])) - and type(zero_terminate) is bool - and typedefs.VALUE_REPR.UNSIGNED <= value_repr <= typedefs.VALUE_REPR.HEX - and (len(data) == 4 or typedefs.ENDIANNESS.HOST <= data[4] <= typedefs.ENDIANNESS.BIG) - ) - - -def is_valid_session_data(content: dict[str, Any]) -> bool: - # PCT-archive mirrors these checks to validate submitted .pct files, keep both in sync - if not isinstance(content, dict): - return False - keys = ["version", "notes", "bookmarks", "address_tree", "process_name"] - for key in keys: - if key not in content: - return False - if type(content["version"]) is not int or content["version"] != LATEST_VERSION: - return False - if not isinstance(content["notes"], str) or not isinstance(content["process_name"], str): - return False - if not isinstance(content["bookmarks"], dict): - return False - for addr, value in content["bookmarks"].items(): - try: - int(addr) - except (TypeError, ValueError, OverflowError): - return False - if not isinstance(value, dict): - return False - for field in ("comment", "symbol", "address_region_details"): - if field not in value: - return False - details = value["address_region_details"] - if not isinstance(details, dict): - return False - if not isinstance(value["comment"], str) or not isinstance(value["symbol"], str): - return False - if not isinstance(details.get("region_name"), str) or not isinstance(details.get("offset_in_region"), str): - return False - if type(details.get("region_index")) is not int: - return False - try: - int(details["offset_in_region"], 16) - except ValueError: - return False - record_lists = [(content["address_tree"], 0)] - while record_lists: - records, depth = record_lists.pop() - if depth > 900 or not isinstance(records, list): - return False - for record in records: - if not isinstance(record, list) or len(record) not in (4, 5): - return False - if not isinstance(record[0], str) or not _valid_value_type(record[2]): - return False - address = record[1] - if isinstance(address, list): - if len(address) != 2 or type(address[0]) not in (str, int) or not isinstance(address[1], list): - return False - if any(type(offset) is not int for offset in address[1]): - return False - elif address is not None and type(address) not in (str, int): - return False - if len(record) == 5 and (not isinstance(record[3], dict) or not isinstance(record[3].get("script"), str)): - return False - record_lists.append((record[-1], depth + 1)) - structures = content.get("structures", {}) - if not isinstance(structures, dict): - return False - for key, data in structures.items(): - if not isinstance(key, str) or not isinstance(data, list) or len(data) != 2: - return False - name, members = data - if not isinstance(name, str) or not isinstance(members, list): - return False - for member in members: - if not isinstance(member, list) or len(member) != 5: - return False - member_name, offset, value_type, struct_ref, is_pointer = member - if not isinstance(member_name, str) or type(offset) is not int or type(is_pointer) is not bool: - return False - if (value_type is None) == (struct_ref is None): - return False - if value_type is not None and not _valid_value_type(value_type): - return False - if struct_ref is not None and not isinstance(struct_ref, str): - return False - return True - - -class Session: - def __init__(self) -> None: - # Anything labeled with pct should be saved to the session file - self.pct_notes: str = "" - self.pct_bookmarks: dict[int, dict] = {} - self.pct_version: int = LATEST_VERSION - self.pct_address_tree: list = [] - self.pct_process_name: str = "" - self.pct_structures: dict[str, tuple] = {} - self.data_changed = SessionDataChanged.NONE - self.file_path: str = os.path.expanduser("~") - self.last_file_name: str = "" # process name or file name - self.file_backed: bool = False # True when the session was loaded from or saved to a file - - def get_dialog_path(self) -> str: - """ - Returns the path the pct file dialogs should start at. - Sessions without a file of their own fall back to the directory of the last saved or loaded file, even if it - belongs to a previous run of PINCE, only if the user asked for it. - Directories that no longer exist are discarded and previous home user default is used, because Qt will just use "/root" otherwise. - - Args: - None - Returns: - str: Absolute path of the directory to open the dialog in, joined with the current file name. - """ - - directory = self.file_path - if not self.file_backed: - directory = QSettings().value(settings.LAST_PCT_DIRECTORY, "", type=str) - if not os.path.isdir(directory): - directory = os.path.expanduser("~") - return os.path.join(directory, self.last_file_name) - - def remember_session_file(self, file_path: str) -> None: - """ - Marks the session as backed by the given file and stores its directory for the next run of PINCE. - The directory is stored only if the setting exists, otherwise we stick to the default. - - Args: - file_path (str): Absolute path of the session file that was just saved or loaded - Returns: - None - """ - - self.file_path = os.path.dirname(os.path.abspath(file_path)) - self.last_file_name = os.path.basename(file_path) - self.file_backed = True - settings_instance = QSettings() - if settings_instance.contains(settings.LAST_PCT_DIRECTORY): - settings_instance.setValue(settings.LAST_PCT_DIRECTORY, self.file_path) - settings_instance.sync() - - def save_session(self, *, ask_for_path: bool = True) -> bool: - """ - Save the current session to a file. - - Args: - ask_for_path (bool): Always ask for a path, even if the session already has a file of its own - Returns: - bool: True if the session was saved successfully, False otherwise. - """ - # until address tree is model view and properly read from this new session object, - # address tree must save its data to the session object via signal - if self.data_changed & SessionDataChanged.ADDRESS_TREE: - states.session_signals.on_save.emit() - session = { - "version": self.pct_version, - "notes": self.pct_notes, - "bookmarks": self.pct_bookmarks, - "address_tree": self.pct_address_tree, - "process_name": self.pct_process_name, - "structures": self.pct_structures, - } - if not ask_for_path and self.file_backed: - file_path = os.path.join(self.file_path, self.last_file_name) - if utils.save_file(session, file_path): - guiutils.own_path_as_user(file_path) - self.data_changed = SessionDataChanged.NONE - return True - QMessageBox.information(None, tr.ERROR, tr.FILE_SAVE_ERROR) - - with guiutils.save_dialog_as_user(None, tr.SAVE_PCT_FILE, self.get_dialog_path(), tr.FILE_TYPES_PCT, "pct") as file_path: - if not file_path: - return False - if not utils.save_file(session, file_path): - QMessageBox.information(None, tr.ERROR, tr.FILE_SAVE_ERROR) - return False - self.remember_session_file(file_path) - self.data_changed = SessionDataChanged.NONE - return True - - def check_unsaved_changes(self, allow_cancel: bool = True) -> QMessageBox.StandardButton: - if self.data_changed == SessionDataChanged.NONE: - return QMessageBox.StandardButton.No - - buttons = QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No - if allow_cancel: - buttons |= QMessageBox.StandardButton.Cancel - unsaved_changes_result = QMessageBox.question( - None, - tr.SAVE_SESSION_QUESTION_TITLE, - tr.SAVE_SESSION_QUESTION_PROMPT, - buttons, - ) - return unsaved_changes_result - - def load_session(self, file_path: str | None = None) -> bool: - """ - Load a pct session file from passed argument, otherwise, opens the file picker. Will check for unsaved changes and prompt - the user to save them before loading a new session. - If the user chooses to cancel, the function will return False. - Will also attempt to migrate the session data to the latest version. - - Args: - file_path: Optional absolute path to load a session file - Returns: - bool: True if the session was loaded successfully, False otherwise. - - """ - - unsaved_changes_result = self.check_unsaved_changes() - if unsaved_changes_result == QMessageBox.StandardButton.Cancel: - return False - elif unsaved_changes_result == QMessageBox.StandardButton.Yes: - if not self.save_session(): - return False - - if file_path is None or not isinstance(file_path, str): - file_path, _ = QFileDialog.getOpenFileName(None, tr.OPEN_PCT_FILE, self.get_dialog_path(), tr.FILE_TYPES_PCT) - - if not file_path: - return False - - content = utils.load_file(file_path) - if content is None: - QMessageBox.information(None, tr.ERROR, tr.FILE_LOAD_ERROR.format(file_path)) - return False - content = migrate_version(content) - if not is_valid_session_data(content): - QMessageBox.information(None, tr.ERROR, tr.FILE_LOAD_ERROR.format(file_path)) - return False - - self.pct_version = content["version"] - self.pct_notes = content["notes"] - - # Load bookmarks with symbol resolution - self.pct_bookmarks = {int(addr): value for addr, value in content["bookmarks"].items()} - - if utils.is_process_valid(debugcore.currentpid): - self.recalculate_bookmarks() - - self.pct_address_tree = content["address_tree"] - self.pct_process_name = content["process_name"] - self.pct_structures = content.get("structures", {}) - - self.remember_session_file(file_path) - - states.session_signals.on_load.emit() - self.data_changed = SessionDataChanged.NONE - return True - - def pre_exit(self, close_event: QCloseEvent) -> None: - """ - Event handler for the close event of the application. - If there are unsaved changes, prompt the user to save them unless their decision was remembered. - Accepts or ignores the close event based on the outcome. - - Args: - close_event (QCloseEvent): The close event to be handled. - Returns: - None - """ - - if self.data_changed == SessionDataChanged.NONE: - close_event.accept() - return - - settings_instance = QSettings() - remembered = settings_instance.contains(settings.SAVE_SESSION_ON_EXIT) - if remembered: - save = settings_instance.value(settings.SAVE_SESSION_ON_EXIT, type=bool) - else: - unsaved_changes = QMessageBox() - remember_choice = QCheckBox(tr.REMEMBER_MY_DECISION) - unsaved_changes.setCheckBox(remember_choice) - unsaved_changes.setIcon(QMessageBox.Icon.Question) - unsaved_changes.setWindowTitle(tr.SAVE_SESSION_QUESTION_TITLE) - unsaved_changes.setText(tr.SAVE_SESSION_QUESTION_PROMPT) - unsaved_changes.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel) - result = QMessageBox.StandardButton(unsaved_changes.exec()) - if result == QMessageBox.StandardButton.Cancel: - close_event.ignore() - return - save = result == QMessageBox.StandardButton.Yes - if remember_choice.isChecked(): - settings_instance.setValue(settings.SAVE_SESSION_ON_EXIT, save) - settings_instance.sync() - if save and not self.save_session(ask_for_path=False) and not remembered: - close_event.ignore() - else: - close_event.accept() - - def recalculate_bookmarks(self) -> None: - """ - Recalculate all bookmarks to update their addresses based on their symbols or region info. - This is useful when the process has changed and the addresses may have shifted. - Will not mark session as changed. - - Args: - None - Returns: - None - """ - - region_dict = utils.get_region_dict(debugcore.currentpid) - - new_bookmarks: dict[int, dict] = {} - for addr, value in self.pct_bookmarks.items(): - comment = value["comment"] - symbol = value["symbol"] - address_region_details = value["address_region_details"] - new_addr = addr - - # We used to resolve the symbol first but parentheses in symbols causes the functions to be called - # For instance, main() won't be resolved to main but rather the function main() will be called - # Because of this behavior, we rely on resolving via regions - # Resolving via regions is more reliable unless the binary has been changed - # TODO: Resolving via symbols could be re-addressed if this behavior were fixed - - # resolve via region details - region_name = address_region_details["region_name"] - offset = address_region_details["offset_in_region"] - region_index = address_region_details["region_index"] - region = region_dict.get(region_name, None) - if region is None: - utils.logger.warning(f"Could not find region with name: {region_name}") - continue - if region_index < 0 or region_index >= len(region): - utils.logger.warning( - f"Region '{region_name}' now has {len(region)} mapping(s). " f"Bookmark expected index {region_index}, dropping it..." - ) - continue - new_addr = utils.safe_str_to_int(region[region_index], 16) + utils.safe_str_to_int(offset, 16) - if new_addr == 0: - continue - - new_bookmarks[new_addr] = { - "symbol": symbol, - "comment": comment, - "address_region_details": address_region_details, - } - - self.pct_bookmarks = new_bookmarks - - -class SessionManager: - session = Session() - - @staticmethod - def get_session() -> Session: - return SessionManager.session - - @staticmethod - def reset_session() -> bool: - session = SessionManager.get_session() - unsaved_changes_result = session.check_unsaved_changes(allow_cancel=False) - if unsaved_changes_result == QMessageBox.StandardButton.Yes and not session.save_session(): - QMessageBox.information(None, tr.INFO, tr.SESSION_RESET_CANCELLED) - return False - SessionManager.session = Session() - states.session_signals.new_session.emit() - SessionManager.session.data_changed = SessionDataChanged.NONE - return True - - @staticmethod - def save_session() -> None: - SessionManager.get_session().save_session() - - @staticmethod - def load_session(file_path: str | None = None) -> None: - SessionManager.get_session().load_session(file_path) - - @staticmethod - def on_process_changed() -> None: - if debugcore.currentpid == -1: - return - - if states.exiting: - return - - process_name = utils.get_process_name(debugcore.currentpid) - session = SessionManager.get_session() - - if session.pct_process_name == process_name: - # process is the same as last one, probably process restarted / reattached - session.recalculate_bookmarks() - return - - if session.pct_process_name == "": - # silently set the process name and file name if necessary - session.pct_process_name = process_name - if session.last_file_name == "": - session.last_file_name = utils.append_file_extension(process_name, "pct") - return - - if session.pct_process_name != process_name: - # Ask if the user wants to keep the session - keep_session_result = QMessageBox.question( - None, - tr.SESSION_PROCESS_CHANGED_TITLE, - tr.SESSION_PROCESS_CHANGED_PROMPT, - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - ) - if keep_session_result == QMessageBox.StandardButton.Yes: - session.pct_process_name = process_name - session.data_changed |= SessionDataChanged.PROCESS_NAME - else: - if not SessionManager.reset_session(): - return - session = SessionManager.get_session() - session.pct_process_name = process_name - session.last_file_name = utils.append_file_extension(process_name, "pct") - - -class StructureManager: - @staticmethod - def _registry() -> dict[str, tuple]: - return SessionManager.get_session().pct_structures - - @staticmethod - def list_names() -> list[str]: - return sorted(StructureManager._registry().keys()) - - @staticmethod - def get(name: str) -> typedefs.Structure | None: - data = StructureManager._registry().get(name) - return typedefs.Structure.deserialize(data) if data is not None else None - - @staticmethod - def add(structure: typedefs.Structure) -> bool: - registry = StructureManager._registry() - if structure.name in registry: - return False - registry[structure.name] = structure.serialize() - StructureManager._mark_changed() - return True - - @staticmethod - def update(structure: typedefs.Structure) -> None: - StructureManager._registry()[structure.name] = structure.serialize() - StructureManager._mark_changed() - - @staticmethod - def rename(old: str, new: str) -> bool: - registry = StructureManager._registry() - if old not in registry or new in registry: - return False - registry[new] = registry.pop(old) - for key, data in registry.items(): - structure = typedefs.Structure.deserialize(data) - if key == new: - structure.name = new - for member in structure.members: - if member.struct_ref == old: - member.struct_ref = new - registry[key] = structure.serialize() - StructureManager._mark_changed() - return True - - @staticmethod - def delete(name: str) -> None: - if StructureManager._registry().pop(name, None) is not None: - StructureManager._mark_changed() - - @staticmethod - def _mark_changed() -> None: - SessionManager.get_session().data_changed |= SessionDataChanged.STRUCTURES diff --git a/GUI/Settings/settings.py b/GUI/Settings/settings.py deleted file mode 100644 index 4d9e0aaa..00000000 --- a/GUI/Settings/settings.py +++ /dev/null @@ -1,188 +0,0 @@ -from PyQt6.QtCore import QSettings -from PyQt6.QtGui import QIcon -from PyQt6.QtWidgets import QApplication -from GUI.States import states -from GUI.Settings import themes -from GUI.Utils import guiutils -from tr.tr import get_locale -from libpince import debugcore, utils, typedefs -import json, os - -current_settings_version = "37" # Increase version by one if you change settings -CHECK_UPDATES_ON_STARTUP = "General/check_updates_on_startup" -SAVE_SESSION_ON_EXIT = "General/save_session_on_exit" -LAST_PCT_DIRECTORY = "General/last_pct_directory" - -# Due to community feedback, these signals are disabled by default: SIGUSR1, SIGUSR2, SIGPWR, SIGXCPU, SIGXFSZ, SIGSYS -default_signals = [ - ["SIGHUP", True, True], - ["SIGINT", True, False], - ["SIGQUIT", True, True], - ["SIGILL", True, True], - ["SIGTRAP", True, False], - ["SIGABRT", True, True], - ["SIGEMT", True, True], - ["SIGFPE", True, True], - ["SIGKILL", True, True], - ["SIGBUS", True, True], - ["SIGSEGV", True, True], - ["SIGSYS", False, True], - ["SIGPIPE", True, True], - ["SIGALRM", False, True], - ["SIGTERM", True, True], - ["SIGURG", False, True], - ["SIGSTOP", True, True], - ["SIGTSTP", True, True], - ["SIGCONT", True, True], - ["SIGCHLD", False, True], - ["SIGTTIN", True, True], - ["SIGTTOU", True, True], - ["SIGIO", False, True], - ["SIGXCPU", False, True], - ["SIGXFSZ", False, True], - ["SIGVTALRM", False, True], - ["SIGPROF", False, True], - ["SIGWINCH", False, True], - ["SIGLOST", True, True], - ["SIGUSR1", False, True], - ["SIGUSR2", False, True], - ["SIGPWR", False, True], - ["SIGPOLL", False, True], - ["SIGWIND", True, True], - ["SIGPHONE", True, True], - ["SIGWAITING", False, True], - ["SIGLWP", False, True], - ["SIGDANGER", True, True], - ["SIGGRANT", True, True], - ["SIGRETRACT", True, True], - ["SIGMSG", True, True], - ["SIGSOUND", True, True], - ["SIGSAK", True, True], - ["SIGPRIO", False, True], - ["SIGCANCEL", False, True], - ["SIGINFO", True, True], - ["EXC_BAD_ACCESS", True, True], - ["EXC_BAD_INSTRUCTION", True, True], - ["EXC_ARITHMETIC", True, True], - ["EXC_EMULATION", True, True], - ["EXC_SOFTWARE", True, True], - ["EXC_BREAKPOINT", True, True], - ["SIGLIBRT", False, True], -] -for x in range(32, 128): # Add signals SIG32-SIG127 - default_signals.append([f"SIG{x}", True, True]) - - -def init_settings() -> None: - settings = QSettings() - if not os.path.exists(settings.fileName()): - set_default_settings() - try: - settings_version = settings.value("Misc/version", type=str) - except Exception: - utils.logger.exception("An exception occurred while reading settings version") - settings_version = None - if settings_version != current_settings_version: - utils.logger.warning("Settings version mismatch, rolling back to the default configuration") - settings.clear() - set_default_settings() - try: - apply_settings() - except Exception: - utils.logger.exception("An exception occurred while loading settings, rolling back to the default configuration") - settings.clear() - set_default_settings() - - -# Please refrain from using python specific objects in settings, use json-compatible ones instead -# Using python objects causes issues when filenames change -def set_default_settings() -> None: - settings = QSettings() - settings.beginGroup("General") - settings.setValue("auto_update_address_table", True) - settings.setValue("address_table_update_interval", 500) - settings.setValue("freeze_interval", 100) - settings.setValue("gdb_output_mode", json.dumps([True, True, True])) - settings.setValue("auto_attach", "") - settings.setValue("auto_attach_regex", False) - settings.setValue("locale", get_locale()) - settings.setValue("logo_path", "ozgurozbek/pince_small_transparent.png") - settings.setValue("theme", themes.Themes.DEFAULT.value) - settings.endGroup() - settings.remove(SAVE_SESSION_ON_EXIT) - settings.remove(LAST_PCT_DIRECTORY) - settings.beginGroup("Hotkeys") - for hotkey in states.hotkeys.get_hotkeys(): - settings.setValue(hotkey.name, hotkey.default) - settings.endGroup() - settings.beginGroup("MemoryView") - settings.setValue("show_memory_view_on_stop", False) - settings.setValue("instructions_per_scroll", 3) - settings.setValue("bytes_per_scroll", 0x40) - settings.endGroup() - settings.beginGroup("Debug") - settings.setValue("gdb_path", typedefs.PATHS.GDB) - settings.setValue("gdb_logging", False) - settings.setValue("interrupt_signal", "SIGINT") - settings.setValue("handle_signals", json.dumps(default_signals)) - settings.endGroup() - settings.beginGroup("Java") - settings.setValue("ignore_segfault", True) - settings.endGroup() - settings.beginGroup("Misc") - settings.setValue("version", current_settings_version) - settings.endGroup() - apply_settings() - - -def apply_settings() -> None: - settings = QSettings() - states.update_table = settings.value("General/auto_update_address_table", type=bool) - states.table_update_interval = settings.value("General/address_table_update_interval", type=int) - states.freeze_interval = settings.value("General/freeze_interval", type=int) - gdb_output_mode = json.loads(settings.value("General/gdb_output_mode", type=str)) - gdb_output_mode = typedefs.gdb_output_mode(*gdb_output_mode) - states.auto_attach = settings.value("General/auto_attach", type=str) - states.auto_attach_regex = settings.value("General/auto_attach_regex", type=bool) - QApplication.setWindowIcon(QIcon(os.path.join(utils.get_logo_directory(), settings.value("General/logo_path", type=str)))) - QApplication.setPalette(themes.get_theme(settings.value("General/theme", type=str))) - debugcore.set_gdb_output_mode(gdb_output_mode) - for hotkey in states.hotkeys.get_hotkeys(): - try: - hotkey.change_key(settings.value("Hotkeys/" + hotkey.name)) - except: - # if the hotkey cannot be applied for whatever reason, reset it to the default - settings.setValue("Hotkeys/" + hotkey.name, hotkey.default) - hotkey.change_key(hotkey.default) - states.show_memory_view_on_stop = settings.value("MemoryView/show_memory_view_on_stop", type=bool) - states.instructions_per_scroll = settings.value("MemoryView/instructions_per_scroll", type=int) - states.bytes_per_scroll = settings.value("MemoryView/bytes_per_scroll", type=int) - states.gdb_path = settings.value("Debug/gdb_path", type=str) - if debugcore.gdb_initialized: - apply_after_init() - states.setting_signals.changed.emit() - - -def apply_after_init() -> None: - settings = QSettings() - states.exp_cache.clear() - states.gdb_logging = settings.value("Debug/gdb_logging", type=bool) - interrupt_signal = settings.value("Debug/interrupt_signal", type=str) - handle_signals = json.loads(settings.value("Debug/handle_signals", type=str)) - java_ignore_segfault = settings.value("Java/ignore_segfault", type=bool) - debugcore.set_logging(states.gdb_logging) - - # Don't handle signals if a process isn't present, a small optimization to gain time on launch and detach - if debugcore.currentpid != -1: - debugcore.handle_signals(handle_signals) - # Not a great method but okayish until the implementation of the libpince engine and the java dissector - # "jps" command could be used instead if we ever need to install openjdk - if java_ignore_segfault and utils.get_process_name(debugcore.currentpid).startswith("java"): - debugcore.handle_signal("SIGSEGV", False, True) - debugcore.set_interrupt_signal(interrupt_signal) # Needs to be called after handle_signals - - # gdb init/attach has just created root-owned files so we'll chown them as the real user. - guiutils.own_path_as_user("/var/log/pince.log") # mirrors utils.init_logging - guiutils.own_path_as_user(utils.get_user_path(typedefs.USER_PATHS.ROOT), recursive=True) - guiutils.own_path_as_user(typedefs.PATHS.TMP, recursive=True) - guiutils.own_path_as_user(typedefs.PATHS.IPC, recursive=True) diff --git a/GUI/Settings/themes.py b/GUI/Settings/themes.py deleted file mode 100644 index fd8f6498..00000000 --- a/GUI/Settings/themes.py +++ /dev/null @@ -1,246 +0,0 @@ -from PyQt6.QtGui import QColor, QPalette -from tr.tr import TranslationConstants as tr -from enum import Enum -from collections import OrderedDict -from libpince import utils - - -# For settings -class Themes(Enum): - DARK = "dark" - LIGHT = "light" - DEFAULT = "default" - WONG = "wong" - - -# For translations -theme_strings = OrderedDict( - [ - (Themes.DARK.value, tr.DARK), - (Themes.LIGHT.value, tr.LIGHT), - (Themes.DEFAULT.value, tr.SYSTEM_DEFAULT), - (Themes.WONG.value, tr.WONG), - ] -) - -grp_dict = { - "ACTIVE": QPalette.ColorGroup.Active, - "INACTIVE": QPalette.ColorGroup.Inactive, - "DISABLED": QPalette.ColorGroup.Disabled, -} - -role_dict = { - "WINDOW_TEXT": QPalette.ColorRole.WindowText, - "BUTTON": QPalette.ColorRole.Button, - "LIGHT": QPalette.ColorRole.Light, - "MID_LIGHT": QPalette.ColorRole.Midlight, - "DARK": QPalette.ColorRole.Dark, - "MID": QPalette.ColorRole.Mid, - "TEXT": QPalette.ColorRole.Text, - "BRIGHT_TEXT": QPalette.ColorRole.BrightText, - "BUTTON_TEXT": QPalette.ColorRole.ButtonText, - "BASE": QPalette.ColorRole.Base, - "WINDOW": QPalette.ColorRole.Window, - "SHADOW": QPalette.ColorRole.Shadow, - "HIGHLIGHT": QPalette.ColorRole.Highlight, - "HIGHLIGHTED_TEXT": QPalette.ColorRole.HighlightedText, - "LINK": QPalette.ColorRole.Link, - "LINK_VISITED": QPalette.ColorRole.LinkVisited, - "ALTERNATE_BASE": QPalette.ColorRole.AlternateBase, - "TOOLTIP_BASE": QPalette.ColorRole.ToolTipBase, - "TOOLTIP_TEXT": QPalette.ColorRole.ToolTipText, - "PLACEHOLDER_TEXT": QPalette.ColorRole.PlaceholderText, -} - - -def get_theme(theme_name: str) -> QPalette: - """Returns a customized theme based on the specified theme choice - - Args: - theme_name (str): Predefined theme chosen from Themes - - Returns: - QPalette: Complete color palette swap for the app - """ - match theme_name: - case Themes.DARK.value: - dup_dict = { - "WINDOW_TEXT": "#FFFFFF", - "BUTTON": "#241F31", - "LIGHT": "#80FFFFFF", - "MID_LIGHT": "#2D263D", - "DARK": "#80000000", - "MID": "#000000", - "TEXT": "#FFFFFF", - "BRIGHT_TEXT": "#FFFFFF", - "BUTTON_TEXT": "#FFFFFF", - "BASE": "#000000", - "WINDOW": "#241F31", - "SHADOW": "#000000", - "HIGHLIGHT": "#308CC6", - "HIGHLIGHTED_TEXT": "#FFFFFF", - "LINK": "#0000FF", - "LINK_VISITED": "#FF00FF", - "ALTERNATE_BASE": "#120F18", - "TOOLTIP_BASE": "#FFFFDC", - "TOOLTIP_TEXT": "#000000", - "PLACEHOLDER_TEXT": "#80FFFFFF", - } - - dark_dict = { - "ACTIVE": dup_dict, - "INACTIVE": dup_dict, - "DISABLED": { - "WINDOW_TEXT": "#80FFFFFF", - "BUTTON": "#241F31", - "LIGHT": "#362E49", - "MID_LIGHT": "#2D263D", - "DARK": "#120F18", - "MID": "#181521", - "TEXT": "#44414A", - "BRIGHT_TEXT": "#FFFFFF", - "BUTTON_TEXT": "#80FFFFFF", - "BASE": "#241F31", - "WINDOW": "#241F31", - "SHADOW": "#000000", - "HIGHLIGHT": "#919191", - "HIGHLIGHTED_TEXT": "#FFFFFF", - "LINK": "#0000FF", - "LINK_VISITED": "#FF00FF", - "ALTERNATE_BASE": "#241F31", - "TOOLTIP_BASE": "#FFFFDC", - "TOOLTIP_TEXT": "#000000", - "PLACEHOLDER_TEXT": "#80FFFFFF", - }, - } - return apply_palette(dark_dict) - case Themes.LIGHT.value: - dup_dict = { - "WINDOW_TEXT": "#000000", - "BUTTON": "#EFEFEF", - "LIGHT": "#FFFFFF", - "MID_LIGHT": "#CACACA", - "DARK": "#5E5C64", - "MID": "#B8B8B8", - "TEXT": "#000000", - "BRIGHT_TEXT": "#FFFFFF", - "BUTTON_TEXT": "#000000", - "BASE": "#FFFFFF", - "WINDOW": "#EFEFEF", - "SHADOW": "#767676", - "HIGHLIGHT": "#308CC6", - "HIGHLIGHTED_TEXT": "#FFFFFF", - "LINK": "#0000FF", - "LINK_VISITED": "#FF00FF", - "ALTERNATE_BASE": "#F7F7F7", - "TOOLTIP_BASE": "#FFFFDC", - "TOOLTIP_TEXT": "#000000", - "PLACEHOLDER_TEXT": "#80000000", - } - - light_dict = { - "ACTIVE": dup_dict, - "INACTIVE": dup_dict, - "DISABLED": { - "WINDOW_TEXT": "#BEBEBE", - "BUTTON": "#EFEFEF", - "LIGHT": "#FFFFFF", - "MID_LIGHT": "#CACACA", - "DARK": "#BEBEBE", - "MID": "#B8B8B8", - "TEXT": "#BEBEBE", - "BRIGHT_TEXT": "#FFFFFF", - "BUTTON_TEXT": "#BEBEBE", - "BASE": "#EFEFEF", - "WINDOW": "#EFEFEF", - "SHADOW": "#B1B1B1", - "HIGHLIGHT": "#919191", - "HIGHLIGHTED_TEXT": "#FFFFFF", - "LINK": "#0000FF", - "LINK_VISITED": "#FF00FF", - "ALTERNATE_BASE": "#F7F7F7", - "TOOLTIP_BASE": "#FFFFDC", - "TOOLTIP_TEXT": "#000000", - "PLACEHOLDER_TEXT": "#80000000", - }, - } - return apply_palette(light_dict) - case Themes.DEFAULT.value: - palette_with_fix = QPalette() - palette_with_fix.setColor(QPalette.ColorRole.PlaceholderText, palette_with_fix.color(QPalette.ColorRole.Text).darker()) - return palette_with_fix - case Themes.WONG.value: - dup_dict = { - "WINDOW_TEXT": "#000000", - "BUTTON": "#E69F00", - "LIGHT": "#FFFFFF", - "MID_LIGHT": "#000000", - "DARK": "#000000", - "MID": "#000000", - "TEXT": "#000000", - "BRIGHT_TEXT": "#FFFFFF", - "BUTTON_TEXT": "#000000", - "BASE": "#E69F00", - "WINDOW": "#009E73", - "SHADOW": "#009E73", - "HIGHLIGHT": "#0072B2", - "HIGHLIGHTED_TEXT": "#FFFFFF", - "LINK": "#56B4E9", - "LINK_VISITED": "#CC79A7", - "ALTERNATE_BASE": "#E69F00", - "TOOLTIP_BASE": "#FFFFDC", - "TOOLTIP_TEXT": "#000000", - "PLACEHOLDER_TEXT": "#80000000", - } - - wong_dict = { - "ACTIVE": dup_dict, - "INACTIVE": dup_dict, - "DISABLED": { - "WINDOW_TEXT": "#80000000", - "BUTTON": "#E69F00", - "LIGHT": "#FFFFFF", - "MID_LIGHT": "#FFFFFF", - "DARK": "#FFFFFF", - "MID": "#FFFFFF", - "TEXT": "#FFFFFF", - "BRIGHT_TEXT": "#000000", - "BUTTON_TEXT": "#80000000", - "BASE": "#E69F00", - "WINDOW": "#000000", - "SHADOW": "#F0E442", - "HIGHLIGHT": "#919191", - "HIGHLIGHTED_TEXT": "#000000", - "LINK": "#56b4E9", - "LINK_VISITED": "#CC79A7", - "ALTERNATE_BASE": "#919191", - "TOOLTIP_BASE": "#000000", - "TOOLTIP_TEXT": "#FFFFFF", - "PLACEHOLDER_TEXT": "#80000000", - }, - } - return apply_palette(wong_dict) - case _: - utils.logger.error("There was an error parsing themes") - return QPalette() - - -def apply_palette(theme_dict: dict[str, dict[str, str]]) -> QPalette: - """Creates a palette based on the given theme dictionary - - Args: - theme_dict (dict): See the usage in get_theme - - Return: - QPalette: Self-explanatory - """ - new_palette = QPalette() - - for group in theme_dict: - cur_grp = grp_dict[group] - - for color in theme_dict[group]: - cur_role = role_dict[color] - new_palette.setColor(cur_grp, cur_role, QColor(theme_dict[group][color])) - - return new_palette diff --git a/GUI/SettingsDialog.py b/GUI/SettingsDialog.py new file mode 100644 index 00000000..6a6435c7 --- /dev/null +++ b/GUI/SettingsDialog.py @@ -0,0 +1,245 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'SettingsDialog.ui' +# +# Created: Wed Aug 24 16:12:06 2016 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_Dialog(object): + def setupUi(self, Dialog): + Dialog.setObjectName("Dialog") + Dialog.resize(658, 555) + self.gridLayout_2 = QtWidgets.QGridLayout(Dialog) + self.gridLayout_2.setObjectName("gridLayout_2") + self.verticalLayout = QtWidgets.QVBoxLayout() + self.verticalLayout.setObjectName("verticalLayout") + self.horizontalLayout_2 = QtWidgets.QHBoxLayout() + self.horizontalLayout_2.setObjectName("horizontalLayout_2") + self.listWidget_Options = QtWidgets.QListWidget(Dialog) + sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding) + sizePolicy.setHorizontalStretch(0) + sizePolicy.setVerticalStretch(0) + sizePolicy.setHeightForWidth(self.listWidget_Options.sizePolicy().hasHeightForWidth()) + self.listWidget_Options.setSizePolicy(sizePolicy) + self.listWidget_Options.setMaximumSize(QtCore.QSize(130, 16777215)) + self.listWidget_Options.setObjectName("listWidget_Options") + item = QtWidgets.QListWidgetItem() + self.listWidget_Options.addItem(item) + item = QtWidgets.QListWidgetItem() + self.listWidget_Options.addItem(item) + item = QtWidgets.QListWidgetItem() + self.listWidget_Options.addItem(item) + item = QtWidgets.QListWidgetItem() + self.listWidget_Options.addItem(item) + self.horizontalLayout_2.addWidget(self.listWidget_Options) + self.stackedWidget = QtWidgets.QStackedWidget(Dialog) + self.stackedWidget.setMinimumSize(QtCore.QSize(500, 500)) + self.stackedWidget.setObjectName("stackedWidget") + self.page = QtWidgets.QWidget() + self.page.setObjectName("page") + self.gridLayout = QtWidgets.QGridLayout(self.page) + self.gridLayout.setObjectName("gridLayout") + self.verticalLayout_5 = QtWidgets.QVBoxLayout() + self.verticalLayout_5.setObjectName("verticalLayout_5") + self.horizontalLayout_7 = QtWidgets.QHBoxLayout() + self.horizontalLayout_7.setObjectName("horizontalLayout_7") + self.verticalLayout_3 = QtWidgets.QVBoxLayout() + self.verticalLayout_3.setObjectName("verticalLayout_3") + self.verticalLayout_2 = QtWidgets.QVBoxLayout() + self.verticalLayout_2.setObjectName("verticalLayout_2") + self.checkBox_AutoUpdateAddressTable = QtWidgets.QCheckBox(self.page) + self.checkBox_AutoUpdateAddressTable.setChecked(True) + self.checkBox_AutoUpdateAddressTable.setObjectName("checkBox_AutoUpdateAddressTable") + self.verticalLayout_2.addWidget(self.checkBox_AutoUpdateAddressTable) + self.verticalLayout_3.addLayout(self.verticalLayout_2) + self.QWidget_UpdateInterval = QtWidgets.QWidget(self.page) + self.QWidget_UpdateInterval.setObjectName("QWidget_UpdateInterval") + self.horizontalLayout_UpdateInterval = QtWidgets.QHBoxLayout(self.QWidget_UpdateInterval) + self.horizontalLayout_UpdateInterval.setContentsMargins(0, 0, 0, 0) + self.horizontalLayout_UpdateInterval.setObjectName("horizontalLayout_UpdateInterval") + self.label = QtWidgets.QLabel(self.QWidget_UpdateInterval) + self.label.setObjectName("label") + self.horizontalLayout_UpdateInterval.addWidget(self.label) + self.lineEdit_UpdateInterval = QtWidgets.QLineEdit(self.QWidget_UpdateInterval) + self.lineEdit_UpdateInterval.setObjectName("lineEdit_UpdateInterval") + self.horizontalLayout_UpdateInterval.addWidget(self.lineEdit_UpdateInterval) + self.label_2 = QtWidgets.QLabel(self.QWidget_UpdateInterval) + self.label_2.setObjectName("label_2") + self.horizontalLayout_UpdateInterval.addWidget(self.label_2) + self.verticalLayout_3.addWidget(self.QWidget_UpdateInterval) + self.horizontalLayout_7.addLayout(self.verticalLayout_3) + spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_7.addItem(spacerItem) + self.verticalLayout_5.addLayout(self.horizontalLayout_7) + spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_5.addItem(spacerItem1) + self.gridLayout.addLayout(self.verticalLayout_5, 0, 0, 1, 1) + self.stackedWidget.addWidget(self.page) + self.page_2 = QtWidgets.QWidget() + self.page_2.setObjectName("page_2") + self.gridLayout_3 = QtWidgets.QGridLayout(self.page_2) + self.gridLayout_3.setObjectName("gridLayout_3") + self.horizontalLayout_5 = QtWidgets.QHBoxLayout() + self.horizontalLayout_5.setObjectName("horizontalLayout_5") + self.verticalLayout_4 = QtWidgets.QVBoxLayout() + self.verticalLayout_4.setObjectName("verticalLayout_4") + self.label_3 = QtWidgets.QLabel(self.page_2) + self.label_3.setObjectName("label_3") + self.verticalLayout_4.addWidget(self.label_3) + self.listWidget_Functions = QtWidgets.QListWidget(self.page_2) + self.listWidget_Functions.setObjectName("listWidget_Functions") + item = QtWidgets.QListWidgetItem() + self.listWidget_Functions.addItem(item) + item = QtWidgets.QListWidgetItem() + self.listWidget_Functions.addItem(item) + self.verticalLayout_4.addWidget(self.listWidget_Functions) + self.horizontalLayout_5.addLayout(self.verticalLayout_4) + self.verticalLayout_6 = QtWidgets.QVBoxLayout() + self.verticalLayout_6.setObjectName("verticalLayout_6") + self.verticalLayout_Hotkey = QtWidgets.QVBoxLayout() + self.verticalLayout_Hotkey.setObjectName("verticalLayout_Hotkey") + self.label_4 = QtWidgets.QLabel(self.page_2) + self.label_4.setObjectName("label_4") + self.verticalLayout_Hotkey.addWidget(self.label_4) + self.verticalLayout_6.addLayout(self.verticalLayout_Hotkey) + self.horizontalLayout_4 = QtWidgets.QHBoxLayout() + self.horizontalLayout_4.setObjectName("horizontalLayout_4") + spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_4.addItem(spacerItem2) + self.pushButton_ClearHotkey = QtWidgets.QPushButton(self.page_2) + self.pushButton_ClearHotkey.setObjectName("pushButton_ClearHotkey") + self.horizontalLayout_4.addWidget(self.pushButton_ClearHotkey) + self.verticalLayout_6.addLayout(self.horizontalLayout_4) + spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_6.addItem(spacerItem3) + self.horizontalLayout_5.addLayout(self.verticalLayout_6) + self.gridLayout_3.addLayout(self.horizontalLayout_5, 0, 0, 1, 1) + self.stackedWidget.addWidget(self.page_2) + self.page_3 = QtWidgets.QWidget() + self.page_3.setObjectName("page_3") + self.gridLayout_4 = QtWidgets.QGridLayout(self.page_3) + self.gridLayout_4.setObjectName("gridLayout_4") + self.verticalLayout_9 = QtWidgets.QVBoxLayout() + self.verticalLayout_9.setObjectName("verticalLayout_9") + self.horizontalLayout_8 = QtWidgets.QHBoxLayout() + self.horizontalLayout_8.setObjectName("horizontalLayout_8") + self.verticalLayout_8 = QtWidgets.QVBoxLayout() + self.verticalLayout_8.setObjectName("verticalLayout_8") + self.label_5 = QtWidgets.QLabel(self.page_3) + self.label_5.setObjectName("label_5") + self.verticalLayout_8.addWidget(self.label_5) + self.horizontalLayout_6 = QtWidgets.QHBoxLayout() + self.horizontalLayout_6.setObjectName("horizontalLayout_6") + spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_6.addItem(spacerItem4) + self.verticalLayout_7 = QtWidgets.QVBoxLayout() + self.verticalLayout_7.setObjectName("verticalLayout_7") + self.radioButton_SimpleDLopenCall = QtWidgets.QRadioButton(self.page_3) + self.radioButton_SimpleDLopenCall.setChecked(True) + self.radioButton_SimpleDLopenCall.setObjectName("radioButton_SimpleDLopenCall") + self.verticalLayout_7.addWidget(self.radioButton_SimpleDLopenCall) + self.radioButton_AdvancedInjection = QtWidgets.QRadioButton(self.page_3) + self.radioButton_AdvancedInjection.setEnabled(False) + self.radioButton_AdvancedInjection.setObjectName("radioButton_AdvancedInjection") + self.verticalLayout_7.addWidget(self.radioButton_AdvancedInjection) + self.horizontalLayout_6.addLayout(self.verticalLayout_7) + self.verticalLayout_8.addLayout(self.horizontalLayout_6) + self.horizontalLayout_8.addLayout(self.verticalLayout_8) + spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_8.addItem(spacerItem5) + self.verticalLayout_9.addLayout(self.horizontalLayout_8) + spacerItem6 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_9.addItem(spacerItem6) + self.gridLayout_4.addLayout(self.verticalLayout_9, 0, 0, 1, 1) + self.stackedWidget.addWidget(self.page_3) + self.page_4 = QtWidgets.QWidget() + self.page_4.setObjectName("page_4") + self.gridLayout_5 = QtWidgets.QGridLayout(self.page_4) + self.gridLayout_5.setObjectName("gridLayout_5") + self.verticalLayout_10 = QtWidgets.QVBoxLayout() + self.verticalLayout_10.setObjectName("verticalLayout_10") + self.checkBox_BringDisassembleToFront = QtWidgets.QCheckBox(self.page_4) + self.checkBox_BringDisassembleToFront.setChecked(True) + self.checkBox_BringDisassembleToFront.setObjectName("checkBox_BringDisassembleToFront") + self.verticalLayout_10.addWidget(self.checkBox_BringDisassembleToFront) + self.horizontalLayout_10 = QtWidgets.QHBoxLayout() + self.horizontalLayout_10.setObjectName("horizontalLayout_10") + self.horizontalLayout_9 = QtWidgets.QHBoxLayout() + self.horizontalLayout_9.setObjectName("horizontalLayout_9") + self.label_6 = QtWidgets.QLabel(self.page_4) + self.label_6.setObjectName("label_6") + self.horizontalLayout_9.addWidget(self.label_6) + self.lineEdit_InstructionsPerScroll = QtWidgets.QLineEdit(self.page_4) + self.lineEdit_InstructionsPerScroll.setObjectName("lineEdit_InstructionsPerScroll") + self.horizontalLayout_9.addWidget(self.lineEdit_InstructionsPerScroll) + self.horizontalLayout_10.addLayout(self.horizontalLayout_9) + spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout_10.addItem(spacerItem7) + self.verticalLayout_10.addLayout(self.horizontalLayout_10) + spacerItem8 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) + self.verticalLayout_10.addItem(spacerItem8) + self.gridLayout_5.addLayout(self.verticalLayout_10, 0, 0, 1, 1) + self.stackedWidget.addWidget(self.page_4) + self.horizontalLayout_2.addWidget(self.stackedWidget) + self.verticalLayout.addLayout(self.horizontalLayout_2) + self.horizontalLayout = QtWidgets.QHBoxLayout() + self.horizontalLayout.setObjectName("horizontalLayout") + self.pushButton_ResetSettings = QtWidgets.QPushButton(Dialog) + self.pushButton_ResetSettings.setObjectName("pushButton_ResetSettings") + self.horizontalLayout.addWidget(self.pushButton_ResetSettings) + spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) + self.horizontalLayout.addItem(spacerItem9) + self.buttonBox = QtWidgets.QDialogButtonBox(Dialog) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) + self.buttonBox.setObjectName("buttonBox") + self.horizontalLayout.addWidget(self.buttonBox) + self.verticalLayout.addLayout(self.horizontalLayout) + self.gridLayout_2.addLayout(self.verticalLayout, 0, 0, 1, 1) + + self.retranslateUi(Dialog) + self.stackedWidget.setCurrentIndex(0) + self.listWidget_Functions.setCurrentRow(-1) + self.buttonBox.accepted.connect(Dialog.accept) + self.buttonBox.rejected.connect(Dialog.reject) + QtCore.QMetaObject.connectSlotsByName(Dialog) + + def retranslateUi(self, Dialog): + _translate = QtCore.QCoreApplication.translate + Dialog.setWindowTitle(_translate("Dialog", "Settings")) + __sortingEnabled = self.listWidget_Options.isSortingEnabled() + self.listWidget_Options.setSortingEnabled(False) + item = self.listWidget_Options.item(0) + item.setText(_translate("Dialog", "General")) + item = self.listWidget_Options.item(1) + item.setText(_translate("Dialog", "Hotkeys")) + item = self.listWidget_Options.item(2) + item.setText(_translate("Dialog", "Code Injection")) + item = self.listWidget_Options.item(3) + item.setText(_translate("Dialog", "Disassemble")) + self.listWidget_Options.setSortingEnabled(__sortingEnabled) + self.checkBox_AutoUpdateAddressTable.setText(_translate("Dialog", "Auto-update address table")) + self.label.setText(_translate("Dialog", "Update interval")) + self.lineEdit_UpdateInterval.setText(_translate("Dialog", "0.5")) + self.label_2.setText(_translate("Dialog", "sec")) + self.label_3.setText(_translate("Dialog", "Functions")) + __sortingEnabled = self.listWidget_Functions.isSortingEnabled() + self.listWidget_Functions.setSortingEnabled(False) + item = self.listWidget_Functions.item(0) + item.setText(_translate("Dialog", "Pause the process")) + item = self.listWidget_Functions.item(1) + item.setText(_translate("Dialog", "Continue the process")) + self.listWidget_Functions.setSortingEnabled(__sortingEnabled) + self.label_4.setText(_translate("Dialog", "Hotkey")) + self.pushButton_ClearHotkey.setText(_translate("Dialog", "Clear")) + self.label_5.setText(_translate("Dialog", "Code injection method:")) + self.radioButton_SimpleDLopenCall.setText(_translate("Dialog", "Simple dlopen call")) + self.radioButton_AdvancedInjection.setText(_translate("Dialog", "Advanced Injection")) + self.checkBox_BringDisassembleToFront.setText(_translate("Dialog", "Bring disassemble screen to front when the inferior is stopped")) + self.label_6.setText(_translate("Dialog", "Instructions shown per scroll")) + self.pushButton_ResetSettings.setText(_translate("Dialog", "Reset Settings")) + diff --git a/GUI/SettingsDialog.ui b/GUI/SettingsDialog.ui new file mode 100644 index 00000000..7cc72195 --- /dev/null +++ b/GUI/SettingsDialog.ui @@ -0,0 +1,468 @@ + + + Dialog + + + + 0 + 0 + 658 + 555 + + + + Settings + + + + + + + + + + + 0 + 0 + + + + + 130 + 16777215 + + + + + General + + + + + Hotkeys + + + + + Code Injection + + + + + Disassemble + + + + + + + + + 500 + 500 + + + + 0 + + + + + + + + + + + + + + + Auto-update address table + + + true + + + + + + + + + + + + Update interval + + + + + + + 0.5 + + + + + + + sec + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + + Functions + + + + + + + -1 + + + + Pause the process + + + + + Continue the process + + + + + + + + + + + + + + Hotkey + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Clear + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + + + + + + Code injection method: + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Simple dlopen call + + + true + + + + + + + false + + + Advanced Injection + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + Bring disassemble screen to front when the inferior is stopped + + + true + + + + + + + + + + + Instructions shown per scroll + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + + Reset Settings + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + + + buttonBox + accepted() + Dialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + Dialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/GUI/Widgets/StackTraceInfo/Form/StackTraceInfoWidget.py b/GUI/StackTraceInfoWidget.py similarity index 52% rename from GUI/Widgets/StackTraceInfo/Form/StackTraceInfoWidget.py rename to GUI/StackTraceInfoWidget.py index 52c47cb7..e9877bcc 100644 --- a/GUI/Widgets/StackTraceInfo/Form/StackTraceInfoWidget.py +++ b/GUI/StackTraceInfoWidget.py @@ -1,13 +1,13 @@ -# Form implementation generated from reading ui file 'Widgets/StackTraceInfo/Form/StackTraceInfoWidget.ui' +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'stacktraceinfowidget.ui' # -# Created by: PyQt6 UI code generator 6.11.0 +# Created: Tue Jul 26 21:56:27 2016 +# by: PyQt5 UI code generator 5.2.1 # -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets +# WARNING! All changes made in this file will be lost! +from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): @@ -15,35 +15,29 @@ def setupUi(self, Form): Form.resize(768, 440) self.gridLayout = QtWidgets.QGridLayout(Form) self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=Form) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) + self.splitter = QtWidgets.QSplitter(Form) + self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") - self.layoutWidget = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget.setObjectName("layoutWidget") - self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) + self.widget = QtWidgets.QWidget(self.splitter) + self.widget.setObjectName("widget") + self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") - self.label = QtWidgets.QLabel(parent=self.layoutWidget) + self.label = QtWidgets.QLabel(self.widget) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) - self.listWidget_ReturnAddresses = QtWidgets.QListWidget(parent=self.layoutWidget) - font = QtGui.QFont() - font.setFamily("Monospace") - self.listWidget_ReturnAddresses.setFont(font) + self.listWidget_ReturnAddresses = QtWidgets.QListWidget(self.widget) self.listWidget_ReturnAddresses.setObjectName("listWidget_ReturnAddresses") self.verticalLayout.addWidget(self.listWidget_ReturnAddresses) - self.layoutWidget1 = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget1.setObjectName("layoutWidget1") - self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget1) + self.widget1 = QtWidgets.QWidget(self.splitter) + self.widget1.setObjectName("widget1") + self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget1) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") - self.label_2 = QtWidgets.QLabel(parent=self.layoutWidget1) + self.label_2 = QtWidgets.QLabel(self.widget1) self.label_2.setObjectName("label_2") self.verticalLayout_2.addWidget(self.label_2) - self.textBrowser_Info = QtWidgets.QTextBrowser(parent=self.layoutWidget1) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_Info.setFont(font) + self.textBrowser_Info = QtWidgets.QTextBrowser(self.widget1) self.textBrowser_Info.setObjectName("textBrowser_Info") self.verticalLayout_2.addWidget(self.textBrowser_Info) self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) @@ -56,3 +50,4 @@ def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "StackTrace Information")) self.label.setText(_translate("Form", "Return Address")) self.label_2.setText(_translate("Form", "Info")) + diff --git a/GUI/Widgets/StackTraceInfo/Form/StackTraceInfoWidget.ui b/GUI/StackTraceInfoWidget.ui similarity index 74% rename from GUI/Widgets/StackTraceInfo/Form/StackTraceInfoWidget.ui rename to GUI/StackTraceInfoWidget.ui index c8092fc3..857ef1ba 100644 --- a/GUI/Widgets/StackTraceInfo/Form/StackTraceInfoWidget.ui +++ b/GUI/StackTraceInfoWidget.ui @@ -19,7 +19,7 @@ Qt::Horizontal - + @@ -29,17 +29,11 @@ - - - - Monospace - - - + - + @@ -49,13 +43,7 @@ - - - - Monospace - - - + diff --git a/GUI/States/states.py b/GUI/States/states.py deleted file mode 100644 index fb3aad86..00000000 --- a/GUI/States/states.py +++ /dev/null @@ -1,48 +0,0 @@ -from PyQt6.QtCore import QThreadPool -from GUI.Utils import guitypedefs -from libpince import debugcore - -process_signals = guitypedefs.ProcessSignals() -setting_signals = guitypedefs.SettingSignals() -session_signals = guitypedefs.SessionSignals() -backend_signals = guitypedefs.BackendSignals() - -debugcore.breakpoints_changed.connect(lambda: backend_signals.breakpoints_changed.emit()) - -debugcore.instructions_changed.connect(lambda: backend_signals.instructions_changed.emit()) - -debugcore.dissect_code_status_changed.connect(lambda: backend_signals.dissect_code_status_changed.emit()) - -status_thread = guitypedefs.CheckInferiorStatus() -status_thread.start() - -threadpool = QThreadPool() -# Placeholder number, may have to be changed in the future -threadpool.setMaxThreadCount(10) - -# GDB expression cache -# TODO: Try to find a fast and non-gdb way to calculate symbols so we don't need this -# This is one of the few tricks we do to minimize examine_expression calls -# This solution might bring problems if the symbols are changing frequently -# Address table manual refresh, process changes, inferior stops and user run GDB commands/script clear this cache -# Currently only used in address_table_loop -exp_cache: dict[str, str] = {} - -# Set to True when app is about to exit -exiting = False - -hotkeys = guitypedefs.Hotkeys() - -# The variables below are used for quick global access to settings for optimization or simplification purposes -# Initial values of these variables doesn't matter, they'll be set when apply_settings function is called -# Please don't throw every single settings variable here, only add variables that needs to be accessed frequently -update_table = False -table_update_interval = 0 -freeze_interval = 0 -auto_attach = "" -auto_attach_regex = False -show_memory_view_on_stop = False -instructions_per_scroll = 0 -bytes_per_scroll = 0 -gdb_path = "" -gdb_logging = False diff --git a/GUI/TableViews/AsciiView.py b/GUI/TableViews/AsciiView.py deleted file mode 100644 index 04aabeb8..00000000 --- a/GUI/TableViews/AsciiView.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtWidgets import QWidget -from GUI.TableViews.HexView import HexView -from GUI.ItemDelegates.HexDelegate import HexDelegate -from libpince import typedefs - - -class AsciiView(HexView): - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.write_type = typedefs.StringValueType("utf-8", length=1, zero_terminate=False) - self.delegate = HexDelegate(1, ".+") - self.delegate.closeEditor.connect(self.on_editor_close) - self.setItemDelegate(self.delegate) diff --git a/GUI/TableViews/HexView.py b/GUI/TableViews/HexView.py deleted file mode 100644 index a9f39a3f..00000000 --- a/GUI/TableViews/HexView.py +++ /dev/null @@ -1,102 +0,0 @@ -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtGui import QKeyEvent, QWheelEvent -from PyQt6.QtWidgets import QTableView, QAbstractItemView, QWidget, QStyledItemDelegate -from PyQt6.QtCore import QItemSelectionModel, QModelIndex, Qt, pyqtSignal -from GUI.ItemDelegates.HexDelegate import HexDelegate -from GUI.AbstractTableModels.HexModel import HexModel -from libpince import utils, debugcore, typedefs - - -class HexView(QTableView): - scroll_requested = pyqtSignal(int) - page_scroll_requested = pyqtSignal(int) - - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.setWordWrap(False) - self.horizontalHeader().setVisible(False) - self.verticalHeader().setVisible(False) - self.setShowGrid(False) - self.setEditTriggers(QAbstractItemView.EditTrigger.DoubleClicked) - self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.setAutoScroll(False) - self.write_type = typedefs.ByteArrayValueType(1) - self.delegate = HexDelegate() - self.delegate.closeEditor.connect(self.on_editor_close) - self.setItemDelegate(self.delegate) - - def adjust_cell_size(self, char_count: int) -> None: - font_metrics = self.fontMetrics() - col_width = font_metrics.horizontalAdvance("F" * char_count) + 4 * char_count - row_height = font_metrics.height() - self.horizontalHeader().setMinimumSectionSize(col_width) - self.horizontalHeader().setDefaultSectionSize(col_width) - self.horizontalHeader().setMaximumSectionSize(col_width) - self.verticalHeader().setMinimumSectionSize(row_height) - self.verticalHeader().setDefaultSectionSize(row_height) - self.verticalHeader().setMaximumSectionSize(row_height) - - def wheelEvent(self, event: QWheelEvent) -> None: - event.ignore() - - def keyPressEvent(self, event: QKeyEvent) -> None: - if event.key() == Qt.Key.Key_Return and self.state() != QAbstractItemView.State.EditingState: - self.edit(self.currentIndex()) - elif event.key() == Qt.Key.Key_Up and self.currentIndex().row() == 0: - self.scroll_requested.emit(-1) - elif event.key() == Qt.Key.Key_Down and self.currentIndex().row() == self.model().rowCount() - 1: - self.scroll_requested.emit(1) - elif event.key() == Qt.Key.Key_PageUp: - self.page_scroll_requested.emit(-1) - elif event.key() == Qt.Key.Key_PageDown: - self.page_scroll_requested.emit(1) - else: - return super().keyPressEvent(event) - - def selectionCommand(self, index: QModelIndex, event: QKeyEvent) -> QItemSelectionModel.SelectionFlag: - if event and event.modifiers() == Qt.KeyboardModifier.ControlModifier: - # Disable multi-selection when Ctrl key is pressed - return QItemSelectionModel.SelectionFlag.ClearAndSelect - else: - return super().selectionCommand(index, event) - - def resize_to_contents(self) -> None: - size = self.columnWidth(0) * self.model().columnCount() - self.setMinimumWidth(size) - self.setMaximumWidth(size) - - def on_editor_close(self, editor: QWidget | None = None, hint: QStyledItemDelegate.EndEditHint | None = None) -> None: - if hint == QStyledItemDelegate.EndEditHint.RevertModelCache: - return - if not self.delegate.editor.isModified(): - return - model: HexModel = self.model() - cell = self.currentIndex() - index = cell.row() * model.columnCount() + cell.column() - address = utils.modulo_address(model.current_address + index, debugcore.inferior_arch) - data = self.delegate.editor.text() - if isinstance(self.write_type, typedefs.ByteArrayValueType): - data = data.upper() - if len(data) == 1: # pad a single nibble with zero so it matches hex_dump's "0A" formatting. - data = "0" + data - elif len(data.encode("utf-8")) != 1: # an ASCII cell holds one byte so we ignore multi-byte input. - return - debugcore.write_memory(address, self.write_type, data) - model.update_index(index, data) diff --git a/GUI/TreeWidgets/AddressTree.py b/GUI/TreeWidgets/AddressTree.py deleted file mode 100644 index 32b5e079..00000000 --- a/GUI/TreeWidgets/AddressTree.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Copyright (C) Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtGui import QDropEvent -from PyQt6.QtWidgets import QTreeWidget, QWidget - - -class AddressTree(QTreeWidget): - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - - def dropEvent(self, event: QDropEvent | None) -> None: - super().dropEvent(event) - self.parent().parent().update_address_table() - self.parent().parent().mark_address_tree_changed() diff --git a/GUI/Utils/__init__.py b/GUI/Utils/__init__.py deleted file mode 100644 index 9bd5e10d..00000000 --- a/GUI/Utils/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -import keyboard -from . import keyboard_hack - -# replace keyboard.parse_hotkey() with fix for literal '+' in hotkey strings -keyboard.parse_hotkey = keyboard_hack.parse_hotkey diff --git a/GUI/Utils/guitypedefs.py b/GUI/Utils/guitypedefs.py deleted file mode 100644 index c95410ae..00000000 --- a/GUI/Utils/guitypedefs.py +++ /dev/null @@ -1,216 +0,0 @@ -from PyQt6.QtCore import QThread, QRunnable, pyqtSignal, QObject -from keyboard import add_hotkey, remove_hotkey -from typing import Any, Callable -from tr.tr import TranslationConstants as tr -from libpince import debugcore, typedefs -import queue -import threading - -# Docstrings of pyqtSignal causes Sphinx to throw a warning about inline emphasis strings -# The hack below overwrites the docstrings of pyqtSignal so we avoid the warnings -# TODO: Wait for Qt to fix this issue or find a better way of handling this - -pyqtSignal.__doc__ = "pyqtSignal" - - -class SettingSignals(QObject): - changed = pyqtSignal() - - -class WorkerSignals(QObject): - finished = pyqtSignal(object) - error = pyqtSignal(Exception) - - -class ProcessSignals(QObject): - attach = pyqtSignal() - exit = pyqtSignal() - - -class SessionSignals(QObject): - new_session = pyqtSignal() - on_save = pyqtSignal() - on_load = pyqtSignal() - bookmarks_changed = pyqtSignal() - - -# Qt mirror of debugcore's backend signals (e.g. debugcore.breakpoints_changed), bridged in states.py. -# debugcore is GUI-agnostic and its signals fire synchronously on whatever thread emits them, which -# can be a worker thread like the tracer. -# Re-emitting through these Qt signals lets widgets connect with the default AutoConnection, -# so the refresh is marshalled to the GUI thread instead of touching widgets off-thread. -class BackendSignals(QObject): - breakpoints_changed = pyqtSignal() - instructions_changed = pyqtSignal() - dissect_code_status_changed = pyqtSignal() - - -class Worker(QRunnable): - def __init__(self, fn: Callable, *args: Any, **kwargs: Any) -> None: - super().__init__() - self.fn = fn - self.args = args - self.kwargs = kwargs - self.signals = WorkerSignals() - - def run(self) -> None: - try: - result = self.fn(*self.args, **self.kwargs) - except Exception as e: - self.signals.error.emit(e) - return - self.signals.finished.emit(result) - - -class InterruptibleWorker(QThread): - def __init__(self, fn: Callable, *args: Any, **kwargs: Any) -> None: - super().__init__() - self.fn = fn - self.args = args - self.kwargs = kwargs - self.signals = WorkerSignals() - - def run(self) -> None: - try: - result = self.fn(*self.args, **self.kwargs) - except Exception as e: - self.signals.error.emit(e) - return - self.signals.finished.emit(result) - - -# Await async output from gdb -class AwaitAsyncOutput(QThread): - async_output_ready = pyqtSignal(str) - - def __init__(self) -> None: - super().__init__() - self.queue_active = True - - def run(self) -> None: - async_output_queue = debugcore.gdb_async_output.register_queue() - while self.queue_active: - try: - async_output = async_output_queue.get(timeout=5) - except queue.Empty: - pass - else: - self.async_output_ready.emit(async_output) - debugcore.gdb_async_output.delete_queue(async_output_queue) - - def stop(self) -> None: - self.queue_active = False - - -# Checks if the inferior has been terminated -class AwaitProcessExit(QThread): - process_exited = pyqtSignal() - - def __init__(self) -> None: - super().__init__() - self._shutdown = threading.Event() - - def request_shutdown(self) -> None: - self._shutdown.set() - with debugcore.process_exited_condition: - debugcore.process_exited_condition.notify_all() - - def run(self) -> None: - while not self._shutdown.is_set(): - with debugcore.process_exited_condition: - if self._shutdown.is_set(): - break - debugcore.process_exited_condition.wait() - if self._shutdown.is_set(): - break - self.process_exited.emit() - - -# Checks if the inferior is running or stopped -class CheckInferiorStatus(QThread): - process_stopped = pyqtSignal() - process_running = pyqtSignal() - - def run(self) -> None: - while True: - with debugcore.status_changed_condition: - debugcore.status_changed_condition.wait() - if debugcore.inferior_status == typedefs.INFERIOR_STATUS.STOPPED: - self.process_stopped.emit() - elif debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - self.process_running.emit() - - -class Hotkey: - def __init__( - self, - name: str = "", - desc: str = "", - default: str = "", - func: Callable | None = None, - custom: str = "", - handle: Any = None, - ) -> None: - self.name = name - self.desc = desc - self.default = default - self.func = func - self.custom = custom - if default == "" or func is None: - self.handle = handle - else: - self.handle = add_hotkey(default, func) - - def change_key(self, custom: str) -> None: - if self.handle is not None: - remove_hotkey(self.handle) - self.handle = None - self.custom = custom - if custom != "": - self.handle = add_hotkey(custom.lower(), self.func) - elif self.default != "": - self.handle = add_hotkey(self.default, self.func) - - def change_func(self, func: Callable) -> None: - self.func = func - if self.handle is not None: - remove_hotkey(self.handle) - if self.custom != "": - self.handle = add_hotkey(self.custom, func) - elif self.default != "": - self.handle = add_hotkey(self.default, func) - - def get_active_key(self) -> str: - if self.custom == "": - return self.default - return self.custom - - -class Hotkeys: - def __init__(self) -> None: - self.pause_hotkey = Hotkey("pause_hotkey", tr.PAUSE_HOTKEY, "F1") - self.break_hotkey = Hotkey("break_hotkey", tr.BREAK_HOTKEY, "F2") - self.continue_hotkey = Hotkey("continue_hotkey", tr.CONTINUE_HOTKEY, "F3") - self.cancel_hotkey = Hotkey("cancel_hotkey", tr.CANCEL_HOTKEY, "Ctrl+k") - self.toggle_attach_hotkey = Hotkey("toggle_attach_hotkey", tr.TOGGLE_ATTACH_HOTKEY, "Shift+F10") - self.speedhack_toggle_hotkey = Hotkey("speedhack_toggle_hotkey", tr.SPEEDHACK_TOGGLE_HOTKEY, "Ctrl+Shift+s") - self.speedhack_speed_down_hotkey = Hotkey("speedhack_speed_down_hotkey", tr.SPEEDHACK_SPEED_DOWN_HOTKEY, "Ctrl+Shift+Down") - self.speedhack_speed_up_hotkey = Hotkey("speedhack_speed_up_hotkey", tr.SPEEDHACK_SPEED_UP_HOTKEY, "Ctrl+Shift+Up") - self.exact_scan_hotkey = Hotkey("exact_scan_hotkey", tr.EXACT_SCAN_HOTKEY, "") - self.not_scan_hotkey = Hotkey("not_scan_hotkey", tr.NOT_SCAN_HOTKEY, "") - self.increased_scan_hotkey = Hotkey("increased_scan_hotkey", tr.INC_SCAN_HOTKEY, "") - self.increased_by_scan_hotkey = Hotkey("increased_by_scan_hotkey", tr.INC_BY_SCAN_HOTKEY, "") - self.decreased_scan_hotkey = Hotkey("decreased_scan_hotkey", tr.DEC_SCAN_HOTKEY, "") - self.decreased_by_scan_hotkey = Hotkey("decreased_by_scan_hotkey", tr.DEC_BY_SCAN_HOTKEY, "") - self.less_scan_hotkey = Hotkey("less_scan_hotkey", tr.LESS_SCAN_HOTKEY, "") - self.more_scan_hotkey = Hotkey("more_scan_hotkey", tr.MORE_SCAN_HOTKEY, "") - self.between_scan_hotkey = Hotkey("between_scan_hotkey", tr.BETWEEN_SCAN_HOTKEY, "") - self.changed_scan_hotkey = Hotkey("changed_scan_hotkey", tr.CHANGED_SCAN_HOTKEY, "") - self.unchanged_scan_hotkey = Hotkey("unchanged_scan_hotkey", tr.UNCHANGED_SCAN_HOTKEY, "") - - def get_hotkeys(self) -> list[Hotkey]: - hotkey_list = [] - for _, value in vars(self).items(): - if isinstance(value, Hotkey): - hotkey_list.append(value) - return hotkey_list diff --git a/GUI/Utils/guiutils.py b/GUI/Utils/guiutils.py deleted file mode 100644 index c6988606..00000000 --- a/GUI/Utils/guiutils.py +++ /dev/null @@ -1,481 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from PyQt6.QtWidgets import ( - QWidget, - QScrollBar, - QTableWidget, - QTableWidgetItem, - QTreeWidget, - QTreeWidgetItem, - QListWidget, - QListWidgetItem, - QComboBox, - QMenu, - QLayout, - QMessageBox, - QFileDialog, -) -from PyQt6.QtCore import Qt, QObject, QRegularExpression -from PyQt6.QtGui import QShortcut, QRegularExpressionValidator -from libpince import debugcore, utils, typedefs, regexes -from libpince.libmemscan.memscan import ScanLevel -from tr.tr import TranslationConstants as tr -from typing import overload -from contextlib import contextmanager -import copy, os - -validator_map: dict[str, QRegularExpressionValidator | None] = { - "int": QRegularExpressionValidator(QRegularExpression(regexes.decimal_number.pattern)), # integers - "int_hex": QRegularExpressionValidator(QRegularExpression(regexes.hex_number_gui.pattern)), # hexadecimals - "float": QRegularExpressionValidator(QRegularExpression(regexes.float_number.pattern)), # floats - "bytearray": QRegularExpressionValidator(QRegularExpression(regexes.bytearray_input.pattern)), # array of bytes - "string": None, -} - - -def own_path_as_user(path: str, recursive: bool = False) -> None: - """chowns a path PINCE created as root back to the user who launched it. - - Args: - path (str): Path to chown - recursive (bool): Also chown everything under path if it's a directory - """ - if os.geteuid() != 0: - return - uid, gid = utils.get_user_ids() - if not uid.isdigit() or not gid.isdigit() or int(uid) == 0: - return - uid, gid = int(uid), int(gid) - paths = [path] - if recursive: - for root, dirs, files in os.walk(path): - paths += [os.path.join(root, name) for name in dirs + files] - for target in paths: - try: - os.chown(target, uid, gid) - except OSError as e: - utils.logger.error(f"Failed to chown {target}: {e}") - - -@contextmanager -def save_dialog_as_user(parent: QWidget | None, caption: str, directory: str, file_filter: str, extension: str = ""): - """Opens a save dialog and chowns the chosen path back to the user once the block exits.""" - file_path, _ = QFileDialog.getSaveFileName(parent, caption, directory, file_filter) - if file_path and extension: - file_path = utils.append_file_extension(file_path, extension) - try: - yield file_path or None - finally: - if file_path and os.path.exists(file_path): - own_path_as_user(file_path) - - -def get_icons_directory() -> str: - """Gets the directory of the icons - - Returns: - str: Path to the icons directory - """ - return utils.get_script_directory() + "/media/icons" - - -def center(window: QWidget) -> None: - """Center the given window to desktop - - Args: - window (QWidget): The window that'll be centered to desktop - """ - frame = window.frameGeometry() - frame.moveCenter(window.screen().availableGeometry().center()) - window.move(frame.topLeft()) - - -def center_to_parent(window: QWidget) -> None: - """Center the given window to its parent - - Args: - window (QWidget): The window that'll be centered to its parent - """ - parent: QWidget = window.parent() - window.move(parent.frameGeometry().center() - window.rect().center()) - - -def center_scroll_bar(scrollbar: QScrollBar) -> None: - """Center the given scrollbar - - Args: - scrollbar (QScrollbar): Self-explanatory - """ - maximum = scrollbar.maximum() - minimum = scrollbar.minimum() - scrollbar.setValue((maximum + minimum) // 2) - - -def resize_to_contents(tablewidget: QTableWidget) -> None: - """Resizes the columns of the given QTableWidget to its contents - This also fixes the stretch problem of the last column - - Args: - tablewidget (QTableWidget): Self-explanatory - """ - tablewidget.resizeColumnsToContents() - default_size = tablewidget.horizontalHeader().defaultSectionSize() - tablewidget.horizontalHeader().resizeSection(tablewidget.columnCount() - 1, default_size) - - -def fill_value_combobox(combobox: QComboBox, current_type: typedefs.ValueType | None = None, *, include_bit_field: bool = False) -> None: - """Fill a combobox with value-type prototypes.""" - target = current_type or typedefs.IntegerValueType() - target_key = (type(target), getattr(target, "bits", None), getattr(target, "encoding", None)) - choices = ( - [typedefs.IntegerValueType(bits) for bits in (8, 16, 32, 64)] - + [typedefs.FloatValueType(bits) for bits in (32, 64)] - + [typedefs.StringValueType(encoding) for encoding in ("ascii", "utf-8", "utf-16", "utf-32")] - + [typedefs.ByteArrayValueType()] - ) - if include_bit_field: - choices.append(copy.copy(target) if isinstance(target, typedefs.BitFieldValueType) else typedefs.BitFieldValueType()) - combobox.setCurrentIndex(0) - for value_type in choices: - combobox.addItem(value_type.text().split("[", 1)[0], value_type) - if (type(value_type), getattr(value_type, "bits", None), getattr(value_type, "encoding", None)) == target_key: - combobox.setCurrentIndex(combobox.count() - 1) - - -def configure_value_type( - value_type: typedefs.ValueType, - *, - length: int | None = None, - zero_terminate: bool | None = None, - value_repr: int | None = None, - endian: int | None = None, -) -> typedefs.ValueType: - """Copy a combobox prototype and apply the options controlled by its dialog.""" - configured = copy.copy(value_type) - for name, value in (("length", length), ("zero_terminate", zero_terminate), ("value_repr", value_repr), ("endian", endian)): - if value is not None and hasattr(configured, name): - setattr(configured, name, value) - return configured - - -def fill_endianness_combobox(combobox: QComboBox, current_index: int = typedefs.ENDIANNESS.HOST) -> None: - """Fills the given QComboBox with endianness strings - - Args: - combobox (QComboBox): The combobox that'll be filled - current_index (int): Can be a member of typedefs.ENDIANNESS - """ - endianness_text = [ - (typedefs.ENDIANNESS.HOST, tr.HOST), - (typedefs.ENDIANNESS.LITTLE, tr.LITTLE), - (typedefs.ENDIANNESS.BIG, tr.BIG), - ] - for endian, text in endianness_text: - combobox.addItem(text, endian) - idx = combobox.findData(current_index) - if idx >= 0: - combobox.setCurrentIndex(idx) - else: - combobox.setCurrentIndex(0) - - -def fill_scope_combobox(combobox: QComboBox, current_index: ScanLevel = ScanLevel.HEAP_STACK_EXE_BSS) -> None: - scan_scope_text = [ - (ScanLevel.HEAP_STACK_EXE, tr.BASIC), - (ScanLevel.HEAP_STACK_EXE_BSS, tr.NORMAL), - (ScanLevel.ALL_RW, tr.RW), - (ScanLevel.ALL, tr.FULL), - ] - for scope, text in scan_scope_text: - combobox.addItem(text, scope) - idx = combobox.findData(current_index) - if idx >= 0: - combobox.setCurrentIndex(idx) - else: - combobox.setCurrentIndex(0) - - -def fill_alignment_combobox(combobox: QComboBox) -> None: - """Fills the given QComboBox with alignment strings - - Args: - combobox (QComboBox): The combobox that'll be filled - """ - alignment_text_val = [ - (tr.AUTO, 0), - ("1", 1), - ("2", 2), - ("4", 4), - ("8", 8), - ("16", 16), - ] - for text, value in alignment_text_val: - combobox.addItem(text, value) - combobox.setCurrentIndex(combobox.findData(0)) - - -def fill_scan_index_combobox(combobox: QComboBox, current_index: int = typedefs.SCAN_INDEX.INT32) -> None: - """Fills the given QComboBox with scan value type strings - - Args: - combobox (QComboBox): The combobox that'll be filled - current_index (int): Can be a member of typedefs.SCAN_INDEX - """ - # Type names are used as they are, no need to make these translatable - scan_index_text = [ - (typedefs.SCAN_INDEX.INT_ANY, "Int(any)"), - (typedefs.SCAN_INDEX.INT8, "Int8"), - (typedefs.SCAN_INDEX.INT16, "Int16"), - (typedefs.SCAN_INDEX.INT32, "Int32"), - (typedefs.SCAN_INDEX.INT64, "Int64"), - (typedefs.SCAN_INDEX.FLOAT_ANY, "Float(any)"), - (typedefs.SCAN_INDEX.FLOAT32, "Float32"), - (typedefs.SCAN_INDEX.FLOAT64, "Float64"), - (typedefs.SCAN_INDEX.ANY, "Any(int, float)"), - (typedefs.SCAN_INDEX.STRING, "String"), - (typedefs.SCAN_INDEX.AOB, "ByteArray"), - ] - combobox.clear() - for scan_index, text in scan_index_text: - combobox.addItem(text, scan_index) - idx = combobox.findData(current_index) - if idx >= 0: - combobox.setCurrentIndex(idx) - else: - combobox.setCurrentIndex(0) - - -def fill_scan_type_combobox(combobox: QComboBox, scan_mode: int, value_type: int) -> None: - """Fills the given QComboBox with the scan types that can be used with the given scan mode and value type - Keeps the current scan type selected if it's still available after the refill - - Args: - combobox (QComboBox): The combobox that'll be filled - scan_mode (int): Can be a member of typedefs.SCAN_MODE - value_type (int): Can be a member of typedefs.SCAN_INDEX - """ - scan_type_text = { - typedefs.SCAN_TYPE.EXACT: tr.EXACT, - typedefs.SCAN_TYPE.NOT: tr.NOT, - typedefs.SCAN_TYPE.INCREASED: tr.INCREASED, - typedefs.SCAN_TYPE.INCREASED_BY: tr.INCREASED_BY, - typedefs.SCAN_TYPE.DECREASED: tr.DECREASED, - typedefs.SCAN_TYPE.DECREASED_BY: tr.DECREASED_BY, - typedefs.SCAN_TYPE.LESS: tr.LESS_THAN, - typedefs.SCAN_TYPE.MORE: tr.MORE_THAN, - typedefs.SCAN_TYPE.BETWEEN: tr.BETWEEN, - typedefs.SCAN_TYPE.CHANGED: tr.CHANGED, - typedefs.SCAN_TYPE.UNCHANGED: tr.UNCHANGED, - typedefs.SCAN_TYPE.UNKNOWN: tr.UNKNOWN_VALUE, - } - text_types = value_type == typedefs.SCAN_INDEX.STRING or value_type == typedefs.SCAN_INDEX.AOB - if scan_mode == typedefs.SCAN_MODE.NEW: - if text_types: - scan_types = [typedefs.SCAN_TYPE.EXACT, typedefs.SCAN_TYPE.UNKNOWN] - else: - scan_types = [ - typedefs.SCAN_TYPE.EXACT, - typedefs.SCAN_TYPE.NOT, - typedefs.SCAN_TYPE.LESS, - typedefs.SCAN_TYPE.MORE, - typedefs.SCAN_TYPE.BETWEEN, - typedefs.SCAN_TYPE.UNKNOWN, - ] - else: - if text_types: - scan_types = [typedefs.SCAN_TYPE.EXACT] - else: - scan_types = [ - typedefs.SCAN_TYPE.EXACT, - typedefs.SCAN_TYPE.NOT, - typedefs.SCAN_TYPE.INCREASED, - typedefs.SCAN_TYPE.INCREASED_BY, - typedefs.SCAN_TYPE.DECREASED, - typedefs.SCAN_TYPE.DECREASED_BY, - typedefs.SCAN_TYPE.LESS, - typedefs.SCAN_TYPE.MORE, - typedefs.SCAN_TYPE.BETWEEN, - typedefs.SCAN_TYPE.CHANGED, - typedefs.SCAN_TYPE.UNCHANGED, - ] - current_type = combobox.currentData(Qt.ItemDataRole.UserRole) - combobox.clear() - for scan_type in scan_types: - combobox.addItem(scan_type_text[scan_type], scan_type) - idx = combobox.findData(current_type) - if idx >= 0: - combobox.setCurrentIndex(idx) - else: - combobox.setCurrentIndex(0) - - -def get_current_row(tablewidget: QTableWidget) -> int: - r"""Returns the currently selected row index for the given QTableWidget - If you try to use only selectionModel().currentIndex().row() for this purpose, you'll get the last selected row even - if it was unselected afterwards. This is why this function exists, it checks the selection state before returning - the selected row - - Args: - tablewidget (QTableWidget): Self-explanatory - - Returns: - int: Currently selected row. Returns -1 if nothing is selected - - Note: - This function doesn't work properly when used within signals such as currentItemChanged, currentIndexChanged, - currentChanged and currentRowChanged. Use the row, item, QModelIndex or whatever the signal provides instead. - This bug occurs because those signals only update the changed row, not the selectionModel. This causes - selectionModel().selectedRows() to return None and this function to behave improperly - - For developers: You can use the regex \.current.*\.connect to search signals if a cleanup is needed - """ - if tablewidget.selectionModel().selectedRows(): - return tablewidget.selectionModel().currentIndex().row() - return -1 - - -@overload -def get_current_item(listwidget: QListWidget) -> QListWidgetItem | None: ... - - -@overload -def get_current_item(tablewidget: QTableWidget) -> QTableWidgetItem | None: ... - - -@overload -def get_current_item(treewidget: QTreeWidget) -> QTreeWidgetItem | None: ... - - -def get_current_item( - widget: QListWidget | QTableWidget | QTreeWidget, -) -> QListWidgetItem | QTableWidgetItem | QTreeWidgetItem | None: - r"""Returns the currently selected item for the given widget - If you try to use only selectionModel().currentItem() for this purpose, you'll get the last selected item even - if it was unselected afterwards. This is why this function exists, it checks the selection state before returning - the selected item. Unlike get_current_row, this function can be used with QTreeWidget - - Args: - widget (QListWidget | QTableWidget | QTreeWidget): Self-explanatory - - Returns: - Any: Currently selected item. Returns None if nothing is selected - - Note: - This function doesn't work properly when used within signals such as currentItemChanged, currentIndexChanged, - currentChanged and currentRowChanged. Use the row, item, QModelIndex or whatever the signal provides instead. - This bug occurs because those signals only update the changed row, not the selectionModel. This causes - selectionModel().selectedRows() to return None and this function to behave improperly - - For developers: You can use the regex \.current.*\.connect to search signals if a cleanup is needed - """ - if widget.selectionModel().selectedRows(): - return widget.currentItem() - - -def delete_menu_entries(menu: QMenu, QAction_list: list) -> None: - """Deletes given QActions from the QMenu recursively and cleans up the remaining redundant separators and menus - Doesn't support menus that includes types other than actions, separators and menus - - Args: - menu (QMenu): Self-explanatory - QAction_list (list): List of QActions. Leave blank if you just want to clean the redundant separators up - """ - - def remove_entries(menu: QMenu) -> None: - for action in menu.actions(): - if action in QAction_list: - menu.removeAction(action) - elif action.menu() is not None: # descend into submenus to delete nested entries - remove_entries(action.menu()) - - def clean_entries(menu: QMenu) -> None: - for action in menu.actions(): - if action.menu() is not None: - clean_entries(action.menu()) - elif action.isSeparator(): - actions = menu.actions() - current_index = actions.index(action) - if ( - len(actions) == 1 - or (current_index == 0 and actions[1].isSeparator()) - or (current_index == len(actions) - 1 and actions[-2].isSeparator()) - or ( - 0 < current_index < len(actions) - 1 and actions[current_index - 1].isSeparator() and actions[current_index + 1].isSeparator() - ) - ): - menu.removeAction(action) - - remove_entries(menu) - clean_entries(menu) - - -def get_layout_widgets(layout: QLayout) -> list[QWidget]: - """Returns the widgets of a QLayout as a list - - Args: - layout: Self-explanatory - - Returns: - list: A list that contains the widgets of the given layout - """ - return [layout.itemAt(x).widget() for x in range(layout.count())] - - -def contains_reference_mark(string: str) -> bool: - """Checks if given string contains the reference mark - - Args: - string (str): String that'll be checked for the reference mark - - Returns: - bool: True if given string contains the reference mark, False otherwise - """ - return True if regexes.reference_mark.search(string) else False - - -def append_shortcut_to_tooltip(qt_object: QObject, shortcut: QShortcut) -> None: - """Appends key string of the given QShortcut to the toolTip of the given QObject - - Args: - qt_object (QObject): Self-explanatory - shortcut (QShortcut): Self-explanatory - """ - qt_object.setToolTip(qt_object.toolTip() + "[" + shortcut.key().toString() + "]") - - -def check_inferior_running(widget: QWidget | None = None, show_message: bool = True) -> str | None: - """Checks if a process is selected and is running - - Args: - widget (QWidget | None): Parent widget for the message box. If None, message box will have no parent - show_message (bool): If True, a message box will be shown if the inferior is running - - Returns: - str: The error message, if the inferior is running or no process is selected - None: If the inferior is stopped and a process is selected - """ - if debugcore.currentpid == -1: - if show_message: - QMessageBox.information(widget, tr.ERROR, tr.NO_PROCESS_SELECTED) - return tr.NO_PROCESS_SELECTED - if debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - if show_message: - QMessageBox.information(widget, tr.ERROR, tr.REQUIRE_PROCESS_STOP) - return tr.REQUIRE_PROCESS_STOP - return None diff --git a/GUI/Utils/keyboard_hack.py b/GUI/Utils/keyboard_hack.py deleted file mode 100644 index 543dc4dc..00000000 --- a/GUI/Utils/keyboard_hack.py +++ /dev/null @@ -1,42 +0,0 @@ -from keyboard import key_to_scan_codes -import re as _re - -# copied from keyboard.__init__.py -_is_number = lambda x: isinstance(x, int) -_is_list = lambda x: isinstance(x, (list, tuple)) - - -def parse_hotkey(hotkey: str | int | list | tuple) -> tuple | list: - ## function to replace keyboard.parse_hotkey() with fix for literal '+' in hotkey strings - """ - Parses a user-provided hotkey into nested tuples representing the - parsed structure, with the bottom values being lists of scan codes. - Also accepts raw scan codes, which are then wrapped in the required - number of nestings. - - Example: - - parse_hotkey("alt+shift+a, alt+b, c") - # Keys: ^~^ ^~~~^ ^ ^~^ ^ ^ - # Steps: ^~~~~~~~~~^ ^~~~^ ^ - - # ((alt_codes, shift_codes, a_codes), (alt_codes, b_codes), (c_codes,)) - """ - if _is_number(hotkey) or len(hotkey) == 1: - scan_codes = key_to_scan_codes(hotkey) - step = (scan_codes,) - steps = (step,) - return steps - elif _is_list(hotkey): - if not any(map(_is_list, hotkey)): - step = tuple(key_to_scan_codes(k) for k in hotkey) - steps = (step,) - return steps - return hotkey - - steps = [] - # since we don't have spaces in hotkey strings, we can ignore whitespace in the regex - for step in _re.split(r"(? None: - super().__init__(parent) - self.result = UpdateCheckResult(UpdateCheckStatus.ERROR, "Update check did not finish") - - def run(self) -> None: - self.result = check_for_update() - - -def check_for_update() -> UpdateCheckResult: - try: - appimage_path = os.environ.get("APPIMAGE") - if not appimage_path or not os.path.isfile(appimage_path): - raise RuntimeError("Not running from an AppImage") - config = _read_config() - if config.get("type") != "zsync": - raise ValueError("Unsupported update check config") - zsync_url = config["url"] - zsync_headers = _fetch_zsync_headers(zsync_url) - remote_sha1 = zsync_headers.get("sha-1") - if remote_sha1: - with open(appimage_path, "rb") as appimage: - local_sha1 = hashlib.file_digest(appimage, "sha1").hexdigest() - return _get_result(local_sha1.lower() != remote_sha1.lower()) - remote_length = zsync_headers.get("length") - if remote_length: - return _get_result(os.path.getsize(appimage_path) != int(remote_length)) - raise ValueError("The update metadata does not contain a comparable file hash or size") - except Exception as exc: - return UpdateCheckResult(UpdateCheckStatus.ERROR, str(exc)) - - -def _get_result(update_available: bool) -> UpdateCheckResult: - status = UpdateCheckStatus.UPDATE_AVAILABLE if update_available else UpdateCheckStatus.UP_TO_DATE - return UpdateCheckResult(status) - - -def _read_config() -> dict[str, Any]: - with open(os.path.join(sys.path[0], "update-check.json"), encoding="utf-8") as config_file: - config = json.load(config_file) - if not isinstance(config, dict): - raise ValueError("Update config must be a JSON object") - return config - - -def _fetch_zsync_headers(url: str) -> dict[str, str]: - request = urllib.request.Request(url, headers={"User-Agent": "PINCE update checker"}) - with urllib.request.urlopen(request, timeout=10, context=_get_ssl_context()) as response: - data = response.read(65536) - text = data.decode("utf-8", errors="replace") - headers: dict[str, str] = {} - for line in text.splitlines(): - if not line: - break - key, sep, value = line.partition(":") - if sep: - headers[key.strip().lower()] = value.strip() - return headers - - -def _get_ssl_context() -> ssl.SSLContext: - cafile = os.path.join(os.environ.get("APPDIR", ""), "usr/conda/ssl/cacert.pem") - if os.path.isfile(cafile): - return ssl.create_default_context(cafile=cafile) - return ssl.create_default_context() diff --git a/GUI/Utils/utilwidgets.py b/GUI/Utils/utilwidgets.py deleted file mode 100644 index 84e02cf2..00000000 --- a/GUI/Utils/utilwidgets.py +++ /dev/null @@ -1,92 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QLineEdit, QLabel, QWidget, QComboBox -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils - -# This module includes utility widgets that doesn't have ui files - - -class InputDialog(QDialog): - """A dialog that allows for one or more QLabels and corresponding QLineEdit fields""" - - def __init__( - self, - parent: QWidget, - items: str | list[tuple[str, str]], - alignment: Qt.AlignmentFlag = Qt.AlignmentFlag.AlignCenter, - cancel_button: bool = True, - ) -> None: - """ - Args: - parent (QWidget): Parent of this dialog - items (str | list[tuple[str, str]]): If a string is provided, a single label will be created - If a list is provided, it must be in this format -> [(label_text, lineedit_text)] - Providing a list will create labels and lineedits by using given texts, stacked vertically - alignment (Qt.AlignmentFlag): Text alignment of the labels - cancel_button (bool): Both Ok and Cancel buttons will appear if True, only Ok button will appear if False - """ - super().__init__(parent) - self.input_fields: list[QLineEdit] = [] - layout = QVBoxLayout() - if isinstance(items, str): - label = QLabel(items) - label.setAlignment(alignment) - label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - layout.addWidget(label) - elif isinstance(items, list): - for label_text, edit_text in items: - label = QLabel(label_text) - label.setAlignment(alignment) - label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - layout.addWidget(label) - lineedit = QLineEdit(edit_text) - layout.addWidget(lineedit) - self.input_fields.append(lineedit) - else: - raise Exception("Type of items isn't str or list") - if cancel_button: - button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) - else: - button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok) - button_box.accepted.connect(self.accept) - button_box.rejected.connect(self.reject) - layout.addWidget(button_box) - self.setLayout(layout) - self.adjustSize() - if self.input_fields: - self.input_fields[0].setFocus() - guiutils.center_to_parent(self) - - def get_values(self) -> list[str] | None: - if self.input_fields: - return [item.text() for item in self.input_fields] - - -class ComboBoxDialog(QDialog): - """A dialog that allows for one QLabel and a corresponding QComboBox""" - - def __init__(self, parent: QWidget, label_text: str, items: list[str], current_index: int = 0) -> None: - """ - Args: - parent (QWidget): Parent of this dialog - label_text (str): Text of the label - items (list[str]): List of strings that'll be used as items of the combobox - current_index (int): Sets the current index of the combobox - """ - super().__init__(parent) - layout = QVBoxLayout() - label = QLabel(label_text) - self.combobox = QComboBox() - self.combobox.addItems(items) - self.combobox.setCurrentIndex(current_index) - button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) - button_box.accepted.connect(self.accept) - button_box.rejected.connect(self.reject) - layout.addWidget(label) - layout.addWidget(self.combobox) - layout.addWidget(button_box) - self.setLayout(layout) - self.adjustSize() - guiutils.center_to_parent(self) - - def get_values(self) -> str: - return self.combobox.currentText() diff --git a/GUI/Validators/HexValidator.py b/GUI/Validators/HexValidator.py deleted file mode 100644 index 8ce2c78f..00000000 --- a/GUI/Validators/HexValidator.py +++ /dev/null @@ -1,17 +0,0 @@ -from PyQt6.QtCore import QObject -from PyQt6.QtGui import QValidator - - -class HexValidator(QValidator): - def __init__(self, max_limit: int, parent: QObject | None = None) -> None: - super().__init__(parent) - self.max_limit = max_limit - - def validate(self, p_str: str, p_int: int) -> tuple[QValidator.State, str, int]: - try: - int_repr = int(p_str, 0) - except ValueError: - return QValidator.State.Intermediate, p_str, p_int - if int_repr > self.max_limit: - return QValidator.State.Invalid, p_str, p_int - return QValidator.State.Acceptable, p_str, p_int diff --git a/GUI/Widgets/About/About.py b/GUI/Widgets/About/About.py deleted file mode 100644 index 9a9081ba..00000000 --- a/GUI/Widgets/About/About.py +++ /dev/null @@ -1,35 +0,0 @@ -from PyQt6.QtWidgets import QTabWidget, QWidget -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils -from GUI.Widgets.About.Form.AboutWidget import Ui_TabWidget -from libpince import utils - - -class AboutWidget(QTabWidget, Ui_TabWidget): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - - # This section has untranslated text since it's just a placeholder - pince_dir = utils.get_script_directory() - with open(f"{pince_dir}/COPYING", encoding="utf-8") as f: - license_text = f.read() - with open(f"{pince_dir}/AUTHORS", encoding="utf-8") as f: - authors_text = f.read() - with open(f"{pince_dir}/THANKS", encoding="utf-8") as f: - thanks_text = f.read() - self.textBrowser_License.setPlainText(license_text) - self.textBrowser_Contributors.append( - "This is only a placeholder, this section may look different when the project finishes" - + "\nIn fact, something like a demo-scene for here would look absolutely fabulous <:" - ) - self.textBrowser_Contributors.append("\n########") - self.textBrowser_Contributors.append("#AUTHORS#") - self.textBrowser_Contributors.append("########\n") - self.textBrowser_Contributors.append(authors_text) - self.textBrowser_Contributors.append("\n#######") - self.textBrowser_Contributors.append("#THANKS#") - self.textBrowser_Contributors.append("#######\n") - self.textBrowser_Contributors.append(thanks_text) - guiutils.center_to_parent(self) diff --git a/GUI/Widgets/Bookmark/Bookmark.py b/GUI/Widgets/Bookmark/Bookmark.py deleted file mode 100644 index 860330e1..00000000 --- a/GUI/Widgets/Bookmark/Bookmark.py +++ /dev/null @@ -1,125 +0,0 @@ -from PyQt6.QtCore import Qt, pyqtSignal -from PyQt6.QtGui import QContextMenuEvent, QKeySequence, QShortcut -from PyQt6.QtWidgets import QListWidgetItem, QMenu, QMessageBox, QWidget - -from GUI.Session.session import SessionManager -from GUI.States import states -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.Bookmark.Form.BookmarkWidget import Ui_Form -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr - - -# This widget is too intertwined with MemoryViewer, it will be need to be reworked if it gets used in anywhere else -class BookmarkWidget(QWidget, Ui_Form): - bookmarked = pyqtSignal(object) - comment_changed = pyqtSignal(object) - double_clicked = pyqtSignal(str) - deleted = pyqtSignal(object) - - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.listWidget.contextMenuEvent = self.listWidget_context_menu_event - self.listWidget.currentRowChanged.connect(self.change_display) - self.listWidget.itemDoubleClicked.connect(self.listWidget_item_double_clicked) - self.shortcut_delete = QShortcut(QKeySequence("Del"), self) - self.shortcut_delete.activated.connect(self.delete_record) - self.shortcut_refresh = QShortcut(QKeySequence("R"), self) - self.shortcut_refresh.activated.connect(self.refresh_table) - self.session = SessionManager.get_session() - self.refresh_table() - states.session_signals.new_session.connect(self.on_new_session) - states.session_signals.bookmarks_changed.connect(self.refresh_table) - states.session_signals.on_load.connect(self.refresh_table) - guiutils.center_to_parent(self) - - def refresh_table(self) -> None: - self.listWidget.clear() - address_list = [hex(address) for address in self.session.pct_bookmarks.keys()] - if debugcore.currentpid != -1: - results = debugcore.examine_expressions(address_list) - if results: - address_list = [item.all or addr for item, addr in zip(results, address_list)] - self.listWidget.addItems(address_list) - self.repaint() - - def change_display(self, row: int) -> None: - if row == -1: - self.lineEdit_Info.clear() - self.lineEdit_Comment.clear() - return - current_address = utils.extract_hex_address(self.listWidget.item(row).text()) - if not current_address: - self.lineEdit_Info.clear() - self.lineEdit_Comment.clear() - return - if debugcore.currentpid == -1: - self.lineEdit_Info.clear() - else: - self.lineEdit_Info.setText(debugcore.get_address_info(current_address)) - bookmark = self.session.pct_bookmarks.get(int(current_address, 16)) - if bookmark: - self.lineEdit_Comment.setText(bookmark["comment"]) - else: - self.lineEdit_Comment.clear() - - def listWidget_item_double_clicked(self, item: QListWidgetItem) -> None: - self.double_clicked.emit(utils.extract_hex_address(item.text())) - - def exec_add_entry_dialog(self) -> None: - entry_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_EXPRESSION, "")]) - if entry_dialog.exec(): - text = entry_dialog.get_values()[0] - address = debugcore.examine_expression(text).address - if not address: - QMessageBox.information(self, tr.ERROR, tr.INVALID_EXPRESSION) - return - self.bookmarked.emit(int(address, 16)) - - def exec_change_comment_dialog(self, current_address: int) -> None: - self.comment_changed.emit(current_address) - - def listWidget_context_menu_event(self, event: QContextMenuEvent) -> None: - current_item = guiutils.get_current_item(self.listWidget) - if current_item: - current_address = utils.safe_str_to_int(utils.extract_hex_address(current_item.text()), 16) - if current_address not in self.session.pct_bookmarks: - QMessageBox.information(self, tr.ERROR, tr.INVALID_ENTRY) - self.refresh_table() - return - else: - current_address = None - menu = QMenu() - add_entry = menu.addAction(tr.ADD_ENTRY) - change_comment = menu.addAction(tr.CHANGE_COMMENT) - delete_record = menu.addAction(f"{tr.DELETE}[Del]") - if current_item is None: - guiutils.delete_menu_entries(menu, [change_comment, delete_record]) - menu.addSeparator() - refresh = menu.addAction(f"{tr.REFRESH}[R]") - font_size = self.listWidget.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - add_entry: self.exec_add_entry_dialog, - change_comment: lambda: self.exec_change_comment_dialog(current_address), - delete_record: self.delete_record, - refresh: self.refresh_table, - } - try: - actions[action]() - except KeyError: - pass - - def delete_record(self) -> None: - current_item = guiutils.get_current_item(self.listWidget) - if not current_item: - return - current_address = utils.safe_str_to_int(utils.extract_hex_address(current_item.text()), 16) - self.deleted.emit(current_address) - - def on_new_session(self) -> None: - self.session = SessionManager.get_session() - self.refresh_table() diff --git a/GUI/Widgets/BreakpointInfo/BreakpointInfo.py b/GUI/Widgets/BreakpointInfo/BreakpointInfo.py deleted file mode 100644 index 9220d9a7..00000000 --- a/GUI/Widgets/BreakpointInfo/BreakpointInfo.py +++ /dev/null @@ -1,174 +0,0 @@ -from PyQt6.QtWidgets import QTabWidget, QWidget, QTableWidgetItem, QMenu, QMessageBox -from PyQt6.QtGui import QKeyEvent, QContextMenuEvent -from PyQt6.QtCore import Qt, QKeyCombination -from GUI.Utils import guiutils, utilwidgets -from GUI.States import states -from GUI.Widgets.BreakpointInfo.Form.BreakpointInfoWidget import Ui_TabWidget -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - -# represents the index of columns in breakpoint table -BREAK_NUM_COL = 0 -BREAK_TYPE_COL = 1 -BREAK_DISP_COL = 2 -BREAK_ENABLED_COL = 3 -BREAK_ADDR_COL = 4 -BREAK_SIZE_COL = 5 -BREAK_ON_HIT_COL = 6 -BREAK_HIT_COUNT_COL = 7 -BREAK_COND_COL = 8 - - -class BreakpointInfoWidget(QTabWidget, Ui_TabWidget): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.tableWidget_BreakpointInfo.contextMenuEvent = self.tableWidget_BreakpointInfo_context_menu_event - - # Saving the original function because super() doesn't work when we override functions like this - self.tableWidget_BreakpointInfo_keyPressEvent_original = self.tableWidget_BreakpointInfo.keyPressEvent - self.tableWidget_BreakpointInfo.keyPressEvent = self.tableWidget_BreakpointInfo_key_press_event - self.tableWidget_BreakpointInfo.itemDoubleClicked.connect(self.tableWidget_BreakpointInfo_double_clicked) - self.refresh() - states.backend_signals.breakpoints_changed.connect(self.refresh) - guiutils.center_to_parent(self) - - def refresh(self) -> None: - break_info = debugcore.get_breakpoint_info() - self.tableWidget_BreakpointInfo.setRowCount(0) - self.tableWidget_BreakpointInfo.setRowCount(len(break_info)) - for row, item in enumerate(break_info): - self.tableWidget_BreakpointInfo.setItem(row, BREAK_NUM_COL, QTableWidgetItem(item.number)) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_TYPE_COL, QTableWidgetItem(item.breakpoint_type)) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_DISP_COL, QTableWidgetItem(item.disp)) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_ENABLED_COL, QTableWidgetItem(item.enabled)) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_ADDR_COL, QTableWidgetItem(item.address or "")) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_SIZE_COL, QTableWidgetItem(str(item.size))) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_ON_HIT_COL, QTableWidgetItem(item.on_hit)) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_HIT_COUNT_COL, QTableWidgetItem(item.hit_count)) - self.tableWidget_BreakpointInfo.setItem(row, BREAK_COND_COL, QTableWidgetItem(item.condition)) - guiutils.resize_to_contents(self.tableWidget_BreakpointInfo) - self.textBrowser_BreakpointInfo.clear() - self.textBrowser_BreakpointInfo.setText(debugcore.send_command("info break", cli_output=True)) - self.repaint() - - def delete_breakpoint(self, breakpoint_num: int | None) -> None: - if breakpoint_num is not None: - debugcore.delete_breakpoint(breakpoint_num) - self.refresh_all() - - def tableWidget_BreakpointInfo_key_press_event(self, event: QKeyEvent) -> None: - selected_row = guiutils.get_current_row(self.tableWidget_BreakpointInfo) - if selected_row != -1: - breakpoint_num = utils.safe_int_cast(self.tableWidget_BreakpointInfo.item(selected_row, BREAK_NUM_COL).text()) - else: - breakpoint_num = None - - actions = {QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Delete): lambda: self.delete_breakpoint(breakpoint_num)} - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - pass - self.tableWidget_BreakpointInfo_keyPressEvent_original(event) - - def exec_enable_count_dialog(self, breakpoint_number: int) -> None: - hit_count_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_HIT_COUNT.format(1), "")]) - if hit_count_dialog.exec(): - count = hit_count_dialog.get_values()[0] - try: - count = int(count) - except ValueError: - QMessageBox.information(self, tr.ERROR, tr.HIT_COUNT_ASSERT_INT) - else: - if count < 1: - QMessageBox.information(self, tr.ERROR, tr.HIT_COUNT_ASSERT_LT.format(1)) - else: - debugcore.modify_breakpoint(breakpoint_number, typedefs.BREAKPOINT_MODIFY.ENABLE_COUNT, count=count) - - def tableWidget_BreakpointInfo_context_menu_event(self, event: QContextMenuEvent) -> None: - selected_row = guiutils.get_current_row(self.tableWidget_BreakpointInfo) - if selected_row != -1: - bp_num = utils.safe_int_cast(self.tableWidget_BreakpointInfo.item(selected_row, BREAK_NUM_COL).text()) - current_address_text = self.tableWidget_BreakpointInfo.item(selected_row, BREAK_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - if current_address: - current_address_int = utils.safe_str_to_int(current_address, 16) - else: - current_address_int = None - else: - bp_num = None - current_address_int = None - - menu = QMenu() - change_condition = menu.addAction(tr.CHANGE_CONDITION) - enable = menu.addAction(tr.ENABLE) - disable = menu.addAction(tr.DISABLE) - enable_once = menu.addAction(tr.DISABLE_AFTER_HIT) - enable_count = menu.addAction(tr.DISABLE_AFTER_COUNT) - enable_delete = menu.addAction(tr.DELETE_AFTER_HIT) - menu.addSeparator() - delete_breakpoint = menu.addAction(f"{tr.DELETE}[Del]") - menu.addSeparator() - if bp_num is None: - deletion_list = [ - change_condition, - enable, - disable, - enable_once, - enable_count, - enable_delete, - delete_breakpoint, - ] - guiutils.delete_menu_entries(menu, deletion_list) - if current_address_int is None: - deletion_list = [ - change_condition, - ] - guiutils.delete_menu_entries(menu, deletion_list) - font_size = self.tableWidget_BreakpointInfo.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - change_condition: lambda: self.edit_breakpoint_condition(current_address_int), - enable: lambda: debugcore.modify_breakpoint(bp_num, typedefs.BREAKPOINT_MODIFY.ENABLE), - disable: lambda: debugcore.modify_breakpoint(bp_num, typedefs.BREAKPOINT_MODIFY.DISABLE), - enable_once: lambda: debugcore.modify_breakpoint(bp_num, typedefs.BREAKPOINT_MODIFY.ENABLE_ONCE), - enable_count: lambda: self.exec_enable_count_dialog(bp_num), - enable_delete: lambda: debugcore.modify_breakpoint(bp_num, typedefs.BREAKPOINT_MODIFY.ENABLE_DELETE), - delete_breakpoint: lambda: debugcore.delete_breakpoint(bp_num), - } - try: - actions[action]() - except KeyError: - pass - if action != -1 and action is not None: - self.refresh_all() - - def refresh_all(self) -> None: - self.parent().refresh_hex_view() - self.parent().refresh_disassemble_view() - self.refresh() - - def edit_breakpoint_condition(self, address: int | None) -> None: - # Parent the condition dialog to ourselves instead of the memory view window (its default parent), - # so closing the dialog returns activation straight here without flickering through the memory view. - self.parent().add_breakpoint_condition(address, dialog_parent=self) - - def tableWidget_BreakpointInfo_double_clicked(self, index: QTableWidgetItem) -> None: - current_address_text = self.tableWidget_BreakpointInfo.item(index.row(), BREAK_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - if current_address is None: - # Catchpoints won't have an address, we don't need to change conditions or hex_dump - return - current_address_int = utils.safe_str_to_int(current_address, 16) - - if index.column() == BREAK_COND_COL: - self.edit_breakpoint_condition(current_address_int) - self.refresh_all() - else: - current_breakpoint_type = self.tableWidget_BreakpointInfo.item(index.row(), BREAK_TYPE_COL).text() - if "breakpoint" in current_breakpoint_type: - self.parent().disassemble_expression(current_address) - else: - self.parent().hex_dump_address(current_address_int) diff --git a/GUI/Widgets/BreakpointInfo/Form/BreakpointInfoWidget.py b/GUI/Widgets/BreakpointInfo/Form/BreakpointInfoWidget.py deleted file mode 100644 index 82a93e6d..00000000 --- a/GUI/Widgets/BreakpointInfo/Form/BreakpointInfoWidget.py +++ /dev/null @@ -1,94 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/BreakpointInfo/Form/BreakpointInfoWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_TabWidget(object): - def setupUi(self, TabWidget): - TabWidget.setObjectName("TabWidget") - TabWidget.resize(659, 496) - self.tab_BreakpointInfo = QtWidgets.QWidget() - self.tab_BreakpointInfo.setObjectName("tab_BreakpointInfo") - self.gridLayout_2 = QtWidgets.QGridLayout(self.tab_BreakpointInfo) - self.gridLayout_2.setObjectName("gridLayout_2") - self.tableWidget_BreakpointInfo = QtWidgets.QTableWidget(parent=self.tab_BreakpointInfo) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_BreakpointInfo.setFont(font) - self.tableWidget_BreakpointInfo.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_BreakpointInfo.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_BreakpointInfo.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_BreakpointInfo.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollMode.ScrollPerPixel) - self.tableWidget_BreakpointInfo.setWordWrap(False) - self.tableWidget_BreakpointInfo.setObjectName("tableWidget_BreakpointInfo") - self.tableWidget_BreakpointInfo.setColumnCount(9) - self.tableWidget_BreakpointInfo.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(2, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(3, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(4, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(5, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(6, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(7, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_BreakpointInfo.setHorizontalHeaderItem(8, item) - self.tableWidget_BreakpointInfo.horizontalHeader().setStretchLastSection(True) - self.tableWidget_BreakpointInfo.verticalHeader().setVisible(False) - self.tableWidget_BreakpointInfo.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_BreakpointInfo.verticalHeader().setMinimumSectionSize(16) - self.gridLayout_2.addWidget(self.tableWidget_BreakpointInfo, 0, 0, 1, 1) - TabWidget.addTab(self.tab_BreakpointInfo, "") - self.tab_RawBreakpointInfo = QtWidgets.QWidget() - self.tab_RawBreakpointInfo.setObjectName("tab_RawBreakpointInfo") - self.gridLayout = QtWidgets.QGridLayout(self.tab_RawBreakpointInfo) - self.gridLayout.setObjectName("gridLayout") - self.textBrowser_BreakpointInfo = QtWidgets.QTextBrowser(parent=self.tab_RawBreakpointInfo) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_BreakpointInfo.setFont(font) - self.textBrowser_BreakpointInfo.setObjectName("textBrowser_BreakpointInfo") - self.gridLayout.addWidget(self.textBrowser_BreakpointInfo, 0, 0, 1, 1) - TabWidget.addTab(self.tab_RawBreakpointInfo, "") - - self.retranslateUi(TabWidget) - TabWidget.setCurrentIndex(0) - QtCore.QMetaObject.connectSlotsByName(TabWidget) - - def retranslateUi(self, TabWidget): - _translate = QtCore.QCoreApplication.translate - TabWidget.setWindowTitle(_translate("TabWidget", "Breakpoints")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(0) - item.setText(_translate("TabWidget", "No")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(1) - item.setText(_translate("TabWidget", "Type")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(2) - item.setText(_translate("TabWidget", "Disp")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(3) - item.setText(_translate("TabWidget", "Enabled")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(4) - item.setText(_translate("TabWidget", "Address")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(5) - item.setText(_translate("TabWidget", "Size")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(6) - item.setText(_translate("TabWidget", "On Hit")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(7) - item.setText(_translate("TabWidget", "Hit Count")) - item = self.tableWidget_BreakpointInfo.horizontalHeaderItem(8) - item.setText(_translate("TabWidget", "Condition")) - TabWidget.setTabText(TabWidget.indexOf(self.tab_BreakpointInfo), _translate("TabWidget", "Interactive")) - TabWidget.setTabText(TabWidget.indexOf(self.tab_RawBreakpointInfo), _translate("TabWidget", "Raw")) diff --git a/GUI/Widgets/BreakpointInfo/Form/BreakpointInfoWidget.ui b/GUI/Widgets/BreakpointInfo/Form/BreakpointInfoWidget.ui deleted file mode 100644 index e8137ed3..00000000 --- a/GUI/Widgets/BreakpointInfo/Form/BreakpointInfoWidget.ui +++ /dev/null @@ -1,126 +0,0 @@ - - - TabWidget - - - - 0 - 0 - 659 - 496 - - - - Breakpoints - - - 0 - - - - Interactive - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - QAbstractItemView::ScrollPerPixel - - - false - - - true - - - false - - - 16 - - - 16 - - - - No - - - - - Type - - - - - Disp - - - - - Enabled - - - - - Address - - - - - Size - - - - - On Hit - - - - - Hit Count - - - - - Condition - - - - - - - - - Raw - - - - - - - Monospace - - - - - - - - - - diff --git a/GUI/Widgets/Console/Console.py b/GUI/Widgets/Console/Console.py deleted file mode 100644 index d1334c2f..00000000 --- a/GUI/Widgets/Console/Console.py +++ /dev/null @@ -1,138 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QCompleter -from PyQt6.QtGui import QShortcut, QKeySequence, QKeyEvent, QCloseEvent, QTextCursor -from PyQt6.QtCore import Qt, QKeyCombination, QStringListModel, pyqtSignal -from GUI.Utils import guitypedefs, guiutils -from GUI.Widgets.Console.Form.ConsoleWidget import Ui_Form -from GUI.Widgets.TextEdit.TextEdit import TextEditDialog -from libpince import debugcore -from tr.tr import TranslationConstants as tr - - -class ConsoleWidget(QWidget, Ui_Form): - gdb_command_sent = pyqtSignal() - phase_out_request = pyqtSignal() - attach_state_changed = pyqtSignal() - - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.completion_model = QStringListModel() - self.completer = QCompleter() - self.completer.setModel(self.completion_model) - self.completer.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion) - self.completer.setMaxVisibleItems(8) - self.lineEdit.setCompleter(self.completer) - self.quit_commands = ("q", "quit", "-gdb-exit") - self.continue_commands = ("c", "continue", "-exec-continue") - self.input_history = [""] - self.current_history_index = -1 - self.await_async_output_thread = guitypedefs.AwaitAsyncOutput() - self.await_async_output_thread.async_output_ready.connect(self.on_async_output) - self.await_async_output_thread.start() - self.pushButton_Send.clicked.connect(self.communicate) - self.shortcut_send = QShortcut(QKeySequence("Return"), self) - self.shortcut_send.activated.connect(self.communicate) - self.shortcut_complete_command = QShortcut(QKeySequence("Tab"), self) - self.shortcut_complete_command.activated.connect(self.complete_command) - self.shortcut_multiline_mode = QShortcut(QKeySequence("Ctrl+Return"), self) - self.shortcut_multiline_mode.activated.connect(self.enter_multiline_mode) - self.lineEdit.textEdited.connect(self.finish_completion) - - # Saving the original function because super() doesn't work when we override functions like this - self.lineEdit_keyPressEvent_original = self.lineEdit.keyPressEvent - self.lineEdit.keyPressEvent = self.lineEdit_key_press_event - self.reset_console_text() - guiutils.center_to_parent(self) - - def communicate(self) -> None: - self.current_history_index = -1 - self.input_history[-1] = "" - console_input = self.lineEdit.text() - last_input = self.input_history[-2] if len(self.input_history) > 1 else "" - if console_input != last_input and console_input != "": - self.input_history[-1] = console_input - self.input_history.append("") - if console_input.lower() == "/clear": - self.lineEdit.clear() - self.reset_console_text() - return - self.lineEdit.clear() - command = console_input.strip() - command_lower = command.lower() - gdb_command_sent = False - if command_lower in self.quit_commands: - console_output = tr.QUIT_SESSION_CRASH - elif command_lower in self.continue_commands: - console_output = tr.CONT_SESSION_CRASH - else: - if command == "phase-out": - self.phase_out_request.emit() - console_output = debugcore.send_command(console_input, cli_output=self.radioButton_CLI.isChecked()) - gdb_command_sent = bool(command) - self.textBrowser.append("-->" + console_input) - if console_output: - self.textBrowser.append(console_output) - self.scroll_to_bottom() - if command in ("phase-out", "phase-in"): - self.attach_state_changed.emit() - if gdb_command_sent: - self.gdb_command_sent.emit() - - def reset_console_text(self) -> None: - self.textBrowser.clear() - self.textBrowser.append(tr.GDB_CONSOLE_INIT) - - def scroll_to_bottom(self) -> None: - cursor = self.textBrowser.textCursor() - cursor.movePosition(QTextCursor.MoveOperation.End) - self.textBrowser.setTextCursor(cursor) - self.textBrowser.ensureCursorVisible() - - def enter_multiline_mode(self) -> None: - multiline_dialog = TextEditDialog(self, self.lineEdit.text()) - if multiline_dialog.exec(): - self.lineEdit.setText(multiline_dialog.get_values()) - self.communicate() - - def on_async_output(self, async_output: str) -> None: - self.textBrowser.append(async_output) - self.scroll_to_bottom() - - def scroll_backwards_history(self) -> None: - if self.current_history_index - 1 < -len(self.input_history): - return - new_text = self.input_history[self.current_history_index - 1] - self.input_history[self.current_history_index] = self.lineEdit.text() - self.current_history_index -= 1 - self.lineEdit.setText(new_text) - - def scroll_forwards_history(self) -> None: - if self.current_history_index == -1: - return - self.input_history[self.current_history_index] = self.lineEdit.text() - self.current_history_index += 1 - self.lineEdit.setText(self.input_history[self.current_history_index]) - - def lineEdit_key_press_event(self, event: QKeyEvent) -> None: - actions = { - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Up): self.scroll_backwards_history, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Down): self.scroll_forwards_history, - } - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - self.lineEdit_keyPressEvent_original(event) - - def finish_completion(self) -> None: - self.completion_model.setStringList([]) - - def complete_command(self) -> None: - if debugcore.gdb_initialized and debugcore.currentpid != -1 and self.lineEdit.text(): - self.completion_model.setStringList(debugcore.complete_command(self.lineEdit.text())) - self.completer.complete() - else: - self.finish_completion() - - def closeEvent(self, event: QCloseEvent) -> None: - self.await_async_output_thread.stop() diff --git a/GUI/Widgets/DissectCode/DissectCode.py b/GUI/Widgets/DissectCode/DissectCode.py deleted file mode 100644 index e788c1f4..00000000 --- a/GUI/Widgets/DissectCode/DissectCode.py +++ /dev/null @@ -1,144 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QTableWidgetItem, QMessageBox -from PyQt6.QtGui import QCloseEvent -from PyQt6.QtCore import QThread, pyqtSignal -from GUI.States import states -from GUI.Utils import guiutils -from GUI.Widgets.DissectCode.Form.DissectCodeDialog import Ui_Dialog -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr - -# represents the index of columns in dissect code table -DISSECT_CODE_ADDR_COL = 0 -DISSECT_CODE_PATH_COL = 1 - - -class DissectCodeDialog(QDialog, Ui_Dialog): - scan_finished_signal = pyqtSignal() - - def __init__(self, parent: QWidget, int_address: int = -1) -> None: - super().__init__(parent) - self.setupUi(self) - self.init_pre_scan_gui() - self.update_dissect_results() - self.show_memory_regions() - self.splitter.setStretchFactor(0, 1) - self.pushButton_StartCancel.clicked.connect(self.pushButton_StartCancel_clicked) - states.backend_signals.dissect_code_status_changed.connect(self.refresh_dissect_status) - if int_address != -1: - for row in range(self.tableWidget_ExecutableMemoryRegions.rowCount()): - item = self.tableWidget_ExecutableMemoryRegions.item(row, DISSECT_CODE_ADDR_COL).text() - start_addr, end_addr = item.split("-") - if utils.safe_str_to_int(start_addr, 16) <= int_address <= utils.safe_str_to_int(end_addr, 16): - self.tableWidget_ExecutableMemoryRegions.clearSelection() - self.tableWidget_ExecutableMemoryRegions.selectRow(row) - self.pushButton_StartCancel_clicked() - break - else: - QMessageBox.information(self, tr.ERROR, tr.INVALID_REGION) - else: - if self.tableWidget_ExecutableMemoryRegions.rowCount() > 0: - self.tableWidget_ExecutableMemoryRegions.selectRow(0) - guiutils.center_to_parent(self) - - class BackgroundThread(QThread): - output_ready = pyqtSignal() - is_canceled = False - - def __init__(self, region_list: list, discard_invalid_strings: bool) -> None: - super().__init__() - self.region_list = region_list - self.discard_invalid_strings = discard_invalid_strings - - def run(self) -> None: - try: - debugcore.dissect_code(self.region_list, self.discard_invalid_strings) - finally: - if not self.is_canceled: - self.output_ready.emit() - - def init_pre_scan_gui(self) -> None: - self.is_scanning = False - self.is_canceled = False - self.pushButton_StartCancel.setText(tr.START) - - def init_after_scan_gui(self) -> None: - self.is_scanning = True - self.label_ScanInfo.setText(tr.CURRENT_SCAN_REGION) - self.pushButton_StartCancel.setText(tr.CANCEL) - - def refresh_dissect_status(self) -> None: - region, region_count, range, string_count, jump_count, call_count = debugcore.get_dissect_code_status() - if not region: - return - self.label_RegionInfo.setText(region) - self.label_RegionCountInfo.setText(region_count) - self.label_CurrentRange.setText(range) - self.label_StringReferenceCount.setText(str(string_count)) - self.label_JumpReferenceCount.setText(str(jump_count)) - self.label_CallReferenceCount.setText(str(call_count)) - - def update_dissect_results(self) -> None: - referenced_strings = None - referenced_jumps = None - referenced_calls = None - try: - referenced_strings, referenced_jumps, referenced_calls = debugcore.get_dissect_code_data() - except: - return - try: - self.label_StringReferenceCount.setText(str(len(referenced_strings))) - self.label_JumpReferenceCount.setText(str(len(referenced_jumps))) - self.label_CallReferenceCount.setText(str(len(referenced_calls))) - finally: - for ref_dict in (referenced_strings, referenced_jumps, referenced_calls): - if ref_dict is not None: - ref_dict.close() - - def show_memory_regions(self) -> None: - executable_regions = utils.filter_regions(debugcore.currentpid, "permissions", "..x.") - self.region_list = [] - self.tableWidget_ExecutableMemoryRegions.setRowCount(0) - self.tableWidget_ExecutableMemoryRegions.setRowCount(len(executable_regions)) - for row, (start, end, _, _, _, _, path) in enumerate(executable_regions): - address = start + "-" + end - self.region_list.append((start, end)) - self.tableWidget_ExecutableMemoryRegions.setItem(row, DISSECT_CODE_ADDR_COL, QTableWidgetItem(address)) - self.tableWidget_ExecutableMemoryRegions.setItem(row, DISSECT_CODE_PATH_COL, QTableWidgetItem(path)) - guiutils.resize_to_contents(self.tableWidget_ExecutableMemoryRegions) - - def scan_finished(self) -> None: - self.init_pre_scan_gui() - if not self.is_canceled: - self.label_ScanInfo.setText(tr.SCAN_FINISHED) - self.is_canceled = False - self.refresh_dissect_status() - self.update_dissect_results() - self.scan_finished_signal.emit() - - def pushButton_StartCancel_clicked(self) -> None: - if self.is_scanning: - self.is_canceled = True - self.background_thread.is_canceled = True - debugcore.cancel_dissect_code() - self.update_dissect_results() - self.label_ScanInfo.setText(tr.SCAN_CANCELED) - else: - selected_rows = self.tableWidget_ExecutableMemoryRegions.selectionModel().selectedRows() - if not selected_rows: - QMessageBox.information(self, tr.ERROR, tr.SELECT_ONE_REGION) - return - selected_indexes = [selected_row.row() for selected_row in selected_rows] - selected_regions = [self.region_list[selected_index] for selected_index in selected_indexes] - self.background_thread = self.BackgroundThread(selected_regions, self.checkBox_DiscardInvalidStrings.isChecked()) - self.background_thread.output_ready.connect(self.scan_finished) - self.background_thread.finished.connect(self.init_pre_scan_gui) - self.init_after_scan_gui() - self.background_thread.start() - - def closeEvent(self, event: QCloseEvent) -> None: - debugcore.cancel_dissect_code() - if hasattr(self, "background_thread"): - self.is_canceled = True - self.background_thread.is_canceled = True - self.background_thread.wait() - super().closeEvent(event) diff --git a/GUI/Widgets/DissectCode/Form/DissectCodeDialog.py b/GUI/Widgets/DissectCode/Form/DissectCodeDialog.py deleted file mode 100644 index 71d43ab8..00000000 --- a/GUI/Widgets/DissectCode/Form/DissectCodeDialog.py +++ /dev/null @@ -1,148 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/DissectCode/Form/DissectCodeDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(799, 412) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=Dialog) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter.setObjectName("splitter") - self.tableWidget_ExecutableMemoryRegions = QtWidgets.QTableWidget(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_ExecutableMemoryRegions.setFont(font) - self.tableWidget_ExecutableMemoryRegions.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_ExecutableMemoryRegions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_ExecutableMemoryRegions.setWordWrap(False) - self.tableWidget_ExecutableMemoryRegions.setObjectName("tableWidget_ExecutableMemoryRegions") - self.tableWidget_ExecutableMemoryRegions.setColumnCount(2) - self.tableWidget_ExecutableMemoryRegions.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_ExecutableMemoryRegions.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_ExecutableMemoryRegions.setHorizontalHeaderItem(1, item) - self.tableWidget_ExecutableMemoryRegions.horizontalHeader().setStretchLastSection(True) - self.tableWidget_ExecutableMemoryRegions.verticalHeader().setVisible(False) - self.tableWidget_ExecutableMemoryRegions.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_ExecutableMemoryRegions.verticalHeader().setMinimumSectionSize(16) - self.layoutWidget = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget.setObjectName("layoutWidget") - self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget) - self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) - self.verticalLayout_2.setObjectName("verticalLayout_2") - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.label_ScanInfo = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_ScanInfo.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.label_ScanInfo.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_ScanInfo.setObjectName("label_ScanInfo") - self.verticalLayout.addWidget(self.label_ScanInfo) - self.label_RegionInfo = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_RegionInfo.setText("-") - self.label_RegionInfo.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.label_RegionInfo.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_RegionInfo.setObjectName("label_RegionInfo") - self.verticalLayout.addWidget(self.label_RegionInfo) - self.label_RegionCountInfo = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_RegionCountInfo.setText("-") - self.label_RegionCountInfo.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.label_RegionCountInfo.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_RegionCountInfo.setObjectName("label_RegionCountInfo") - self.verticalLayout.addWidget(self.label_RegionCountInfo) - self.label_4 = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_4.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.label_4.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_4.setObjectName("label_4") - self.verticalLayout.addWidget(self.label_4) - self.label_CurrentRange = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_CurrentRange.setText("-") - self.label_CurrentRange.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.label_CurrentRange.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_CurrentRange.setObjectName("label_CurrentRange") - self.verticalLayout.addWidget(self.label_CurrentRange) - self.verticalLayout_2.addLayout(self.verticalLayout) - self.line = QtWidgets.QFrame(parent=self.layoutWidget) - self.line.setFrameShape(QtWidgets.QFrame.Shape.HLine) - self.line.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line.setObjectName("line") - self.verticalLayout_2.addWidget(self.line) - self.label = QtWidgets.QLabel(parent=self.layoutWidget) - self.label.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label.setObjectName("label") - self.verticalLayout_2.addWidget(self.label) - self.label_StringReferenceCount = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_StringReferenceCount.setText("") - self.label_StringReferenceCount.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_StringReferenceCount.setObjectName("label_StringReferenceCount") - self.verticalLayout_2.addWidget(self.label_StringReferenceCount) - self.label_2 = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_2.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_2.setObjectName("label_2") - self.verticalLayout_2.addWidget(self.label_2) - self.label_JumpReferenceCount = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_JumpReferenceCount.setText("") - self.label_JumpReferenceCount.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_JumpReferenceCount.setObjectName("label_JumpReferenceCount") - self.verticalLayout_2.addWidget(self.label_JumpReferenceCount) - self.label_3 = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_3.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_3.setObjectName("label_3") - self.verticalLayout_2.addWidget(self.label_3) - self.label_CallReferenceCount = QtWidgets.QLabel(parent=self.layoutWidget) - self.label_CallReferenceCount.setText("") - self.label_CallReferenceCount.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_CallReferenceCount.setObjectName("label_CallReferenceCount") - self.verticalLayout_2.addWidget(self.label_CallReferenceCount) - self.line_2 = QtWidgets.QFrame(parent=self.layoutWidget) - self.line_2.setFrameShape(QtWidgets.QFrame.Shape.HLine) - self.line_2.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line_2.setObjectName("line_2") - self.verticalLayout_2.addWidget(self.line_2) - self.checkBox_DiscardInvalidStrings = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_DiscardInvalidStrings.setChecked(True) - self.checkBox_DiscardInvalidStrings.setObjectName("checkBox_DiscardInvalidStrings") - self.verticalLayout_2.addWidget(self.checkBox_DiscardInvalidStrings) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.pushButton_StartCancel = QtWidgets.QPushButton(parent=self.layoutWidget) - self.pushButton_StartCancel.setText("") - self.pushButton_StartCancel.setObjectName("pushButton_StartCancel") - self.horizontalLayout.addWidget(self.pushButton_StartCancel) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem1) - self.verticalLayout_2.addLayout(self.horizontalLayout) - spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_2.addItem(spacerItem2) - self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Dissect Code")) - item = self.tableWidget_ExecutableMemoryRegions.horizontalHeaderItem(0) - item.setText(_translate("Dialog", "Regions")) - item = self.tableWidget_ExecutableMemoryRegions.horizontalHeaderItem(1) - item.setText(_translate("Dialog", "Path")) - self.label_ScanInfo.setText(_translate("Dialog", "Selected regions will be scanned")) - self.label_4.setText(_translate("Dialog", "Currently scanning range:")) - self.label.setText(_translate("Dialog", "String references found:")) - self.label_2.setText(_translate("Dialog", "Jumps found:")) - self.label_3.setText(_translate("Dialog", "Calls found:")) - self.checkBox_DiscardInvalidStrings.setToolTip(_translate("Dialog", "Entries that can\'t be decoded as utf-8 won\'t be included in referenced strings\n" -"Unchecking it makes ReferencedStringsWidget load slower but allows you to examine non-string pointers on it")) - self.checkBox_DiscardInvalidStrings.setText(_translate("Dialog", "Discard invalid strings")) diff --git a/GUI/Widgets/DissectCode/Form/DissectCodeDialog.ui b/GUI/Widgets/DissectCode/Form/DissectCodeDialog.ui deleted file mode 100644 index 74cbe9cd..00000000 --- a/GUI/Widgets/DissectCode/Form/DissectCodeDialog.ui +++ /dev/null @@ -1,277 +0,0 @@ - - - Dialog - - - - 0 - 0 - 799 - 412 - - - - Dissect Code - - - - - - Qt::Horizontal - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SelectRows - - - false - - - true - - - false - - - 16 - - - 16 - - - - Regions - - - - - Path - - - - - - - - - - - Selected regions will be scanned - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Currently scanning range: - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - Qt::AlignCenter - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - Qt::Horizontal - - - - - - - String references found: - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Jumps found: - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Calls found: - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Qt::Horizontal - - - - - - - Entries that can't be decoded as utf-8 won't be included in referenced strings -Unchecking it makes ReferencedStringsWidget load slower but allows you to examine non-string pointers on it - - - Discard invalid strings - - - true - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - - diff --git a/GUI/Widgets/EditInstruction/EditInstruction.py b/GUI/Widgets/EditInstruction/EditInstruction.py deleted file mode 100644 index 3a0fe0ed..00000000 --- a/GUI/Widgets/EditInstruction/EditInstruction.py +++ /dev/null @@ -1,71 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QDialogButtonBox -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.EditInstruction.Form.EditInstructionDialog import Ui_Dialog -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - - -class EditInstructionDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, address: str, bytes_aob: str) -> None: - super().__init__(parent) - self.setupUi(self) - self.orig_bytes = bytes_aob - self.lineEdit_Address.setText(address) - self.lineEdit_Bytes.setText(bytes_aob) - self.lineEdit_Bytes_text_edited() - self.lineEdit_Bytes.textEdited.connect(self.lineEdit_Bytes_text_edited) - self.lineEdit_Instruction.textEdited.connect(self.lineEdit_Instruction_text_edited) - guiutils.center_to_parent(self) - - def set_valid(self, valid: bool) -> None: - if valid: - self.is_valid = True - self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(True) - else: - self.is_valid = False - self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) - - def lineEdit_Bytes_text_edited(self) -> None: - bytes_aob = self.lineEdit_Bytes.text() - if typedefs.ByteArrayValueType().parse(bytes_aob): - address = utils.safe_str_to_int(self.lineEdit_Address.text(), 0) - instruction = utils.disassemble(bytes_aob, address, debugcore.inferior_arch) - if instruction: - self.set_valid(True) - self.lineEdit_Instruction.setText(instruction) - return - self.set_valid(False) - self.lineEdit_Instruction.setText("??") - - def lineEdit_Instruction_text_edited(self) -> None: - instruction = self.lineEdit_Instruction.text() - address = utils.safe_str_to_int(self.lineEdit_Address.text(), 0) - result = utils.assemble(instruction, address, debugcore.inferior_arch) - if result: - byte_list = result[0] - self.set_valid(True) - bytes_str = " ".join([format(num, "02x") for num in byte_list]) - self.lineEdit_Bytes.setText(bytes_str) - else: - self.set_valid(False) - self.lineEdit_Bytes.setText("??") - - def accept(self) -> None: - if not self.is_valid: - return - - # No need to check for validity since address is not editable and instruction is checked in text_edited - address = utils.safe_str_to_int(self.lineEdit_Address.text(), 0) - bytes_aob = self.lineEdit_Bytes.text() - if bytes_aob != self.orig_bytes: - new_length = len(bytes_aob.split()) - old_length = len(self.orig_bytes.split()) - if new_length < old_length: - bytes_aob += " 90" * (old_length - new_length) # Append NOPs if we are short on bytes - elif new_length > old_length: - if not utilwidgets.InputDialog(self, tr.NEW_INSTR.format(new_length, old_length)).exec(): - return - debugcore.modify_instruction(address, bytes_aob) - self.parent().refresh_hex_view() - self.parent().refresh_disassemble_view() - super().accept() diff --git a/GUI/Widgets/EditInstruction/Form/EditInstructionDialog.py b/GUI/Widgets/EditInstruction/Form/EditInstructionDialog.py deleted file mode 100644 index e1b5f4d9..00000000 --- a/GUI/Widgets/EditInstruction/Form/EditInstructionDialog.py +++ /dev/null @@ -1,57 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/EditInstruction/Form/EditInstructionDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.setEnabled(True) - Dialog.resize(500, 124) - Dialog.setMaximumSize(QtCore.QSize(16777215, 124)) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.lineEdit_Bytes = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Bytes.setObjectName("lineEdit_Bytes") - self.gridLayout.addWidget(self.lineEdit_Bytes, 1, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 2, 0, 1, 1) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.horizontalLayout.addWidget(self.label) - self.lineEdit_Address = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Address.setEnabled(False) - self.lineEdit_Address.setAutoFillBackground(False) - self.lineEdit_Address.setReadOnly(True) - self.lineEdit_Address.setObjectName("lineEdit_Address") - self.horizontalLayout.addWidget(self.lineEdit_Address) - self.label_2 = QtWidgets.QLabel(parent=Dialog) - self.label_2.setObjectName("label_2") - self.horizontalLayout.addWidget(self.label_2) - self.lineEdit_Instruction = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Instruction.setObjectName("lineEdit_Instruction") - self.horizontalLayout.addWidget(self.lineEdit_Instruction) - self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Edit Instruction")) - self.label.setText(_translate("Dialog", "Address:")) - self.label_2.setText(_translate("Dialog", "Instruction:")) - self.lineEdit_Instruction.setToolTip(_translate("Dialog", "Multiple entries are separated with ;")) diff --git a/GUI/Widgets/EditInstruction/Form/EditInstructionDialog.ui b/GUI/Widgets/EditInstruction/Form/EditInstructionDialog.ui deleted file mode 100644 index a1376f0e..00000000 --- a/GUI/Widgets/EditInstruction/Form/EditInstructionDialog.ui +++ /dev/null @@ -1,114 +0,0 @@ - - - Dialog - - - true - - - - 0 - 0 - 500 - 124 - - - - - 16777215 - 124 - - - - Edit Instruction - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - Address: - - - - - - - false - - - false - - - true - - - - - - - Instruction: - - - - - - - Multiple entries are separated with ; - - - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/GUI/Widgets/EditType/EditType.py b/GUI/Widgets/EditType/EditType.py deleted file mode 100644 index ac6d942b..00000000 --- a/GUI/Widgets/EditType/EditType.py +++ /dev/null @@ -1,95 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QMessageBox, QApplication -from GUI.Utils import guiutils -from GUI.Validators.HexValidator import HexValidator -from GUI.Widgets.EditType.Form.EditTypeDialog import Ui_Dialog -from libpince import typedefs, utils -from tr.tr import TranslationConstants as tr - - -class EditTypeDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, value_type: typedefs.ValueType | None = None) -> None: - super().__init__(parent) - self.setupUi(self) - vt = typedefs.IntegerValueType() if not value_type else value_type - self.lineEdit_Length.setValidator(HexValidator(99, self)) - self.lineEdit_Length.setFixedWidth(40) - guiutils.fill_value_combobox(self.comboBox_ValueType, vt, include_bit_field=True) - guiutils.fill_endianness_combobox(self.comboBox_Endianness, getattr(vt, "endian", typedefs.ENDIANNESS.HOST)) - if isinstance(vt, (typedefs.StringValueType, typedefs.ByteArrayValueType)): - self.lineEdit_Length.setText(str(vt.length)) - elif isinstance(vt, typedefs.BitFieldValueType): - self.lineEdit_Length.setText(str(vt.bits)) - self.spinBox_StartBit.setValue(vt.start_bit) - if isinstance(vt, typedefs.StringValueType): - self.checkBox_ZeroTerminate.setChecked(vt.zero_terminate) - value_repr = getattr(vt, "value_repr", typedefs.VALUE_REPR.UNSIGNED) - if value_repr == typedefs.VALUE_REPR.HEX: - self.checkBox_Hex.setChecked(True) - self.checkBox_Signed.setEnabled(False) - elif value_repr == typedefs.VALUE_REPR.SIGNED: - self.checkBox_Signed.setChecked(True) - else: - self.checkBox_Signed.setChecked(False) - self.comboBox_ValueType.currentIndexChanged.connect(self.comboBox_ValueType_current_index_changed) - self.checkBox_Hex.stateChanged.connect(self.repr_changed) - self.comboBox_ValueType_current_index_changed() - guiutils.center_to_parent(self) - - def comboBox_ValueType_current_index_changed(self) -> None: - value_type = self.comboBox_ValueType.currentData() - is_bit_field = isinstance(value_type, typedefs.BitFieldValueType) - self.widget_Length.setVisible(isinstance(value_type, (typedefs.StringValueType, typedefs.ByteArrayValueType)) or is_bit_field) - self.label_StartBit.setVisible(is_bit_field) - self.spinBox_StartBit.setVisible(is_bit_field) - self.checkBox_ZeroTerminate.setVisible(isinstance(value_type, typedefs.StringValueType)) - self.label_Endianness.setVisible(not is_bit_field) - self.comboBox_Endianness.setVisible(not is_bit_field) - QApplication.processEvents() - self.adjustSize() - - def repr_changed(self) -> None: - if self.checkBox_Hex.isChecked(): - self.checkBox_Signed.setEnabled(False) - else: - self.checkBox_Signed.setEnabled(True) - - def reject(self) -> None: - super().reject() - - def accept(self) -> None: - if self.label_Length.isVisible(): - length = self.lineEdit_Length.text() - try: - length = int(length, 0) - except: - QMessageBox.information(self, tr.ERROR, tr.LENGTH_NOT_VALID) - return - if not length > 0: - QMessageBox.information(self, tr.ERROR, tr.LENGTH_GT) - return - if isinstance(self.comboBox_ValueType.currentData(), typedefs.BitFieldValueType) and length > 64: - QMessageBox.information(self, tr.ERROR, tr.LENGTH_NOT_VALID) - return - super().accept() - - def get_values(self) -> typedefs.ValueType: - value_type = self.comboBox_ValueType.currentData() - length = self.lineEdit_Length.text() - length = utils.safe_str_to_int(length, 0) - zero_terminate = self.checkBox_ZeroTerminate.isChecked() - if self.checkBox_Hex.isChecked(): - value_repr = typedefs.VALUE_REPR.HEX - elif self.checkBox_Signed.isChecked(): - value_repr = typedefs.VALUE_REPR.SIGNED - else: - value_repr = typedefs.VALUE_REPR.UNSIGNED - if isinstance(value_type, typedefs.BitFieldValueType): - return typedefs.BitFieldValueType(length, self.spinBox_StartBit.value(), value_repr=value_repr) - endian = self.comboBox_Endianness.currentData() - return guiutils.configure_value_type( - value_type, - length=length, - zero_terminate=zero_terminate, - value_repr=value_repr, - endian=endian, - ) diff --git a/GUI/Widgets/EditType/Form/EditTypeDialog.py b/GUI/Widgets/EditType/Form/EditTypeDialog.py deleted file mode 100644 index 9789991d..00000000 --- a/GUI/Widgets/EditType/Form/EditTypeDialog.py +++ /dev/null @@ -1,98 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/EditType/Form/EditTypeDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(235, 163) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout_3 = QtWidgets.QHBoxLayout() - self.horizontalLayout_3.setObjectName("horizontalLayout_3") - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.verticalLayout.addWidget(self.label) - self.comboBox_ValueType = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_ValueType.setObjectName("comboBox_ValueType") - self.verticalLayout.addWidget(self.comboBox_ValueType) - self.horizontalLayout_3.addLayout(self.verticalLayout) - self.verticalLayout_3 = QtWidgets.QVBoxLayout() - self.verticalLayout_3.setObjectName("verticalLayout_3") - self.label_Endianness = QtWidgets.QLabel(parent=Dialog) - self.label_Endianness.setObjectName("label_Endianness") - self.verticalLayout_3.addWidget(self.label_Endianness) - self.comboBox_Endianness = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_Endianness.setObjectName("comboBox_Endianness") - self.verticalLayout_3.addWidget(self.comboBox_Endianness) - self.horizontalLayout_3.addLayout(self.verticalLayout_3) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_3.addItem(spacerItem) - self.gridLayout.addLayout(self.horizontalLayout_3, 0, 0, 1, 1) - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.checkBox_Hex = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_Hex.setObjectName("checkBox_Hex") - self.horizontalLayout_2.addWidget(self.checkBox_Hex) - self.checkBox_Signed = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_Signed.setObjectName("checkBox_Signed") - self.horizontalLayout_2.addWidget(self.checkBox_Signed) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_2.addItem(spacerItem1) - self.gridLayout.addLayout(self.horizontalLayout_2, 1, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 3, 0, 1, 1, QtCore.Qt.AlignmentFlag.AlignLeft) - self.widget_Length = QtWidgets.QWidget(parent=Dialog) - self.widget_Length.setObjectName("widget_Length") - self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.widget_Length) - self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0) - self.horizontalLayout_4.setObjectName("horizontalLayout_4") - self.label_Length = QtWidgets.QLabel(parent=self.widget_Length) - self.label_Length.setObjectName("label_Length") - self.horizontalLayout_4.addWidget(self.label_Length) - self.lineEdit_Length = QtWidgets.QLineEdit(parent=self.widget_Length) - self.lineEdit_Length.setText("10") - self.lineEdit_Length.setObjectName("lineEdit_Length") - self.horizontalLayout_4.addWidget(self.lineEdit_Length) - self.checkBox_ZeroTerminate = QtWidgets.QCheckBox(parent=self.widget_Length) - self.checkBox_ZeroTerminate.setChecked(True) - self.checkBox_ZeroTerminate.setObjectName("checkBox_ZeroTerminate") - self.horizontalLayout_4.addWidget(self.checkBox_ZeroTerminate) - self.label_StartBit = QtWidgets.QLabel(parent=self.widget_Length) - self.label_StartBit.setObjectName("label_StartBit") - self.horizontalLayout_4.addWidget(self.label_StartBit) - self.spinBox_StartBit = QtWidgets.QSpinBox(parent=self.widget_Length) - self.spinBox_StartBit.setMaximum(7) - self.spinBox_StartBit.setObjectName("spinBox_StartBit") - self.horizontalLayout_4.addWidget(self.spinBox_StartBit) - spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_4.addItem(spacerItem2) - self.gridLayout.addWidget(self.widget_Length, 2, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Type")) - self.label.setText(_translate("Dialog", "Type")) - self.label_Endianness.setText(_translate("Dialog", "Endianness")) - self.checkBox_Hex.setText(_translate("Dialog", "Hex")) - self.checkBox_Signed.setText(_translate("Dialog", "Signed")) - self.label_Length.setText(_translate("Dialog", "Length")) - self.checkBox_ZeroTerminate.setText(_translate("Dialog", "Zero-Terminated")) - self.label_StartBit.setText(_translate("Dialog", "Start bit")) diff --git a/GUI/Widgets/EditType/Form/EditTypeDialog.ui b/GUI/Widgets/EditType/Form/EditTypeDialog.ui deleted file mode 100644 index f9955e2a..00000000 --- a/GUI/Widgets/EditType/Form/EditTypeDialog.ui +++ /dev/null @@ -1,209 +0,0 @@ - - - Dialog - - - - 0 - 0 - 235 - 163 - - - - Type - - - - - - - - - - Type - - - - - - - - - - - - - - Endianness - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Hex - - - - - - - Signed - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Length - - - - - - - 10 - - - - - - - Zero-Terminated - - - true - - - - - - - Start bit - - - - - - - 7 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - diff --git a/GUI/Widgets/ExamineReferrers/ExamineReferrers.py b/GUI/Widgets/ExamineReferrers/ExamineReferrers.py deleted file mode 100644 index 7b93b592..00000000 --- a/GUI/Widgets/ExamineReferrers/ExamineReferrers.py +++ /dev/null @@ -1,115 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QMenu, QMessageBox, QListWidgetItem, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QContextMenuEvent, QTextCursor -from PyQt6.QtCore import Qt, QModelIndex -from GUI.Utils import guiutils -from GUI.Widgets.ExamineReferrers.Form.ExamineReferrersWidget import Ui_Form -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr -import re - - -class ExamineReferrersWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget, int_address: int) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.splitter.setStretchFactor(0, 1) - self.textBrowser_DisasInfo.resize(600, self.textBrowser_DisasInfo.height()) - self.referenced_hex = hex(int_address) - self.collect_referrer_data() - self.refresh_table() - self.listWidget_Referrers.sortItems(Qt.SortOrder.AscendingOrder) - self.listWidget_Referrers.selectionModel().currentChanged.connect(self.listWidget_Referrers_current_changed) - self.listWidget_Referrers.itemDoubleClicked.connect(self.listWidget_Referrers_item_double_clicked) - self.listWidget_Referrers.contextMenuEvent = self.listWidget_Referrers_context_menu_event - self.pushButton_Search.clicked.connect(self.refresh_table) - self.shortcut_search = QShortcut(QKeySequence("Return"), self) - self.shortcut_search.activated.connect(self.refresh_table) - guiutils.center_to_parent(self) - - def collect_referrer_data(self) -> None: - jmp_dict, call_dict = debugcore.get_dissect_code_data(False, True, True) - self.referrer_data = [] - try: - try: - jmp_referrers = jmp_dict[self.referenced_hex] - except KeyError: - pass - else: - jmp_referrers = [hex(item) for item in jmp_referrers] - self.referrer_data.extend([item.all for item in debugcore.examine_expressions(jmp_referrers) if item.all]) - try: - call_referrers = call_dict[self.referenced_hex] - except KeyError: - pass - else: - call_referrers = [hex(item) for item in call_referrers] - self.referrer_data.extend([item.all for item in debugcore.examine_expressions(call_referrers) if item.all]) - finally: - jmp_dict.close() - call_dict.close() - - def refresh_table(self) -> None: - searched_str = self.lineEdit_Regex.text() - case_sensitive = self.checkBox_CaseSensitive.isChecked() - enable_regex = self.checkBox_Regex.isChecked() - if enable_regex: - try: - if case_sensitive: - regex = re.compile(searched_str) - else: - regex = re.compile(searched_str, re.IGNORECASE) - except: - QMessageBox.information(self, tr.ERROR, tr.INVALID_REGEX) - return - self.listWidget_Referrers.setSortingEnabled(False) - self.listWidget_Referrers.clear() - for row, item in enumerate(self.referrer_data): - if enable_regex: - if not regex.search(item): - continue - else: - if case_sensitive: - if item.find(searched_str) == -1: - continue - else: - if item.lower().find(searched_str.lower()) == -1: - continue - self.listWidget_Referrers.addItem(item) - self.listWidget_Referrers.setSortingEnabled(True) - self.listWidget_Referrers.sortItems(Qt.SortOrder.AscendingOrder) - - def listWidget_Referrers_current_changed(self, QModelIndex_current: QModelIndex) -> None: - if QModelIndex_current.row() < 0: - return - self.textBrowser_DisasInfo.clear() - address = utils.extract_hex_address(self.listWidget_Referrers.item(QModelIndex_current.row()).text()) - disas_data = debugcore.disassemble(address, "+200") - for address_info, _, instr in disas_data: - self.textBrowser_DisasInfo.append(address_info + instr) - cursor = self.textBrowser_DisasInfo.textCursor() - cursor.movePosition(QTextCursor.MoveOperation.Start) - self.textBrowser_DisasInfo.setTextCursor(cursor) - self.textBrowser_DisasInfo.ensureCursorVisible() - - def listWidget_Referrers_item_double_clicked(self, item: QListWidgetItem) -> None: - self.parent().disassemble_expression(utils.extract_hex_address(item.text())) - - def listWidget_Referrers_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int) -> None: - QApplication.clipboard().setText(self.listWidget_Referrers.item(row).text()) - - selected_row = guiutils.get_current_row(self.listWidget_Referrers) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address]) - font_size = self.listWidget_Referrers.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {copy_address: lambda: copy_to_clipboard(selected_row)} - try: - actions[action]() - except KeyError: - pass diff --git a/GUI/Widgets/ExamineReferrers/Form/ExamineReferrersWidget.py b/GUI/Widgets/ExamineReferrers/Form/ExamineReferrersWidget.py deleted file mode 100644 index bb3e1186..00000000 --- a/GUI/Widgets/ExamineReferrers/Form/ExamineReferrersWidget.py +++ /dev/null @@ -1,69 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/ExamineReferrers/Form/ExamineReferrersWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(1025, 530) - Form.setToolTip("") - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=Form) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter.setObjectName("splitter") - self.layoutWidget = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget.setObjectName("layoutWidget") - self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) - self.verticalLayout.setContentsMargins(0, 0, 0, 0) - self.verticalLayout.setObjectName("verticalLayout") - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.lineEdit_Regex = QtWidgets.QLineEdit(parent=self.layoutWidget) - self.lineEdit_Regex.setObjectName("lineEdit_Regex") - self.horizontalLayout_2.addWidget(self.lineEdit_Regex) - self.checkBox_CaseSensitive = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_CaseSensitive.setObjectName("checkBox_CaseSensitive") - self.horizontalLayout_2.addWidget(self.checkBox_CaseSensitive) - self.checkBox_Regex = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_Regex.setObjectName("checkBox_Regex") - self.horizontalLayout_2.addWidget(self.checkBox_Regex) - self.pushButton_Search = QtWidgets.QPushButton(parent=self.layoutWidget) - self.pushButton_Search.setObjectName("pushButton_Search") - self.horizontalLayout_2.addWidget(self.pushButton_Search) - self.verticalLayout.addLayout(self.horizontalLayout_2) - self.listWidget_Referrers = QtWidgets.QListWidget(parent=self.layoutWidget) - font = QtGui.QFont() - font.setFamily("Monospace") - self.listWidget_Referrers.setFont(font) - self.listWidget_Referrers.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.listWidget_Referrers.setObjectName("listWidget_Referrers") - self.verticalLayout.addWidget(self.listWidget_Referrers) - self.textBrowser_DisasInfo = QtWidgets.QTextBrowser(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_DisasInfo.setFont(font) - self.textBrowser_DisasInfo.setLineWrapMode(QtWidgets.QTextEdit.LineWrapMode.NoWrap) - self.textBrowser_DisasInfo.setObjectName("textBrowser_DisasInfo") - self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Examine Referrers")) - self.lineEdit_Regex.setToolTip(_translate("Form", "Enter a string or a python regex")) - self.lineEdit_Regex.setPlaceholderText(_translate("Form", "Enter a string or a python regex")) - self.checkBox_CaseSensitive.setToolTip(_translate("Form", "Ignore case if checked")) - self.checkBox_CaseSensitive.setText(_translate("Form", "Case sensitive")) - self.checkBox_Regex.setToolTip(_translate("Form", "Your string will be treated as a regex if checked")) - self.checkBox_Regex.setText(_translate("Form", "Regex")) - self.pushButton_Search.setText(_translate("Form", "Search(Enter)")) diff --git a/GUI/Widgets/ExamineReferrers/Form/ExamineReferrersWidget.ui b/GUI/Widgets/ExamineReferrers/Form/ExamineReferrersWidget.ui deleted file mode 100644 index 2af499d9..00000000 --- a/GUI/Widgets/ExamineReferrers/Form/ExamineReferrersWidget.ui +++ /dev/null @@ -1,98 +0,0 @@ - - - Form - - - - 0 - 0 - 1025 - 530 - - - - Examine Referrers - - - - - - - - - Qt::Horizontal - - - - - - - - - Enter a string or a python regex - - - Enter a string or a python regex - - - - - - - Ignore case if checked - - - Case sensitive - - - - - - - Your string will be treated as a regex if checked - - - Regex - - - - - - - Search(Enter) - - - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - - - - - - - Monospace - - - - QTextEdit::NoWrap - - - - - - - - - diff --git a/GUI/Widgets/FloatRegister/FloatRegister.py b/GUI/Widgets/FloatRegister/FloatRegister.py deleted file mode 100644 index bffdc051..00000000 --- a/GUI/Widgets/FloatRegister/FloatRegister.py +++ /dev/null @@ -1,54 +0,0 @@ -from PyQt6.QtWidgets import QTabWidget, QWidget, QTableWidgetItem -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.FloatRegister.Form.FloatRegisterWidget import Ui_TabWidget -from libpince import debugcore -from tr.tr import TranslationConstants as tr - -# represents the index of columns in floating point table -NAME_COL = 0 -VALUE_COL = 1 - - -class FloatRegisterWidget(QTabWidget, Ui_TabWidget): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.tableWidget_FPU.itemDoubleClicked.connect(self.set_register) - self.tableWidget_XMM.itemDoubleClicked.connect(self.set_register) - - def update_registers(self) -> None: - float_registers = list(debugcore.read_float_registers().items()) - st_registers = float_registers[:8] - xmm_registers = float_registers[8:] - self.tableWidget_FPU.setRowCount(len(st_registers)) - self.tableWidget_XMM.setRowCount(len(xmm_registers)) - for row, (name, value) in enumerate(st_registers): - self.tableWidget_FPU.setItem(row, NAME_COL, QTableWidgetItem(name)) - self.tableWidget_FPU.setItem(row, VALUE_COL, QTableWidgetItem(value)) - for row, (name, value) in enumerate(xmm_registers): - self.tableWidget_XMM.setItem(row, NAME_COL, QTableWidgetItem(name)) - self.tableWidget_XMM.setItem(row, VALUE_COL, QTableWidgetItem(value)) - - def set_register(self, index: QTableWidgetItem) -> None: - if guiutils.check_inferior_running(self): - return - current_row = index.row() - if self.currentWidget() == self.FPU: - current_table_widget = self.tableWidget_FPU - elif self.currentWidget() == self.XMM: - current_table_widget = self.tableWidget_XMM - else: - raise Exception("Current widget is invalid: " + str(self.currentWidget().objectName())) - current_register = current_table_widget.item(current_row, NAME_COL).text() - current_value = current_table_widget.item(current_row, VALUE_COL).text() - label_text = tr.ENTER_REGISTER_VALUE.format(current_register.upper()) - register_dialog = utilwidgets.InputDialog(self, [(label_text, current_value)]) - if register_dialog.exec(): - if guiutils.check_inferior_running(self): - return - if self.currentWidget() == self.XMM: - current_register += ".v4_float" - debugcore.set_convenience_variable(current_register, register_dialog.get_values()[0]) - self.update_registers() diff --git a/GUI/Widgets/FunctionsInfo/Form/FunctionsInfoWidget.py b/GUI/Widgets/FunctionsInfo/Form/FunctionsInfoWidget.py deleted file mode 100644 index 922249b6..00000000 --- a/GUI/Widgets/FunctionsInfo/Form/FunctionsInfoWidget.py +++ /dev/null @@ -1,75 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/FunctionsInfo/Form/FunctionsInfoWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(640, 555) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.tableWidget_SymbolInfo = QtWidgets.QTableWidget(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_SymbolInfo.setFont(font) - self.tableWidget_SymbolInfo.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_SymbolInfo.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_SymbolInfo.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_SymbolInfo.setWordWrap(False) - self.tableWidget_SymbolInfo.setObjectName("tableWidget_SymbolInfo") - self.tableWidget_SymbolInfo.setColumnCount(2) - self.tableWidget_SymbolInfo.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_SymbolInfo.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_SymbolInfo.setHorizontalHeaderItem(1, item) - self.tableWidget_SymbolInfo.horizontalHeader().setStretchLastSection(True) - self.tableWidget_SymbolInfo.verticalHeader().setVisible(False) - self.tableWidget_SymbolInfo.verticalHeader().setDefaultSectionSize(20) - self.tableWidget_SymbolInfo.verticalHeader().setMinimumSectionSize(20) - self.gridLayout.addWidget(self.tableWidget_SymbolInfo, 2, 0, 1, 1) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.lineEdit_SearchInput = QtWidgets.QLineEdit(parent=Form) - self.lineEdit_SearchInput.setObjectName("lineEdit_SearchInput") - self.horizontalLayout.addWidget(self.lineEdit_SearchInput) - self.checkBox_CaseSensitive = QtWidgets.QCheckBox(parent=Form) - self.checkBox_CaseSensitive.setObjectName("checkBox_CaseSensitive") - self.horizontalLayout.addWidget(self.checkBox_CaseSensitive) - self.pushButton_Search = QtWidgets.QPushButton(parent=Form) - self.pushButton_Search.setObjectName("pushButton_Search") - self.horizontalLayout.addWidget(self.pushButton_Search) - self.pushButton_Help = QtWidgets.QPushButton(parent=Form) - self.pushButton_Help.setText("") - self.pushButton_Help.setObjectName("pushButton_Help") - self.horizontalLayout.addWidget(self.pushButton_Help) - self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) - self.textBrowser_AddressInfo = QtWidgets.QTextBrowser(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_AddressInfo.setFont(font) - self.textBrowser_AddressInfo.setObjectName("textBrowser_AddressInfo") - self.gridLayout.addWidget(self.textBrowser_AddressInfo, 1, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Functions")) - self.tableWidget_SymbolInfo.setSortingEnabled(True) - item = self.tableWidget_SymbolInfo.horizontalHeaderItem(0) - item.setText(_translate("Form", "Address")) - item = self.tableWidget_SymbolInfo.horizontalHeaderItem(1) - item.setText(_translate("Form", "Symbol")) - self.lineEdit_SearchInput.setPlaceholderText(_translate("Form", "Enter the regex. Leave blank to see all functions")) - self.checkBox_CaseSensitive.setToolTip(_translate("Form", "Ignore case if checked")) - self.checkBox_CaseSensitive.setText(_translate("Form", "Case sensitive")) - self.pushButton_Search.setText(_translate("Form", "Search(Enter)")) diff --git a/GUI/Widgets/FunctionsInfo/Form/FunctionsInfoWidget.ui b/GUI/Widgets/FunctionsInfo/Form/FunctionsInfoWidget.ui deleted file mode 100644 index 3fb27c7e..00000000 --- a/GUI/Widgets/FunctionsInfo/Form/FunctionsInfoWidget.ui +++ /dev/null @@ -1,111 +0,0 @@ - - - Form - - - - 0 - 0 - 640 - 555 - - - - Functions - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - true - - - false - - - true - - - false - - - 20 - - - 20 - - - - Address - - - - - Symbol - - - - - - - - - - Enter the regex. Leave blank to see all functions - - - - - - - Ignore case if checked - - - Case sensitive - - - - - - - Search(Enter) - - - - - - - - - - - - - - - - - Monospace - - - - - - - - - diff --git a/GUI/Widgets/FunctionsInfo/FunctionsInfo.py b/GUI/Widgets/FunctionsInfo/FunctionsInfo.py deleted file mode 100644 index bac4dcf2..00000000 --- a/GUI/Widgets/FunctionsInfo/FunctionsInfo.py +++ /dev/null @@ -1,118 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMenu, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QIcon, QPixmap, QColor, QColorConstants, QContextMenuEvent -from PyQt6.QtCore import Qt, QModelIndex -from GUI.States import states -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.FunctionsInfo.Form.FunctionsInfoWidget import Ui_Form -from GUI.Widgets.LoadingDialog.LoadingDialog import LoadingDialog -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr - -# represents the index of columns in function info table -ADDR_COL = 0 -SYMBOL_COL = 1 - - -class FunctionsInfoWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.textBrowser_AddressInfo.setFixedHeight(100) - self.pushButton_Search.clicked.connect(self.refresh_table) - self.shortcut_search = QShortcut(QKeySequence("Return"), self) - self.shortcut_search.activated.connect(self.refresh_table) - self.tableWidget_SymbolInfo.selectionModel().currentChanged.connect(self.tableWidget_SymbolInfo_current_changed) - self.tableWidget_SymbolInfo.itemDoubleClicked.connect(self.tableWidget_SymbolInfo_item_double_clicked) - self.tableWidget_SymbolInfo.contextMenuEvent = self.tableWidget_SymbolInfo_context_menu_event - states.process_signals.attach.connect(self._clear_results) - states.process_signals.exit.connect(self._clear_results) - icons_directory = guiutils.get_icons_directory() - self.pushButton_Help.setIcon(QIcon(QPixmap(icons_directory + "/help.png"))) - self.pushButton_Help.clicked.connect(self.pushButton_Help_clicked) - guiutils.center_to_parent(self) - - def _clear_results(self) -> None: - self.tableWidget_SymbolInfo.setRowCount(0) - self.textBrowser_AddressInfo.clear() - - def refresh_table(self) -> None: - input_text = self.lineEdit_SearchInput.text() - case_sensitive = self.checkBox_CaseSensitive.isChecked() - process_identity = debugcore.current_process_identity - self.loading_dialog = LoadingDialog(self) - self.background_thread = self.loading_dialog.background_thread - self.background_thread.overridden_func = lambda: self.process_data(input_text, case_sensitive) - self.background_thread.output_ready.connect( - lambda output: self.apply_data(output) if process_identity == debugcore.current_process_identity else None - ) - self.loading_dialog.exec() - - def process_data(self, gdb_input: str, case_sensitive: bool) -> list: - return debugcore.search_functions(gdb_input, case_sensitive) - - def apply_data(self, output: list) -> None: - if output is None: - return - self.tableWidget_SymbolInfo.setSortingEnabled(False) - self.tableWidget_SymbolInfo.setRowCount(0) - self.tableWidget_SymbolInfo.setRowCount(len(output)) - defined_color = QColor(QColorConstants.Green) - defined_color.setAlpha(96) - for row, item in enumerate(output): - address = item[0] - if address: - address_item = QTableWidgetItem(address) - else: - address_item = QTableWidgetItem(tr.DEFINED) - address_item.setBackground(defined_color) - self.tableWidget_SymbolInfo.setItem(row, ADDR_COL, address_item) - self.tableWidget_SymbolInfo.setItem(row, SYMBOL_COL, QTableWidgetItem(item[1])) - self.tableWidget_SymbolInfo.setSortingEnabled(True) - guiutils.resize_to_contents(self.tableWidget_SymbolInfo) - - def tableWidget_SymbolInfo_current_changed(self, QModelIndex_current: QModelIndex) -> None: - self.textBrowser_AddressInfo.clear() - current_row = QModelIndex_current.row() - if current_row < 0: - return - address = self.tableWidget_SymbolInfo.item(current_row, ADDR_COL).text() - if utils.extract_hex_address(address): - symbol = self.tableWidget_SymbolInfo.item(current_row, SYMBOL_COL).text() - for item in utils.split_symbol(symbol): - info = debugcore.get_symbol_info(item) - self.textBrowser_AddressInfo.append(info) - else: - self.textBrowser_AddressInfo.append(tr.DEFINED_SYMBOL) - - def tableWidget_SymbolInfo_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - QApplication.clipboard().setText(self.tableWidget_SymbolInfo.item(row, column).text()) - - selected_row = guiutils.get_current_row(self.tableWidget_SymbolInfo) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - copy_symbol = menu.addAction(tr.COPY_SYMBOL) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address, copy_symbol]) - font_size = self.tableWidget_SymbolInfo.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - copy_address: lambda: copy_to_clipboard(selected_row, ADDR_COL), - copy_symbol: lambda: copy_to_clipboard(selected_row, SYMBOL_COL), - } - try: - actions[action]() - except KeyError: - pass - - def tableWidget_SymbolInfo_item_double_clicked(self, index: QTableWidgetItem) -> None: - address = self.tableWidget_SymbolInfo.item(index.row(), ADDR_COL).text() - if address == tr.DEFINED: - return - self.parent().disassemble_expression(address) - - def pushButton_Help_clicked(self) -> None: - utilwidgets.InputDialog(self, tr.FUNCTIONS_INFO_HELPER, Qt.AlignmentFlag.AlignLeft, False).exec() diff --git a/GUI/Widgets/HandleSignals/Form/HandleSignalsDialog.py b/GUI/Widgets/HandleSignals/Form/HandleSignalsDialog.py deleted file mode 100644 index 95e4e07a..00000000 --- a/GUI/Widgets/HandleSignals/Form/HandleSignalsDialog.py +++ /dev/null @@ -1,55 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/HandleSignals/Form/HandleSignalsDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(363, 523) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.tableWidget_Signals = QtWidgets.QTableWidget(parent=Dialog) - self.tableWidget_Signals.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Signals.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_Signals.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Signals.setObjectName("tableWidget_Signals") - self.tableWidget_Signals.setColumnCount(3) - self.tableWidget_Signals.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Signals.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Signals.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Signals.setHorizontalHeaderItem(2, item) - self.tableWidget_Signals.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Signals.verticalHeader().setVisible(False) - self.tableWidget_Signals.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Signals.verticalHeader().setMinimumSectionSize(16) - self.gridLayout.addWidget(self.tableWidget_Signals, 0, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Handle Signals")) - item = self.tableWidget_Signals.horizontalHeaderItem(0) - item.setText(_translate("Dialog", "Signal")) - item = self.tableWidget_Signals.horizontalHeaderItem(1) - item.setText(_translate("Dialog", "Stop & Print")) - item = self.tableWidget_Signals.horizontalHeaderItem(2) - item.setText(_translate("Dialog", "Pass to Program")) diff --git a/GUI/Widgets/HandleSignals/Form/HandleSignalsDialog.ui b/GUI/Widgets/HandleSignals/Form/HandleSignalsDialog.ui deleted file mode 100644 index a07fb787..00000000 --- a/GUI/Widgets/HandleSignals/Form/HandleSignalsDialog.ui +++ /dev/null @@ -1,104 +0,0 @@ - - - Dialog - - - - 0 - 0 - 363 - 523 - - - - Handle Signals - - - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - true - - - false - - - 16 - - - 16 - - - - Signal - - - - - Stop & Print - - - - - Pass to Program - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - diff --git a/GUI/Widgets/HandleSignals/HandleSignals.py b/GUI/Widgets/HandleSignals/HandleSignals.py deleted file mode 100644 index c93681b9..00000000 --- a/GUI/Widgets/HandleSignals/HandleSignals.py +++ /dev/null @@ -1,52 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QCheckBox, QHBoxLayout, QTableWidgetItem -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils -from GUI.Widgets.HandleSignals.Form.HandleSignalsDialog import Ui_Dialog -import json - - -class HandleSignalsDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, signal_data: str) -> None: - super().__init__(parent) - self.setupUi(self) - self.signal_data = json.loads(signal_data) - self.tableWidget_Signals.setRowCount(len(self.signal_data)) - for index, (signal, stop, pass_to_program) in enumerate(self.signal_data): - self.tableWidget_Signals.setItem(index, 0, QTableWidgetItem(signal)) - widget, checkbox = self.create_checkbox_widget() - self.tableWidget_Signals.setCellWidget(index, 1, widget) - if stop: - checkbox.setCheckState(Qt.CheckState.Checked) - else: - checkbox.setCheckState(Qt.CheckState.Unchecked) - widget, checkbox = self.create_checkbox_widget() - self.tableWidget_Signals.setCellWidget(index, 2, widget) - if pass_to_program: - checkbox.setCheckState(Qt.CheckState.Checked) - else: - checkbox.setCheckState(Qt.CheckState.Unchecked) - self.tableWidget_Signals.resizeColumnsToContents() - guiutils.center_to_parent(self) - - def create_checkbox_widget(self) -> tuple[QWidget, QCheckBox]: - widget = QWidget() - checkbox = QCheckBox() - layout = QHBoxLayout(widget) - layout.addWidget(checkbox) - layout.setAlignment(Qt.AlignmentFlag.AlignCenter) - layout.setContentsMargins(0, 0, 0, 0) - return widget, checkbox - - def get_values(self) -> str: - signal_data = [] - for index in range(len(self.signal_data)): - current_signal = [] - current_signal.append(self.signal_data[index][0]) - widget = self.tableWidget_Signals.cellWidget(index, 1) - checkbox = widget.findChild(QCheckBox) - current_signal.append(True if checkbox.checkState() == Qt.CheckState.Checked else False) - widget = self.tableWidget_Signals.cellWidget(index, 2) - checkbox = widget.findChild(QCheckBox) - current_signal.append(True if checkbox.checkState() == Qt.CheckState.Checked else False) - signal_data.append(current_signal) - return json.dumps(signal_data) diff --git a/GUI/Widgets/HexEdit/Form/HexEditDialog.py b/GUI/Widgets/HexEdit/Form/HexEditDialog.py deleted file mode 100644 index b1ac620a..00000000 --- a/GUI/Widgets/HexEdit/Form/HexEditDialog.py +++ /dev/null @@ -1,58 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/HexEdit/Form/HexEditDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(515, 138) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.horizontalLayout.addWidget(self.label) - self.lineEdit_Address = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Address.setObjectName("lineEdit_Address") - self.horizontalLayout.addWidget(self.lineEdit_Address) - self.label_2 = QtWidgets.QLabel(parent=Dialog) - self.label_2.setObjectName("label_2") - self.horizontalLayout.addWidget(self.label_2) - self.lineEdit_Length = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Length.setObjectName("lineEdit_Length") - self.horizontalLayout.addWidget(self.lineEdit_Length) - self.pushButton_Refresh = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Refresh.setObjectName("pushButton_Refresh") - self.horizontalLayout.addWidget(self.pushButton_Refresh) - self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) - self.lineEdit_AsciiView = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_AsciiView.setObjectName("lineEdit_AsciiView") - self.gridLayout.addWidget(self.lineEdit_AsciiView, 1, 0, 1, 1) - self.lineEdit_HexView = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_HexView.setObjectName("lineEdit_HexView") - self.gridLayout.addWidget(self.lineEdit_HexView, 2, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 3, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Hex Edit")) - self.label.setText(_translate("Dialog", "Address:")) - self.label_2.setText(_translate("Dialog", "Length:")) - self.pushButton_Refresh.setText(_translate("Dialog", "Refresh")) diff --git a/GUI/Widgets/HexEdit/Form/HexEditDialog.ui b/GUI/Widgets/HexEdit/Form/HexEditDialog.ui deleted file mode 100644 index 8181d69e..00000000 --- a/GUI/Widgets/HexEdit/Form/HexEditDialog.ui +++ /dev/null @@ -1,101 +0,0 @@ - - - Dialog - - - - 0 - 0 - 515 - 138 - - - - Hex Edit - - - - - - - - Address: - - - - - - - - - - Length: - - - - - - - - - - Refresh - - - - - - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/GUI/Widgets/HexEdit/HexEdit.py b/GUI/Widgets/HexEdit/HexEdit.py deleted file mode 100644 index aaebc353..00000000 --- a/GUI/Widgets/HexEdit/HexEdit.py +++ /dev/null @@ -1,141 +0,0 @@ -import re - -from PyQt6.QtWidgets import QDialog, QWidget, QMessageBox -from GUI.Utils import guiutils -from GUI.Validators.HexValidator import HexValidator -from GUI.Widgets.HexEdit.Form.HexEditDialog import Ui_Dialog -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - - -class HexEditDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, address: int, length: int = 20) -> None: - super().__init__(parent) - self.setupUi(self) - self._byte_array_type = typedefs.ByteArrayValueType() - # Guards against the AsciiView<->HexView selection sync recursing into itself, since both - # setSelection() and deselect() re-emit selectionChanged while we mirror the selection - self.is_syncing_selection = False - self.lineEdit_Length.setValidator(HexValidator(999, self)) - self.lineEdit_HexView.setValidator(guiutils.validator_map["bytearray"]) - self.lineEdit_Address.setText(hex(address)) - self.lineEdit_Length.setText(str(length)) - self.refresh_view() - self.lineEdit_AsciiView.selectionChanged.connect(self.lineEdit_AsciiView_selection_changed) - self.lineEdit_HexView.selectionChanged.connect(self.lineEdit_HexView_selection_changed) - guiutils.center_to_parent(self) - - self.lineEdit_HexView.textEdited.connect(self.lineEdit_HexView_text_edited) - self.lineEdit_AsciiView.textEdited.connect(self.lineEdit_AsciiView_text_edited) - self.pushButton_Refresh.pressed.connect(self.refresh_view) - self.lineEdit_Address.textChanged.connect(self.refresh_view) - self.lineEdit_Length.textChanged.connect(self.refresh_view) - - def lineEdit_AsciiView_selection_changed(self) -> None: - if self.is_syncing_selection: - return - hex_start = hex_length = 0 - selected_text = self.lineEdit_AsciiView.selectedText() - if selected_text: - selection_start = self.lineEdit_AsciiView.selectionStart() - selection_end = selection_start + len(selected_text) - tokens = list(re.finditer(r"\S+", self.lineEdit_HexView.text())) - if selection_end <= len(tokens): - hex_start = tokens[selection_start].start() - hex_length = tokens[selection_end - 1].end() - hex_start - # is_syncing_selection must always be reset, otherwise a single failure permanently breaks the sync. With no - # selection we only deselect; setSelection would move the cursor (e.g. when setText regenerates this field) - self.is_syncing_selection = True - try: - self.lineEdit_HexView.deselect() - if hex_length: - self.lineEdit_HexView.setSelection(hex_start, hex_length) - finally: - self.is_syncing_selection = False - - def lineEdit_HexView_selection_changed(self) -> None: - if self.is_syncing_selection: - return - ascii_start = ascii_length = 0 - selected_text = self.lineEdit_HexView.selectedText() - if selected_text: - text = self.lineEdit_HexView.text() - selection_start = self.lineEdit_HexView.selectionStart() - selection_end = selection_start + len(selected_text) - try: - tokens = list(re.finditer(r"\S+", text)) - for token in tokens: - byte = token.group(0) - if byte != "??" and (len(byte) > 2 or not 0 <= int(byte, 16) <= 0xFF): - raise ValueError - selected_bytes = [index for index, token in enumerate(tokens) if token.start() < selection_end and selection_start < token.end()] - if selected_bytes: - ascii_start = selected_bytes[0] - ascii_length = selected_bytes[-1] - ascii_start + 1 - except ValueError: - # Malformed hex (e.g. while the field is being edited) can't be decoded; clear the ascii selection - ascii_start = ascii_length = 0 - # is_syncing_selection must always be reset, otherwise a single failure permanently breaks the sync. With no - # selection we only deselect; setSelection would move the cursor (e.g. when setText regenerates this field) - self.is_syncing_selection = True - try: - self.lineEdit_AsciiView.deselect() - if ascii_length: - self.lineEdit_AsciiView.setSelection(ascii_start, ascii_length) - finally: - self.is_syncing_selection = False - - def lineEdit_HexView_text_edited(self) -> None: - aob_string = self.lineEdit_HexView.text() - if not self._byte_array_type.parse(aob_string): - self.lineEdit_HexView.setStyleSheet("QLineEdit {background-color: rgba(255, 0, 0, 96);}") - return - aob_array = aob_string.split() - self.lineEdit_AsciiView.setText(utils.aob_to_str(aob_array)) - # Both views now hold valid, matching data, so clear any leftover error highlight from either side - self.lineEdit_HexView.setStyleSheet("") # This should set background color back to QT default - self.lineEdit_AsciiView.setStyleSheet("") - - def lineEdit_AsciiView_text_edited(self) -> None: - ascii_str = self.lineEdit_AsciiView.text() - try: - self.lineEdit_HexView.setText(utils.str_to_aob(ascii_str)) - # Both views now hold valid, matching data, so clear any leftover error highlight from either side - self.lineEdit_AsciiView.setStyleSheet("") - self.lineEdit_HexView.setStyleSheet("") - except UnicodeError: - self.lineEdit_AsciiView.setStyleSheet("QLineEdit {background-color: rgba(255, 0, 0, 96);}") - - def refresh_view(self) -> None: - self.lineEdit_AsciiView.clear() - self.lineEdit_HexView.clear() - # Reloading from memory replaces any user edit, so clear any leftover error highlight - self.lineEdit_AsciiView.setStyleSheet("") - self.lineEdit_HexView.setStyleSheet("") - address = debugcore.examine_expression(self.lineEdit_Address.text()).address - if not address: - return - length = self.lineEdit_Length.text() - try: - length = int(length, 0) - address = int(address, 0) - except ValueError: - return - aob_array = debugcore.hex_dump(address, length) - ascii_str = utils.aob_to_str(aob_array) - self.lineEdit_AsciiView.setText(ascii_str) - self.lineEdit_HexView.setText(" ".join(aob_array)) - - def accept(self) -> None: - expression = self.lineEdit_Address.text() - address = debugcore.examine_expression(expression).address - if not address: - QMessageBox.information(self, tr.ERROR, tr.IS_INVALID_EXPRESSION.format(expression)) - return - value = self.lineEdit_HexView.text() - parsed = self._byte_array_type.parse(value) - if parsed is None: - QMessageBox.information(self, tr.ERROR, tr.PARSE_ERROR) - return - debugcore.write_memory(address, self._byte_array_type, parsed) - super().accept() diff --git a/GUI/Widgets/LibpinceEngine/Form/LibpinceEngineWindow.py b/GUI/Widgets/LibpinceEngine/Form/LibpinceEngineWindow.py deleted file mode 100644 index ea79e3f3..00000000 --- a/GUI/Widgets/LibpinceEngine/Form/LibpinceEngineWindow.py +++ /dev/null @@ -1,231 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/LibpinceEngine/Form/LibpinceEngineWindow.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.resize(898, 656) - self.centralwidget = QtWidgets.QWidget(parent=MainWindow) - self.centralwidget.setObjectName("centralwidget") - self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) - self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=self.centralwidget) - self.splitter.setOrientation(QtCore.Qt.Orientation.Vertical) - self.splitter.setChildrenCollapsible(False) - self.splitter.setObjectName("splitter") - self.tabWidget = QtWidgets.QTabWidget(parent=self.splitter) - self.tabWidget.setTabsClosable(True) - self.tabWidget.setObjectName("tabWidget") - self.editorTab = QtWidgets.QWidget() - self.editorTab.setObjectName("editorTab") - self.editorLayout = QtWidgets.QVBoxLayout(self.editorTab) - self.editorLayout.setContentsMargins(0, 0, 0, 0) - self.editorLayout.setObjectName("editorLayout") - self.scriptEditor = ScriptEditor(parent=self.editorTab) - font = QtGui.QFont() - font.setFamily("Monospace") - font.setPointSize(10) - self.scriptEditor.setFont(font) - self.scriptEditor.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.NoWrap) - self.scriptEditor.setTabStopDistance(40.0) - self.scriptEditor.setObjectName("scriptEditor") - self.editorLayout.addWidget(self.scriptEditor) - self.tabWidget.addTab(self.editorTab, "") - self.plusTab = QtWidgets.QWidget() - self.plusTab.setObjectName("plusTab") - self.tabWidget.addTab(self.plusTab, "") - self.outputEdit = QtWidgets.QPlainTextEdit(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.outputEdit.setFont(font) - self.outputEdit.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.NoWrap) - self.outputEdit.setReadOnly(True) - self.outputEdit.setMaximumBlockCount(5000) - self.outputEdit.setObjectName("outputEdit") - self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) - MainWindow.setCentralWidget(self.centralwidget) - self.menubar = QtWidgets.QMenuBar(parent=MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 898, 32)) - self.menubar.setObjectName("menubar") - self.menuFile = QtWidgets.QMenu(parent=self.menubar) - self.menuFile.setObjectName("menuFile") - self.menuTemplates = QtWidgets.QMenu(parent=self.menubar) - self.menuTemplates.setObjectName("menuTemplates") - self.menuHelp = QtWidgets.QMenu(parent=self.menubar) - self.menuHelp.setObjectName("menuHelp") - self.menuRun = QtWidgets.QMenu(parent=self.menubar) - self.menuRun.setObjectName("menuRun") - MainWindow.setMenuBar(self.menubar) - self.statusbar = QtWidgets.QStatusBar(parent=MainWindow) - self.statusbar.setObjectName("statusbar") - MainWindow.setStatusBar(self.statusbar) - self.actionCode_injection = QtGui.QAction(parent=MainWindow) - self.actionCode_injection.setProperty("data", "# Code injection template\n" -"# Prelude runs before both halves.\n" -"target = address(\"0x0\") # <- Make sure to change this!\n" -"\n" -"[ENABLE]\n" -"cave = alloc_cave(0x400, \"engine_code_cave\", near=target)\n" -"if not cave:\n" -" raise RuntimeError(\"Could not allocate a code cave close enough for a relative jump\")\n" -"jump_to_cave = assemble(f\"jmp {cave:#x}\", target)\n" -"\n" -"# Read enough to cover the jmp patch plus one max-length x86 instruction (15B),\n" -"# then round up to the next instruction boundary so we don\'t leave a partial\n" -"# instruction at target after patching.\n" -"probe = read_bytes(target, len(jump_to_cave) + 15)\n" -"stolen_size = utils.instruction_aligned_size(probe, len(jump_to_cave), debugcore.inferior_arch)\n" -"if stolen_size == 0:\n" -" raise RuntimeError(\"Could not align stolen bytes to an instruction boundary\")\n" -"\n" -"# RIP-relative instructions in the stolen bytes may need manual adjustment when relocated.\n" -"original = probe[:stolen_size]\n" -"return_address = target + stolen_size\n" -"\n" -"# Your injection code goes here. The NOPs are a placeholder.\n" -"injected_code = assemble(\"\"\"\n" -"nop\n" -"nop\n" -"\"\"\", cave)\n" -"\n" -"# Cave layout: hook code, then the displaced original bytes, then a jump back.\n" -"# Re-executing the original bytes preserves the target\'s behavior. Drop `+ original` from cave_body to fully replace it.\n" -"cave_body = injected_code + original\n" -"jump_back = assemble(f\"jmp {return_address:#x}\", cave + len(cave_body))\n" -"write_bytes(cave_body + jump_back, cave)\n" -"\n" -"# Pad leftover stolen_size bytes with NOPs so execution resumes on a clean\n" -"# boundary (a partial instruction left over would corrupt decoding).\n" -"patch(jump_to_cave + b\"\\x90\" * (stolen_size - len(jump_to_cave)), target, expected=original)\n" -"print(f\"Injected {target:#x} -> {cave:#x}, return {return_address:#x}\")\n" -"\n" -"[DISABLE]\n" -"restore(target)\n" -"dealloc_cave(\"engine_code_cave\")\n" -"print(f\"Restored {target:#x}\")\n" -"") - self.actionCode_injection.setObjectName("actionCode_injection") - self.actionOpen = QtGui.QAction(parent=MainWindow) - self.actionOpen.setObjectName("actionOpen") - self.actionSave = QtGui.QAction(parent=MainWindow) - self.actionSave.setObjectName("actionSave") - self.actionLibpince = QtGui.QAction(parent=MainWindow) - self.actionLibpince.setObjectName("actionLibpince") - self.actionRun_enable = QtGui.QAction(parent=MainWindow) - self.actionRun_enable.setObjectName("actionRun_enable") - self.actionRun_disable = QtGui.QAction(parent=MainWindow) - self.actionRun_disable.setObjectName("actionRun_disable") - self.actionRun_selection = QtGui.QAction(parent=MainWindow) - self.actionRun_selection.setObjectName("actionRun_selection") - self.actionClear_output = QtGui.QAction(parent=MainWindow) - self.actionClear_output.setObjectName("actionClear_output") - self.actionSend_to_table = QtGui.QAction(parent=MainWindow) - self.actionSend_to_table.setObjectName("actionSend_to_table") - self.actionAOB_scan_nop = QtGui.QAction(parent=MainWindow) - self.actionAOB_scan_nop.setProperty("data", "# AOB scan + NOP template\n" -"[ENABLE]\n" -"addr = aobscan_first(\"48 8B ?? ?? ?? 89\") # <- Make sure to change this!\n" -"if addr is None:\n" -" raise RuntimeError(\"Pattern not found\")\n" -"nop(addr, 6)\n" -"print(f\"NOPed {addr:#x}\")\n" -"\n" -"[DISABLE]\n" -"# addr carries over from [ENABLE]\n" -"restore(addr)\n" -"print(f\"Restored {addr:#x}\")") - self.actionAOB_scan_nop.setObjectName("actionAOB_scan_nop") - self.actionAOB_scan_patch = QtGui.QAction(parent=MainWindow) - self.actionAOB_scan_patch.setProperty("data", "# AOB scan + patch template\n" -"# Example bytes:\n" -"# 83 00 FF add DWORD PTR [rax], 0xffffffff (-0x1)\n" -"# 48 8B 43 10 mov rax, QWORD PTR [rbx+0x10]\n" -"# This changes the -1 decrement to +2 addition (eg. add ammo when shooting instead of subtracting)\n" -"[ENABLE]\n" -"expected = \"83 00 FF 48 8B 43 10\" # <- Make sure to change this!\n" -"addr = aobscan_first(expected)\n" -"if addr is None:\n" -" raise RuntimeError(\"Pattern not found\")\n" -"\n" -"replacement = assemble(f\"\"\"\n" -"add dword ptr [rax], 0x2\n" -"\"\"\", addr)\n" -"\n" -"# Ensure we won\'t corrupt the next instruction after add\n" -"if len(replacement) != 3:\n" -" raise RuntimeError(\"Replacement size must match target instruction\")\n" -"\n" -"patch(replacement, addr, expected=\"83 00 ff\")\n" -"print(f\"Patched instruction at {addr:#x}\")\n" -"\n" -"[DISABLE]\n" -"# addr carries over from [ENABLE]\n" -"restore(addr)\n" -"print(f\"Restored {addr:#x}\")") - self.actionAOB_scan_patch.setObjectName("actionAOB_scan_patch") - self.actionRead_write_address = QtGui.QAction(parent=MainWindow) - self.actionRead_write_address.setProperty("data", "# Read/write template\n" -"addr = address(\"0x0\") # <- Make sure to change this!\n" -"old_value = read_int(addr, size=4)\n" -"write_int(old_value + 1, addr, size=4)\n" -"print(f\"{addr:#x}: {old_value} -> {read_int(addr, size=4)}\")\n" -"") - self.actionRead_write_address.setObjectName("actionRead_write_address") - self.menuFile.addAction(self.actionOpen) - self.menuFile.addAction(self.actionSave) - self.menuTemplates.addAction(self.actionCode_injection) - self.menuTemplates.addAction(self.actionAOB_scan_nop) - self.menuTemplates.addAction(self.actionAOB_scan_patch) - self.menuTemplates.addAction(self.actionRead_write_address) - self.menuHelp.addAction(self.actionLibpince) - self.menuRun.addAction(self.actionRun_enable) - self.menuRun.addAction(self.actionRun_disable) - self.menuRun.addAction(self.actionRun_selection) - self.menuRun.addSeparator() - self.menuRun.addAction(self.actionSend_to_table) - self.menuRun.addAction(self.actionClear_output) - self.menubar.addAction(self.menuFile.menuAction()) - self.menubar.addAction(self.menuTemplates.menuAction()) - self.menubar.addAction(self.menuRun.menuAction()) - self.menubar.addAction(self.menuHelp.menuAction()) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - _translate = QtCore.QCoreApplication.translate - MainWindow.setWindowTitle(_translate("MainWindow", "Libpince Engine")) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.editorTab), _translate("MainWindow", "(untitled)")) - self.tabWidget.setTabText(self.tabWidget.indexOf(self.plusTab), _translate("MainWindow", "+")) - self.outputEdit.setPlaceholderText(_translate("MainWindow", "Script output")) - self.menuFile.setTitle(_translate("MainWindow", "File")) - self.menuTemplates.setTitle(_translate("MainWindow", "Templates")) - self.menuHelp.setTitle(_translate("MainWindow", "Help")) - self.menuRun.setTitle(_translate("MainWindow", "Run")) - self.actionCode_injection.setText(_translate("MainWindow", "Code injection")) - self.actionOpen.setText(_translate("MainWindow", "Open")) - self.actionOpen.setShortcut(_translate("MainWindow", "Ctrl+O")) - self.actionSave.setText(_translate("MainWindow", "Save")) - self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S")) - self.actionLibpince.setText(_translate("MainWindow", "Libpince")) - self.actionRun_enable.setText(_translate("MainWindow", "Run [ENABLE]")) - self.actionRun_enable.setShortcut(_translate("MainWindow", "Ctrl+Shift+E")) - self.actionRun_disable.setText(_translate("MainWindow", "Run [DISABLE]")) - self.actionRun_disable.setShortcut(_translate("MainWindow", "Ctrl+Shift+D")) - self.actionRun_selection.setText(_translate("MainWindow", "Run selection")) - self.actionRun_selection.setShortcut(_translate("MainWindow", "Ctrl+R")) - self.actionClear_output.setText(_translate("MainWindow", "Clear output")) - self.actionSend_to_table.setText(_translate("MainWindow", "Send to cheat table")) - self.actionSend_to_table.setShortcut(_translate("MainWindow", "Ctrl+Shift+T")) - self.actionAOB_scan_nop.setText(_translate("MainWindow", "AOB scan + NOP")) - self.actionAOB_scan_patch.setText(_translate("MainWindow", "AOB scan + patch")) - self.actionRead_write_address.setText(_translate("MainWindow", "Read/write address")) -from GUI.Widgets.LibpinceEngine.ScriptEditor import ScriptEditor diff --git a/GUI/Widgets/LibpinceEngine/Form/LibpinceEngineWindow.ui b/GUI/Widgets/LibpinceEngine/Form/LibpinceEngineWindow.ui deleted file mode 100644 index 1a4d7818..00000000 --- a/GUI/Widgets/LibpinceEngine/Form/LibpinceEngineWindow.ui +++ /dev/null @@ -1,326 +0,0 @@ - - - MainWindow - - - - 0 - 0 - 898 - 656 - - - - Libpince Engine - - - - - - - Qt::Orientation::Vertical - - - false - - - - true - - - - (untitled) - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - Monospace - 10 - - - - QPlainTextEdit::LineWrapMode::NoWrap - - - 40.000000000000000 - - - - - - - - + - - - - - - - Monospace - - - - QPlainTextEdit::LineWrapMode::NoWrap - - - true - - - 5000 - - - Script output - - - - - - - - - - 0 - 0 - 898 - 32 - - - - - File - - - - - - - Templates - - - - - - - - - Help - - - - - - Run - - - - - - - - - - - - - - - - - Code injection - - - # Code injection template -# Prelude runs before both halves. -target = address("0x0") # <- Make sure to change this! - -[ENABLE] -cave = alloc_cave(0x400, "engine_code_cave", near=target) -if not cave: - raise RuntimeError("Could not allocate a code cave close enough for a relative jump") -jump_to_cave = assemble(f"jmp {cave:#x}", target) - -# Read enough to cover the jmp patch plus one max-length x86 instruction (15B), -# then round up to the next instruction boundary so we don't leave a partial -# instruction at target after patching. -probe = read_bytes(target, len(jump_to_cave) + 15) -stolen_size = utils.instruction_aligned_size(probe, len(jump_to_cave), debugcore.inferior_arch) -if stolen_size == 0: - raise RuntimeError("Could not align stolen bytes to an instruction boundary") - -# RIP-relative instructions in the stolen bytes may need manual adjustment when relocated. -original = probe[:stolen_size] -return_address = target + stolen_size - -# Your injection code goes here. The NOPs are a placeholder. -injected_code = assemble(""" -nop -nop -""", cave) - -# Cave layout: hook code, then the displaced original bytes, then a jump back. -# Re-executing the original bytes preserves the target's behavior. Drop `+ original` from cave_body to fully replace it. -cave_body = injected_code + original -jump_back = assemble(f"jmp {return_address:#x}", cave + len(cave_body)) -write_bytes(cave_body + jump_back, cave) - -# Pad leftover stolen_size bytes with NOPs so execution resumes on a clean -# boundary (a partial instruction left over would corrupt decoding). -patch(jump_to_cave + b"\x90" * (stolen_size - len(jump_to_cave)), target, expected=original) -print(f"Injected {target:#x} -> {cave:#x}, return {return_address:#x}") - -[DISABLE] -restore(target) -dealloc_cave("engine_code_cave") -print(f"Restored {target:#x}") - - - - - - Open - - - Ctrl+O - - - - - Save - - - Ctrl+S - - - - - Libpince - - - - - Run [ENABLE] - - - Ctrl+Shift+E - - - - - Run [DISABLE] - - - Ctrl+Shift+D - - - - - Run selection - - - Ctrl+R - - - - - Clear output - - - - - Send to cheat table - - - Ctrl+Shift+T - - - - - AOB scan + NOP - - - # AOB scan + NOP template -[ENABLE] -addr = aobscan_first("48 8B ?? ?? ?? 89") # <- Make sure to change this! -if addr is None: - raise RuntimeError("Pattern not found") -nop(addr, 6) -print(f"NOPed {addr:#x}") - -[DISABLE] -# addr carries over from [ENABLE] -restore(addr) -print(f"Restored {addr:#x}") - - - - - AOB scan + patch - - - # AOB scan + patch template -# Example bytes: -# 83 00 FF add DWORD PTR [rax], 0xffffffff (-0x1) -# 48 8B 43 10 mov rax, QWORD PTR [rbx+0x10] -# This changes the -1 decrement to +2 addition (eg. add ammo when shooting instead of subtracting) -[ENABLE] -expected = "83 00 FF 48 8B 43 10" # <- Make sure to change this! -addr = aobscan_first(expected) -if addr is None: - raise RuntimeError("Pattern not found") - -replacement = assemble(f""" -add dword ptr [rax], 0x2 -""", addr) - -# Ensure we won't corrupt the next instruction after add -if len(replacement) != 3: - raise RuntimeError("Replacement size must match target instruction") - -patch(replacement, addr, expected="83 00 ff") -print(f"Patched instruction at {addr:#x}") - -[DISABLE] -# addr carries over from [ENABLE] -restore(addr) -print(f"Restored {addr:#x}") - - - - - Read/write address - - - # Read/write template -addr = address("0x0") # <- Make sure to change this! -old_value = read_int(addr, size=4) -write_int(old_value + 1, addr, size=4) -print(f"{addr:#x}: {old_value} -> {read_int(addr, size=4)}") - - - - - - - ScriptEditor - QPlainTextEdit -
GUI.Widgets.LibpinceEngine.ScriptEditor
-
-
- - -
diff --git a/GUI/Widgets/LibpinceEngine/LibpinceEngine.py b/GUI/Widgets/LibpinceEngine/LibpinceEngine.py deleted file mode 100644 index 5f05cf99..00000000 --- a/GUI/Widgets/LibpinceEngine/LibpinceEngine.py +++ /dev/null @@ -1,545 +0,0 @@ -import builtins, codecs, contextlib, io, os, traceback -from typing import Any - -from PyQt6.QtCore import pyqtSignal -from PyQt6.QtGui import QTextCursor -from PyQt6.QtWidgets import QFileDialog, QInputDialog, QMainWindow, QMessageBox, QVBoxLayout, QWidget - -from GUI.Utils import guiutils -from GUI.Widgets.LibpinceEngine.Form.LibpinceEngineWindow import Ui_MainWindow -from GUI.Widgets.LibpinceEngine.ScriptEditor import ScriptEditor -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - -# Accepted input for byte-oriented helpers: a hex string, a bytes-like object, or a list of byte values -BytesLike = bytes | bytearray | memoryview | str | list[int] - -ENABLE_TAG = "[ENABLE]" -DISABLE_TAG = "[DISABLE]" - - -def parse_script_sections(script: str) -> tuple[str, str | None]: - """Split a toggle script into runnable (enable, disable) section code. - - Sections are marked by [ENABLE] or [DISABLE] (case-insensitive, surrounding whitespace ignored). - Code before the first tag is the prelude and runs before both halves. - Tag lines and the half that isn't being run are blanked rather than removed - so traceback line numbers still match the editor. - A tagless script is returned as (whole script, None) so it keeps running whole. - """ - lines = script.splitlines() - enable_line = disable_line = None - for i, line in enumerate(lines): - tag = line.strip().upper() - if tag == ENABLE_TAG and enable_line is None: - enable_line = i - elif tag == DISABLE_TAG and disable_line is None: - disable_line = i - if enable_line is None and disable_line is None: - return script, None - if enable_line is None or disable_line is None: - code = "\n".join("" if i in (enable_line, disable_line) else line for i, line in enumerate(lines)) - return (code, None) if enable_line is not None else ("", code) - tags = sorted((enable_line, disable_line)) - prelude_end = tags[0] - - def body(tag_line: int) -> str: - end = next((t for t in tags if t > tag_line), len(lines)) - return "\n".join(ln if i < prelude_end or tag_line < i < end else "" for i, ln in enumerate(lines)) - - return body(enable_line), body(disable_line) - - -class LibpinceScriptApi: - """Class to 'alias' certain libpince functions for easier user experience.""" - - def address(self, expression: int | str) -> int: - """Return an integer address from an int, hex string, register, symbol, or GDB expression.""" - if isinstance(expression, int): - return expression - if not isinstance(expression, str): - raise TypeError("address expects int or str") - try: - return int(expression, 0) - except ValueError: - pass - info = debugcore.examine_expression(expression) - for value in (info.address, info.all): - if not value: - continue - extracted = utils.extract_hex_address(value) - if extracted: - return int(extracted, 16) - try: - return int(value, 0) - except ValueError: - pass - raise ValueError(f"Could not resolve address expression: {expression}") - - def read_int(self, address: int | str, size: int = 4, signed: bool = False) -> int | None: - """Read an integer. size can be 1, 2, 4, or 8.""" - value_repr = typedefs.VALUE_REPR.SIGNED if signed else typedefs.VALUE_REPR.UNSIGNED - return debugcore.read_memory(self.address(address), typedefs.IntegerValueType(int(size) * 8, value_repr=value_repr)) - - def write_int(self, value: int, address: int | str, size: int = 4) -> None: - """Write an integer. size can be 1, 2, 4, or 8.""" - debugcore.write_memory(self.address(address), typedefs.IntegerValueType(int(size) * 8), int(value)) - - def read_bitfield(self, address: int | str, bits: int = 1, start_bit: int = 0, signed: bool = False) -> int | None: - """Read a bit field of "bits" bits beginning at "start_bit".""" - value_repr = typedefs.VALUE_REPR.SIGNED if signed else typedefs.VALUE_REPR.UNSIGNED - return debugcore.read_memory( - self.address(address), - typedefs.BitFieldValueType(int(bits), int(start_bit), value_repr=value_repr), - ) - - def write_bitfield(self, value: int, address: int | str, bits: int = 1, start_bit: int = 0, signed: bool = False) -> None: - """Write a bit field of "bits" bits beginning at "start_bit" without changing surrounding bits.""" - value_repr = typedefs.VALUE_REPR.SIGNED if signed else typedefs.VALUE_REPR.UNSIGNED - debugcore.write_memory( - self.address(address), - typedefs.BitFieldValueType(int(bits), int(start_bit), value_repr=value_repr), - int(value), - ) - - def read_float(self, address: int | str, double: bool = False) -> float | None: - """Read a 32-bit float, or a 64-bit float when double=True.""" - return debugcore.read_memory(self.address(address), typedefs.FloatValueType(64 if double else 32)) - - def write_float(self, value: float, address: int | str, double: bool = False) -> None: - """Write a 32-bit float, or a 64-bit float when double=True.""" - debugcore.write_memory(self.address(address), typedefs.FloatValueType(64 if double else 32), float(value)) - - def read_string(self, address: int | str, length: int = 128, encoding: str = "utf8", zero_terminate: bool = True) -> str | None: - """Read a string using ascii, utf8, utf16, or utf32.""" - value_type = typedefs.StringValueType( - codecs.lookup(encoding).name, - length=int(length), - zero_terminate=zero_terminate, - ) - return debugcore.read_memory(self.address(address), value_type) - - def write_string(self, value: str, address: int | str, encoding: str = "utf8", zero_terminate: bool = True) -> None: - """Write a string using ascii, utf8, utf16, or utf32.""" - value_type = typedefs.StringValueType( - codecs.lookup(encoding).name, - zero_terminate=zero_terminate, - ) - debugcore.write_memory(self.address(address), value_type, str(value)) - - def read_bytes(self, address: int | str, length: int) -> bytes: - """Read bytes from the inferior and return a bytes object.""" - aob = debugcore.read_memory(self.address(address), typedefs.ByteArrayValueType(int(length))) - return bytes.fromhex(aob) if aob else b"" - - def write_bytes(self, data: BytesLike, address: int | str) -> None: - """Write bytes where data can be bytes, bytearray, list[int], or a hex string.""" - data = self._bytes(data) - debugcore.write_memory(self.address(address), typedefs.ByteArrayValueType(len(data)), data) - - def patch(self, data: BytesLike, address: int | str, expected: BytesLike | None = None) -> None: - """Patch instruction bytes, optionally verifying the original bytes first. - Can be restored using restore(address). - """ - data = self._bytes(data) - address = self.address(address) - if expected is not None: - original = self.read_bytes(address, len(data)) - if original != self._bytes(expected): - raise RuntimeError(f"Patch mismatch at {address:#x}: expected {expected}, found {original.hex(' ')}") - debugcore.modify_instruction(address, data.hex(" ")) - - def nop(self, address: int | str, length: int) -> None: - """Replace length bytes at address with NOP instructions. - Can be restored using restore(address). - """ - debugcore.nop_instruction(self.address(address), int(length)) - - def restore(self, address: int | str) -> None: - """Restore bytes previously changed through nop_instruction (nop) or modify_instruction (patch).""" - debugcore.restore_instruction(self.address(address)) - - def alloc(self, size: int, name: str | None = None) -> int: - """Allocate writable (non-executable) memory in the inferior and return its address. - - For executable code (e.g. code caves) use alloc_cave instead. - You can still mprotect this region as executable yourself afterwards, but that's on you. - """ - return debugcore.allocate_memory(int(size), name) - - def dealloc(self, name: str) -> bool: - """Free memory allocated with alloc(size, name).""" - return debugcore.free_memory(str(name)) - - def alloc_cave(self, size: int, name: str | None = None, near: int | None = None) -> int: - """Allocate an executable, page-aligned code cave in the inferior and return its address.""" - return debugcore.allocate_cave(int(size), name, near) - - def dealloc_cave(self, name: str) -> bool: - """Free a code cave allocated with alloc_cave(size, name).""" - return debugcore.free_cave(str(name)) - - def assemble(self, instructions: str, address: int | str = 0) -> bytes: - """Assemble instructions at address and return bytes.""" - result = utils.assemble(str(instructions), self.address(address) if address else 0, debugcore.inferior_arch) - return bytes(result[0]) if result else b"" - - def disassemble_bytes(self, data: BytesLike, address: int | str = 0) -> str | None: - """Disassemble bytes and return a semicolon-separated instruction string.""" - return utils.disassemble(self._bytes(data).hex(" "), self.address(address) if address else 0, debugcore.inferior_arch) - - def module_base(self, name: str) -> int | None: - """Return a module's logical load base by basename or full path when ambiguous.""" - if debugcore.currentpid == -1: - raise RuntimeError("No process is attached!") - needle = str(name).lower() - base = next( - (base for module, base in utils.get_module_dict(debugcore.currentpid).items() if module.lower() == needle), - None, - ) - return int(base, 16) if base is not None else None - - def regs(self) -> dict[str, str | None]: - """Return current general-purpose registers.""" - return debugcore.read_registers() - - def reg(self, name: str) -> str | None: - """Read one register from read_registers(), with or without a leading '$'.""" - registers = self.regs() - raw = str(name) - return registers.get(raw) or registers.get(raw.lstrip("$")) or registers.get("$" + raw.lstrip("$")) - - def set_reg(self, name: str, value: Any) -> Any: - """Set a register through GDB.""" - return debugcore.send_command(f"set ${str(name).lstrip('$')} = {value}", cli_output=True) - - def gdb(self, command: str, cli_output: bool = True) -> Any: - """Run a GDB command and return its output.""" - return debugcore.send_command(str(command), cli_output=cli_output) - - def aobscan_first(self, pattern: str, writable: bool | None = None, executable: bool | None = None) -> int | None: - """Return the first address matching an AOB pattern, or None.""" - matches = self.aobscan(pattern, writable=writable, executable=executable, limit=1) - return matches[0] if matches else None - - def aobscan(self, pattern: str, writable: bool | None = None, executable: bool | None = None, limit: int = 1000) -> list[int]: - """Scan readable maps for an AOB pattern. Wildcards can be '?' or '??'.""" - if debugcore.currentpid == -1: - raise RuntimeError("No process is attached!") - return debugcore.aob_scan(str(pattern), writable=writable, executable=executable, limit=limit) - - def _bytes(self, data: BytesLike) -> bytes: - if isinstance(data, str): - return bytes.fromhex(data.replace(" ", "")) - if isinstance(data, (bytes, bytearray, memoryview)): - return bytes(data) - return bytes(int(item) & 0xFF for item in data) - - -def create_script_namespace() -> dict[str, Any]: - """Build a fresh execution namespace exposing the LibpinceScriptApi helpers.""" - api = LibpinceScriptApi() - namespace = { - "__builtins__": builtins, - "__name__": "__libpince_engine__", - "api": api, - "debugcore": debugcore, - "typedefs": typedefs, - "utils": utils, - "VALUE_REPR": typedefs.VALUE_REPR, - } - for name in dir(api): - function = getattr(api, name) - if not name.startswith("_") and callable(function): - namespace[name] = function - return namespace - - -def run_script_code(script_content: str, namespace: dict[str, Any], filename: str) -> tuple[bool, str]: - """Compile and exec script_content in namespace, capturing its combined output. - - Returns (succeeded, output). - Namespace is mutated in place so variables set by an [ENABLE] run survive into a later [DISABLE] run. - Used by the engine window and any headless caller (e.g. address-table script entries). - """ - namespace["__file__"] = filename - output = io.StringIO() - succeeded = True - try: - with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): - exec(compile(script_content, filename, "exec"), namespace, namespace) - except Exception: - traceback.print_exc(file=output) - succeeded = False - return succeeded, output.getvalue() - - -class LibpinceEngineWindow(QMainWindow, Ui_MainWindow): - # Emitted with (title, entry) when the user pushes the current editor to the address table - send_to_table = pyqtSignal(str, object) - # Emitted when a tab bound to a table script entry is edited, so the session can be marked dirty - entry_modified = pyqtSignal() - # Emitted after a script run, because scripts can change GDB state, mappings or convenience variables. - script_executed = pyqtSignal() - - def __init__(self, parent: QWidget | None) -> None: - super().__init__(parent) - self.setupUi(self) - self.configure_editor(self.scriptEditor) - index = self.tabWidget.indexOf(self.plusTab) - tab_bar = self.tabWidget.tabBar() - tab_bar.setTabButton(index, tab_bar.ButtonPosition.LeftSide, None) - tab_bar.setTabButton(index, tab_bar.ButtonPosition.RightSide, None) - - for action in ( - self.actionCode_injection, - self.actionAOB_scan_nop, - self.actionAOB_scan_patch, - self.actionRead_write_address, - ): - action.triggered.connect(lambda checked=False, a=action: self.insert_template(a.property("data"))) - self.tabWidget.tabBarClicked.connect(self.handle_tab_click) - self.tabWidget.tabCloseRequested.connect(self.close_tab) - self.actionOpen.triggered.connect(self.open_file) - self.actionSave.triggered.connect(self.save_file) - self.actionLibpince.triggered.connect(self.actionLibpince_triggered) - self.actionRun_enable.triggered.connect(self.run_enable) - self.actionRun_disable.triggered.connect(self.run_disable) - self.actionRun_selection.triggered.connect(self.run_selection) - self.actionSend_to_table.triggered.connect(self.send_to_cheat_table) - self.actionClear_output.triggered.connect(self.outputEdit.clear) - if parent is not None: - guiutils.center_to_parent(self) - - def configure_editor(self, editor: ScriptEditor) -> None: - editor.bind_tab_widget(self.tabWidget) - editor.set_namespace(create_script_namespace()) - editor.update_line_number_area_width() - - def create_new_tab(self) -> ScriptEditor: - new_tab = QWidget() - layout = QVBoxLayout(new_tab) - layout.setContentsMargins(0, 0, 0, 0) - text_editor = ScriptEditor(new_tab) - text_editor.setFont(self.scriptEditor.font()) - text_editor.setLineWrapMode(self.scriptEditor.lineWrapMode()) - text_editor.setTabStopDistance(self.scriptEditor.tabStopDistance()) - self.configure_editor(text_editor) - layout.addWidget(text_editor) - index = self.tabWidget.indexOf(self.plusTab) - self.tabWidget.insertTab(index, new_tab, tr.UNTITLED) - self.tabWidget.setCurrentIndex(index) - return text_editor - - def get_current_editor(self) -> ScriptEditor | None: - current_tab = self.tabWidget.currentWidget() - return current_tab.findChild(ScriptEditor) if current_tab else None - - def handle_tab_click(self, index: int) -> None: - if index == self.tabWidget.count() - 1: - self.create_new_tab() - - def close_tab(self, index: int) -> None: - if index == self.tabWidget.count() - 1: - return - editor = self.tabWidget.widget(index).findChild(ScriptEditor) - if editor and editor.is_modified: - result = QMessageBox.question( - self, - tr.UNSAVED_SCRIPT, - tr.SAVE_SCRIPT_CHANGES.format(self.tabWidget.tabText(index).rstrip("*")), - QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard | QMessageBox.StandardButton.Cancel, - ) - if result == QMessageBox.StandardButton.Cancel: - return - if result == QMessageBox.StandardButton.Save: - self.tabWidget.setCurrentIndex(index) - self.save_file() - if editor.is_modified: - return - current_index = self.tabWidget.currentIndex() - self.tabWidget.removeTab(index) - if index == current_index and index > 0: - self.tabWidget.setCurrentIndex(index - 1) - if self.get_current_editor() is None: - self.create_new_tab() - - def open_file(self) -> None: - file_path, _ = QFileDialog.getOpenFileName(self, tr.OPEN_SCRIPT_FILE, os.path.expanduser("~"), tr.FILE_TYPES_SCRIPT) - if not file_path: - return - editor = self.create_new_tab() - try: - with open(file_path, "r", encoding="utf-8") as file: - content = file.read() - editor.setPlainText(content) - editor.file_path = file_path - editor.saved_content = content - editor.is_modified = False - editor.update_tab_title() - except Exception as e: - QMessageBox.critical(self, tr.ERROR, str(e)) - - def save_file(self) -> None: - editor = self.get_current_editor() - if not editor: - return - if not editor.file_path: - file_path, _ = QFileDialog.getSaveFileName(self, tr.SAVE_SCRIPT_FILE, os.path.expanduser("~"), tr.FILE_TYPES_SCRIPT) - if not file_path: - return - if not file_path.lower().endswith(".py"): - file_path += ".py" - editor.file_path = file_path - try: - with open(editor.file_path, "w", encoding="utf-8") as file: - content = editor.toPlainText() - file.write(content) - guiutils.own_path_as_user(editor.file_path) - editor.saved_content = content - editor.is_modified = False - editor.update_tab_title() - except Exception as e: - QMessageBox.critical(self, tr.ERROR, str(e)) - - def run_enable(self) -> None: - editor = self.get_current_editor() - if editor: - enable_code, _ = parse_script_sections(editor.toPlainText()) - self.run_script(editor, enable_code) - - def run_disable(self) -> None: - editor = self.get_current_editor() - if not editor: - return - _, disable_code = parse_script_sections(editor.toPlainText()) - if disable_code is None: - self.statusbar.showMessage(tr.SCRIPT_NO_DISABLE, 3000) - return - self.run_script(editor, disable_code) - - def run_selection(self) -> None: - editor = self.get_current_editor() - if not editor: - return - cursor = editor.textCursor() - script = cursor.selectedText().replace("\u2029", "\n") if cursor.hasSelection() else editor.toPlainText() - self.run_script(editor, script) - - def run_script(self, editor: ScriptEditor, script_content: str) -> None: - if not script_content.strip(): - return - filename = editor.file_path or f"" - entry = editor.script_entry - namespace = (entry.namespace if entry else None) or editor.namespace or create_script_namespace() - self.append_output("\n" + tr.SCRIPT_RUNNING.format(filename)) - succeeded, output = run_script_code(script_content, namespace, filename) - editor.set_namespace(namespace) - if entry is not None: - entry.namespace = namespace - self.append_output(output) - message = tr.SCRIPT_FINISHED if succeeded else tr.SCRIPT_FAILED - if succeeded: - self.append_output(message) - self.statusbar.showMessage(message, 3000) - self.script_executed.emit() - - def send_to_cheat_table(self) -> None: - editor = self.get_current_editor() - if not editor: - return - script = editor.toPlainText() - if not script.strip(): - return - default = self.tabWidget.tabText(self.tabWidget.currentIndex()).rstrip("*") - name, accepted = QInputDialog.getText(self, tr.SEND_TO_TABLE, tr.ENTER_DESCRIPTION, text=default) - if not accepted: - return - entry = typedefs.ScriptEntry(script) - # Adopt an unsaved scratch tab as the entry's live tab. A file or already-bound tab keeps its identity. - if editor.script_entry is None and not editor.file_path: - self._bind_editor(editor, entry, name) - self.send_to_table.emit(name, entry) - self.statusbar.showMessage(tr.SENT_TO_TABLE, 3000) - - def _iter_editors(self): - # Walks every tab's editor. The trailing "+" tab holds none and is skipped. - for index in range(self.tabWidget.count()): - tab = self.tabWidget.widget(index) - editor = tab.findChild(ScriptEditor) if tab else None - if editor is not None: - yield editor - - def _editor_for_entry(self, entry: typedefs.ScriptEntry) -> ScriptEditor | None: - return next((e for e in self._iter_editors() if e.script_entry is entry), None) - - def _scratch_editor(self) -> ScriptEditor | None: - # An unbound, empty, unsaved tab (e.g. the one a fresh window starts with) an entry can take over - scratch = ( - e for e in self._iter_editors() if e.script_entry is None and not e.file_path and not e.is_modified and not e.toPlainText().strip() - ) - return next(scratch, None) - - def _bind_editor(self, editor: ScriptEditor, entry: typedefs.ScriptEntry, title: str) -> None: - # Tie editor to a table script entry so its edits mirror back into it. Editor must already hold entry.script. - editor.script_entry = entry - editor.display_name = title - editor.saved_content = entry.script - editor.is_modified = False - editor.update_tab_title() - editor.textChanged.connect(lambda e=editor: self.mirror_script_entry(e)) - - def open_script_entry(self, entry: typedefs.ScriptEntry, title: str) -> None: - """Open or focus if already open, a tab bound to a table script entry. - - The tab shares the entry object so edits mirror straight back into it (see mirror_script_entry). - """ - editor = self._editor_for_entry(entry) - if editor is None: - editor = self._scratch_editor() or self.create_new_tab() - editor.setPlainText(entry.script) - self._bind_editor(editor, entry, title) - self.tabWidget.setCurrentIndex(self.tabWidget.indexOf(editor.parent())) - editor.setFocus() - - def rename_script_entry(self, entry: typedefs.ScriptEntry, title: str) -> None: - # Keep an open bound tab's title in sync when the row description is edited from the table - editor = self._editor_for_entry(entry) - if editor is not None: - editor.display_name = title - editor.update_tab_title() - - def close_script_entry(self, entry: typedefs.ScriptEntry) -> None: - # Close the bound tab when its table row is deleted so edits can't orphan onto a gone entry - editor = self._editor_for_entry(entry) - if editor is not None: - self.close_tab(self.tabWidget.indexOf(editor.parent())) - - def mirror_script_entry(self, editor: ScriptEditor) -> None: - entry = editor.script_entry - if entry is None: - return - text = editor.toPlainText() - entry.script = text - # Bound tabs are live so keep them unmodified to skip the "*" marker and the close-save prompt - editor.saved_content = text - if editor.is_modified: - editor.is_modified = False - editor.update_tab_title() - self.entry_modified.emit() - - def append_output(self, text: str) -> None: - if not text: - return - self.outputEdit.moveCursor(QTextCursor.MoveOperation.End) - self.outputEdit.insertPlainText(text if text.endswith("\n") else text + "\n") - self.outputEdit.moveCursor(QTextCursor.MoveOperation.End) - - def insert_template(self, template: str) -> None: - editor = self.get_current_editor() - if editor: - editor.textCursor().insertText(template) - editor.setFocus() - - def actionLibpince_triggered(self) -> None: - utils.execute_command_as_user('python3 -m webbrowser "https://korcankaraokcu.github.io/PINCE/"') diff --git a/GUI/Widgets/LibpinceEngine/ScriptEditor.py b/GUI/Widgets/LibpinceEngine/ScriptEditor.py deleted file mode 100644 index b41398cd..00000000 --- a/GUI/Widgets/LibpinceEngine/ScriptEditor.py +++ /dev/null @@ -1,478 +0,0 @@ -import builtins, inspect, keyword, os, re -from typing import Any, Iterator - -from PyQt6.QtCore import QModelIndex, QRect, QSize, QStringListModel, Qt -from PyQt6.QtGui import ( - QColor, - QKeyEvent, - QPainter, - QPaintEvent, - QResizeEvent, - QTextBlock, - QTextCharFormat, - QTextCursor, - QTextDocument, - QTextFormat, - QSyntaxHighlighter, -) -from PyQt6.QtWidgets import QApplication, QCompleter, QPlainTextEdit, QTabWidget, QTextEdit, QToolTip, QWidget - -from tr.tr import TranslationConstants as tr - -INDENT = " " * 4 -MAX_COMPLETIONS = 300 - - -def make_format(color: str, bold: bool = False, italic: bool = False) -> QTextCharFormat: - fmt = QTextCharFormat() - fmt.setForeground(QColor(color)) - if bold: - fmt.setFontWeight(700) - if italic: - fmt.setFontItalic(True) - return fmt - - -class PythonHighlighter(QSyntaxHighlighter): - STRING_STATES = { - 1: ("'''", False), - 2: ('"""', False), - 3: ("'''", True), - 4: ('"""', True), - } - - def __init__(self, document: QTextDocument | None) -> None: - super().__init__(document) - self.default_format = QTextCharFormat() - self.string_format = make_format("#98c379") - self.comment_format = make_format("#7f848e", italic=True) - self.variable_format = make_format("#e06c75") - self.function_format = make_format("#61afef") - self.keywords = set(keyword.kwlist) - self.builtins = set(dir(builtins)) - self.namespaces = {"api", "debugcore", "libpince", "scancore", "typedefs", "utils", "VALUE_REPR"} - self.reserved = self.keywords | self.builtins | self.namespaces - self.identifier_regex = re.compile(r"\b[A-Za-z_]\w*\b") - self.function_regex = re.compile(r"\b([A-Za-z_]\w*)\s*(?=\()") - self.rules = [ - (re.compile(r"\b(" + "|".join(keyword.kwlist) + r")\b"), make_format("#c678dd", bold=True), 0), - (re.compile(r"\b(" + "|".join(dir(builtins)) + r")\b"), make_format("#e5c07b"), 0), - (re.compile(r"\b(" + "|".join(self.namespaces) + r")\b"), make_format("#56b6c2", bold=True), 0), - (re.compile(r"\b(?:def|class)\s+([A-Za-z_]\w*)"), make_format("#61afef", bold=True), 1), - (re.compile(r"\b(0x[0-9a-fA-F]+|\d+(\.\d+)?)\b"), make_format("#d19a66"), 0), - ] - - def highlightBlock(self, text: str) -> None: - self.setCurrentBlockState(0) - state = self.previousBlockState() - i = 0 - quote, is_fstring = self.STRING_STATES.get(state, (None, False)) - if quote: - end = text.find(quote) - span_end = len(text) if end == -1 else end + 3 - self.setFormat(0, span_end, self.string_format) - if is_fstring: - self.format_fstring_expressions(text, 0, span_end) - if end == -1: - self.setCurrentBlockState(state) - return - i = span_end - code_start = i - while i < len(text): - string_info = self.string_at(text, i) - if string_info: - prefix_start, quote_start, quote, quote_len, is_fstring = string_info - self.apply_code_rules(text, code_start, prefix_start) - if quote_len == 3: - end = text.find(quote * 3, quote_start + 3) - span_end = len(text) if end == -1 else end + 3 - self.setFormat(prefix_start, span_end - prefix_start, self.string_format) - if is_fstring: - self.format_fstring_expressions(text, prefix_start, span_end) - if end == -1: - if is_fstring: - self.setCurrentBlockState(3 if quote == "'" else 4) - else: - self.setCurrentBlockState(1 if quote == "'" else 2) - return - else: - span_end = self.find_string_end(text, quote_start + 1, quote) - self.setFormat(prefix_start, span_end - prefix_start, self.string_format) - if is_fstring: - self.format_fstring_expressions(text, prefix_start, span_end) - i = span_end - code_start = i - continue - if text[i] == "#": - self.apply_code_rules(text, code_start, i) - self.setFormat(i, len(text) - i, self.comment_format) - return - i += 1 - self.apply_code_rules(text, code_start, len(text)) - - def apply_code_rules(self, text: str, start: int, end: int) -> None: - if start >= end: - return - segment = text[start:end] - for match in self.identifier_regex.finditer(segment): - name = match.group() - absolute_start = start + match.start() - next_index = start + match.end() - next_char = text[next_index:].lstrip()[:1] - if name not in self.reserved and next_char != "(" and (absolute_start == 0 or text[absolute_start - 1] != "."): - self.setFormat(absolute_start, len(name), self.variable_format) - for match in self.function_regex.finditer(segment): - name = match.group(1) - if name not in self.keywords: - self.setFormat(start + match.start(1), len(name), self.function_format) - for regex, fmt, group in self.rules: - for match in regex.finditer(segment): - span_start, span_end = match.span(group) - self.setFormat(start + span_start, span_end - span_start, fmt) - - def string_at(self, text: str, index: int) -> tuple[int, int, str, int, bool] | None: - match = re.match(r"(?i)([rubf]*)(['\"])", text[index:]) - if not match: - return - prefix = match.group(1) - if prefix and index > 0 and (text[index - 1].isalnum() or text[index - 1] == "_"): - return - quote_start = index + len(prefix) - quote = match.group(2) - quote_len = 3 if text.startswith(quote * 3, quote_start) else 1 - return index, quote_start, quote, quote_len, "f" in prefix.lower() - - def find_string_end(self, text: str, index: int, quote: str) -> int: - escape = False - while index < len(text): - if escape: - escape = False - elif text[index] == "\\": - escape = True - elif text[index] == quote: - return index + 1 - index += 1 - return len(text) - - def format_fstring_expressions(self, text: str, start: int, end: int) -> None: - i = start - while i < end: - if text.startswith("{{", i) or text.startswith("}}", i): - i += 2 - continue - if text[i] == "{": - expression_end = self.find_fstring_expression_end(text, i + 1, end) - if expression_end == -1: - return - self.setFormat(i + 1, expression_end - i - 1, self.default_format) - self.apply_code_rules(text, i + 1, i + 1 + self.fstring_code_length(text[i + 1 : expression_end])) - i = expression_end + 1 - continue - i += 1 - - def find_fstring_expression_end(self, text: str, index: int, end: int) -> int: - depth = 0 - while index < end: - if text.startswith("{{", index) or text.startswith("}}", index): - index += 2 - continue - if text[index] == "{": - depth += 1 - elif text[index] == "}": - if depth == 0: - return index - depth -= 1 - index += 1 - return -1 - - def fstring_code_length(self, expression: str) -> int: - depth = 0 - quote = None - escape = False - for index, char in enumerate(expression): - if quote: - if escape: - escape = False - elif char == "\\": - escape = True - elif char == quote: - quote = None - continue - if char in "'\"": - quote = char - elif char in "([{": - depth += 1 - elif char in ")]}": - depth = max(0, depth - 1) - elif depth == 0 and (char == ":" or (char == "!" and expression[index + 1 : index + 2] != "=")): - return index - return len(expression) - - -class LineNumberArea(QWidget): - def __init__(self, editor: "ScriptEditor") -> None: - super().__init__(editor) - self.editor = editor - - def sizeHint(self) -> QSize: - return QSize(self.editor.line_number_area_width(), 0) - - def paintEvent(self, event: QPaintEvent) -> None: - self.editor.line_number_area_paint_event(event) - - -class ScriptEditor(QPlainTextEdit): - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.file_path: str | None = None - self.saved_content = "" - self.is_modified = False - self.tab_widget: QTabWidget | None = None - self.namespace: dict[str, Any] = {} - self.script_entry: Any = None # set when this tab is bound to a .pct script entry - self.display_name: str | None = None # overrides the tab title, used by bound entry tabs - - self.line_number_area = LineNumberArea(self) - self.completion_model = QStringListModel(self) - self.completer = QCompleter(self.completion_model, self) - self.completer.setWidget(self) - self.completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) - self.completer.setCompletionMode(QCompleter.CompletionMode.PopupCompletion) - self.completer.setMaxVisibleItems(12) - self.completer.activated.connect(self.insert_completion) - self.completer.highlighted.connect(self.show_help) - - self.highlighter = PythonHighlighter(self.document()) - self.blockCountChanged.connect(self.update_line_number_area_width) - self.updateRequest.connect(self.update_line_number_area) - self.cursorPositionChanged.connect(self.highlight_current_line) - self.textChanged.connect(self.handle_text_changed) - self.update_line_number_area_width() - self.highlight_current_line() - - def bind_tab_widget(self, tab_widget: QTabWidget) -> None: - self.tab_widget = tab_widget - - def set_namespace(self, namespace: dict[str, Any]) -> None: - self.namespace = namespace - - def handle_text_changed(self) -> None: - modified = self.toPlainText() != self.saved_content - if modified != self.is_modified: - self.is_modified = modified - self.update_tab_title() - - def update_tab_title(self) -> None: - if not self.tab_widget: - return - index = self.tab_widget.indexOf(self.parent()) - base_title = self.display_name or (os.path.basename(self.file_path) if self.file_path else tr.UNTITLED) - self.tab_widget.setTabText(index, f"{base_title}*" if self.is_modified else base_title) - - def line_number_area_width(self) -> int: - return 12 + self.fontMetrics().horizontalAdvance("9") * len(str(max(1, self.blockCount()))) - - def update_line_number_area_width(self) -> None: - self.setViewportMargins(self.line_number_area_width(), 0, 0, 0) - - def update_line_number_area(self, rect: QRect, dy: int) -> None: - if dy: - self.line_number_area.scroll(0, dy) - else: - self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) - if rect.contains(self.viewport().rect()): - self.update_line_number_area_width() - - def resizeEvent(self, event: QResizeEvent) -> None: - super().resizeEvent(event) - rect = self.contentsRect() - self.line_number_area.setGeometry(QRect(rect.left(), rect.top(), self.line_number_area_width(), rect.height())) - - def line_number_area_paint_event(self, event: QPaintEvent) -> None: - painter = QPainter(self.line_number_area) - painter.fillRect(event.rect(), QColor("#252830")) - painter.setPen(QColor("#7f848e")) - block = self.firstVisibleBlock() - number = block.blockNumber() - top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) - bottom = top + round(self.blockBoundingRect(block).height()) - while block.isValid() and top <= event.rect().bottom(): - if block.isVisible() and bottom >= event.rect().top(): - painter.drawText( - 0, - top, - self.line_number_area.width() - 5, - self.fontMetrics().height(), - Qt.AlignmentFlag.AlignRight, - str(number + 1), - ) - block = block.next() - if not block.isValid(): - break - top = bottom - bottom = top + round(self.blockBoundingRect(block).height()) - number += 1 - - def highlight_current_line(self) -> None: - selection = QTextEdit.ExtraSelection() - selection.format.setBackground(QColor("#2c313a")) - selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True) - selection.cursor = self.textCursor() - selection.cursor.clearSelection() - self.setExtraSelections([selection]) - - def keyPressEvent(self, event: QKeyEvent) -> None: - popup = self.completer.popup() - if popup.isVisible(): - if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter, Qt.Key.Key_Tab): - self.insert_completion(popup.currentIndex().data()) - popup.hide() - return - if event.key() == Qt.Key.Key_Escape: - popup.hide() - return - if event.key() in (Qt.Key.Key_Up, Qt.Key.Key_Down, Qt.Key.Key_PageUp, Qt.Key.Key_PageDown): - QApplication.sendEvent(popup, event) - return - - key = event.key() - modifiers = event.modifiers() - if key == Qt.Key.Key_Space and modifiers & Qt.KeyboardModifier.ControlModifier: - self.complete(force=True) - return - if key == Qt.Key.Key_Tab and not modifiers: - self.indent_selection() - return - if key == Qt.Key.Key_Backtab or (key == Qt.Key.Key_Tab and modifiers & Qt.KeyboardModifier.ShiftModifier): - self.unindent_selection() - return - if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter): - self.insert_auto_indent() - return - if key == Qt.Key.Key_Backspace and self.backspace_unindent(): - return - - super().keyPressEvent(event) - text = event.text() - if text == ".": - self.complete(force=True) - elif text == "(": - self.show_help(self.callable_before_cursor()) - elif text and (text.isalnum() or text == "_"): - self.complete() - elif not text.strip(): - popup.hide() - - def word_before_cursor(self) -> str: - text = self.textCursor().block().text()[: self.textCursor().positionInBlock()] - match = re.search(r"([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*\.?)$", text) - return match.group(1) if match else "" - - def callable_before_cursor(self) -> str: - text = self.textCursor().block().text()[: self.textCursor().positionInBlock()].rstrip("(").rstrip() - match = re.search(r"([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)$", text) - return match.group(1) if match else "" - - def resolve(self, name: str) -> Any: - parts = name.split(".") - obj = self.namespace.get(parts[0], getattr(builtins, parts[0], None)) - for item in parts[1:]: - try: - obj = getattr(obj, item) - except Exception: - return - return obj - - def complete(self, force: bool = False) -> None: - prefix = self.word_before_cursor() - if not force and not prefix.endswith(".") and len(prefix) < 2: - self.completer.popup().hide() - return - if "." in prefix: - base, partial = prefix.rsplit(".", 1) - obj = self.resolve(base) - names = ( - [] - if obj is None - else [f"{base}.{name}" for name in dir(obj) if name.startswith(partial) and (partial.startswith("_") or not name.startswith("_"))] - ) - else: - all_names = sorted(set(keyword.kwlist) | set(dir(builtins)) | set(self.namespace)) - names = all_names if force and not prefix else [name for name in all_names if name.startswith(prefix) or prefix in name] - if not names: - self.completer.popup().hide() - return - self.completion_model.setStringList(names[:MAX_COMPLETIONS]) - self.completer.setCompletionPrefix(prefix) - popup = self.completer.popup() - popup.setCurrentIndex(self.completer.completionModel().index(0, 0)) - rect = self.cursorRect() - width = popup.sizeHintForColumn(0) + popup.verticalScrollBar().sizeHint().width() + 20 - rect.setWidth(min(max(width, 240), 620)) - self.completer.complete(rect) - - def insert_completion(self, completion: str) -> None: - if not completion: - return - prefix = self.word_before_cursor() - self.textCursor().insertText(completion[len(prefix) :] if completion.startswith(prefix) else completion) - - def show_help(self, name: str | QModelIndex | None) -> None: - if not isinstance(name, str): - name = name.data() if name is not None else "" - obj = self.resolve(name) - if obj is None: - return - try: - signature = str(inspect.signature(obj)) if callable(obj) else "" - except (TypeError, ValueError): - signature = "" - text = f"{name}{signature}\n{inspect.getdoc(obj) or ''}".strip() - if text: - QToolTip.showText(self.mapToGlobal(self.cursorRect().bottomRight()), text[:1200], self) - - def selected_blocks(self) -> Iterator[QTextBlock]: - cursor = self.textCursor() - document = self.document() - start = document.findBlock(cursor.selectionStart()) - end = document.findBlock(cursor.selectionEnd()) - last = end.blockNumber() - int(cursor.hasSelection() and end.positionInBlock() == 0) - return map(document.findBlockByNumber, range(start.blockNumber(), max(start.blockNumber(), last) + 1)) - - def indent_selection(self) -> None: - cursor = self.textCursor() - if not cursor.hasSelection(): - cursor.insertText(INDENT) - return - cursor.beginEditBlock() - for block in self.selected_blocks(): - cursor.setPosition(block.position()) - cursor.insertText(INDENT) - cursor.endEditBlock() - - def unindent_selection(self) -> None: - cursor = self.textCursor() - cursor.beginEditBlock() - for block in self.selected_blocks(): - count = min(len(block.text()) - len(block.text().lstrip(" ")), len(INDENT)) - count = count or int(block.text().startswith("\t")) - if count: - cursor.setPosition(block.position()) - cursor.movePosition(QTextCursor.MoveOperation.Right, QTextCursor.MoveMode.KeepAnchor, count) - cursor.removeSelectedText() - cursor.endEditBlock() - - def insert_auto_indent(self) -> None: - text = self.textCursor().block().text()[: self.textCursor().positionInBlock()] - indent = re.match(r"\s*", text).group(0).replace("\t", INDENT) - self.textCursor().insertText("\n" + indent + (INDENT if text.rstrip().endswith(":") else "")) - - def backspace_unindent(self) -> bool: - cursor = self.textCursor() - text = cursor.block().text()[: cursor.positionInBlock()] - if cursor.hasSelection() or not text.isspace(): - return False - count = min(cursor.positionInBlock() % len(INDENT) or len(INDENT), cursor.positionInBlock()) - cursor.movePosition(QTextCursor.MoveOperation.Left, QTextCursor.MoveMode.KeepAnchor, count) - cursor.removeSelectedText() - return True diff --git a/GUI/Widgets/LoadingDialog/Form/LoadingDialog.py b/GUI/Widgets/LoadingDialog/Form/LoadingDialog.py deleted file mode 100644 index a1a59197..00000000 --- a/GUI/Widgets/LoadingDialog/Form/LoadingDialog.py +++ /dev/null @@ -1,48 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/LoadingDialog/Form/LoadingDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(107, 71) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.label_Animated = QtWidgets.QLabel(parent=Dialog) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.label_Animated.sizePolicy().hasHeightForWidth()) - self.label_Animated.setSizePolicy(sizePolicy) - self.label_Animated.setText("") - self.label_Animated.setScaledContents(False) - self.label_Animated.setObjectName("label_Animated") - self.horizontalLayout.addWidget(self.label_Animated) - self.label_StatusText = QtWidgets.QLabel(parent=Dialog) - self.label_StatusText.setObjectName("label_StatusText") - self.horizontalLayout.addWidget(self.label_StatusText) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem1) - self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) - self.pushButton_Cancel = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Cancel.setObjectName("pushButton_Cancel") - self.gridLayout.addWidget(self.pushButton_Cancel, 1, 0, 1, 1) - - self.retranslateUi(Dialog) - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - self.label_StatusText.setText(_translate("Dialog", "Processing")) - self.pushButton_Cancel.setText(_translate("Dialog", "Cancel")) diff --git a/GUI/Widgets/LoadingDialog/LoadingDialog.py b/GUI/Widgets/LoadingDialog/LoadingDialog.py deleted file mode 100644 index f89b32ad..00000000 --- a/GUI/Widgets/LoadingDialog/LoadingDialog.py +++ /dev/null @@ -1,65 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget -from PyQt6.QtGui import QCloseEvent, QMovie -from PyQt6.QtCore import QEvent, QByteArray, QSize, QThread, pyqtSignal -from GUI.Utils import guiutils -from GUI.Widgets.LoadingDialog.Form.LoadingDialog import Ui_Dialog -from libpince import debugcore, utils -from libpince.utils import logger -from typing import Any -import traceback - - -class LoadingDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(self.windowFlags()) - self.keyPressEvent = QEvent.ignore - - # Make use of this background_thread when you spawn a LoadingDialog - # Warning: overridden_func() can only return one value, so if your overridden function returns more than one - # value, refactor your overridden function to return only one object(convert tuple to list etc.) - # Check refresh_table method of FunctionsInfoWidget for exemplary usage - self.background_thread = self.BackgroundThread() - self.background_thread.output_ready.connect(self.accept) - self.pushButton_Cancel.clicked.connect(self.close) - media_directory = utils.get_media_directory() - self.movie = QMovie(media_directory + "/LoadingDialog/ajax-loader.gif", QByteArray()) - self.label_Animated.setMovie(self.movie) - self.movie.setScaledSize(QSize(25, 25)) - self.movie.setCacheMode(QMovie.CacheMode.CacheAll) - self.movie.setSpeed(100) - self.movie.start() - guiutils.center_to_parent(self) - - # TODO: This function only cancels the last command sent, redesign this if it's needed to cancel non-gdb functions - def cancel_thread(self) -> None: - debugcore.cancel_ongoing_command() - self.background_thread.wait() - - def exec(self) -> None: - self.background_thread.start() - super().exec() - - def closeEvent(self, event: QCloseEvent) -> None: - self.cancel_thread() - super().closeEvent(event) - - class BackgroundThread(QThread): - output_ready = pyqtSignal(object) - - def __init__(self) -> None: - super().__init__() - - # Unhandled exceptions in this thread freezes PINCE - def run(self) -> None: - try: - output = self.overridden_func() - except: - traceback.print_exc() - output = None - self.output_ready.emit(output) - - def overridden_func(self) -> Any: - logger.debug("Override this function") - return 0 diff --git a/GUI/Widgets/LogFile/Form/LogFileWidget.py b/GUI/Widgets/LogFile/Form/LogFileWidget.py deleted file mode 100644 index 582d6399..00000000 --- a/GUI/Widgets/LogFile/Form/LogFileWidget.py +++ /dev/null @@ -1,43 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/LogFile/Form/LogFileWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(582, 558) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.label_FilePath = QtWidgets.QLabel(parent=Form) - self.label_FilePath.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_FilePath.setObjectName("label_FilePath") - self.horizontalLayout.addWidget(self.label_FilePath) - self.label_LoggingStatus = QtWidgets.QLabel(parent=Form) - self.label_LoggingStatus.setObjectName("label_LoggingStatus") - self.horizontalLayout.addWidget(self.label_LoggingStatus) - self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) - self.textBrowser_LogContent = QtWidgets.QTextBrowser(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_LogContent.setFont(font) - self.textBrowser_LogContent.setLineWrapMode(QtWidgets.QTextEdit.LineWrapMode.NoWrap) - self.textBrowser_LogContent.setObjectName("textBrowser_LogContent") - self.gridLayout.addWidget(self.textBrowser_LogContent, 1, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Form")) - self.label_FilePath.setText(_translate("Form", "TextLabel")) - self.label_LoggingStatus.setText(_translate("Form", "TextLabel")) diff --git a/GUI/Widgets/LogFile/Form/LogFileWidget.ui b/GUI/Widgets/LogFile/Form/LogFileWidget.ui deleted file mode 100644 index b0aaf6ad..00000000 --- a/GUI/Widgets/LogFile/Form/LogFileWidget.ui +++ /dev/null @@ -1,54 +0,0 @@ - - - Form - - - - 0 - 0 - 582 - 558 - - - - Form - - - - - - - - TextLabel - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - TextLabel - - - - - - - - - - Monospace - - - - QTextEdit::NoWrap - - - - - - - - diff --git a/GUI/Widgets/LogFile/LogFile.py b/GUI/Widgets/LogFile/LogFile.py deleted file mode 100644 index 060cc05e..00000000 --- a/GUI/Widgets/LogFile/LogFile.py +++ /dev/null @@ -1,61 +0,0 @@ -from PyQt6.QtWidgets import QWidget -from PyQt6.QtGui import QTextCursor, QCloseEvent -from PyQt6.QtCore import Qt, QTimer -from GUI.Utils import guiutils -from GUI.States import states -from GUI.Widgets.LogFile.Form.LogFileWidget import Ui_Form -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr -import io - - -class LogFileWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.contents = "" - self.refresh_contents() - self.refresh_timer = QTimer(self) - self.refresh_timer.setInterval(500) - self.refresh_timer.timeout.connect(self.refresh_contents) - self.refresh_timer.start() - guiutils.center_to_parent(self) - - def refresh_contents(self) -> None: - log_path = utils.get_logging_file(debugcore.currentpid) - self.setWindowTitle(tr.LOG_FILE.format(debugcore.currentpid)) - self.label_FilePath.setText(tr.LOG_CONTENTS.format(log_path, 20000)) - log_status = f"{tr.ON}" if states.gdb_logging else f"{tr.OFF}" - self.label_LoggingStatus.setText(f"{tr.LOG_STATUS.format(log_status)}") - try: - log_file = open(log_path, encoding="utf-8", errors="replace") - except OSError: - self.textBrowser_LogContent.clear() - error_message = tr.LOG_READ_ERROR.format(log_path) + "\n" - if not states.gdb_logging: - error_message += tr.SETTINGS_ENABLE_LOG - self.textBrowser_LogContent.setText(error_message) - return - with log_file: - log_file.seek(0, io.SEEK_END) - end_pos = log_file.tell() - truncated = end_pos > 20000 - log_file.seek(end_pos - 20000 if truncated else 0, io.SEEK_SET) - contents = log_file.read() - if truncated: - contents = contents.split("\n", 1)[-1] - if contents != self.contents: - self.contents = contents - self.textBrowser_LogContent.clear() - self.textBrowser_LogContent.setPlainText(contents) - - # Scrolling to bottom - cursor = self.textBrowser_LogContent.textCursor() - cursor.movePosition(QTextCursor.MoveOperation.End) - self.textBrowser_LogContent.setTextCursor(cursor) - self.textBrowser_LogContent.ensureCursorVisible() - - def closeEvent(self, event: QCloseEvent) -> None: - self.refresh_timer.stop() - super().closeEvent(event) diff --git a/GUI/Widgets/MainWindow/Form/MainWindow.py b/GUI/Widgets/MainWindow/Form/MainWindow.py deleted file mode 100644 index ec0767bf..00000000 --- a/GUI/Widgets/MainWindow/Form/MainWindow.py +++ /dev/null @@ -1,351 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/MainWindow/Form/MainWindow.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.resize(768, 664) - MainWindow.setWindowTitle("PINCE") - self.centralwidget = QtWidgets.QWidget(parent=MainWindow) - self.centralwidget.setObjectName("centralwidget") - self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout_8 = QtWidgets.QHBoxLayout() - self.horizontalLayout_8.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetMinAndMaxSize) - self.horizontalLayout_8.setObjectName("horizontalLayout_8") - self.pushButton_MemoryView = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_MemoryView.setEnabled(False) - self.pushButton_MemoryView.setObjectName("pushButton_MemoryView") - self.horizontalLayout_8.addWidget(self.pushButton_MemoryView) - spacerItem = QtWidgets.QSpacerItem(120, 20, QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_8.addItem(spacerItem) - self.pushButton_CopyToAddressTable = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_CopyToAddressTable.setText("") - self.pushButton_CopyToAddressTable.setObjectName("pushButton_CopyToAddressTable") - self.horizontalLayout_8.addWidget(self.pushButton_CopyToAddressTable) - self.pushButton_CleanAddressTable = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_CleanAddressTable.setText("") - self.pushButton_CleanAddressTable.setObjectName("pushButton_CleanAddressTable") - self.horizontalLayout_8.addWidget(self.pushButton_CleanAddressTable) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_8.addItem(spacerItem1) - self.pushButton_RefreshAddressTable = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_RefreshAddressTable.setText("") - self.pushButton_RefreshAddressTable.setObjectName("pushButton_RefreshAddressTable") - self.horizontalLayout_8.addWidget(self.pushButton_RefreshAddressTable) - spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_8.addItem(spacerItem2) - self.pushButton_AddAddressManually = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_AddAddressManually.setEnabled(False) - self.pushButton_AddAddressManually.setObjectName("pushButton_AddAddressManually") - self.horizontalLayout_8.addWidget(self.pushButton_AddAddressManually) - self.gridLayout.addLayout(self.horizontalLayout_8, 2, 0, 1, 1) - self.treeWidget_AddressTable = AddressTree(parent=self.centralwidget) - self.treeWidget_AddressTable.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.treeWidget_AddressTable.setDragDropMode(QtWidgets.QAbstractItemView.DragDropMode.DragDrop) - self.treeWidget_AddressTable.setDefaultDropAction(QtCore.Qt.DropAction.MoveAction) - self.treeWidget_AddressTable.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection) - self.treeWidget_AddressTable.setIndentation(12) - self.treeWidget_AddressTable.setExpandsOnDoubleClick(False) - self.treeWidget_AddressTable.setObjectName("treeWidget_AddressTable") - self.gridLayout.addWidget(self.treeWidget_AddressTable, 3, 0, 1, 1) - self.horizontalLayout_9 = QtWidgets.QHBoxLayout() - self.horizontalLayout_9.setObjectName("horizontalLayout_9") - self.verticalLayout_6 = QtWidgets.QVBoxLayout() - self.verticalLayout_6.setObjectName("verticalLayout_6") - self.label_MatchCount = QtWidgets.QLabel(parent=self.centralwidget) - self.label_MatchCount.setObjectName("label_MatchCount") - self.verticalLayout_6.addWidget(self.label_MatchCount) - self.tableWidget_valuesearchtable = QtWidgets.QTableWidget(parent=self.centralwidget) - self.tableWidget_valuesearchtable.setEnabled(True) - self.tableWidget_valuesearchtable.setAutoFillBackground(False) - self.tableWidget_valuesearchtable.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.tableWidget_valuesearchtable.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_valuesearchtable.setAlternatingRowColors(True) - self.tableWidget_valuesearchtable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_valuesearchtable.setShowGrid(False) - self.tableWidget_valuesearchtable.setWordWrap(False) - self.tableWidget_valuesearchtable.setObjectName("tableWidget_valuesearchtable") - self.tableWidget_valuesearchtable.setColumnCount(3) - self.tableWidget_valuesearchtable.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_valuesearchtable.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_valuesearchtable.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_valuesearchtable.setHorizontalHeaderItem(2, item) - self.tableWidget_valuesearchtable.horizontalHeader().setSortIndicatorShown(True) - self.tableWidget_valuesearchtable.horizontalHeader().setStretchLastSection(True) - self.tableWidget_valuesearchtable.verticalHeader().setVisible(False) - self.tableWidget_valuesearchtable.verticalHeader().setDefaultSectionSize(23) - self.tableWidget_valuesearchtable.verticalHeader().setMinimumSectionSize(20) - self.verticalLayout_6.addWidget(self.tableWidget_valuesearchtable) - self.horizontalLayout_9.addLayout(self.verticalLayout_6) - self.widget_Scanbox = QtWidgets.QWidget(parent=self.centralwidget) - self.widget_Scanbox.setEnabled(False) - self.widget_Scanbox.setObjectName("widget_Scanbox") - self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.widget_Scanbox) - self.verticalLayout_5.setObjectName("verticalLayout_5") - self.horizontalLayout_ScanButtons = QtWidgets.QHBoxLayout() - self.horizontalLayout_ScanButtons.setObjectName("horizontalLayout_ScanButtons") - self.pushButton_NewFirstScan = QtWidgets.QPushButton(parent=self.widget_Scanbox) - self.pushButton_NewFirstScan.setObjectName("pushButton_NewFirstScan") - self.horizontalLayout_ScanButtons.addWidget(self.pushButton_NewFirstScan) - self.pushButton_NextScan = QtWidgets.QPushButton(parent=self.widget_Scanbox) - self.pushButton_NextScan.setObjectName("pushButton_NextScan") - self.horizontalLayout_ScanButtons.addWidget(self.pushButton_NextScan) - spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_ScanButtons.addItem(spacerItem3) - self.pushButton_CancelScan = QtWidgets.QPushButton(parent=self.widget_Scanbox) - self.pushButton_CancelScan.setObjectName("pushButton_CancelScan") - self.horizontalLayout_ScanButtons.addWidget(self.pushButton_CancelScan) - self.pushButton_UndoScan = QtWidgets.QPushButton(parent=self.widget_Scanbox) - self.pushButton_UndoScan.setObjectName("pushButton_UndoScan") - self.horizontalLayout_ScanButtons.addWidget(self.pushButton_UndoScan) - self.verticalLayout_5.addLayout(self.horizontalLayout_ScanButtons) - self.widget_ScanFields = QtWidgets.QWidget(parent=self.widget_Scanbox) - self.widget_ScanFields.setObjectName("widget_ScanFields") - self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.widget_ScanFields) - self.horizontalLayout_7.setContentsMargins(0, -1, 0, 0) - self.horizontalLayout_7.setObjectName("horizontalLayout_7") - self.checkBox_Hex = QtWidgets.QCheckBox(parent=self.widget_ScanFields) - self.checkBox_Hex.setObjectName("checkBox_Hex") - self.horizontalLayout_7.addWidget(self.checkBox_Hex) - self.lineEdit_Scan = QtWidgets.QLineEdit(parent=self.widget_ScanFields) - self.lineEdit_Scan.setObjectName("lineEdit_Scan") - self.horizontalLayout_7.addWidget(self.lineEdit_Scan) - self.label_Between = QtWidgets.QLabel(parent=self.widget_ScanFields) - self.label_Between.setText("<->") - self.label_Between.setObjectName("label_Between") - self.horizontalLayout_7.addWidget(self.label_Between) - self.lineEdit_Scan2 = QtWidgets.QLineEdit(parent=self.widget_ScanFields) - self.lineEdit_Scan2.setObjectName("lineEdit_Scan2") - self.horizontalLayout_7.addWidget(self.lineEdit_Scan2) - self.verticalLayout_5.addWidget(self.widget_ScanFields) - self.horizontalLayout_ScanOptions = QtWidgets.QHBoxLayout() - self.horizontalLayout_ScanOptions.setObjectName("horizontalLayout_ScanOptions") - self.widget_ScanOptions = QtWidgets.QWidget(parent=self.widget_Scanbox) - self.widget_ScanOptions.setObjectName("widget_ScanOptions") - self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.widget_ScanOptions) - self.verticalLayout_4.setObjectName("verticalLayout_4") - self.horizontalLayout_ScanType = QtWidgets.QHBoxLayout() - self.horizontalLayout_ScanType.setObjectName("horizontalLayout_ScanType") - self.label_ScanType = QtWidgets.QLabel(parent=self.widget_ScanOptions) - self.label_ScanType.setObjectName("label_ScanType") - self.horizontalLayout_ScanType.addWidget(self.label_ScanType) - self.comboBox_ScanType = QtWidgets.QComboBox(parent=self.widget_ScanOptions) - self.comboBox_ScanType.setObjectName("comboBox_ScanType") - self.horizontalLayout_ScanType.addWidget(self.comboBox_ScanType) - self.verticalLayout_4.addLayout(self.horizontalLayout_ScanType) - self.horizontalLayout_ValueType = QtWidgets.QHBoxLayout() - self.horizontalLayout_ValueType.setObjectName("horizontalLayout_ValueType") - self.label_ValueType = QtWidgets.QLabel(parent=self.widget_ScanOptions) - self.label_ValueType.setObjectName("label_ValueType") - self.horizontalLayout_ValueType.addWidget(self.label_ValueType) - self.comboBox_ValueType = QtWidgets.QComboBox(parent=self.widget_ScanOptions) - self.comboBox_ValueType.setObjectName("comboBox_ValueType") - self.horizontalLayout_ValueType.addWidget(self.comboBox_ValueType) - self.verticalLayout_4.addLayout(self.horizontalLayout_ValueType) - self.horizontalLayout_ScanScope = QtWidgets.QHBoxLayout() - self.horizontalLayout_ScanScope.setObjectName("horizontalLayout_ScanScope") - self.label_ScanScope = QtWidgets.QLabel(parent=self.widget_ScanOptions) - self.label_ScanScope.setObjectName("label_ScanScope") - self.horizontalLayout_ScanScope.addWidget(self.label_ScanScope) - self.comboBox_ScanScope = QtWidgets.QComboBox(parent=self.widget_ScanOptions) - self.comboBox_ScanScope.setObjectName("comboBox_ScanScope") - self.horizontalLayout_ScanScope.addWidget(self.comboBox_ScanScope) - self.verticalLayout_4.addLayout(self.horizontalLayout_ScanScope) - self.horizontalLayout_Endianness = QtWidgets.QHBoxLayout() - self.horizontalLayout_Endianness.setObjectName("horizontalLayout_Endianness") - self.label_Endianness = QtWidgets.QLabel(parent=self.widget_ScanOptions) - self.label_Endianness.setObjectName("label_Endianness") - self.horizontalLayout_Endianness.addWidget(self.label_Endianness) - self.comboBox_Endianness = QtWidgets.QComboBox(parent=self.widget_ScanOptions) - self.comboBox_Endianness.setObjectName("comboBox_Endianness") - self.horizontalLayout_Endianness.addWidget(self.comboBox_Endianness) - self.verticalLayout_4.addLayout(self.horizontalLayout_Endianness) - self.horizontalLayout_Alignment = QtWidgets.QHBoxLayout() - self.horizontalLayout_Alignment.setObjectName("horizontalLayout_Alignment") - self.label_Alignment = QtWidgets.QLabel(parent=self.widget_ScanOptions) - self.label_Alignment.setObjectName("label_Alignment") - self.horizontalLayout_Alignment.addWidget(self.label_Alignment) - self.comboBox_Alignment = QtWidgets.QComboBox(parent=self.widget_ScanOptions) - self.comboBox_Alignment.setObjectName("comboBox_Alignment") - self.horizontalLayout_Alignment.addWidget(self.comboBox_Alignment) - self.verticalLayout_4.addLayout(self.horizontalLayout_Alignment) - self.pushButton_ScanRegions = QtWidgets.QPushButton(parent=self.widget_ScanOptions) - self.pushButton_ScanRegions.setObjectName("pushButton_ScanRegions") - self.verticalLayout_4.addWidget(self.pushButton_ScanRegions) - spacerItem4 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_4.addItem(spacerItem4) - self.horizontalLayout_ScanOptions.addWidget(self.widget_ScanOptions) - self.widget_VerticalSpacer = QtWidgets.QWidget(parent=self.widget_Scanbox) - self.widget_VerticalSpacer.setObjectName("widget_VerticalSpacer") - self.verticalLayout = QtWidgets.QVBoxLayout(self.widget_VerticalSpacer) - self.verticalLayout.setContentsMargins(0, 0, 0, 0) - self.verticalLayout.setSpacing(0) - self.verticalLayout.setObjectName("verticalLayout") - self.verticalLayout_3 = QtWidgets.QVBoxLayout() - self.verticalLayout_3.setObjectName("verticalLayout_3") - self.checkBox_Speedhack = QtWidgets.QCheckBox(parent=self.widget_VerticalSpacer) - self.checkBox_Speedhack.setObjectName("checkBox_Speedhack") - self.verticalLayout_3.addWidget(self.checkBox_Speedhack) - self.doubleSpinBox_Speedhack = QtWidgets.QDoubleSpinBox(parent=self.widget_VerticalSpacer) - self.doubleSpinBox_Speedhack.setEnabled(False) - self.doubleSpinBox_Speedhack.setDecimals(1) - self.doubleSpinBox_Speedhack.setMinimum(0.2) - self.doubleSpinBox_Speedhack.setMaximum(10.0) - self.doubleSpinBox_Speedhack.setSingleStep(0.1) - self.doubleSpinBox_Speedhack.setProperty("value", 1.0) - self.doubleSpinBox_Speedhack.setObjectName("doubleSpinBox_Speedhack") - self.verticalLayout_3.addWidget(self.doubleSpinBox_Speedhack) - spacerItem5 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_3.addItem(spacerItem5) - self.verticalLayout.addLayout(self.verticalLayout_3) - self.horizontalLayout_ScanOptions.addWidget(self.widget_VerticalSpacer) - self.verticalLayout_5.addLayout(self.horizontalLayout_ScanOptions) - self.horizontalLayout_9.addWidget(self.widget_Scanbox) - self.gridLayout.addLayout(self.horizontalLayout_9, 1, 0, 1, 1) - self.horizontalLayout_11 = QtWidgets.QHBoxLayout() - self.horizontalLayout_11.setObjectName("horizontalLayout_11") - spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_11.addItem(spacerItem6) - self.pushButton_Notes = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_Notes.setObjectName("pushButton_Notes") - self.horizontalLayout_11.addWidget(self.pushButton_Notes) - self.gridLayout.addLayout(self.horizontalLayout_11, 4, 0, 1, 1) - self.horizontalLayout_5 = QtWidgets.QHBoxLayout() - self.horizontalLayout_5.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetFixedSize) - self.horizontalLayout_5.setObjectName("horizontalLayout_5") - self.pushButton_AttachProcess = QtWidgets.QPushButton(parent=self.centralwidget) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Minimum) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.pushButton_AttachProcess.sizePolicy().hasHeightForWidth()) - self.pushButton_AttachProcess.setSizePolicy(sizePolicy) - self.pushButton_AttachProcess.setText("") - self.pushButton_AttachProcess.setObjectName("pushButton_AttachProcess") - self.horizontalLayout_5.addWidget(self.pushButton_AttachProcess) - self.pushButton_Open = QtWidgets.QPushButton(parent=self.centralwidget) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Minimum) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.pushButton_Open.sizePolicy().hasHeightForWidth()) - self.pushButton_Open.setSizePolicy(sizePolicy) - self.pushButton_Open.setText("") - self.pushButton_Open.setObjectName("pushButton_Open") - self.horizontalLayout_5.addWidget(self.pushButton_Open) - self.pushButton_Save = QtWidgets.QPushButton(parent=self.centralwidget) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Minimum) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.pushButton_Save.sizePolicy().hasHeightForWidth()) - self.pushButton_Save.setSizePolicy(sizePolicy) - self.pushButton_Save.setText("") - self.pushButton_Save.setObjectName("pushButton_Save") - self.horizontalLayout_5.addWidget(self.pushButton_Save) - self.pushButton_Wiki = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_Wiki.setText("") - self.pushButton_Wiki.setObjectName("pushButton_Wiki") - self.horizontalLayout_5.addWidget(self.pushButton_Wiki) - self.pushButton_About = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_About.setText("") - self.pushButton_About.setObjectName("pushButton_About") - self.horizontalLayout_5.addWidget(self.pushButton_About) - self.label_SelectedProcess = QtWidgets.QLabel(parent=self.centralwidget) - self.label_SelectedProcess.setObjectName("label_SelectedProcess") - self.horizontalLayout_5.addWidget(self.label_SelectedProcess) - self.label_InferiorStatus = QtWidgets.QLabel(parent=self.centralwidget) - self.label_InferiorStatus.setText("") - self.label_InferiorStatus.setObjectName("label_InferiorStatus") - self.horizontalLayout_5.addWidget(self.label_InferiorStatus) - self.progressBar = QtWidgets.QProgressBar(parent=self.centralwidget) - self.progressBar.setProperty("value", 0) - self.progressBar.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.progressBar.setObjectName("progressBar") - self.horizontalLayout_5.addWidget(self.progressBar) - self.pushButton_Console = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_Console.setText("") - self.pushButton_Console.setObjectName("pushButton_Console") - self.horizontalLayout_5.addWidget(self.pushButton_Console) - self.pushButton_CheckForUpdates = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_CheckForUpdates.setEnabled(False) - self.pushButton_CheckForUpdates.setText("") - self.pushButton_CheckForUpdates.setObjectName("pushButton_CheckForUpdates") - self.horizontalLayout_5.addWidget(self.pushButton_CheckForUpdates) - self.pushButton_Settings = QtWidgets.QPushButton(parent=self.centralwidget) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Minimum) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.pushButton_Settings.sizePolicy().hasHeightForWidth()) - self.pushButton_Settings.setSizePolicy(sizePolicy) - self.pushButton_Settings.setText("") - self.pushButton_Settings.setObjectName("pushButton_Settings") - self.horizontalLayout_5.addWidget(self.pushButton_Settings) - self.gridLayout.addLayout(self.horizontalLayout_5, 0, 0, 1, 1) - MainWindow.setCentralWidget(self.centralwidget) - self.menubar = QtWidgets.QMenuBar(parent=MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 768, 32)) - self.menubar.setObjectName("menubar") - MainWindow.setMenuBar(self.menubar) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - _translate = QtCore.QCoreApplication.translate - self.pushButton_MemoryView.setText(_translate("MainWindow", "Memory View")) - self.pushButton_CopyToAddressTable.setToolTip(_translate("MainWindow", "Copy selected items to the address table")) - self.pushButton_CleanAddressTable.setToolTip(_translate("MainWindow", "Erase all the table contents")) - self.pushButton_RefreshAddressTable.setToolTip(_translate("MainWindow", "Refresh the address table[R]")) - self.pushButton_AddAddressManually.setText(_translate("MainWindow", "Add Address Manually")) - self.treeWidget_AddressTable.setSortingEnabled(True) - self.treeWidget_AddressTable.headerItem().setText(0, _translate("MainWindow", "Freeze")) - self.treeWidget_AddressTable.headerItem().setToolTip(0, _translate("MainWindow", "Freeze the value. Click just to the right of checkbox to cycle between freeze types:\n" -"- No arrow: Frozen at current value\n" -"- ▲: Allow increments only\n" -"- ▼: Allow decrements only")) - self.treeWidget_AddressTable.headerItem().setText(1, _translate("MainWindow", "Description")) - self.treeWidget_AddressTable.headerItem().setText(2, _translate("MainWindow", "Address")) - self.treeWidget_AddressTable.headerItem().setText(3, _translate("MainWindow", "Type")) - self.treeWidget_AddressTable.headerItem().setText(4, _translate("MainWindow", "Value")) - self.label_MatchCount.setText(_translate("MainWindow", "Match count: 0")) - self.tableWidget_valuesearchtable.setSortingEnabled(True) - item = self.tableWidget_valuesearchtable.horizontalHeaderItem(0) - item.setText(_translate("MainWindow", "Address")) - item = self.tableWidget_valuesearchtable.horizontalHeaderItem(1) - item.setText(_translate("MainWindow", "Value")) - item = self.tableWidget_valuesearchtable.horizontalHeaderItem(2) - item.setText(_translate("MainWindow", "Previous")) - self.pushButton_NewFirstScan.setText(_translate("MainWindow", "First Scan")) - self.pushButton_NextScan.setText(_translate("MainWindow", "Next Scan")) - self.pushButton_CancelScan.setText(_translate("MainWindow", "Cancel Scan")) - self.pushButton_UndoScan.setText(_translate("MainWindow", "Undo Scan")) - self.checkBox_Hex.setText(_translate("MainWindow", "Hex")) - self.label_ScanType.setText(_translate("MainWindow", "Scan Type:")) - self.label_ValueType.setText(_translate("MainWindow", "Value Type:")) - self.label_ScanScope.setText(_translate("MainWindow", "Scan Scope:")) - self.label_Endianness.setText(_translate("MainWindow", "Endianness:")) - self.label_Alignment.setText(_translate("MainWindow", "Alignment:")) - self.pushButton_ScanRegions.setText(_translate("MainWindow", "Manage Scan Regions")) - self.checkBox_Speedhack.setText(_translate("MainWindow", "Enable Speedhack")) - self.pushButton_Notes.setToolTip(_translate("MainWindow", "Open session notes")) - self.pushButton_Notes.setText(_translate("MainWindow", "Notes")) - self.pushButton_AttachProcess.setToolTip(_translate("MainWindow", "Create or attach to a process")) - self.pushButton_Open.setToolTip(_translate("MainWindow", "Open a cheat table")) - self.pushButton_Save.setToolTip(_translate("MainWindow", "Save current table to a file")) - self.pushButton_Wiki.setToolTip(_translate("MainWindow", "Wiki")) - self.pushButton_About.setToolTip(_translate("MainWindow", "About")) - self.label_SelectedProcess.setText(_translate("MainWindow", "No Process Selected")) - self.pushButton_Console.setToolTip(_translate("MainWindow", "Open a gdb console")) - self.pushButton_CheckForUpdates.setToolTip(_translate("MainWindow", "Check for updates")) - self.pushButton_Settings.setToolTip(_translate("MainWindow", "Configure options")) -from GUI.TreeWidgets.AddressTree import AddressTree diff --git a/GUI/Widgets/MainWindow/MainWindow.py b/GUI/Widgets/MainWindow/MainWindow.py deleted file mode 100644 index a7662217..00000000 --- a/GUI/Widgets/MainWindow/MainWindow.py +++ /dev/null @@ -1,2102 +0,0 @@ -from PyQt6.QtWidgets import QMainWindow, QTableWidgetItem, QTreeWidgetItem, QTreeWidgetItemIterator, QMenu, QMessageBox, QCheckBox, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QIcon, QPixmap, QBrush, QColor, QKeyEvent, QMouseEvent, QContextMenuEvent, QCloseEvent -from PyQt6.QtCore import Qt, QTimer, QSettings, QKeyCombination, pyqtSignal -from GUI.Session.session import SessionDataChanged, SessionManager, StructureManager -from GUI.Settings import settings -from GUI.States import states -from GUI.Utils import guitypedefs, guiutils, update_check, utilwidgets -from GUI.Widgets.About.About import AboutWidget -from GUI.Widgets.Console.Console import ConsoleWidget -from GUI.Widgets.EditType.EditType import EditTypeDialog -from GUI.Widgets.LibpinceEngine.LibpinceEngine import LibpinceEngineWindow, create_script_namespace, parse_script_sections, run_script_code -from GUI.Widgets.MainWindow.Form.MainWindow import Ui_MainWindow -from GUI.Widgets.ManageScanRegions.ManageScanRegions import ManageScanRegionsDialog -from GUI.Widgets.ManualAddress.ManualAddress import ManualAddressDialog -from GUI.Widgets.MemoryView.MemoryView import MemoryViewWindow -from GUI.Widgets.PointerScan.PointerScan import PointerScanWindow -from GUI.Widgets.PointerScanSearch.PointerScanSearch import PointerScanSearchDialog -from GUI.Widgets.SelectProcess.SelectProcess import SelectProcessWindow -from GUI.Widgets.SessionNotes.SessionNotes import SessionNotesWidget -from GUI.Widgets.Settings.Settings import SettingsDialog -from GUI.Widgets.Structures.StructuresWindow import StructuresWindow -from GUI.Widgets.Structures.StructureViewDialog import StructureViewDialog -from GUI.Widgets.TrackSelector.TrackSelector import TrackSelectorDialog -from GUI.Widgets.TrackWatchpoint.TrackWatchpoint import TrackWatchpointWidget -from libpince import debugcore, monocore, scancore, speedhack, typedefs, utils -from libpince.libmemscan.memscan import DataType, BytePattern -from libpince.scancore import memscan -from libpince.utils import logger -from tr.tr import TranslationConstants as tr -from typing import Any -import ast, collections, copy, os, re, sys, traceback - -# represents the index of columns in address table -FROZEN_COL = 0 # Frozen -DESC_COL = 1 # Description -ADDR_COL = 2 # Address -TYPE_COL = 3 # Type -VALUE_COL = 4 # Value - -# represents the index of columns in search results table -SEARCH_TABLE_ADDRESS_COL = 0 -SEARCH_TABLE_VALUE_COL = 1 -SEARCH_TABLE_PREVIOUS_COL = 2 - - -class MainWindow(QMainWindow, Ui_MainWindow): - # Workaround to avoid race condition with temporary interrupt execution decorator. - # Routes speedhack hotkeys from the keyboard thread back onto the Qt main thread. - # Payload is the step delta: -1 = down, 0 = toggle, +1 = up. - speedhack_action_requested = pyqtSignal(int) - - # Payload is the toggle_attach() result (a typedefs.TOGGLE_ATTACH member or None on failure). - attach_toggled = pyqtSignal(object) - - # Payload is the requested SCAN_TYPE - nextscan_requested = pyqtSignal(int) - - def __init__(self) -> None: - super().__init__() - self.setupUi(self) - self.doubleSpinBox_Speedhack.setFocusPolicy(Qt.FocusPolicy.ClickFocus) - self.update_check_thread: update_check.UpdateCheckThread | None = None - self.show_update_check_result = True - self.deleted_regions: list[int] = [] - self.is_wine_process = False - self.speedhack: speedhack.LinuxSpeedhack | speedhack.WineSpeedhack | None = None - self.speedhack_action_requested.connect(self.on_speedhack_hotkey_action) - self.attach_toggled.connect(self.on_attach_toggled) - self.nextscan_requested.connect(self.on_nextscan_requested) - self.checkBox_Speedhack.toggled.connect(self.apply_speedhack) - self.doubleSpinBox_Speedhack.valueChanged.connect(self.apply_speedhack) - hotkey_to_func = { - states.hotkeys.pause_hotkey: self.pause_hotkey_pressed, - states.hotkeys.break_hotkey: self.break_hotkey_pressed, - states.hotkeys.continue_hotkey: self.continue_hotkey_pressed, - states.hotkeys.cancel_hotkey: self.cancel_hotkey_pressed, - states.hotkeys.toggle_attach_hotkey: self.toggle_attach_hotkey_pressed, - states.hotkeys.speedhack_toggle_hotkey: self.speedhack_toggle_hotkey_pressed, - states.hotkeys.speedhack_speed_up_hotkey: self.speedhack_speed_up_hotkey_pressed, - states.hotkeys.speedhack_speed_down_hotkey: self.speedhack_speed_down_hotkey_pressed, - states.hotkeys.exact_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.EXACT), - states.hotkeys.not_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.NOT), - states.hotkeys.increased_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.INCREASED), - states.hotkeys.increased_by_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.INCREASED_BY), - states.hotkeys.decreased_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.DECREASED), - states.hotkeys.decreased_by_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.DECREASED_BY), - states.hotkeys.less_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.LESS), - states.hotkeys.more_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.MORE), - states.hotkeys.between_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.BETWEEN), - states.hotkeys.changed_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.CHANGED), - states.hotkeys.unchanged_scan_hotkey: lambda: self.nextscan_hotkey_pressed(typedefs.SCAN_TYPE.UNCHANGED), - } - for hotkey, func in hotkey_to_func.items(): - hotkey.change_func(func) - self.treeWidget_AddressTable.setColumnWidth(FROZEN_COL, 50) - self.treeWidget_AddressTable.setColumnWidth(DESC_COL, 150) - self.treeWidget_AddressTable.setColumnWidth(ADDR_COL, 150) - self.treeWidget_AddressTable.setColumnWidth(TYPE_COL, 150) - self.tableWidget_valuesearchtable.setColumnWidth(SEARCH_TABLE_ADDRESS_COL, 120) - self.tableWidget_valuesearchtable.setColumnWidth(SEARCH_TABLE_VALUE_COL, 80) - self.tableWidget_valuesearchtable.horizontalHeader().setSortIndicatorClearable(True) - self.await_exit_thread = guitypedefs.AwaitProcessExit() - self.auto_attach_timer = QTimer(self, timeout=self.auto_attach_loop) - - settings.init_settings() - self.settings_changed() - self.memory_view_window = MemoryViewWindow(self) - self.session_notes = SessionNotesWidget(None) - - if os.environ.get("APPDIR"): - gdb_path = utils.get_default_gdb_path() - else: - gdb_path = states.gdb_path - if debugcore.init_gdb(gdb_path): - settings.apply_after_init() - else: - utilwidgets.InputDialog(self, tr.GDB_INIT_ERROR, cancel_button=False).exec() - self.await_exit_thread.process_exited.connect(self.on_inferior_exit) - self.await_exit_thread.start() - states.status_thread.process_stopped.connect(self.on_status_stopped) - states.status_thread.process_running.connect(self.on_status_running) - states.setting_signals.changed.connect(self.settings_changed) - self.address_table_timer = QTimer(self, timeout=self.address_table_loop, singleShot=True) - self.address_table_timer.start() - self.search_table_timer = QTimer(self, timeout=self.search_table_loop, singleShot=True) - self.search_table_timer.start() - self.freeze_timer = QTimer(self, timeout=self.freeze_loop, singleShot=True) - self.freeze_timer.start() - self.shortcut_open_file = QShortcut(QKeySequence("Ctrl+O"), self) - self.shortcut_open_file.activated.connect(SessionManager.load_session) - guiutils.append_shortcut_to_tooltip(self.pushButton_Open, self.shortcut_open_file) - self.shortcut_save_file = QShortcut(QKeySequence("Ctrl+S"), self) - self.shortcut_save_file.activated.connect(SessionManager.save_session) - guiutils.append_shortcut_to_tooltip(self.pushButton_Save, self.shortcut_save_file) - - # Saving the original function because super() doesn't work when we override functions like this - self.treeWidget_AddressTable_mouseReleaseEvent_original = self.treeWidget_AddressTable.mouseReleaseEvent - self.treeWidget_AddressTable.mouseReleaseEvent = self.treeWidget_AddressTable_mouse_release_event - self.treeWidget_AddressTable_keyPressEvent_original = self.treeWidget_AddressTable.keyPressEvent - self.treeWidget_AddressTable.keyPressEvent = self.treeWidget_AddressTable_key_press_event - self.treeWidget_AddressTable.contextMenuEvent = self.treeWidget_AddressTable_context_menu_event - self.pushButton_AttachProcess.clicked.connect(self.pushButton_AttachProcess_clicked) - self.pushButton_Open.clicked.connect(SessionManager.load_session) - self.pushButton_Save.clicked.connect(SessionManager.save_session) - states.session_signals.on_save.connect(self.on_session_save) - states.session_signals.on_load.connect(self.on_session_loaded) - states.session_signals.new_session.connect(self.on_new_session) - self.session = SessionManager.get_session() - self.pushButton_CheckForUpdates.clicked.connect(lambda: self.check_for_updates()) - if os.environ.get("APPDIR"): - self._set_update_button_enabled(True) - self.update_check_timer = QTimer(self, timeout=self.check_for_updates_on_startup, singleShot=True) - self.update_check_timer.start(500) - else: - self.pushButton_CheckForUpdates.hide() - self.libpince_engine_window: LibpinceEngineWindow | None = None - self.structures_window: StructuresWindow | None = None - self.pushButton_NewFirstScan.clicked.connect(self.pushButton_NewFirstScan_clicked) - self.pushButton_UndoScan.clicked.connect(self.pushButton_UndoScan_clicked) - self.pushButton_CancelScan.clicked.connect(self.pushButton_CancelScan_clicked) - self.pushButton_NextScan.clicked.connect(self.pushButton_NextScan_clicked) - self.pushButton_ScanRegions.clicked.connect(self.pushButton_ScanRegions_clicked) - self.scan_mode = typedefs.SCAN_MODE.NEW - self.pushButton_NewFirstScan_clicked() - self.comboBox_ScanScope_init() - self.comboBox_ValueType_init() - guiutils.fill_endianness_combobox(self.comboBox_Endianness) - guiutils.fill_alignment_combobox(self.comboBox_Alignment) - self.comboBox_Endianness.currentIndexChanged.connect(self.on_endianness_changed) - self.comboBox_Alignment.currentIndexChanged.connect(self.comboBox_Alignment_current_index_changed) - self.checkBox_Hex.stateChanged.connect(self.checkBox_Hex_stateChanged) - self.comboBox_ValueType.currentIndexChanged.connect(self.comboBox_ValueType_current_index_changed) - self.lineEdit_Scan.setValidator(guiutils.validator_map.get("int")) - self.lineEdit_Scan2.setValidator(guiutils.validator_map.get("int")) - self.lineEdit_Scan_keyPressEvent_original = self.lineEdit_Scan.keyPressEvent - self.lineEdit_Scan2_keyPressEvent_original = self.lineEdit_Scan2.keyPressEvent - self.lineEdit_Scan.keyPressEvent = self.lineEdit_Scan_on_key_press_event - self.lineEdit_Scan2.keyPressEvent = self.lineEdit_Scan2_on_key_press_event - self.comboBox_ScanType.currentIndexChanged.connect(self.comboBox_ScanType_current_index_changed) - self.comboBox_ScanType_current_index_changed() - self.pushButton_Settings.clicked.connect(self.pushButton_Settings_clicked) - self.pushButton_Console.clicked.connect(self.pushButton_Console_clicked) - self.pushButton_Wiki.clicked.connect(self.pushButton_Wiki_clicked) - self.pushButton_About.clicked.connect(self.pushButton_About_clicked) - self.pushButton_AddAddressManually.clicked.connect(self.pushButton_AddAddressManually_clicked) - self.pushButton_MemoryView.clicked.connect(self.pushButton_MemoryView_clicked) - self.pushButton_RefreshAddressTable.clicked.connect(self.pushButton_RefreshAddressTable_clicked) - self.pushButton_CopyToAddressTable.clicked.connect(self.copy_to_address_table) - self.pushButton_CleanAddressTable.clicked.connect(self.clear_address_table) - self.tableWidget_valuesearchtable.cellDoubleClicked.connect(self.tableWidget_valuesearchtable_cell_double_clicked) - self.tableWidget_valuesearchtable_keyPressEvent_original = self.tableWidget_valuesearchtable.keyPressEvent - self.tableWidget_valuesearchtable.keyPressEvent = self.tableWidget_valuesearchtable_key_press_event - self.tableWidget_valuesearchtable.contextMenuEvent = self.tableWidget_valuesearchtable_context_menu_event - self.treeWidget_AddressTable.itemDoubleClicked.connect(self.treeWidget_AddressTable_item_double_clicked) - self.treeWidget_AddressTable.expanded.connect(self.resize_address_table) - self.treeWidget_AddressTable.collapsed.connect(self.resize_address_table) - self.treeWidget_AddressTable.header().setSortIndicatorClearable(True) - self.treeWidget_AddressTable.header().setSortIndicator(-1, Qt.SortOrder.AscendingOrder) # Clear sort indicator - icons_directory = guiutils.get_icons_directory() - self.pushButton_AttachProcess.setIcon(QIcon(QPixmap(icons_directory + "/monitor.png"))) - self.pushButton_Open.setIcon(QIcon(QPixmap(icons_directory + "/folder.png"))) - self.pushButton_Save.setIcon(QIcon(QPixmap(icons_directory + "/disk.png"))) - self.pushButton_CheckForUpdates.setIcon(QIcon(QPixmap(icons_directory + "/arrow_refresh.png"))) - self.pushButton_Settings.setIcon(QIcon(QPixmap(icons_directory + "/wrench.png"))) - self.pushButton_CopyToAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/arrow_down.png"))) - self.pushButton_CleanAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/bin_closed.png"))) - self.pushButton_RefreshAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/table_refresh.png"))) - self.pushButton_Console.setIcon(QIcon(QPixmap(icons_directory + "/application_xp_terminal.png"))) - self.pushButton_Wiki.setIcon(QIcon(QPixmap(icons_directory + "/book_open.png"))) - self.pushButton_About.setIcon(QIcon(QPixmap(icons_directory + "/information.png"))) - self.pushButton_NextScan.setEnabled(False) - self.pushButton_UndoScan.setEnabled(False) - self.pushButton_CancelScan.setEnabled(False) - self.flashAttachButton = True - self.flashAttachButtonTimer = QTimer(self) - self.flashAttachButtonTimer.timeout.connect(self.flash_attach_button) - self.flashAttachButton_gradientState = 0 - self.flashAttachButtonTimer.start(100) - self.is_scanning = False - self.undo_scan_available = False - - self.pushButton_Notes.clicked.connect(self.session_notes.toggle_visibility) - guiutils.center(self) - - def settings_changed(self) -> None: - if states.auto_attach: - self.auto_attach_timer.start(100) - else: - self.auto_attach_timer.stop() - - # Check if any process should be attached to automatically - # Patterns at former positions have higher priority if regex is off - def auto_attach_loop(self) -> None: - if debugcore.currentpid != -1: - return - if states.auto_attach_regex: - try: - compiled_re = re.compile(states.auto_attach) - except: - logger.exception(f"Auto-attach failed: {states.auto_attach} isn't a valid regex") - return - for pid, _, name in utils.get_process_list(): - if compiled_re.search(name): - self.attach_to_pid(int(pid)) - return - else: - for target in filter(None, map(str.strip, states.auto_attach.split(";"))): - for pid, _, name in utils.get_process_list(): - if name.find(target) != -1: - self.attach_to_pid(int(pid)) - return - - # Keyboard package has an issue with exceptions, any trigger function that throws an exception stops the event loop - # Writing a custom event loop instead of ignoring exceptions could work as well but honestly, this looks cleaner - # Keyboard package does not play well with Qt, do not use anything Qt related with hotkeys - # Instead of using Qt functions, try to use their signals to prevent crashes - @utils.ignore_exceptions - def pause_hotkey_pressed(self) -> None: - if not debugcore.driving_inferior: - debugcore.interrupt_inferior(typedefs.STOP_REASON.PAUSE) - - @utils.ignore_exceptions - def break_hotkey_pressed(self) -> None: - if not debugcore.driving_inferior: - debugcore.interrupt_inferior() - - @utils.ignore_exceptions - def continue_hotkey_pressed(self) -> None: - if not (debugcore.currentpid == -1 or debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING or debugcore.driving_inferior): - debugcore.continue_inferior() - - @utils.ignore_exceptions - def cancel_hotkey_pressed(self) -> None: - if debugcore.cancel_ongoing_command(): - logger.info("Cancelled the ongoing GDB command") - - @utils.ignore_exceptions - def toggle_attach_hotkey_pressed(self) -> None: - self.prepare_detach() - self.attach_toggled.emit(debugcore.toggle_attach()) - - def prepare_detach(self) -> None: - if debugcore.currentpid == -1 or not debugcore.is_attached(): - return - self.cleanup_speedhack() - - def sync_attach_state(self) -> None: - if debugcore.currentpid == -1: - return - self.on_attach_toggled(typedefs.TOGGLE_ATTACH.ATTACHED if debugcore.is_attached() else typedefs.TOGGLE_ATTACH.DETACHED) - - def on_attach_toggled(self, result: int | None) -> None: - if not result: - logger.error("Unable to toggle attach") - elif result == typedefs.TOGGLE_ATTACH.DETACHED: - self.on_status_detached() - self.pushButton_MemoryView.setEnabled(False) - self.memory_view_window.close() - else: - self.pushButton_MemoryView.setEnabled(True) - # Attaching back doesn't update the status if the process is already stopped before detachment - with debugcore.status_changed_condition: - debugcore.status_changed_condition.notify_all() - - def speedhack_toggle_hotkey_pressed(self) -> None: - self.speedhack_action_requested.emit(0) - - def speedhack_speed_up_hotkey_pressed(self) -> None: - self.speedhack_action_requested.emit(1) - - def speedhack_speed_down_hotkey_pressed(self) -> None: - self.speedhack_action_requested.emit(-1) - - def cleanup_speedhack(self) -> None: - if self.speedhack is not None: - if self.speedhack.is_installed(): - self.speedhack.set_speed(speedhack.DEFAULT_SPEED) - self.speedhack.reset() - self.reset_speedhack_widgets() - - def on_speedhack_hotkey_action(self, delta: int) -> None: - # We drive the widgets and let their signals run apply_speedhack, so hotkeys and clicks share the same code path. - if debugcore.currentpid == -1 or self.speedhack is None: - return - if delta == 0: - self.checkBox_Speedhack.toggle() - else: - # Up/Down also turns the hack on with the spinbox value becoming the live speed. - if not self.checkBox_Speedhack.isChecked(): - self.checkBox_Speedhack.setChecked(True) - self.doubleSpinBox_Speedhack.setValue(self.doubleSpinBox_Speedhack.value() + delta * speedhack.STEP) - - def apply_speedhack(self, *_: Any) -> None: - # Both widget signals and the hotkeys (via on_speedhack_hotkey_action) funnel through here. - if debugcore.currentpid == -1 or self.speedhack is None: - return - enabled = self.checkBox_Speedhack.isChecked() - self.doubleSpinBox_Speedhack.setEnabled(enabled) - # The hooks stay installed across toggles and we just change the speed, so we patch only once per session. - # Doing so means we avoid racing thread RIPs sitting in the prologue that we'd be overwriting on every keypress, - # which can cause freezes during rapid toggling. - if enabled: - # A failure here is usually a Wine inferior whose ntdll exports couldn't be resolved. - if not self.speedhack.set_speed(self.doubleSpinBox_Speedhack.value()): - QMessageBox.information(self, tr.INFO, tr.SPEEDHACK_UNAVAILABLE) - self.reset_speedhack_widgets() - # Only restore the default speed if the hooks already exist otherwise set_speed would install them. - elif self.speedhack.is_installed(): - self.speedhack.set_speed(speedhack.DEFAULT_SPEED) - - def reset_speedhack_widgets(self) -> None: - self.checkBox_Speedhack.blockSignals(True) - self.doubleSpinBox_Speedhack.blockSignals(True) - self.checkBox_Speedhack.setChecked(False) - self.doubleSpinBox_Speedhack.setValue(speedhack.DEFAULT_SPEED) - self.doubleSpinBox_Speedhack.setEnabled(False) - self.checkBox_Speedhack.blockSignals(False) - self.doubleSpinBox_Speedhack.blockSignals(False) - - def nextscan_hotkey_pressed(self, index: int) -> None: - self.nextscan_requested.emit(index) - - def on_nextscan_requested(self, index: int) -> None: - if self.scan_mode == typedefs.SCAN_MODE.NEW or self.is_scanning: - return - row = self.comboBox_ScanType.findData(index) - if row == -1: - return - self.comboBox_ScanType.setCurrentIndex(row) - self.pushButton_NextScan.clicked.emit() - - def treeWidget_AddressTable_context_menu_event(self, event: QContextMenuEvent) -> None: - current_row = guiutils.get_current_item(self.treeWidget_AddressTable) - current_address = self._resolved_address(current_row) if current_row else None - header = self.treeWidget_AddressTable.headerItem() - menu = QMenu() - delete_record = menu.addAction(f"{tr.DELETE}[Del]") - edit_menu = menu.addMenu(tr.EDIT) - edit_desc = edit_menu.addAction(f"{header.text(DESC_COL)}[Ctrl+Enter]") - edit_address = edit_menu.addAction(f"{header.text(ADDR_COL)}[Ctrl+Alt+Enter]") - edit_type = edit_menu.addAction(f"{header.text(TYPE_COL)}[Alt+Enter]") - edit_value = edit_menu.addAction(f"{header.text(VALUE_COL)}[Enter]") - edit_script = menu.addAction(tr.EDIT_SCRIPT) - view_as_struct_menu = menu.addMenu(tr.VIEW_AS_STRUCT) - structure_names = StructureManager.list_names() - structure_actions = {} - for name in structure_names: - structure_actions[view_as_struct_menu.addAction(name)] = name - show_hex = menu.addAction(tr.SHOW_HEX) - show_dec = menu.addAction(tr.SHOW_DEC) - show_unsigned = menu.addAction(tr.SHOW_UNSIGNED) - show_signed = menu.addAction(tr.SHOW_SIGNED) - toggle_record = menu.addAction(f"{tr.TOGGLE}[Space]") - toggle_children = menu.addAction(f"{tr.TOGGLE_CHILDREN}[Ctrl+Space]") - menu.addSeparator() - browse_region = menu.addAction(f"{tr.BROWSE_MEMORY_REGION}[Ctrl+B]") - disassemble = menu.addAction(f"{tr.DISASSEMBLE_ADDRESS}[Ctrl+D]") - menu.addSeparator() - pointer_scanner = menu.addAction(tr.POINTER_SCANNER) - pointer_scan = menu.addAction(tr.POINTER_SCAN) - menu.addSeparator() - what_writes = menu.addAction(tr.WHAT_WRITES) - what_reads = menu.addAction(tr.WHAT_READS) - what_accesses = menu.addAction(tr.WHAT_ACCESSES) - menu.addSeparator() - cut_record = menu.addAction(f"{tr.CUT}[Ctrl+X]") - copy_record = menu.addAction(f"{tr.COPY}[Ctrl+C]") - paste_record = menu.addAction(f"{tr.PASTE}[Ctrl+V]") - paste_inside = menu.addAction(f"{tr.PASTE_INSIDE}[V]") - menu.addSeparator() - add_group = menu.addAction(tr.ADD_GROUP) - create_group = menu.addAction(tr.CREATE_GROUP) - if current_row is None: - deletion_list = [ - edit_menu.menuAction(), - edit_script, - view_as_struct_menu.menuAction(), - show_hex, - show_dec, - show_unsigned, - show_signed, - toggle_record, - toggle_children, - browse_region, - disassemble, - pointer_scan, - what_writes, - what_reads, - what_accesses, - cut_record, - copy_record, - paste_inside, - delete_record, - add_group, - ] - guiutils.delete_menu_entries(menu, deletion_list) - elif self.get_script_entry(current_row) is not None: - # A script entry only edits its description and script, the rest is address oriented - script_deletion = [ - edit_address, - edit_type, - edit_value, - view_as_struct_menu.menuAction(), - show_hex, - show_dec, - show_unsigned, - show_signed, - browse_region, - disassemble, - pointer_scanner, - pointer_scan, - what_writes, - what_reads, - what_accesses, - ] - if current_row.childCount() == 0: - script_deletion.append(toggle_children) - guiutils.delete_menu_entries(menu, script_deletion) - else: - guiutils.delete_menu_entries(menu, [edit_script]) - if not structure_names: - guiutils.delete_menu_entries(menu, [view_as_struct_menu.menuAction()]) - value_type = current_row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - if self._is_struct_row(current_row): # struct rows have no editable value or type, only an address. - guiutils.delete_menu_entries( - menu, - [edit_value, edit_type, view_as_struct_menu.menuAction(), what_writes, what_reads, what_accesses], - ) - if isinstance(value_type, (typedefs.IntegerValueType, typedefs.BitFieldValueType)): - if value_type.value_repr is typedefs.VALUE_REPR.HEX: - guiutils.delete_menu_entries(menu, [show_unsigned, show_signed, show_hex]) - elif value_type.value_repr is typedefs.VALUE_REPR.UNSIGNED: - guiutils.delete_menu_entries(menu, [show_unsigned, show_dec]) - elif value_type.value_repr is typedefs.VALUE_REPR.SIGNED: - guiutils.delete_menu_entries(menu, [show_signed, show_dec]) - else: - guiutils.delete_menu_entries(menu, [show_hex, show_dec, show_unsigned, show_signed]) - if current_row.childCount() == 0: - guiutils.delete_menu_entries(menu, [toggle_children]) - guiutils.delete_menu_entries(menu, [pointer_scanner]) - if debugcore.currentpid == -1: - browse_region.setEnabled(False) - disassemble.setEnabled(False) - pointer_scan.setEnabled(False) - if not debugcore.is_attached(): - what_writes.setEnabled(False) - what_reads.setEnabled(False) - what_accesses.setEnabled(False) - font_size = self.treeWidget_AddressTable.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - delete_record: self.delete_records, - edit_desc: self.treeWidget_AddressTable_edit_desc, - edit_address: self.treeWidget_AddressTable_edit_address, - edit_type: self.treeWidget_AddressTable_edit_type, - edit_value: self.treeWidget_AddressTable_edit_value, - edit_script: lambda: self.open_script_entry_in_engine(current_row, self.get_script_entry(current_row)), - show_hex: lambda: self.treeWidget_AddressTable_change_repr(typedefs.VALUE_REPR.HEX), - show_dec: lambda: self.treeWidget_AddressTable_change_repr(typedefs.VALUE_REPR.UNSIGNED), - show_unsigned: lambda: self.treeWidget_AddressTable_change_repr(typedefs.VALUE_REPR.UNSIGNED), - show_signed: lambda: self.treeWidget_AddressTable_change_repr(typedefs.VALUE_REPR.SIGNED), - toggle_record: self.toggle_records, - toggle_children: lambda: self.toggle_records(True), - browse_region: lambda: self.browse_region_for_address(current_address), - disassemble: lambda: self.disassemble_for_address(current_address), - pointer_scanner: self.exec_pointer_scanner, - pointer_scan: self.exec_pointer_scan, - what_writes: lambda: self.exec_track_watchpoint_widget(typedefs.WATCHPOINT_TYPE.WRITE_ONLY), - what_reads: lambda: self.exec_track_watchpoint_widget(typedefs.WATCHPOINT_TYPE.READ_ONLY), - what_accesses: lambda: self.exec_track_watchpoint_widget(typedefs.WATCHPOINT_TYPE.BOTH), - cut_record: self.cut_records, - copy_record: self.copy_records, - paste_record: self.paste_records, - paste_inside: lambda: self.paste_records(True), - add_group: self.group_records, - create_group: self.create_group, - } - for struct_action, struct_name in structure_actions.items(): - actions[struct_action] = lambda n=struct_name: self._view_struct_at_row(current_row, n) - try: - actions[action]() - except KeyError: - pass - - def _view_struct_at_row(self, row: QTreeWidgetItem, structure_name: str) -> None: - if row is None: - return - resolved_address = self._resolved_address(row) - view = StructureViewDialog(self, structure_name, resolved_address) - view.add_to_table_requested.connect(self._add_structure_records_to_table) - view.show() - - def exec_pointer_scanner(self) -> None: - pointer_window = PointerScanWindow(self, "0x0") - pointer_window.show() - - def exec_pointer_scan(self) -> None: - selected_row = guiutils.get_current_item(self.treeWidget_AddressTable) - if not selected_row: - return - address = self._resolved_address(selected_row) - pointer_window = PointerScanWindow(self, address) - pointer_window.show() - dialog = PointerScanSearchDialog(pointer_window, address) - if dialog.exec() and dialog.result_map_path: - pointer_window.load_map(dialog.result_map_path) - - def exec_track_watchpoint_widget(self, watchpoint_type: int) -> None: - selected_row = guiutils.get_current_item(self.treeWidget_AddressTable) - if not selected_row: - return - address = self._resolved_address(selected_row) - value_type = selected_row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - if isinstance(value_type, typedefs.StringValueType): - value_text = selected_row.text(VALUE_COL) - errors = "surrogateescape" if value_type.encoding == "utf-8" else "replace" - byte_len = len(value_text.encode(value_type.encoding, errors)) - else: - byte_len = value_type.read_size - address_data = selected_row.data(ADDR_COL, Qt.ItemDataRole.UserRole) - if isinstance(address_data, typedefs.PointerChainRequest): - selection_dialog = TrackSelectorDialog(self) - selection_dialog.exec() - if not selection_dialog.selection: - return - if selection_dialog.selection == "pointer": - address = address_data.get_base_address_as_str() - parent = selected_row.parent() - if address.startswith(("+", "-")) and parent: - address = (parent.data(ADDR_COL, Qt.ItemDataRole.UserRole + 1) or "") + address - byte_len = 4 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 8 - TrackWatchpointWidget(self, address, byte_len, watchpoint_type) - - def browse_region_for_address(self, address: str) -> None: - address = utils.safe_str_to_int((address or "").removeprefix("P->"), 16) - if address: - self.memory_view_window.hex_dump_address(address) - self.memory_view_window.show() - self.memory_view_window.activateWindow() - - def disassemble_for_address(self, address: str) -> None: - if address and self.memory_view_window.disassemble_expression(address.removeprefix("P->")): - self.memory_view_window.show() - self.memory_view_window.activateWindow() - - def change_freeze_type(self, freeze_type: int | None = None, row: QTreeWidgetItem | None = None) -> None: - if freeze_type is None: - # No type has been specified, iterate through the freeze types - # This usually happens if user clicks the freeze type text instead of the checkbox - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - if not isinstance(frozen, typedefs.Frozen): # script entries have no freeze type - return - if frozen.freeze_type == typedefs.FREEZE_TYPE.ALLOW_DECREMENT: - # Decrement is the last freeze type - freeze_type = typedefs.FREEZE_TYPE.DEFAULT - else: - freeze_type = frozen.freeze_type + 1 - rows = [row] if row else self.treeWidget_AddressTable.selectedItems() - for row in rows: - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - if not isinstance(frozen, typedefs.Frozen): # skip script entries - continue - if row.checkState(FROZEN_COL) == Qt.CheckState.Checked: - frozen.freeze_type = freeze_type - if freeze_type == typedefs.FREEZE_TYPE.DEFAULT: - row.setText(FROZEN_COL, "") - row.setForeground(FROZEN_COL, QBrush()) - elif freeze_type == typedefs.FREEZE_TYPE.ALLOW_INCREMENT: - row.setText(FROZEN_COL, "▲") - row.setForeground(FROZEN_COL, QBrush(QColor(0, 255, 0))) - elif freeze_type == typedefs.FREEZE_TYPE.ALLOW_DECREMENT: - row.setText(FROZEN_COL, "▼") - row.setForeground(FROZEN_COL, QBrush(QColor(255, 0, 0))) - else: - frozen.freeze_type = typedefs.FREEZE_TYPE.DEFAULT - row.setText(FROZEN_COL, "") - row.setForeground(FROZEN_COL, QBrush()) - - def toggle_records(self, toggle_children: bool = False) -> None: - selected_items = self.treeWidget_AddressTable.selectedItems() - for row in selected_items: - check_state = row.checkState(FROZEN_COL) - new_state = Qt.CheckState.Checked if check_state == Qt.CheckState.Unchecked else Qt.CheckState.Unchecked - self.handle_freeze_change(row, new_state) - if toggle_children: - for index in range(row.childCount()): - child = row.child(index) - child_old_state = child.checkState(FROZEN_COL) - child_new_state = Qt.CheckState.Checked if child_old_state == Qt.CheckState.Unchecked else Qt.CheckState.Unchecked - self.handle_freeze_change(child, child_new_state) - - def cut_records(self) -> None: - self.copy_records() - self.delete_records() - - def copy_records(self) -> None: - # Recursive copy - items = self.treeWidget_AddressTable.selectedItems() - - def index_of(item: QTreeWidgetItem) -> list[int]: - """Returns the index used to access the given QTreeWidgetItem - as a list of ints.""" - result = [] - while True: - parent = item.parent() - if parent: - result.append(parent.indexOfChild(item)) - item = parent - else: - result.append(item.treeWidget().indexOfTopLevelItem(item)) - return result[::-1] - - # First, order the items by their indices in the tree widget. - # Store the indices for later usage. - index_items = [(index_of(item), item) for item in items] - index_items.sort(key=lambda x: x[0]) # sort by index - - # Now filter any selected items that is a descendant of another selected items. - items = [] - last_index = [-1] # any invalid list of indices are fine - for index, item in index_items: - if index[: len(last_index)] == last_index: - continue # this item is a descendant of the last item - items.append(item) - last_index = index - - QApplication.clipboard().setText(repr([self._read_for_copy(item) for item in items])) - - def _read_for_copy(self, row: QTreeWidgetItem) -> tuple: - record = self.read_address_table_recursively(row) - if self.get_script_entry(row) is not None: # scripts carry no address to absolutize - return record - desc, address_expr, vt, *rest = record - return (desc, self._absolutize_root(row, address_expr), vt, *rest) - - def _absolutize_root(self, row: QTreeWidgetItem, address_expr: str | tuple) -> str | tuple: - # Rewrite a relative (+/-) address into an absolute one using the parent's resolved address, - # so a row copied out of its group still points somewhere when pasted alone. - # Pointer chains keep their offsets, only the base is absolutized. - parent = row.parent() - if not parent: - return address_expr - parent_resolved = parent.data(ADDR_COL, Qt.ItemDataRole.UserRole + 1) - if not parent_resolved: - return address_expr - if isinstance(address_expr, str) and address_expr.startswith(("+", "-")): - return row.data(ADDR_COL, Qt.ItemDataRole.UserRole + 1) or parent_resolved + address_expr - if isinstance(address_expr, (list, tuple)) and address_expr: - base = address_expr[0] - if isinstance(base, str) and base.startswith(("+", "-")): - return (parent_resolved + base, *address_expr[1:]) - return address_expr - - def insert_records(self, records: list, parent_row: QTreeWidgetItem, insert_index: int) -> None: - # parent_row should be a QTreeWidgetItem in treeWidget_AddressTable - # records should be an iterable of valid output of read_address_table_recursively - assert isinstance(parent_row, QTreeWidgetItem) - for rec in records: - row = QTreeWidgetItem() - row.setCheckState(FROZEN_COL, Qt.CheckState.Unchecked) - - # A 5 element record carries an extra dict before its children (see read_address_table_recursively) - extra = rec[3] if len(rec) == 5 else None - if isinstance(extra, dict) and "script" in extra: - self.init_script_row(row, rec[0], typedefs.ScriptEntry(extra["script"])) - else: - frozen = typedefs.Frozen("", typedefs.FREEZE_TYPE.DEFAULT) - row.setData(FROZEN_COL, Qt.ItemDataRole.UserRole, frozen) - # Deserialize address_expr and value_type from rec - if isinstance(rec[1], (list, tuple)): - address_expr = typedefs.PointerChainRequest(*rec[1]) - else: - address_expr = rec[1] - value_type = typedefs.ValueType.deserialize(rec[2]) - self.change_address_table_entries(row, rec[0], address_expr, value_type) - - # Insert the row at the current insert_index - parent_row.insertChild(insert_index, row) - insert_index += 1 - - # Recursively insert children of this row - self.insert_records(rec[-1], row, 0) - self.mark_address_tree_changed() - - def paste_records(self, insert_inside: bool = False) -> None: - try: - records = ast.literal_eval(QApplication.clipboard().text()) - except (SyntaxError, ValueError, MemoryError, RecursionError): - QMessageBox.information(self, tr.ERROR, tr.INVALID_CLIPBOARD) - return - if not isinstance(records, list): - QMessageBox.information(self, tr.ERROR, tr.INVALID_CLIPBOARD) - return - - insert_row = guiutils.get_current_item(self.treeWidget_AddressTable) - root = self.treeWidget_AddressTable.invisibleRootItem() - try: - if not insert_row: # this is common when the treeWidget_AddressTable is empty - self.insert_records(records, root, self.treeWidget_AddressTable.topLevelItemCount()) - elif insert_inside: - self.insert_records(records, insert_row, 0) - else: - parent = insert_row.parent() or root - self.insert_records(records, parent, parent.indexOfChild(insert_row) + 1) - except (TypeError, ValueError, IndexError, KeyError, AttributeError): - QMessageBox.information(self, tr.ERROR, tr.INVALID_CLIPBOARD) - return - self.update_address_table() - - def group_records(self) -> None: - selected_items = self.treeWidget_AddressTable.selectedItems() - for item in selected_items.copy(): - parent = item.parent() - while parent: - if parent in selected_items: - selected_items.remove(item) - break - parent = parent.parent() - group = self.create_group() - if group: - for item in selected_items: - parent = item.parent() - if parent: - parent.removeChild(item) - else: - index = self.treeWidget_AddressTable.indexOfTopLevelItem(item) - self.treeWidget_AddressTable.takeTopLevelItem(index) - group.addChild(item) - self.treeWidget_AddressTable.setCurrentItem(group) - group.setExpanded(True) - - def create_group(self) -> QTreeWidgetItem | None: - dialog = utilwidgets.InputDialog(self, [(tr.ENTER_DESCRIPTION, tr.GROUP)]) - if dialog.exec(): - desc = dialog.get_values()[0] - return self.add_entry_to_addresstable(desc, "0x0") - return None - - def script_entries_in(self, item: QTreeWidgetItem): - # Yields the script entries of item and all its descendants - entry = self.get_script_entry(item) - if entry is not None: - yield entry - for index in range(item.childCount()): - yield from self.script_entries_in(item.child(index)) - - def delete_records(self) -> None: - selected_items = self.treeWidget_AddressTable.selectedItems() - if self.libpince_engine_window: # close any bound tabs before their rows go away - for item in selected_items: - for entry in self.script_entries_in(item): - self.libpince_engine_window.close_script_entry(entry) - root = self.treeWidget_AddressTable.invisibleRootItem() - for item in selected_items: - (item.parent() or root).removeChild(item) - if selected_items: - self.mark_address_tree_changed() - - def treeWidget_AddressTable_mouse_release_event(self, event: QMouseEvent) -> None: - item = self.treeWidget_AddressTable.itemAt(event.pos()) - column = self.treeWidget_AddressTable.columnAt(event.pos().x()) - if item and column == FROZEN_COL: - old_state = item.checkState(FROZEN_COL) - self.treeWidget_AddressTable_mouseReleaseEvent_original(event) - new_state = item.checkState(FROZEN_COL) - if old_state != new_state: - self.handle_freeze_change(item, new_state) - elif new_state == Qt.CheckState.Checked: - self.change_freeze_type(row=item) - frozen = item.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - if isinstance(frozen, typedefs.Frozen): - self.change_freeze_type(frozen.freeze_type, item) - else: - self.treeWidget_AddressTable_mouseReleaseEvent_original(event) - - def treeWidget_AddressTable_key_press_event(self, event: QKeyEvent) -> None: - current_row = guiutils.get_current_item(self.treeWidget_AddressTable) - current_address = self._resolved_address(current_row) if current_row else None - actions = { - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Delete): self.delete_records, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_B): lambda: self.browse_region_for_address(current_address), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_D): lambda: self.disassemble_for_address(current_address), - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_R): self.pushButton_RefreshAddressTable_clicked, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Space): self.toggle_records, - QKeyCombination(Qt.KeyboardModifier.ShiftModifier, Qt.Key.Key_Space): self.toggle_records, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_Space): lambda: self.toggle_records(True), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_X): self.cut_records, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_C): self.copy_records, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_V): self.paste_records, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_V): lambda: self.paste_records(True), - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Return): self.treeWidget_AddressTable_edit_value, - QKeyCombination(Qt.KeyboardModifier.KeypadModifier, Qt.Key.Key_Enter): self.treeWidget_AddressTable_edit_value, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_Return): self.treeWidget_AddressTable_edit_desc, - QKeyCombination( - Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier, Qt.Key.Key_Return - ): self.treeWidget_AddressTable_edit_address, - QKeyCombination(Qt.KeyboardModifier.AltModifier, Qt.Key.Key_Return): self.treeWidget_AddressTable_edit_type, - } - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - self.treeWidget_AddressTable_keyPressEvent_original(event) - - def invalidate_address_expression_cache(self, refresh: bool = False) -> None: - states.exp_cache.clear() - if refresh: - self.update_address_table() - - def update_address_table(self) -> None: - if debugcore.currentpid == -1 or self.treeWidget_AddressTable.topLevelItemCount() == 0: - return - it = QTreeWidgetItemIterator(self.treeWidget_AddressTable) - with debugcore.memory_handle() as mem_handle: - basic_math_exp = re.compile(r"^[0-9a-fA-F][/*+\-0-9a-fA-FxX]+$") - while True: - row = it.value() - if not row: - break - it += 1 - if self.get_script_entry(row) is not None: # script entries have no address/value to refresh - continue - address_data = row.data(ADDR_COL, Qt.ItemDataRole.UserRole) - if isinstance(address_data, typedefs.PointerChainRequest): - expression = address_data.get_base_address_as_str() - else: - expression = address_data - parent = row.parent() - if parent and expression.startswith(("+", "-")): - parent_resolved = parent.data(ADDR_COL, Qt.ItemDataRole.UserRole + 1) - if parent_resolved: - expression = parent_resolved + expression - if expression in states.exp_cache: - address = states.exp_cache[expression] - elif expression.startswith(("+", "-")): - address = None - elif basic_math_exp.match(expression.replace(" ", "")) and "**" not in expression.replace(" ", ""): - try: - address = hex(eval(expression)) - states.exp_cache[expression] = address - except: - address = debugcore.examine_expression(expression).address - if address is not None: - states.exp_cache[expression] = address - else: - address = debugcore.examine_expression(expression).address - if address is not None: - states.exp_cache[expression] = address - vt = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - is_struct_child = parent and self._is_struct_row(parent) - if isinstance(address_data, typedefs.PointerChainRequest): - # The original base could be a symbol so we have to save it - # This little hack avoids the unnecessary examine_expression call - # TODO: Consider implementing exp_cache inside libpince so we don't need this hack - pointer_chain_req = address_data - if address: - old_base = pointer_chain_req.base_address # save the old base - pointer_chain_req.base_address = address - try: - pointer_chain_result = debugcore.read_pointer_chain(pointer_chain_req) - finally: - address_data.base_address = old_base # then set it back - if pointer_chain_result and pointer_chain_result.get_final_address(): - address = pointer_chain_result.get_final_address_as_hex() - else: - address = None - if address: - row.setText(ADDR_COL, address_data.get_base_address_as_str() if is_struct_child else f"P->{address}") - else: - row.setText(ADDR_COL, "P->??") - else: - row.setText(ADDR_COL, "P->??") - else: - if address: - if is_struct_child and isinstance(address_data, str) and address_data.startswith(("+", "-")): - row.setText(ADDR_COL, address_data) - else: - row.setText(ADDR_COL, address) - elif expression.startswith(("+", "-")): - row.setText(ADDR_COL, "???") - else: - row.setText(ADDR_COL, address_data) - address = "" if not address else address - row.setData(ADDR_COL, Qt.ItemDataRole.UserRole + 1, address) - value = debugcore.read_memory(address, vt, mem_handle=mem_handle) - value = "" if value is None else str(value) - row.setText(VALUE_COL, value) - - def update_scan_box_state(self) -> None: - if self.is_scanning == True: - self.pushButton_CancelScan.setEnabled(True) - self.pushButton_NewFirstScan.setEnabled(False) - self.pushButton_NextScan.setEnabled(False) - self.pushButton_UndoScan.setEnabled(False) - self.widget_ScanOptions.setEnabled(False) - self.widget_ScanFields.setEnabled(False) - else: - is_new_scan = self.scan_mode == typedefs.SCAN_MODE.NEW - self.pushButton_CancelScan.setEnabled(False) - self.pushButton_NewFirstScan.setEnabled(True) - self.pushButton_NextScan.setEnabled(not is_new_scan) - self.pushButton_UndoScan.setEnabled(self.undo_scan_available) - self.widget_ScanOptions.setEnabled(True) - self.comboBox_ScanType_current_index_changed() - self.comboBox_ScanScope.setEnabled(is_new_scan) - self.comboBox_ValueType.setEnabled(is_new_scan) - self.comboBox_Endianness.setEnabled(is_new_scan) - self.comboBox_Alignment.setEnabled(is_new_scan) - self.pushButton_ScanRegions.setEnabled(is_new_scan) - - # Create properly typed values for memscan - def validate_search_values(self, search_for: str, search_for2: str) -> tuple[int | float | str | BytePattern | None, int | float | None]: - # Manually fix an edge case in number validators - if search_for == "-": - search_for = "" - if search_for2 == "-": - search_for2 = "" - - if search_for == "": - return None, None - - value_2 = None - - # none of these should be possible to be true at the same time - scan_index = self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole) - if scan_index >= typedefs.SCAN_INDEX.FLOAT_ANY and scan_index <= typedefs.SCAN_INDEX.ANY: - # Manually fix an edge case in float_number validator - if search_for[-1] in {"e", "E"}: - search_for += "0" - if len(search_for2) != 0 and search_for2[-1] in {"e", "E"}: - search_for2 += "0" - # Python's float() only accepts '.' as the decimal separator, so always normalize to '.' - search_for = search_for.replace(",", ".") - search_for2 = search_for2.replace(",", ".") - try: - value_1 = float(search_for) - value_2 = float(search_for2) if search_for2 != "" else None - except ValueError: - return None, None - elif scan_index == typedefs.SCAN_INDEX.STRING: - value_1 = search_for - elif scan_index == typedefs.SCAN_INDEX.AOB: - value_1 = BytePattern.from_string(search_for) - else: # Integers - if self.checkBox_Hex.isChecked(): - if not search_for.startswith(("0x", "-0x")): - negative_str = "-" if search_for.startswith("-") else "" - search_for = negative_str + "0x" + search_for.lstrip("-") - if search_for in {"0x", "-0x"}: - return None, None - if search_for2 != "": - if not search_for2.startswith(("0x", "-0x")): - negative_str = "-" if search_for2.startswith("-") else "" - search_for2 = negative_str + "0x" + search_for2.lstrip("-") - if search_for2 in {"0x", "-0x"}: - search_for2 = "" - value_1 = int(search_for, 16) - value_2 = int(search_for2, 16) if search_for2 != "" else None - else: - value_1 = int(search_for) - value_2 = int(search_for2) if search_for2 != "" else None - - return value_1, value_2 - - def scan_values(self) -> None: - if debugcore.currentpid == -1: - return - is_next_scan = self.scan_mode == typedefs.SCAN_MODE.ONGOING - type_index = self.comboBox_ScanType.currentData(Qt.ItemDataRole.UserRole) - if type_index == typedefs.SCAN_TYPE.UNKNOWN: - scan_thread = guitypedefs.Worker(memscan.snapshot) - else: - value_1, value_2 = None, None - if self.widget_ScanFields.isEnabled(): - search_for2 = self.lineEdit_Scan2.text() if type_index == typedefs.SCAN_TYPE.BETWEEN else "" - try: - value_1, value_2 = self.validate_search_values(self.lineEdit_Scan.text(), search_for2) - except ValueError: - return - if value_1 == None: - return - scan_type = scancore.scan_type_to_memscan_dict[type_index] - scan_thread = guitypedefs.Worker(memscan.scan, scan_type, value_1, value_2) - self.progressBar.setValue(0) - self.progress_bar_timer = QTimer(self, timeout=self.update_progress_bar) - self.progress_bar_timer.start(100) - scan_thread.signals.finished.connect(lambda _: self.scan_callback(is_next_scan)) - scan_thread.signals.error.connect(lambda error: self.scan_error(error, not is_next_scan)) - self.is_scanning = True - self.undo_scan_available = False - self.update_scan_box_state() - states.threadpool.start(scan_thread) - - def resize_address_table(self) -> None: - self.treeWidget_AddressTable.resizeColumnToContents(FROZEN_COL) - - # gets the information from the dialog then adds it to addresstable - def pushButton_AddAddressManually_clicked(self) -> None: - manual_address_dialog = ManualAddressDialog(self) - if manual_address_dialog.exec(): - desc, address_expr, vt = manual_address_dialog.get_values() - self.add_entry_to_addresstable(desc, address_expr, vt) - self.update_address_table() - - def pushButton_RefreshAddressTable_clicked(self) -> None: - self.invalidate_address_expression_cache(refresh=True) - - def pushButton_MemoryView_clicked(self) -> None: - self.memory_view_window.showMaximized() - self.memory_view_window.activateWindow() - - def pushButton_Wiki_clicked(self) -> None: - utils.execute_command_as_user('python3 -m webbrowser "https://github.com/korcankaraokcu/PINCE/wiki"') - - def pushButton_About_clicked(self) -> None: - about_widget = AboutWidget(self) - about_widget.show() - about_widget.activateWindow() - - def check_for_updates_on_startup(self) -> None: - if not os.environ.get("APPDIR"): - return - settings_instance = QSettings() - if not settings_instance.contains(settings.CHECK_UPDATES_ON_STARTUP): - message_box = QMessageBox(self) - message_box.setIcon(QMessageBox.Icon.Question) - message_box.setWindowTitle(tr.INFO) - message_box.setText(tr.UPDATE_CHECK_ON_STARTUP_PROMPT) - checkbox = QCheckBox(tr.CHECK_FOR_UPDATES_ON_STARTUP) - message_box.setCheckBox(checkbox) - message_box.setStandardButtons(QMessageBox.StandardButton.Ok) - message_box.exec() - settings_instance.setValue(settings.CHECK_UPDATES_ON_STARTUP, checkbox.isChecked()) - if settings_instance.value(settings.CHECK_UPDATES_ON_STARTUP, False, type=bool): - self.check_for_updates(show_result=False) - - def check_for_updates(self, show_result: bool = True) -> None: - if self.update_check_thread and self.update_check_thread.isRunning(): - return - self.show_update_check_result = show_result - self._set_update_button_enabled(False) - self.update_check_thread = update_check.UpdateCheckThread(self) - self.update_check_thread.finished.connect(self._on_update_check_thread_finished) - self.update_check_thread.start() - - def _on_update_check_thread_finished(self) -> None: - self._set_update_button_enabled(True) - thread = self.update_check_thread - self.update_check_thread = None - if thread: - self.on_update_check_finished(thread.result, self.show_update_check_result) - thread.deleteLater() - self.show_update_check_result = True - - def _set_update_button_enabled(self, enabled: bool) -> None: - self.pushButton_CheckForUpdates.setEnabled(enabled and bool(os.environ.get("APPDIR"))) - - def on_update_check_finished(self, result: update_check.UpdateCheckResult, show_result: bool = True) -> None: - status = result.status - if status == update_check.UpdateCheckStatus.UPDATE_AVAILABLE: - QMessageBox.information(self, tr.INFO, tr.UPDATE_AVAILABLE_MESSAGE) - elif show_result and status == update_check.UpdateCheckStatus.UP_TO_DATE: - QMessageBox.information(self, tr.INFO, tr.UPDATE_NOT_AVAILABLE) - elif status == update_check.UpdateCheckStatus.ERROR: - logger.warning("Update check failed: %s", result.message) - if show_result: - QMessageBox.information(self, tr.ERROR, tr.UPDATE_CHECK_FAILED) - - def pushButton_Settings_clicked(self) -> None: - SettingsDialog(self).exec() - - def pushButton_Console_clicked(self) -> None: - console_widget = ConsoleWidget(self) - console_widget.gdb_command_sent.connect(lambda: self.invalidate_address_expression_cache(refresh=True)) - console_widget.phase_out_request.connect(self.prepare_detach) - console_widget.attach_state_changed.connect(self.sync_attach_state) - console_widget.showMaximized() - - def checkBox_Hex_stateChanged(self, state: int) -> None: - if Qt.CheckState(state) == Qt.CheckState.Checked: - # allows only things that are hex, can also start with 0x - self.lineEdit_Scan.setValidator(guiutils.validator_map.get("int_hex")) - self.lineEdit_Scan2.setValidator(guiutils.validator_map.get("int_hex")) - base, converter = 10, hex - else: - # sets it back to integers only - self.lineEdit_Scan.setValidator(guiutils.validator_map.get("int")) - self.lineEdit_Scan2.setValidator(guiutils.validator_map.get("int")) - base, converter = 16, str - if self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole) <= typedefs.SCAN_INDEX.INT64: - for line_edit in (self.lineEdit_Scan, self.lineEdit_Scan2): - try: - line_edit.setText(converter(int(line_edit.text(), base))) - except ValueError: - pass - - def pushButton_NewFirstScan_clicked(self) -> None: - if debugcore.currentpid == -1: - self.comboBox_ScanType_init() - return - if self.scan_mode == typedefs.SCAN_MODE.ONGOING: - self.reset_scan() - for region_id in self.deleted_regions: - scancore.memscan.remove_region_by_id(int(region_id)) - else: - self.scan_values() - if self.is_scanning == True: - self.scan_mode = typedefs.SCAN_MODE.ONGOING - self.pushButton_NewFirstScan.setText(tr.NEW_SCAN) - self.comboBox_ScanType_init() - - def handle_line_edit_scan_key_press_event(self, event: QKeyEvent) -> None: - valid_keys = [Qt.Key.Key_Return, Qt.Key.Key_Enter] - if event.key() in valid_keys and Qt.KeyboardModifier.ControlModifier in event.modifiers(): - self.pushButton_NewFirstScan_clicked() - return - - if event.key() in valid_keys: - if self.scan_mode == typedefs.SCAN_MODE.ONGOING: - self.pushButton_NextScan_clicked() - else: - self.pushButton_NewFirstScan_clicked() - return - - def lineEdit_Scan_on_key_press_event(self, event: QKeyEvent) -> None: - self.handle_line_edit_scan_key_press_event(event) - self.lineEdit_Scan_keyPressEvent_original(event) - - def lineEdit_Scan2_on_key_press_event(self, event: QKeyEvent) -> None: - self.handle_line_edit_scan_key_press_event(event) - self.lineEdit_Scan2_keyPressEvent_original(event) - - def pushButton_UndoScan_clicked(self) -> None: - if debugcore.currentpid == -1: - return - undo_thread = guitypedefs.Worker(memscan.undo_scan) - undo_thread.signals.finished.connect(lambda _: self.scan_callback(False)) - undo_thread.signals.error.connect(self.scan_error) - self.is_scanning = True - self.undo_scan_available = False - self.update_scan_box_state() - self.pushButton_CancelScan.setEnabled(False) - states.threadpool.start(undo_thread) - - def pushButton_CancelScan_clicked(self) -> None: - if debugcore.currentpid == -1: - return - memscan.set_stop_flag(True) - self.pushButton_CancelScan.setEnabled(False) - - def comboBox_ScanType_current_index_changed(self) -> None: - hidden_types = [ - typedefs.SCAN_TYPE.INCREASED, - typedefs.SCAN_TYPE.DECREASED, - typedefs.SCAN_TYPE.CHANGED, - typedefs.SCAN_TYPE.UNCHANGED, - typedefs.SCAN_TYPE.UNKNOWN, - ] - if self.comboBox_ScanType.currentData(Qt.ItemDataRole.UserRole) in hidden_types: - self.widget_ScanFields.setEnabled(False) - else: - self.widget_ScanFields.setEnabled(True) - if self.comboBox_ScanType.currentData(Qt.ItemDataRole.UserRole) == typedefs.SCAN_TYPE.BETWEEN: - self.label_Between.setVisible(True) - self.lineEdit_Scan2.setVisible(True) - else: - self.label_Between.setVisible(False) - self.lineEdit_Scan2.setVisible(False) - - def comboBox_ScanType_init(self) -> None: - value_type = self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole) - guiutils.fill_scan_type_combobox(self.comboBox_ScanType, self.scan_mode, value_type) - - def comboBox_ScanScope_init(self) -> None: - guiutils.fill_scope_combobox(self.comboBox_ScanScope) - self.comboBox_ScanScope.currentIndexChanged.connect(self.on_scan_scope_changed) - - def on_scan_scope_changed(self) -> None: - self.deleted_regions.clear() - scan_level = self.comboBox_ScanScope.currentData(Qt.ItemDataRole.UserRole) - memscan.set_scan_level(scan_level) - memscan.reset() - - def comboBox_Alignment_current_index_changed(self) -> None: - alignment = self.comboBox_Alignment.currentData(Qt.ItemDataRole.UserRole) - memscan.set_alignment(alignment) - - def on_endianness_changed(self) -> None: - endian = self.comboBox_Endianness.currentData(Qt.ItemDataRole.UserRole) - if endian == typedefs.ENDIANNESS.HOST: - memscan.set_reverse_endianness(False) - elif endian == typedefs.ENDIANNESS.LITTLE: - memscan.set_reverse_endianness(sys.byteorder != "little") - elif endian == typedefs.ENDIANNESS.BIG: - memscan.set_reverse_endianness(sys.byteorder != "big") - - def comboBox_ValueType_init(self) -> None: - guiutils.fill_scan_index_combobox(self.comboBox_ValueType) - self.comboBox_ValueType_current_index_changed() - - def pushButton_NextScan_clicked(self) -> None: - self.scan_values() - - def pushButton_ScanRegions_clicked(self) -> None: - scan_regions_dialog = ManageScanRegionsDialog(self) - if scan_regions_dialog.exec(): - self.deleted_regions.extend(scan_regions_dialog.get_values()) - - def scan_error(self, error: Exception, first_scan: bool = False) -> None: - self.is_scanning = False - self.undo_scan_available = False - self.progress_bar_timer.stop() - if first_scan: - self.scan_mode = typedefs.SCAN_MODE.NEW - self.pushButton_NewFirstScan.setText(tr.FIRST_SCAN) - self.comboBox_ScanType_init() - self.update_scan_box_state() - QMessageBox.information(self, tr.ERROR, str(error)) - - def scan_callback(self, undo_available: bool) -> None: - self.is_scanning = False - self.undo_scan_available = undo_available and self.scan_mode == typedefs.SCAN_MODE.ONGOING - self.progress_bar_timer.stop() - self.progressBar.setValue(100) - self.update_scan_box_state() - matches = memscan.matches() - self.update_match_count() - self.tableWidget_valuesearchtable.setRowCount(0) - current_type = self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole) - scan_text = self.lineEdit_Scan.text() - length = ( - len(scan_text.split()) if current_type == typedefs.SCAN_INDEX.AOB else len(scan_text) if current_type == typedefs.SCAN_INDEX.STRING else 0 - ) - hex_values = self.checkBox_Hex.isChecked() - endian = self.comboBox_Endianness.currentData(Qt.ItemDataRole.UserRole) - with debugcore.memory_handle() as mem_handle: - row = 0 - self.tableWidget_valuesearchtable.setSortingEnabled(False) - for match in matches: - address = hex(match.address) - match_info = match.match_info - if match_info.raw_bits == 0: - # Ignore unknown entries (no match flags), should not happen as every received match is valid - logger.error("Found invalid/unknown match! Skipping...") - continue - # This is technically wrong because we can have multiple possible value types through a match - # but we'll go with the lowest matching value type - if hex_values: - value_repr = typedefs.VALUE_REPR.HEX - else: - value_repr = typedefs.VALUE_REPR.SIGNED if match_info.is_signed_integer_only() else typedefs.VALUE_REPR.UNSIGNED - if match.is_string_match(): - value_type = typedefs.StringValueType("utf-8", length=length, endian=endian) - elif match.is_bytearray_match(): - value_type = typedefs.ByteArrayValueType(length) - elif match_info.has_int8() or match_info.has_uint8(): - value_type = typedefs.IntegerValueType(8, value_repr=value_repr, endian=endian) - elif match_info.has_int16() or match_info.has_uint16(): - value_type = typedefs.IntegerValueType(16, value_repr=value_repr, endian=endian) - elif match_info.has_int32() or match_info.has_uint32(): - value_type = typedefs.IntegerValueType(32, value_repr=value_repr, endian=endian) - elif match_info.has_int64() or match_info.has_uint64(): - value_type = typedefs.IntegerValueType(64, value_repr=value_repr, endian=endian) - elif match_info.has_float32(): - value_type = typedefs.FloatValueType(32, endian=endian) - elif match_info.has_float64(): - value_type = typedefs.FloatValueType(64, endian=endian) - else: - logger.error("Passed invalid match to value type retrieval! Shouldn't be possible!") - continue - current_item = QTableWidgetItem(address) - current_item.setData(Qt.ItemDataRole.UserRole, value_type) - # TODO: Change GDB reading to memscan - value = debugcore.read_memory(address, value_type, mem_handle=mem_handle) - value = "" if value is None else str(value) - stored_value = match.stored_value - if stored_value is None: - previous_value = "" - elif isinstance(value_type, (typedefs.ByteArrayValueType, typedefs.StringValueType)): - previous_value = value_type.decode(bytes(stored_value)) - elif isinstance(value_type, typedefs.IntegerValueType): - prefix = "int" if value_type.value_repr == typedefs.VALUE_REPR.SIGNED else "uint" - number = getattr(stored_value.data, f"{prefix}{value_type.bits}_value") - previous_value = hex(number) if value_type.value_repr == typedefs.VALUE_REPR.HEX else str(number) - elif isinstance(value_type, typedefs.FloatValueType): - previous_value = str(getattr(stored_value.data, f"float{value_type.bits}_value")) - else: - previous_value = "" - if debugcore.is_address_static(address): - current_item.setForeground(QColor(0, 136, 85)) - self.tableWidget_valuesearchtable.insertRow(row) - self.tableWidget_valuesearchtable.setItem(row, SEARCH_TABLE_ADDRESS_COL, current_item) - self.tableWidget_valuesearchtable.setItem(row, SEARCH_TABLE_VALUE_COL, QTableWidgetItem(value)) - self.tableWidget_valuesearchtable.setItem(row, SEARCH_TABLE_PREVIOUS_COL, QTableWidgetItem(previous_value)) - row += 1 - if row == 5000: - break - self.tableWidget_valuesearchtable.resizeColumnsToContents() - self.tableWidget_valuesearchtable.setSortingEnabled(True) - - def update_match_count(self) -> None: - match_count = memscan.get_match_count() - if match_count > 5000: - self.label_MatchCount.setText(tr.MATCH_COUNT_LIMITED.format(match_count, 5000)) - else: - self.label_MatchCount.setText(tr.MATCH_COUNT.format(match_count)) - - def tableWidget_valuesearchtable_cell_double_clicked(self, row: int, col: int) -> None: - current_item = self.tableWidget_valuesearchtable.item(row, SEARCH_TABLE_ADDRESS_COL) - vt = copy.copy(current_item.data(Qt.ItemDataRole.UserRole)) - self.add_entry_to_addresstable(tr.NO_DESCRIPTION, current_item.text(), vt) - self.update_address_table() - - def tableWidget_valuesearchtable_key_press_event(self, event: QKeyEvent) -> None: - current_item = self.tableWidget_valuesearchtable.currentItem() - if debugcore.currentpid == -1 or not current_item: - return - current_address = self.tableWidget_valuesearchtable.item(current_item.row(), SEARCH_TABLE_ADDRESS_COL).text() - actions = { - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_C): self.copy_valuesearchtable_selection, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_B): lambda: self.browse_region_for_address(current_address), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_D): lambda: self.disassemble_for_address(current_address), - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Delete): self.delete_valuesearchtable_selection, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Return): self.copy_to_address_table, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Enter): self.copy_to_address_table, - } - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - self.tableWidget_valuesearchtable_keyPressEvent_original(event) - - def tableWidget_valuesearchtable_context_menu_event(self, event: QContextMenuEvent) -> None: - selected_indexes = self.tableWidget_valuesearchtable.selectionModel().selectedRows() - if debugcore.currentpid == -1 or not selected_indexes: - return - current_item = self.tableWidget_valuesearchtable.currentItem() - if current_item is None: - return - current_row = current_item.row() - address = self.tableWidget_valuesearchtable.item(current_row, SEARCH_TABLE_ADDRESS_COL).text() - menu = QMenu() - if len(selected_indexes) > 1: - copy_selection = menu.addAction(f"{tr.COPY_ADDRESSES}[Ctrl+C]") - else: - copy_selection = menu.addAction(f"{tr.COPY_ADDRESS}[Ctrl+C]") - menu.addSeparator() - browse_region = menu.addAction(f"{tr.BROWSE_MEMORY_REGION}[Ctrl+B]") - disassemble = menu.addAction(f"{tr.DISASSEMBLE_ADDRESS}[Ctrl+D]") - menu.addSeparator() - delete_selection = menu.addAction(f"{tr.DELETE_SELECTION}[Del]") - font_size = self.tableWidget_valuesearchtable.font().pointSize() - menu.setStyleSheet(f"font-size: {font_size}pt;") - action = menu.exec(event.globalPos()) - actions = { - copy_selection: self.copy_valuesearchtable_selection, - browse_region: lambda: self.browse_region_for_address(address), - disassemble: lambda: self.disassemble_for_address(address), - delete_selection: self.delete_valuesearchtable_selection, - } - try: - actions[action]() - except KeyError: - pass - - def copy_valuesearchtable_selection(self) -> None: - selected_indexes = self.tableWidget_valuesearchtable.selectionModel().selectedRows() - address_list = [] - for index in selected_indexes: - row = index.row() - address = self.tableWidget_valuesearchtable.item(row, SEARCH_TABLE_ADDRESS_COL).text() - address_list.append(address) - QApplication.clipboard().setText(" ".join(address_list)) - - def delete_valuesearchtable_selection(self) -> None: - selected_rows = self.tableWidget_valuesearchtable.selectedItems() - if not selected_rows: - return - - # get the row indexes - rows = set() - for item in selected_rows: - rows.add(item.row()) - - # remove the rows from the table - removing in reverse sorted order to avoid index issues - for row in sorted(rows, reverse=True): - address = self.tableWidget_valuesearchtable.item(row, SEARCH_TABLE_ADDRESS_COL).text() - memscan.remove_match_by_address(utils.safe_str_to_int(address, 16)) - self.tableWidget_valuesearchtable.removeRow(row) - self.update_match_count() - - def comboBox_ValueType_current_index_changed(self) -> None: - current_type = self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole) - memscan_type = scancore.scan_index_to_memscan_dict[current_type] - match memscan_type: - case DataType.ANYINTEGER | DataType.INTEGER8 | DataType.INTEGER16 | DataType.INTEGER32 | DataType.INTEGER64: - validator_str = "int" - case DataType.ANYNUMBER | DataType.ANYFLOAT | DataType.FLOAT32 | DataType.FLOAT64: - validator_str = "float" - case DataType.STRING: - validator_str = "string" - case DataType.BYTEARRAY: - validator_str = "bytearray" - - # TODO this can probably be made to look nicer, though it doesn't really matter - if "int" in validator_str: - validator_str = "int" - self.checkBox_Hex.setEnabled(True) - # keep hex validator if hex is checked - if self.checkBox_Hex.isChecked(): - validator_str = "int_hex" - else: - self.checkBox_Hex.setChecked(False) - self.checkBox_Hex.setEnabled(False) - - self.comboBox_ScanType_init() - self.lineEdit_Scan.setValidator(guiutils.validator_map[validator_str]) - self.lineEdit_Scan2.setValidator(guiutils.validator_map[validator_str]) - memscan.set_data_type(memscan_type) - # according to memscan instructions you should always do `reset` after changing type - memscan.reset() - - def pushButton_AttachProcess_clicked(self) -> None: - self.processwindow = SelectProcessWindow(self) - self.processwindow.show() - - def on_session_save(self) -> None: - content = [ - self.read_address_table_recursively(self.treeWidget_AddressTable.topLevelItem(i)) - for i in range(self.treeWidget_AddressTable.topLevelItemCount()) - ] - SessionManager.get_session().pct_address_tree = content - - def on_session_loaded(self) -> None: - self.clear_address_table() - self.insert_records( - SessionManager.get_session().pct_address_tree, - self.treeWidget_AddressTable.invisibleRootItem(), - self.treeWidget_AddressTable.topLevelItemCount(), - ) - - def on_new_session(self) -> None: - self.session = SessionManager.get_session() - self.clear_address_table() - - # Returns: a bool value indicates whether the operation succeeded. - def attach_to_pid(self, pid: int) -> bool: - self.cleanup_speedhack() - if os.environ.get("APPDIR"): - gdb_path = utils.get_default_gdb_path() - else: - gdb_path = states.gdb_path - attach_result = debugcore.attach(pid, gdb_path) - if attach_result == typedefs.ATTACH_RESULT.SUCCESSFUL: - settings.apply_after_init() - memscan.detach() - memscan.attach(pid) - self.on_new_process() - SessionManager.on_process_changed() - states.process_signals.attach.emit() - - # TODO: This makes PINCE call on_process_stop twice when attaching - # TODO: Signal design might have to change to something like mutexes eventually - self.memory_view_window.on_process_stop() - debugcore.continue_inferior() - return True - else: - if attach_result == typedefs.ATTACH_RESULT.ALREADY_TRACED: - message = tr.ALREADY_TRACED.format(utils.is_traced(pid)) - else: - messages = { - typedefs.ATTACH_RESULT.ATTACH_SELF: tr.SMARTASS, # easter egg - typedefs.ATTACH_RESULT.PROCESS_NOT_VALID: tr.PROCESS_NOT_VALID, - typedefs.ATTACH_RESULT.ALREADY_DEBUGGING: tr.ALREADY_DEBUGGING, - typedefs.ATTACH_RESULT.PERM_DENIED: tr.PERM_DENIED, - } - message = messages.get(attach_result, tr.GDB_INIT_ERROR) - QMessageBox.information(QApplication.focusWidget(), tr.ERROR, message) - return False - - # Returns: a bool value indicates whether the operation succeeded. - def create_new_process(self, file_path: str, args: str, ld_preload_path: str) -> bool: - self.cleanup_speedhack() - if debugcore.create_process(file_path, args, ld_preload_path): - settings.apply_after_init() - memscan.detach() - memscan.attach(debugcore.currentpid) - self.on_new_process() - SessionManager.on_process_changed() - states.process_signals.attach.emit() - return True - else: - QMessageBox.information(QApplication.focusWidget(), tr.ERROR, tr.CREATE_PROCESS_ERROR) - self.on_inferior_exit() - return False - - # Changes appearance whenever a new process is created or attached - def on_new_process(self) -> None: - monocore.reset() - name = utils.get_process_name(debugcore.currentpid) - self.label_SelectedProcess.setText(str(debugcore.currentpid) + " - " + name) - self.is_wine_process = utils.is_wine_process(debugcore.currentpid) - self.speedhack = speedhack.WineSpeedhack() if self.is_wine_process else speedhack.LinuxSpeedhack() - - # enable scan GUI - self.lineEdit_Scan.setPlaceholderText(tr.SCAN_FOR) - self.widget_Scanbox.setEnabled(True) - self.pushButton_NextScan.setEnabled(False) - self.pushButton_UndoScan.setEnabled(False) - self.pushButton_CancelScan.setEnabled(False) - self.pushButton_AddAddressManually.setEnabled(True) - self.pushButton_MemoryView.setEnabled(True) - - # stop flashing attach button, timer will stop automatically on false value - self.flashAttachButton = False - - def clear_address_table(self) -> None: - if self.treeWidget_AddressTable.topLevelItemCount() == 0: - return - if self.libpince_engine_window: - for entry in self.script_entries_in(self.treeWidget_AddressTable.invisibleRootItem()): - self.libpince_engine_window.close_script_entry(entry) - self.treeWidget_AddressTable.clear() - self.mark_address_tree_changed() - - def copy_to_address_table(self) -> None: - selected_indexes = self.tableWidget_valuesearchtable.selectionModel().selectedRows() - for index in selected_indexes: - address_item = self.tableWidget_valuesearchtable.item(index.row(), SEARCH_TABLE_ADDRESS_COL) - vt = copy.copy(address_item.data(Qt.ItemDataRole.UserRole)) - self.add_entry_to_addresstable(tr.NO_DESCRIPTION, address_item.text(), vt) - self.update_address_table() - self.mark_address_tree_changed() - - def reset_scan(self, inferior_exit: bool = False) -> None: - if inferior_exit: - memscan.detach() - else: - memscan.reset() - self.scan_mode = typedefs.SCAN_MODE.NEW - self.undo_scan_available = False - self.pushButton_NewFirstScan.setText(tr.FIRST_SCAN) - self.tableWidget_valuesearchtable.setRowCount(0) - self.update_scan_box_state() - self.progressBar.setValue(0) - self.label_MatchCount.setText(tr.MATCH_COUNT.format(0)) - - def on_inferior_exit(self) -> None: - monocore.reset() - if debugcore.currentpid == -1: - self.memory_view_window.close() - if self.speedhack is not None: - self.speedhack.reset() - self.speedhack = None - self.reset_speedhack_widgets() - self.pushButton_MemoryView.setEnabled(False) - self.pushButton_AddAddressManually.setEnabled(False) - self.widget_Scanbox.setEnabled(False) - self.lineEdit_Scan.setText("") - self.reset_scan(inferior_exit=True) - self.on_status_running() - self.flashAttachButton = True - self.flashAttachButtonTimer.start(100) - self.label_SelectedProcess.setText(tr.NO_PROCESS_SELECTED) - self.memory_view_window.setWindowTitle(tr.NO_PROCESS_SELECTED) - if os.environ.get("APPDIR"): - gdb_path = utils.get_default_gdb_path() - else: - gdb_path = states.gdb_path - if debugcore.init_gdb(gdb_path): - settings.apply_after_init() - SessionManager.on_process_changed() - states.process_signals.exit.emit() - - def on_status_detached(self) -> None: - self.label_SelectedProcess.setStyleSheet("color: blue") - self.label_InferiorStatus.setText(tr.STATUS_DETACHED) - self.label_InferiorStatus.setVisible(True) - self.label_InferiorStatus.setStyleSheet("color: blue") - - def on_status_stopped(self) -> None: - self.invalidate_address_expression_cache() - self.label_SelectedProcess.setStyleSheet("color: red") - self.label_InferiorStatus.setText(tr.STATUS_STOPPED) - self.label_InferiorStatus.setVisible(True) - self.label_InferiorStatus.setStyleSheet("color: red") - - def on_status_running(self) -> None: - self.label_SelectedProcess.setStyleSheet("") - self.label_InferiorStatus.setVisible(False) - - # closes all windows on exit - def closeEvent(self, event: QCloseEvent) -> None: - # you can no longer emit events at this point. - SessionManager.get_session().pre_exit(event) - if not event.isAccepted(): - # user cancelled the exit - return - - if hasattr(self, "update_check_timer"): - self.update_check_timer.stop() - self.await_exit_thread.request_shutdown() - self.await_exit_thread.wait(1000) - self.cleanup_speedhack() - debugcore.detach() - memscan.close() - QApplication.closeAllWindows() - logger.info("All PINCE windows closed") - - # Call update_address_table manually after this - def add_entry_to_addresstable( - self, - description: str, - address_expr: str | typedefs.PointerChainRequest, - value_type: typedefs.ValueType | None = None, - ) -> QTreeWidgetItem: - current_row = QTreeWidgetItem() - current_row.setCheckState(FROZEN_COL, Qt.CheckState.Unchecked) - frozen = typedefs.Frozen("", typedefs.FREEZE_TYPE.DEFAULT) - current_row.setData(FROZEN_COL, Qt.ItemDataRole.UserRole, frozen) - value_type = typedefs.IntegerValueType() if not value_type else value_type - self.treeWidget_AddressTable.addTopLevelItem(current_row) - self.change_address_table_entries(current_row, description, address_expr, value_type) - self.show() # In case of getting called from elsewhere - self.activateWindow() - self.mark_address_tree_changed() - return current_row - - def get_script_entry(self, row: QTreeWidgetItem | None) -> typedefs.ScriptEntry | None: - # A row is a script entry when its frozen slot holds a ScriptEntry instead of a Frozen. - if row is None: - return None - data = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - return data if isinstance(data, typedefs.ScriptEntry) else None - - def init_script_row(self, row: QTreeWidgetItem, description: str, entry: typedefs.ScriptEntry) -> None: - row.setData(FROZEN_COL, Qt.ItemDataRole.UserRole, entry) - row.setText(DESC_COL, description or tr.SCRIPT) - row.setText(TYPE_COL, tr.SCRIPT) - - def add_script_entry_to_table(self, title: str, entry: typedefs.ScriptEntry) -> None: - # entry comes from the engine already bound to its tab so the row and tab share one object. - row = QTreeWidgetItem() - row.setCheckState(FROZEN_COL, Qt.CheckState.Unchecked) - self.init_script_row(row, title, entry) - self.treeWidget_AddressTable.addTopLevelItem(row) - self.mark_address_tree_changed() - - def open_script_entry_in_engine(self, row: QTreeWidgetItem, entry: typedefs.ScriptEntry) -> None: - self.show_libpince_engine().open_script_entry(entry, row.text(DESC_COL) or tr.SCRIPT) - - def show_libpince_engine(self) -> LibpinceEngineWindow: - # A single window is reused so table script entries can be reopened in their existing tab. - if not self.libpince_engine_window: - self.libpince_engine_window = LibpinceEngineWindow(self) - self.libpince_engine_window.send_to_table.connect(self.add_script_entry_to_table) - self.libpince_engine_window.entry_modified.connect(self.mark_address_tree_changed) - self.libpince_engine_window.script_executed.connect(lambda: self.invalidate_address_expression_cache(refresh=True)) - self.libpince_engine_window.show() - self.libpince_engine_window.activateWindow() - return self.libpince_engine_window - - def show_structures_window(self) -> StructuresWindow: - if not self.structures_window: - self.structures_window = StructuresWindow(self) - self.structures_window.add_to_table_requested.connect(self._add_structure_records_to_table) - self.structures_window.refresh() - self.structures_window.show() - self.structures_window.activateWindow() - return self.structures_window - - def _add_structure_records_to_table(self, records: list) -> None: - self.insert_records(records, self.treeWidget_AddressTable.invisibleRootItem(), 0) - self.update_address_table() - - def mark_address_tree_changed(self) -> None: - self.session.data_changed |= SessionDataChanged.ADDRESS_TREE - - def toggle_script_entry(self, row: QTreeWidgetItem, entry: typedefs.ScriptEntry, check_state: Qt.CheckState) -> None: - is_enable = check_state == Qt.CheckState.Checked - row.setCheckState(FROZEN_COL, check_state) - enable_code, disable_code = parse_script_sections(entry.script) - code = enable_code if is_enable else disable_code - if code is None: # tagless script or no [DISABLE]: nothing to run when toggling off. - return - entry.namespace = entry.namespace or create_script_namespace() - succeeded, output = run_script_code(code, entry.namespace, f"<{row.text(DESC_COL) or tr.SCRIPT}>") - if not succeeded and is_enable: # don't leave a failed enable looking active - row.setCheckState(FROZEN_COL, Qt.CheckState.Unchecked) - self.invalidate_address_expression_cache(refresh=True) - if succeeded: - return - QMessageBox.information(self, tr.ERROR, tr.SCRIPT_RUN_FAILED.format(output)) - - def treeWidget_AddressTable_item_double_clicked(self, row: QTreeWidgetItem, column: int) -> None: - entry = self.get_script_entry(row) - if entry is not None: - self.open_script_entry_in_engine(row, entry) - return - action_for_column = { - VALUE_COL: self.treeWidget_AddressTable_edit_value, - DESC_COL: self.treeWidget_AddressTable_edit_desc, - ADDR_COL: self.treeWidget_AddressTable_edit_address, - TYPE_COL: self.treeWidget_AddressTable_edit_type, - } - action_for_column = collections.defaultdict(lambda *args: lambda: None, action_for_column) - action_for_column[column]() - - # ---------------------------------------------------- - # QTimer loops - - def update_progress_bar(self) -> None: - value = int(round(memscan.get_scan_progress() * 100)) - self.progressBar.setValue(value) - - # Loop restarts itself to wait for function execution, same for the functions below - def address_table_loop(self) -> None: - if states.update_table and not states.exiting: - try: - self.update_address_table() - except: - traceback.print_exc() - self.address_table_timer.start(states.table_update_interval) - - def search_table_loop(self) -> None: - if not states.exiting: - try: - self.update_search_table() - except: - traceback.print_exc() - self.search_table_timer.start(500) - - def freeze_loop(self) -> None: - if not states.exiting: - try: - self.freeze() - except: - traceback.print_exc() - self.freeze_timer.start(states.freeze_interval) - - # ---------------------------------------------------- - - def update_search_table(self) -> None: - if debugcore.currentpid == -1: - return - row_count = self.tableWidget_valuesearchtable.rowCount() - if row_count > 0: - self.tableWidget_valuesearchtable.setSortingEnabled(False) - try: - with debugcore.memory_handle() as mem_handle: - for row_index in range(row_count): - address_item = self.tableWidget_valuesearchtable.item(row_index, SEARCH_TABLE_ADDRESS_COL) - value_item = self.tableWidget_valuesearchtable.item(row_index, SEARCH_TABLE_VALUE_COL) - previous_text = self.tableWidget_valuesearchtable.item(row_index, SEARCH_TABLE_PREVIOUS_COL).text() - address = address_item.text() - value_type = address_item.data(Qt.ItemDataRole.UserRole) - new_value = debugcore.read_memory(address, value_type, mem_handle=mem_handle) - new_value = "" if new_value is None else str(new_value) - if new_value != previous_text: - value_item.setForeground(QBrush(QColor(255, 0, 0))) - value_item.setText(new_value) - finally: - self.tableWidget_valuesearchtable.setSortingEnabled(True) - - def freeze(self) -> None: - if debugcore.currentpid == -1: - return - it = QTreeWidgetItemIterator(self.treeWidget_AddressTable) - while True: - row = it.value() - if not row: - break - it += 1 - if self.get_script_entry(row) is not None: # script entries toggle on the checkbox, nothing to freeze - continue - if row.checkState(FROZEN_COL) == Qt.CheckState.Checked: - vt: typedefs.ValueType = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - address = self._resolved_address(row) - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - value = frozen.value - if value is None: # nothing valid was captured (e.g. frozen while unreadable) so we skip. - continue - freeze_type = frozen.freeze_type - if isinstance(vt, (typedefs.IntegerValueType, typedefs.FloatValueType, typedefs.BitFieldValueType)): - # Freeze comparisons need the stored number, not a signed/hex display value. - read_type = copy.copy(vt) - if isinstance(vt, typedefs.IntegerValueType) or getattr(vt, "value_repr", None) == typedefs.VALUE_REPR.HEX: - read_type.value_repr = typedefs.VALUE_REPR.UNSIGNED - new_value = debugcore.read_memory(address, read_type) - if new_value is None: - continue - compare_value, compare_new_value = value, new_value - if isinstance(vt, typedefs.IntegerValueType) and vt.value_repr == typedefs.VALUE_REPR.SIGNED: - limit = 1 << vt.bits - compare_value -= limit if compare_value >= limit // 2 else 0 - compare_new_value -= limit if compare_new_value >= limit // 2 else 0 - if ( - freeze_type == typedefs.FREEZE_TYPE.ALLOW_INCREMENT - and compare_new_value > compare_value - or freeze_type == typedefs.FREEZE_TYPE.ALLOW_DECREMENT - and compare_new_value < compare_value - ): - frozen.value = new_value - debugcore.write_memory(address, vt, new_value) - continue - debugcore.write_memory(address, vt, value) - - def _frozen_value_for_type(self, row: QTreeWidgetItem, frozen: typedefs.Frozen, new_type: typedefs.ValueType) -> Any | None: - old_type: typedefs.ValueType = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - value = frozen.value - if not frozen.enabled or value is None: - return value - if not isinstance(old_type, typedefs.BitFieldValueType) and not isinstance(new_type, typedefs.BitFieldValueType): - return value - numeric_types = (typedefs.IntegerValueType, typedefs.FloatValueType, typedefs.BitFieldValueType) - if not isinstance(old_type, numeric_types) or not isinstance(new_type, numeric_types): - return - if ( - isinstance(old_type, typedefs.BitFieldValueType) - and isinstance(new_type, typedefs.BitFieldValueType) - and (old_type.bits, old_type.start_bit) == (new_type.bits, new_type.start_bit) - ): - limit = 1 << new_type.bits - value %= limit - return value - limit if new_type.value_repr == typedefs.VALUE_REPR.SIGNED and value >= limit // 2 else value - if isinstance(old_type, typedefs.IntegerValueType): - value = old_type.parse(str(value)) - if value is None: - return - if old_type.value_repr == typedefs.VALUE_REPR.SIGNED and value >= 1 << (old_type.bits - 1): - value -= 1 << old_type.bits - return new_type.parse(str(value)) - - def handle_freeze_change(self, row: QTreeWidgetItem, check_state: Qt.CheckState) -> None: - entry = self.get_script_entry(row) - if entry is not None: - self.toggle_script_entry(row, entry, check_state) - return - if self._is_struct_row(row): - row.setCheckState(FROZEN_COL, Qt.CheckState.Unchecked) - return - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - is_checked = check_state == Qt.CheckState.Checked - frozen_state_toggled = (is_checked and not frozen.enabled) or (not is_checked and frozen.enabled) - row.setCheckState(FROZEN_COL, check_state) - # this helps determine whether the user clicked checkbox or the text - # if the user clicked the text, change the freeze type - - if frozen_state_toggled: - if is_checked: - frozen.enabled = True - # reapply the freeze type, to reflect the current freeze type in the UI - # otherwise the UI will show DEFAULT freeze type after enabling instead of the actual type - self.change_freeze_type(frozen.freeze_type, row) - vt: typedefs.ValueType = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - frozen.value = vt.parse(row.text(VALUE_COL)) - else: - frozen.enabled = False # it has just been toggled off - self.change_freeze_type(typedefs.FREEZE_TYPE.DEFAULT, row) - - def treeWidget_AddressTable_change_repr(self, new_repr: int) -> None: - for row in self.treeWidget_AddressTable.selectedItems(): - if self.get_script_entry(row) is not None: - continue - value_type = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - if isinstance(value_type, (typedefs.IntegerValueType, typedefs.BitFieldValueType)): - value_type.value_repr = new_repr - if isinstance(value_type, typedefs.BitFieldValueType): - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - frozen.value = self._frozen_value_for_type(row, frozen, value_type) - row.setText(TYPE_COL, value_type.text()) - self.update_address_table() - self.mark_address_tree_changed() - - def _is_struct_row(self, row: QTreeWidgetItem) -> bool: - # Only carries an address, has no readable value or editable type. - vt = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - return isinstance(vt, typedefs.StructValueType) - - def _resolved_address(self, row: QTreeWidgetItem) -> str: - # The displayed address can be relative (struct children show "+0x4") or "P->…" for pointers, - # so the resolved absolute kept in UserRole+1 is the source of truth for reads/writes. - # If nothing useful is in UserRole+1, fall back to text. - return row.data(ADDR_COL, Qt.ItemDataRole.UserRole + 1) or row.text(ADDR_COL).removeprefix("P->") - - def treeWidget_AddressTable_edit_value(self) -> None: - row = guiutils.get_current_item(self.treeWidget_AddressTable) - if not row or self.get_script_entry(row) is not None or self._is_struct_row(row): - return - value = row.text(VALUE_COL) - dialog = utilwidgets.InputDialog(self, [(tr.ENTER_VALUE, value)]) - if dialog.exec(): - new_value = dialog.get_values()[0] - parsed_rows = [ - (row, row.data(TYPE_COL, Qt.ItemDataRole.UserRole).parse(new_value)) - for row in self.treeWidget_AddressTable.selectedItems() - if self.get_script_entry(row) is None and not self._is_struct_row(row) - ] - if any(parsed_value is None for _, parsed_value in parsed_rows): - QMessageBox.information(self, tr.ERROR, tr.PARSE_ERROR) - return - length_changed = False - for row, parsed_value in parsed_rows: - address = self._resolved_address(row) - vt: typedefs.ValueType = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - if isinstance(vt, (typedefs.StringValueType, typedefs.ByteArrayValueType)): - if vt.length != len(parsed_value): - length_changed = True - vt.length = len(parsed_value) - row.setText(TYPE_COL, vt.text()) - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - frozen.value = parsed_value - debugcore.write_memory(address, vt, parsed_value) - self.update_address_table() - if length_changed: - self.mark_address_tree_changed() - - def treeWidget_AddressTable_edit_desc(self) -> None: - row = guiutils.get_current_item(self.treeWidget_AddressTable) - if not row: - return - description = row.text(DESC_COL) - dialog = utilwidgets.InputDialog(self, [(tr.ENTER_DESCRIPTION, description)]) - if dialog.exec(): - description_text = dialog.get_values()[0] - for row in self.treeWidget_AddressTable.selectedItems(): - row.setText(DESC_COL, description_text) - entry = self.get_script_entry(row) - if entry is not None and self.libpince_engine_window: - self.libpince_engine_window.rename_script_entry(entry, description_text) - self.mark_address_tree_changed() - - def treeWidget_AddressTable_edit_address(self) -> None: - row = guiutils.get_current_item(self.treeWidget_AddressTable) - if not row or self.get_script_entry(row) is not None: - return - if self._is_struct_row(row): - self._edit_struct_address(row) - return - desc, address_expr, vt = self.read_address_table_entries(row) - parent = row.parent() - # Pass the parent's resolved base so the dialog can preview relative ("+0x4") children - relative_base = parent.data(ADDR_COL, Qt.ItemDataRole.UserRole + 1) if parent else "" - manual_address_dialog = ManualAddressDialog(self, desc, address_expr, vt, relative_base) - manual_address_dialog.setWindowTitle(tr.EDIT_ADDRESS) - if manual_address_dialog.exec(): - desc, address_expr, new_type = manual_address_dialog.get_values() - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - frozen_value = self._frozen_value_for_type(row, frozen, new_type) - if frozen_value is None and frozen.value is not None: - QMessageBox.information(self, tr.ERROR, tr.PARSE_ERROR) - return - self.change_address_table_entries(row, desc, address_expr, new_type) - frozen.value = frozen_value - self.update_address_table() - self.mark_address_tree_changed() - - def _edit_struct_address(self, row: QTreeWidgetItem) -> None: - # Struct rows only carry an address so skip the full manual add dialog and just ask for a new address. - desc, address_expr, vt = self.read_address_table_entries(row) - if isinstance(address_expr, typedefs.PointerChainRequest): - current = address_expr.get_base_address_as_str() - else: - current = address_expr or "" - dialog = utilwidgets.InputDialog(self, [(tr.ENTER_ADDRESS, current)]) - if dialog.exec(): - new_address = dialog.get_values()[0].strip() - if not new_address: - return - if isinstance(address_expr, typedefs.PointerChainRequest): # keep the deref, only the base changed - new_address = typedefs.PointerChainRequest(new_address, address_expr.offsets_list) - self.change_address_table_entries(row, desc, new_address, vt) - self.update_address_table() - self.mark_address_tree_changed() - - def treeWidget_AddressTable_edit_type(self) -> None: - row = guiutils.get_current_item(self.treeWidget_AddressTable) - if not row or self.get_script_entry(row) is not None or self._is_struct_row(row): - return - vt = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - dialog = EditTypeDialog(self, vt) - if dialog.exec(): - vt = dialog.get_values() - type_text = vt.text() - changes = [] - for row in self.treeWidget_AddressTable.selectedItems(): - if self.get_script_entry(row) is not None or self._is_struct_row(row): - continue - frozen: typedefs.Frozen = row.data(FROZEN_COL, Qt.ItemDataRole.UserRole) - frozen_value = self._frozen_value_for_type(row, frozen, vt) - if frozen_value is None and frozen.value is not None: - QMessageBox.information(self, tr.ERROR, tr.PARSE_ERROR) - return - changes.append((row, frozen, frozen_value)) - for row, frozen, frozen_value in changes: - row.setData(TYPE_COL, Qt.ItemDataRole.UserRole, copy.copy(vt)) - row.setText(TYPE_COL, type_text) - frozen.value = frozen_value - self.update_address_table() - self.mark_address_tree_changed() - - # Changes the column values of the given row - def change_address_table_entries( - self, - row: QTreeWidgetItem, - description: str, - address_expr: str | typedefs.PointerChainRequest = "", - vt: typedefs.ValueType | None = None, - ) -> None: - assert isinstance(row, QTreeWidgetItem) - address_expr = "" if address_expr is None else address_expr - row.setText(DESC_COL, description) - row.setData(ADDR_COL, Qt.ItemDataRole.UserRole, address_expr) - if utils.extract_hex_address(address_expr) and debugcore.is_address_static(address_expr): - row.setForeground(ADDR_COL, QColor(0, 136, 85)) - else: - row.setForeground(ADDR_COL, self.palette().text().color()) - row.setData(TYPE_COL, Qt.ItemDataRole.UserRole, vt) - row.setText(TYPE_COL, vt.text()) - - # Returns the column values of the given row - def read_address_table_entries(self, row: QTreeWidgetItem, serialize: bool = False) -> tuple[str, Any, Any]: - description = row.text(DESC_COL) - if serialize: - address_data = row.data(ADDR_COL, Qt.ItemDataRole.UserRole) - if isinstance(address_data, typedefs.PointerChainRequest): - address_expr = address_data.serialize() - else: - address_expr = address_data - value_type = row.data(TYPE_COL, Qt.ItemDataRole.UserRole).serialize() - else: - address_expr = row.data(ADDR_COL, Qt.ItemDataRole.UserRole) - value_type = row.data(TYPE_COL, Qt.ItemDataRole.UserRole) - return description, address_expr, value_type - - # Returns the values inside the given row and all of its descendants. - # A script entry adds an extra dict before them so it stays backward compatible with plain rows, - # which insert_records tells apart by length. - def read_address_table_recursively(self, row: QTreeWidgetItem) -> tuple: - children = [self.read_address_table_recursively(row.child(i)) for i in range(row.childCount())] - entry = self.get_script_entry(row) - if entry is not None: - return row.text(DESC_COL), "", typedefs.IntegerValueType().serialize(), {"script": entry.script}, children - return self.read_address_table_entries(row, True) + (children,) - - # Flashing Attach Button when the process is not attached - def flash_attach_button(self) -> None: - if not self.flashAttachButton: - self.flashAttachButtonTimer.stop() - self.pushButton_AttachProcess.setStyleSheet("") - return - - case = self.flashAttachButton_gradientState % 32 - - if case < 16: - borderstring = "QPushButton {border: 3px solid rgba(0,255,0," + str(case / 16) + ");}" - else: - borderstring = "QPushButton {border: 3px solid rgba(0,255,0," + str((32 - case) / 16) + ");}" - - self.pushButton_AttachProcess.setStyleSheet(borderstring) - self.flashAttachButton_gradientState += 1 - if self.flashAttachButton_gradientState > 768: # 32*24 - self.flashAttachButton_gradientState = 0 diff --git a/GUI/Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.py b/GUI/Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.py deleted file mode 100644 index dfe13bfb..00000000 --- a/GUI/Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.py +++ /dev/null @@ -1,93 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(724, 568) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.horizontalLayout.addWidget(self.label) - self.pushButton_Invert = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Invert.setObjectName("pushButton_Invert") - self.horizontalLayout.addWidget(self.pushButton_Invert) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.pushButton_Reset = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Reset.setObjectName("pushButton_Reset") - self.horizontalLayout.addWidget(self.pushButton_Reset) - self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) - self.tableWidget_Regions = ScanRegionTable(parent=Dialog) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_Regions.setFont(font) - self.tableWidget_Regions.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Regions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Regions.setWordWrap(False) - self.tableWidget_Regions.setObjectName("tableWidget_Regions") - self.tableWidget_Regions.setColumnCount(7) - self.tableWidget_Regions.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(2, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(3, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(4, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(5, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Regions.setHorizontalHeaderItem(6, item) - self.tableWidget_Regions.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Regions.verticalHeader().setVisible(False) - self.tableWidget_Regions.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Regions.verticalHeader().setMinimumSectionSize(16) - self.gridLayout.addWidget(self.tableWidget_Regions, 1, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 2, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Manage Scan Regions")) - self.label.setText(_translate("Dialog", "Selected regions will be deleted from the current scan")) - self.pushButton_Invert.setText(_translate("Dialog", "Invert Selection")) - self.pushButton_Reset.setText(_translate("Dialog", "Reset Regions")) - self.tableWidget_Regions.setSortingEnabled(True) - item = self.tableWidget_Regions.horizontalHeaderItem(0) - item.setText(_translate("Dialog", "ID")) - item = self.tableWidget_Regions.horizontalHeaderItem(1) - item.setText(_translate("Dialog", "Start Address")) - item = self.tableWidget_Regions.horizontalHeaderItem(2) - item.setText(_translate("Dialog", "Size(bytes)")) - item = self.tableWidget_Regions.horizontalHeaderItem(3) - item.setText(_translate("Dialog", "Type")) - item = self.tableWidget_Regions.horizontalHeaderItem(4) - item.setText(_translate("Dialog", "Load Address")) - item = self.tableWidget_Regions.horizontalHeaderItem(5) - item.setText(_translate("Dialog", "Perms")) - item = self.tableWidget_Regions.horizontalHeaderItem(6) - item.setText(_translate("Dialog", "File")) -from GUI.Widgets.ManageScanRegions.ScanRegionTable import ScanRegionTable diff --git a/GUI/Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.ui b/GUI/Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.ui deleted file mode 100644 index 17f4ff93..00000000 --- a/GUI/Widgets/ManageScanRegions/Form/ManageScanRegionsDialog.ui +++ /dev/null @@ -1,177 +0,0 @@ - - - Dialog - - - - 0 - 0 - 724 - 568 - - - - Manage Scan Regions - - - - - - - - Selected regions will be deleted from the current scan - - - - - - - Invert Selection - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Reset Regions - - - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SelectRows - - - true - - - false - - - true - - - false - - - 16 - - - 16 - - - - ID - - - - - Start Address - - - - - Size(bytes) - - - - - Type - - - - - Load Address - - - - - Perms - - - - - File - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - ScanRegionTable - QTableWidget -
GUI.Widgets.ManageScanRegions.ScanRegionTable
-
-
- - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - -
diff --git a/GUI/Widgets/ManageScanRegions/ManageScanRegions.py b/GUI/Widgets/ManageScanRegions/ManageScanRegions.py deleted file mode 100644 index 2ad30332..00000000 --- a/GUI/Widgets/ManageScanRegions/ManageScanRegions.py +++ /dev/null @@ -1,58 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QTableWidgetItem, QWidget -from PyQt6.QtCore import Qt -from GUI.Widgets.ManageScanRegions.Form.ManageScanRegionsDialog import Ui_Dialog -from GUI.Utils import guiutils -from libpince import scancore - - -class ManageScanRegionsDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.deleted_regions: list[int] = [] - self.populate_table() - guiutils.center_to_parent(self) - self.pushButton_Invert.clicked.connect(self.invert_selection) - self.pushButton_Reset.clicked.connect(self.reset_regions) - - def populate_table(self) -> None: - regions = list(scancore.memscan.regions()) - self.tableWidget_Regions.setRowCount(len(regions)) - self.tableWidget_Regions.setSortingEnabled(False) - for row, region in enumerate(regions): - region_id, start_address, size, region_type, load_address, perms, file = region.as_text_fields() - id_item = QTableWidgetItem(region_id) - id_item.setCheckState(Qt.CheckState.Unchecked) - self.tableWidget_Regions.setItem(row, 0, id_item) - self.tableWidget_Regions.setItem(row, 1, QTableWidgetItem(start_address)) - self.tableWidget_Regions.setItem(row, 2, QTableWidgetItem(size)) - self.tableWidget_Regions.setItem(row, 3, QTableWidgetItem(region_type)) - self.tableWidget_Regions.setItem(row, 4, QTableWidgetItem(load_address)) - self.tableWidget_Regions.setItem(row, 5, QTableWidgetItem(perms)) - self.tableWidget_Regions.setItem(row, 6, QTableWidgetItem(file)) - self.tableWidget_Regions.setSortingEnabled(True) - self.tableWidget_Regions.resizeColumnsToContents() - - def reset_regions(self) -> None: - scancore.memscan.reset() - self.parent().deleted_regions.clear() - self.populate_table() - - def invert_selection(self) -> None: - for row in range(self.tableWidget_Regions.rowCount()): - item = self.tableWidget_Regions.item(row, 0) - cur_state = item.checkState() - new_state = Qt.CheckState.Unchecked if cur_state == Qt.CheckState.Checked else Qt.CheckState.Checked - item.setCheckState(new_state) - - def get_values(self) -> list[int]: - return self.deleted_regions - - def accept(self) -> None: - for row in range(self.tableWidget_Regions.rowCount()): - item = self.tableWidget_Regions.item(row, 0) - if item.checkState() == Qt.CheckState.Checked: - region_id = int(item.text()) - self.deleted_regions.append(region_id) - scancore.memscan.remove_region_by_id(int(region_id)) - return super().accept() diff --git a/GUI/Widgets/ManageScanRegions/ScanRegionTable.py b/GUI/Widgets/ManageScanRegions/ScanRegionTable.py deleted file mode 100644 index 1e63a451..00000000 --- a/GUI/Widgets/ManageScanRegions/ScanRegionTable.py +++ /dev/null @@ -1,43 +0,0 @@ -from PyQt6.QtWidgets import QTableWidget, QWidget -from PyQt6.QtCore import Qt -from PyQt6.QtGui import QMouseEvent, QKeyEvent - - -class ScanRegionTable(QTableWidget): - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - - def mousePressEvent(self, event: QMouseEvent | None) -> None: - super().mousePressEvent(event) - item = self.itemAt(event.pos()) - if item and item.column() == 0: - row = item.row() - self.selectRow(row) - - def mouseReleaseEvent(self, event: QMouseEvent | None) -> None: - super().mouseReleaseEvent(event) - item = self.itemAt(event.pos()) - if item and item.column() == 0: - new_state = item.checkState() - for selected_item in self.selectedItems(): - if selected_item.column() == 0: - selected_item.setCheckState(new_state) - - def keyPressEvent(self, event: QKeyEvent | None) -> None: - if event.key() == Qt.Key.Key_Space: - current_row = self.currentRow() - selected_indexes = self.selectedIndexes() - # If only one item is selected and then clicked while ctrl is being held - # There'll be no selected rows even with a current row present - if current_row != -1 and selected_indexes: - if self.currentItem().isSelected(): - selected_row = current_row - else: - selected_row = selected_indexes[0].row() - cur_state = self.item(selected_row, 0).checkState() - new_state = Qt.CheckState.Unchecked if cur_state == Qt.CheckState.Checked else Qt.CheckState.Checked - for selected_item in self.selectedItems(): - if selected_item.column() == 0: - selected_item.setCheckState(new_state) - else: - super().keyPressEvent(event) diff --git a/GUI/Widgets/ManualAddress/Form/ManualAddressDialog.py b/GUI/Widgets/ManualAddress/Form/ManualAddressDialog.py deleted file mode 100644 index c0070bf9..00000000 --- a/GUI/Widgets/ManualAddress/Form/ManualAddressDialog.py +++ /dev/null @@ -1,199 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/ManualAddress/Form/ManualAddressDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(262, 486) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetFixedSize) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout_3 = QtWidgets.QVBoxLayout() - self.verticalLayout_3.setObjectName("verticalLayout_3") - self.horizontalLayout_3 = QtWidgets.QHBoxLayout() - self.horizontalLayout_3.setObjectName("horizontalLayout_3") - self.label_5 = QtWidgets.QLabel(parent=Dialog) - self.label_5.setObjectName("label_5") - self.horizontalLayout_3.addWidget(self.label_5) - self.comboBox_ValueType = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_ValueType.setObjectName("comboBox_ValueType") - self.horizontalLayout_3.addWidget(self.comboBox_ValueType) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_3.addItem(spacerItem) - self.verticalLayout_3.addLayout(self.horizontalLayout_3) - self.horizontalLayout_6 = QtWidgets.QHBoxLayout() - self.horizontalLayout_6.setObjectName("horizontalLayout_6") - self.label_Endianness = QtWidgets.QLabel(parent=Dialog) - self.label_Endianness.setObjectName("label_Endianness") - self.horizontalLayout_6.addWidget(self.label_Endianness) - self.comboBox_Endianness = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_Endianness.setObjectName("comboBox_Endianness") - self.horizontalLayout_6.addWidget(self.comboBox_Endianness) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_6.addItem(spacerItem1) - self.verticalLayout_3.addLayout(self.horizontalLayout_6) - self.widget_Repr = QtWidgets.QWidget(parent=Dialog) - self.widget_Repr.setObjectName("widget_Repr") - self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widget_Repr) - self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.checkBox_Hex = QtWidgets.QCheckBox(parent=self.widget_Repr) - self.checkBox_Hex.setObjectName("checkBox_Hex") - self.horizontalLayout_2.addWidget(self.checkBox_Hex) - self.checkBox_Signed = QtWidgets.QCheckBox(parent=self.widget_Repr) - self.checkBox_Signed.setObjectName("checkBox_Signed") - self.horizontalLayout_2.addWidget(self.checkBox_Signed) - spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_2.addItem(spacerItem2) - self.verticalLayout_3.addWidget(self.widget_Repr) - self.widget_Length = QtWidgets.QWidget(parent=Dialog) - self.widget_Length.setObjectName("widget_Length") - self.horizontalLayout_Length = QtWidgets.QHBoxLayout(self.widget_Length) - self.horizontalLayout_Length.setContentsMargins(0, 0, 0, 0) - self.horizontalLayout_Length.setObjectName("horizontalLayout_Length") - self.label_Length = QtWidgets.QLabel(parent=self.widget_Length) - self.label_Length.setObjectName("label_Length") - self.horizontalLayout_Length.addWidget(self.label_Length) - self.lineEdit_Length = QtWidgets.QLineEdit(parent=self.widget_Length) - self.lineEdit_Length.setMaximumSize(QtCore.QSize(60, 16777215)) - self.lineEdit_Length.setInputMask("") - self.lineEdit_Length.setText("10") - self.lineEdit_Length.setObjectName("lineEdit_Length") - self.horizontalLayout_Length.addWidget(self.lineEdit_Length) - self.checkBox_ZeroTerminate = QtWidgets.QCheckBox(parent=self.widget_Length) - self.checkBox_ZeroTerminate.setChecked(True) - self.checkBox_ZeroTerminate.setObjectName("checkBox_ZeroTerminate") - self.horizontalLayout_Length.addWidget(self.checkBox_ZeroTerminate) - self.label_StartBit = QtWidgets.QLabel(parent=self.widget_Length) - self.label_StartBit.setObjectName("label_StartBit") - self.horizontalLayout_Length.addWidget(self.label_StartBit) - self.spinBox_StartBit = QtWidgets.QSpinBox(parent=self.widget_Length) - self.spinBox_StartBit.setMaximum(7) - self.spinBox_StartBit.setObjectName("spinBox_StartBit") - self.horizontalLayout_Length.addWidget(self.spinBox_StartBit) - spacerItem3 = QtWidgets.QSpacerItem(13, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_Length.addItem(spacerItem3) - self.verticalLayout_3.addWidget(self.widget_Length) - self.gridLayout.addLayout(self.verticalLayout_3, 2, 0, 1, 1) - self.widget_Pointer = QtWidgets.QWidget(parent=Dialog) - self.widget_Pointer.setEnabled(True) - self.widget_Pointer.setMinimumSize(QtCore.QSize(0, 0)) - self.widget_Pointer.setObjectName("widget_Pointer") - self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.widget_Pointer) - self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) - self.verticalLayout_4.setSpacing(0) - self.verticalLayout_4.setObjectName("verticalLayout_4") - self.verticalLayout_Pointers = QtWidgets.QVBoxLayout() - self.verticalLayout_Pointers.setObjectName("verticalLayout_Pointers") - self.label_BaseAddress = QtWidgets.QLabel(parent=self.widget_Pointer) - self.label_BaseAddress.setObjectName("label_BaseAddress") - self.verticalLayout_Pointers.addWidget(self.label_BaseAddress) - self.horizontalLayout_4 = QtWidgets.QHBoxLayout() - self.horizontalLayout_4.setObjectName("horizontalLayout_4") - self.lineEdit_PtrStartAddress = QtWidgets.QLineEdit(parent=self.widget_Pointer) - self.lineEdit_PtrStartAddress.setObjectName("lineEdit_PtrStartAddress") - self.horizontalLayout_4.addWidget(self.lineEdit_PtrStartAddress) - self.label_BaseAddressDeref = QtWidgets.QLabel(parent=self.widget_Pointer) - self.label_BaseAddressDeref.setText("-> ??") - self.label_BaseAddressDeref.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_BaseAddressDeref.setObjectName("label_BaseAddressDeref") - self.horizontalLayout_4.addWidget(self.label_BaseAddressDeref) - self.verticalLayout_Pointers.addLayout(self.horizontalLayout_4) - self.horizontalLayout_5 = QtWidgets.QHBoxLayout() - self.horizontalLayout_5.setObjectName("horizontalLayout_5") - self.pushButton_AddOffset = QtWidgets.QPushButton(parent=self.widget_Pointer) - self.pushButton_AddOffset.setObjectName("pushButton_AddOffset") - self.horizontalLayout_5.addWidget(self.pushButton_AddOffset) - self.pushButton_RemoveOffset = QtWidgets.QPushButton(parent=self.widget_Pointer) - self.pushButton_RemoveOffset.setObjectName("pushButton_RemoveOffset") - self.horizontalLayout_5.addWidget(self.pushButton_RemoveOffset) - spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_5.addItem(spacerItem4) - self.verticalLayout_Pointers.addLayout(self.horizontalLayout_5) - self.verticalLayout_4.addLayout(self.verticalLayout_Pointers) - self.gridLayout.addWidget(self.widget_Pointer, 7, 0, 1, 1) - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.label_4 = QtWidgets.QLabel(parent=Dialog) - self.label_4.setObjectName("label_4") - self.verticalLayout.addWidget(self.label_4) - self.lineEdit_Description = QtWidgets.QLineEdit(parent=Dialog) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.MinimumExpanding, QtWidgets.QSizePolicy.Policy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.lineEdit_Description.sizePolicy().hasHeightForWidth()) - self.lineEdit_Description.setSizePolicy(sizePolicy) - self.lineEdit_Description.setText("") - self.lineEdit_Description.setObjectName("lineEdit_Description") - self.verticalLayout.addWidget(self.lineEdit_Description) - self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.buttonBox.sizePolicy().hasHeightForWidth()) - self.buttonBox.setSizePolicy(sizePolicy) - self.buttonBox.setMaximumSize(QtCore.QSize(16777215, 35)) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 9, 0, 1, 1, QtCore.Qt.AlignmentFlag.AlignLeft) - spacerItem5 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Minimum) - self.gridLayout.addItem(spacerItem5, 8, 0, 1, 1) - self.verticalLayout_2 = QtWidgets.QVBoxLayout() - self.verticalLayout_2.setObjectName("verticalLayout_2") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.verticalLayout_2.addWidget(self.label) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.lineEdit_Address = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Address.setText("") - self.lineEdit_Address.setObjectName("lineEdit_Address") - self.horizontalLayout.addWidget(self.lineEdit_Address) - self.label_2 = QtWidgets.QLabel(parent=Dialog) - self.label_2.setText("=") - self.label_2.setObjectName("label_2") - self.horizontalLayout.addWidget(self.label_2) - self.label_Value = QtWidgets.QLabel(parent=Dialog) - self.label_Value.setText("") - self.label_Value.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_Value.setObjectName("label_Value") - self.horizontalLayout.addWidget(self.label_Value) - spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem6) - self.verticalLayout_2.addLayout(self.horizontalLayout) - self.gridLayout.addLayout(self.verticalLayout_2, 0, 0, 1, 1) - self.checkBox_IsPointer = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_IsPointer.setObjectName("checkBox_IsPointer") - self.gridLayout.addWidget(self.checkBox_IsPointer, 3, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Add Address Manually")) - self.label_5.setText(_translate("Dialog", "Type:")) - self.label_Endianness.setText(_translate("Dialog", "Endianness:")) - self.checkBox_Hex.setText(_translate("Dialog", "Hex")) - self.checkBox_Signed.setText(_translate("Dialog", "Signed")) - self.label_Length.setText(_translate("Dialog", "Length:")) - self.checkBox_ZeroTerminate.setText(_translate("Dialog", "Zero-Terminated")) - self.label_StartBit.setText(_translate("Dialog", "Start bit:")) - self.label_BaseAddress.setText(_translate("Dialog", "Base Address:")) - self.pushButton_AddOffset.setText(_translate("Dialog", "Add Offset")) - self.pushButton_RemoveOffset.setText(_translate("Dialog", "Remove Offset")) - self.label_4.setText(_translate("Dialog", "Description:")) - self.label.setText(_translate("Dialog", "Address:")) - self.checkBox_IsPointer.setText(_translate("Dialog", "Pointer")) diff --git a/GUI/Widgets/ManualAddress/Form/ManualAddressDialog.ui b/GUI/Widgets/ManualAddress/Form/ManualAddressDialog.ui deleted file mode 100644 index 101e0f0e..00000000 --- a/GUI/Widgets/ManualAddress/Form/ManualAddressDialog.ui +++ /dev/null @@ -1,448 +0,0 @@ - - - Dialog - - - - 0 - 0 - 262 - 486 - - - - Add Address Manually - - - - QLayout::SetFixedSize - - - - - - - - - Type: - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Endianness: - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Hex - - - - - - - Signed - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Length: - - - - - - - - 60 - 16777215 - - - - - - - 10 - - - - - - - Zero-Terminated - - - true - - - - - - - Start bit: - - - - - - - 7 - - - - - - - Qt::Horizontal - - - - 13 - 20 - - - - - - - - - - - - - true - - - - 0 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - Base Address: - - - - - - - - - - - - -> <font color=red>??</font> - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - Add Offset - - - - - - - Remove Offset - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - - Description: - - - - - - - - 0 - 0 - - - - - - - - - - - - - - 0 - 0 - - - - - 16777215 - 35 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - Qt::Vertical - - - QSizePolicy::Minimum - - - - 20 - 20 - - - - - - - - - - Address: - - - - - - - - - - - - - - - - = - - - - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Pointer - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 286 - 399 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 286 - 399 - - - 283 - 274 - - - - - diff --git a/GUI/Widgets/ManualAddress/ManualAddress.py b/GUI/Widgets/ManualAddress/ManualAddress.py deleted file mode 100644 index 619af007..00000000 --- a/GUI/Widgets/ManualAddress/ManualAddress.py +++ /dev/null @@ -1,268 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QMenu, QMessageBox -from PyQt6.QtGui import QContextMenuEvent -from GUI.Utils import guiutils -from GUI.Validators.HexValidator import HexValidator -from GUI.Widgets.ManualAddress.Form.ManualAddressDialog import Ui_Dialog -from GUI.Widgets.ManualAddress.PointerChainOffset import PointerChainOffset -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - - -class ManualAddressDialog(QDialog, Ui_Dialog): - def __init__( - self, - parent: QWidget, - description: str | None = None, - address: str | typedefs.PointerChainRequest = "0x", - value_type: typedefs.ValueType | None = None, - relative_base: str = "", - ) -> None: - super().__init__(parent) - self.setupUi(self) - self.relative_base = relative_base - self.lineEdit_PtrStartAddress.setFixedWidth(180) - self.lineEdit_Address.setFixedWidth(180) - vt = typedefs.IntegerValueType() if not value_type else value_type - self.lineEdit_Length.setValidator(HexValidator(99, self)) - guiutils.fill_value_combobox(self.comboBox_ValueType, vt, include_bit_field=True) - guiutils.fill_endianness_combobox(self.comboBox_Endianness, getattr(vt, "endian", typedefs.ENDIANNESS.HOST)) - # Resolved here instead of in the signature because default arguments are evaluated on import, which is before tr.translate() runs. - self.lineEdit_Description.setText(tr.NO_DESCRIPTION if description is None else description) - self.lineEdit_Description.setFixedWidth(180) - self.offsetsList: list[PointerChainOffset] = [] - if not isinstance(address, typedefs.PointerChainRequest): - self.lineEdit_Address.setText(address) - self.widget_Pointer.hide() - else: - self.checkBox_IsPointer.setChecked(True) - self.lineEdit_Address.setReadOnly(True) - self.lineEdit_PtrStartAddress.setText(address.get_base_address_as_str()) - self.create_offsets_list(address) - self.widget_Pointer.show() - if isinstance(vt, (typedefs.StringValueType, typedefs.ByteArrayValueType)): - self.lineEdit_Length.setText(str(vt.length)) - elif isinstance(vt, typedefs.BitFieldValueType): - self.lineEdit_Length.setText(str(vt.bits)) - self.spinBox_StartBit.setValue(vt.start_bit) - if isinstance(vt, typedefs.StringValueType): - self.checkBox_ZeroTerminate.setChecked(vt.zero_terminate) - value_repr = getattr(vt, "value_repr", typedefs.VALUE_REPR.UNSIGNED) - if value_repr == typedefs.VALUE_REPR.HEX: - self.checkBox_Hex.setChecked(True) - self.checkBox_Signed.setEnabled(False) - elif value_repr == typedefs.VALUE_REPR.SIGNED: - self.checkBox_Signed.setChecked(True) - else: - self.checkBox_Signed.setChecked(False) - self.comboBox_ValueType.currentIndexChanged.connect(self.comboBox_ValueType_current_index_changed) - self.comboBox_Endianness.currentIndexChanged.connect(self.update_value) - self.lineEdit_Length.textChanged.connect(self.update_value) - self.spinBox_StartBit.valueChanged.connect(self.update_value) - self.checkBox_Hex.stateChanged.connect(self.repr_changed) - self.checkBox_Signed.stateChanged.connect(self.repr_changed) - self.checkBox_ZeroTerminate.stateChanged.connect(self.update_value) - self.checkBox_IsPointer.stateChanged.connect(self.checkBox_IsPointer_state_changed) - self.lineEdit_PtrStartAddress.textChanged.connect(self.update_value) - self.lineEdit_Address.textChanged.connect(self.update_value) - self.pushButton_AddOffset.clicked.connect(lambda: self.addOffsetLayout(True)) - self.pushButton_RemoveOffset.clicked.connect(self.removeOffsetLayout) - self.label_Value.contextMenuEvent = self.label_Value_context_menu_event - self.comboBox_ValueType_current_index_changed() - # The form's SetFixedSize layout constraint settles lazily. Force it now so center_to_parent - # measures the real content size instead of the design-time geometry - self.adjustSize() - guiutils.center_to_parent(self) - - def label_Value_context_menu_event(self, event: QContextMenuEvent) -> None: - menu = QMenu() - refresh = menu.addAction(tr.REFRESH) - font_size = self.label_Value.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {refresh: self.update_value} - try: - actions[action]() - except KeyError: - pass - - def addOffsetLayout(self, should_update: bool = True) -> None: - offsetFrame = PointerChainOffset(len(self.offsetsList), self.widget_Pointer) - self.offsetsList.append(offsetFrame) - self.verticalLayout_Pointers.insertWidget(0, self.offsetsList[-1]) - offsetFrame.offset_changed_signal.connect(self.update_value) - if should_update: - self.update_value() - - def removeOffsetLayout(self) -> None: - if len(self.offsetsList) == 1: - return - frame = self.offsetsList[-1] - frame.deleteLater() - self.verticalLayout_Pointers.removeWidget(frame) - del self.offsetsList[-1] - self.update_value() - - def update_deref_labels(self, pointer_chain_result: typedefs.PointerChainResult) -> None: - if pointer_chain_result is not None: - base_deref = self.caps_hex_or_error_indicator(pointer_chain_result.pointer_chain[0]) - self.label_BaseAddressDeref.setText(f" → {base_deref}") - for index, offsetFrame in enumerate(self.offsetsList): - if index + 1 >= len(pointer_chain_result.pointer_chain): - offsetFrame.update_deref_label("??") - continue - previousDerefText = self.caps_hex_or_error_indicator(pointer_chain_result.pointer_chain[index]) - currentDerefText = self.caps_hex_or_error_indicator(pointer_chain_result.pointer_chain[index + 1]) - offsetText = utils.upper_hex(offsetFrame.offsetText.text()) - operationalSign = "" if offsetText.startswith("-") else "+" - calculation = f"{previousDerefText} {operationalSign} {offsetText}" - if index + 1 != len(pointer_chain_result.pointer_chain) - 1: - offsetFrame.update_deref_label(f" [{calculation}] → {currentDerefText}") - else: - offsetFrame.update_deref_label(f" {calculation} = {currentDerefText}") - else: - self.label_BaseAddressDeref.setText(" → ??") - for offsetFrame in self.offsetsList: - offsetFrame.update_deref_label("??") - - def caps_hex_or_error_indicator(self, address: int) -> str: - if address == 0: - return "??" - return utils.upper_hex(hex(address)) - - def _apply_relative_base(self, expression: str) -> str: - # Prepend the parent base so a relative offset resolves while the stored expression stays relative. - if self.relative_base and expression.startswith(("+", "-")): - return self.relative_base + expression - return expression - - def update_value(self) -> None: - if self.checkBox_IsPointer.isChecked(): - hex_converted_expr = debugcore.convert_to_hex(self._apply_relative_base(self.lineEdit_PtrStartAddress.text())) - pointer_chain_req = typedefs.PointerChainRequest(hex_converted_expr, self.get_offsets_int_list()) - pointer_chain_result = debugcore.read_pointer_chain(pointer_chain_req) - address = None - if pointer_chain_result is not None and pointer_chain_result.get_final_address() not in {0, None}: - address_text = pointer_chain_result.get_final_address_as_hex() - address = pointer_chain_result.get_final_address() - else: - address_text = "??" - self.lineEdit_Address.setText(address_text) - self.update_deref_labels(pointer_chain_result) - else: - hex_converted_expr = debugcore.convert_to_hex(self._apply_relative_base(self.lineEdit_Address.text())) - address = debugcore.examine_expression(hex_converted_expr).address - try: - value = debugcore.read_memory(address, self._get_value_type()) - except ValueError: - value = None - self.label_Value.setText("??" if value is None else str(value)) - - def _get_value_type(self) -> typedefs.ValueType: - if self.checkBox_Hex.isChecked(): - value_repr = typedefs.VALUE_REPR.HEX - elif self.checkBox_Signed.isChecked(): - value_repr = typedefs.VALUE_REPR.SIGNED - else: - value_repr = typedefs.VALUE_REPR.UNSIGNED - value_type = self.comboBox_ValueType.currentData() - if isinstance(value_type, typedefs.BitFieldValueType): - return typedefs.BitFieldValueType( - utils.safe_str_to_int(self.lineEdit_Length.text(), 0), - self.spinBox_StartBit.value(), - value_repr=value_repr, - ) - return guiutils.configure_value_type( - value_type, - length=utils.safe_str_to_int(self.lineEdit_Length.text(), 0), - zero_terminate=self.checkBox_ZeroTerminate.isChecked(), - value_repr=value_repr, - endian=self.comboBox_Endianness.currentData(), - ) - - def comboBox_ValueType_current_index_changed(self) -> None: - value_type = self.comboBox_ValueType.currentData() - is_bit_field = isinstance(value_type, typedefs.BitFieldValueType) - self.widget_Length.setVisible(isinstance(value_type, (typedefs.StringValueType, typedefs.ByteArrayValueType)) or is_bit_field) - self.label_StartBit.setVisible(is_bit_field) - self.spinBox_StartBit.setVisible(is_bit_field) - self.checkBox_ZeroTerminate.setVisible(isinstance(value_type, typedefs.StringValueType)) - self.label_Endianness.setVisible(not is_bit_field) - self.comboBox_Endianness.setVisible(not is_bit_field) - self.update_value() - - def repr_changed(self) -> None: - if self.checkBox_Hex.isChecked(): - self.checkBox_Signed.setEnabled(False) - else: - self.checkBox_Signed.setEnabled(True) - self.update_value() - - def checkBox_IsPointer_state_changed(self) -> None: - if self.checkBox_IsPointer.isChecked(): - self.lineEdit_Address.setReadOnly(True) - self.lineEdit_PtrStartAddress.setText(self.lineEdit_Address.text()) - if len(self.offsetsList) == 0: - self.addOffsetLayout(False) - self.widget_Pointer.show() - else: - self.lineEdit_Address.setText(self.lineEdit_PtrStartAddress.text()) - self.lineEdit_PtrStartAddress.setText("") - self.lineEdit_Address.setReadOnly(False) - self.widget_Pointer.hide() - self.update_value() - - def reject(self) -> None: - super().reject() - - def accept(self) -> None: - if self.label_Length.isVisible(): - length = self.lineEdit_Length.text() - try: - length = int(length, 0) - except: - QMessageBox.information(self, tr.ERROR, tr.LENGTH_NOT_VALID) - return - if not length > 0: - QMessageBox.information(self, tr.ERROR, tr.LENGTH_GT) - return - if isinstance(self.comboBox_ValueType.currentData(), typedefs.BitFieldValueType) and length > 64: - QMessageBox.information(self, tr.ERROR, tr.LENGTH_NOT_VALID) - return - super().accept() - - def get_values(self) -> tuple[str, str | typedefs.PointerChainRequest, typedefs.ValueType]: - description = self.lineEdit_Description.text() - if self.checkBox_IsPointer.isChecked(): - base_expression = debugcore.convert_to_hex(self.lineEdit_PtrStartAddress.text()) - address = typedefs.PointerChainRequest(base_expression, self.get_offsets_int_list()) - else: - address = debugcore.convert_to_hex(self.lineEdit_Address.text()) - return description, address, self._get_value_type() - - def get_offsets_int_list(self) -> list[int]: - offsetsIntList = [] - for frame in self.offsetsList: - offsetText = frame.layout().itemAt(1).widget().text() - try: - offsetValue = int(offsetText, 16) - except ValueError: - offsetValue = 0 - offsetsIntList.append(offsetValue) - return offsetsIntList - - def create_offsets_list(self, pointer_chain_req: typedefs.PointerChainRequest) -> None: - if not isinstance(pointer_chain_req, typedefs.PointerChainRequest): - raise TypeError("Passed non-PointerChainRequest type to create_offsets_list!") - - for offset in pointer_chain_req.offsets_list: - self.addOffsetLayout(False) - frame = self.offsetsList[-1] - frame.layout().itemAt(1).widget().setText(hex(offset)) - - def get_type_size(self) -> int | None: - try: - value_type = self._get_value_type() - except ValueError: - return - if isinstance(value_type, (typedefs.IntegerValueType, typedefs.FloatValueType, typedefs.BitFieldValueType)): - return value_type.read_size diff --git a/GUI/Widgets/ManualAddress/PointerChainOffset.py b/GUI/Widgets/ManualAddress/PointerChainOffset.py deleted file mode 100644 index 8742f12a..00000000 --- a/GUI/Widgets/ManualAddress/PointerChainOffset.py +++ /dev/null @@ -1,60 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QFrame, QLabel, QLineEdit, QPushButton, QHBoxLayout, QSizePolicy, QSpacerItem -from PyQt6.QtCore import Qt, pyqtSignal -from operator import add as opAdd, sub as opSub -from typing import Callable - -from GUI.Utils import guiutils -from libpince import utils - - -# Only intended to be used by ManualAddressDialog -class PointerChainOffset(QFrame): - offset_changed_signal = pyqtSignal(name="offsetChanged") - - def __init__(self, offset_index: int, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.offset_index = offset_index - self.initUI() - - def initUI(self) -> None: - offsetLayout = QHBoxLayout(self) - offsetLayout.setContentsMargins(0, 3, 0, 3) - self.setLayout(offsetLayout) - buttonLeft = QPushButton("<", self) - buttonLeft.setFixedWidth(20) - offsetLayout.addWidget(buttonLeft) - self.offsetText = QLineEdit(self) - self.offsetText.setValidator(guiutils.validator_map["int_hex"]) - self.offsetText.setText(hex(0)) - self.offsetText.setFixedWidth(70) - self.offsetText.textChanged.connect(self.offset_changed) - offsetLayout.addWidget(self.offsetText) - buttonRight = QPushButton(">", self) - buttonRight.setFixedWidth(20) - offsetLayout.addWidget(buttonRight) - spacer = QSpacerItem(40, 20, QSizePolicy.Policy.Expanding) - self.derefLabel = QLabel(self) - self.derefLabel.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - self.derefLabel.setText(" -> ??") - offsetLayout.addWidget(self.derefLabel) - offsetLayout.addItem(spacer) - buttonLeft.clicked.connect(lambda: self.on_offset_arrow_clicked(self.offsetText, opSub)) - buttonRight.clicked.connect(lambda: self.on_offset_arrow_clicked(self.offsetText, opAdd)) - - def on_offset_arrow_clicked(self, offsetTextWidget: QLineEdit, operator_func: Callable) -> None: - offsetText = offsetTextWidget.text() - try: - offsetValue = int(offsetText, 16) - # first parent is the widget_pointer, second parent is the ManualAddressDialog - dialog = self.parent().parent() - sizeVal = (dialog.get_type_size() or 1) if hasattr(dialog, "get_type_size") else 1 - offsetValue = operator_func(offsetValue, sizeVal) - except ValueError: - offsetValue = 0 - offsetTextWidget.setText(utils.upper_hex(hex(offsetValue))) - - def offset_changed(self) -> None: - self.offset_changed_signal.emit() - - def update_deref_label(self, text: str) -> None: - self.derefLabel.setText(text) diff --git a/GUI/Widgets/MemoryRegions/Form/MemoryRegionsWidget.py b/GUI/Widgets/MemoryRegions/Form/MemoryRegionsWidget.py deleted file mode 100644 index 93224d13..00000000 --- a/GUI/Widgets/MemoryRegions/Form/MemoryRegionsWidget.py +++ /dev/null @@ -1,63 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/MemoryRegions/Form/MemoryRegionsWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(684, 539) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.lineEdit_Search = QtWidgets.QLineEdit(parent=Form) - self.lineEdit_Search.setClearButtonEnabled(True) - self.lineEdit_Search.setObjectName("lineEdit_Search") - self.gridLayout.addWidget(self.lineEdit_Search, 0, 0, 1, 1) - self.tableWidget_MemoryRegions = QtWidgets.QTableWidget(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_MemoryRegions.setFont(font) - self.tableWidget_MemoryRegions.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_MemoryRegions.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_MemoryRegions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_MemoryRegions.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollMode.ScrollPerPixel) - self.tableWidget_MemoryRegions.setWordWrap(False) - self.tableWidget_MemoryRegions.setObjectName("tableWidget_MemoryRegions") - self.tableWidget_MemoryRegions.setColumnCount(4) - self.tableWidget_MemoryRegions.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_MemoryRegions.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_MemoryRegions.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_MemoryRegions.setHorizontalHeaderItem(2, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_MemoryRegions.setHorizontalHeaderItem(3, item) - self.tableWidget_MemoryRegions.horizontalHeader().setStretchLastSection(True) - self.tableWidget_MemoryRegions.verticalHeader().setVisible(False) - self.tableWidget_MemoryRegions.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_MemoryRegions.verticalHeader().setMinimumSectionSize(16) - self.gridLayout.addWidget(self.tableWidget_MemoryRegions, 1, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Memory Regions")) - self.lineEdit_Search.setPlaceholderText(_translate("Form", "Search path")) - self.tableWidget_MemoryRegions.setSortingEnabled(True) - item = self.tableWidget_MemoryRegions.horizontalHeaderItem(0) - item.setText(_translate("Form", "Regions")) - item = self.tableWidget_MemoryRegions.horizontalHeaderItem(1) - item.setText(_translate("Form", "Perms")) - item = self.tableWidget_MemoryRegions.horizontalHeaderItem(2) - item.setText(_translate("Form", "Offset")) - item = self.tableWidget_MemoryRegions.horizontalHeaderItem(3) - item.setText(_translate("Form", "Path")) diff --git a/GUI/Widgets/MemoryRegions/Form/MemoryRegionsWidget.ui b/GUI/Widgets/MemoryRegions/Form/MemoryRegionsWidget.ui deleted file mode 100644 index ef6ee15a..00000000 --- a/GUI/Widgets/MemoryRegions/Form/MemoryRegionsWidget.ui +++ /dev/null @@ -1,90 +0,0 @@ - - - Form - - - - 0 - 0 - 684 - 539 - - - - Memory Regions - - - - - - true - - - Search path - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - QAbstractItemView::ScrollPerPixel - - - true - - - false - - - true - - - false - - - 16 - - - 16 - - - - Regions - - - - - Perms - - - - - Offset - - - - - Path - - - - - - - - - diff --git a/GUI/Widgets/MemoryRegions/MemoryRegions.py b/GUI/Widgets/MemoryRegions/MemoryRegions.py deleted file mode 100644 index 7ad8065e..00000000 --- a/GUI/Widgets/MemoryRegions/MemoryRegions.py +++ /dev/null @@ -1,93 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMenu, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QContextMenuEvent -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils -from GUI.Widgets.MemoryRegions.Form.MemoryRegionsWidget import Ui_Form -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr -import os - -# represents the index of columns in memory regions table -MEMORY_REGIONS_ADDR_COL = 0 -MEMORY_REGIONS_PERM_COL = 1 -MEMORY_REGIONS_OFFSET_COL = 2 -MEMORY_REGIONS_PATH_COL = 3 - - -class MemoryRegionsWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.refresh_table() - self.tableWidget_MemoryRegions.contextMenuEvent = self.tableWidget_MemoryRegions_context_menu_event - self.tableWidget_MemoryRegions.itemDoubleClicked.connect(self.tableWidget_MemoryRegions_item_double_clicked) - self.lineEdit_Search.textChanged.connect(self.filter_table) - self.shortcut_refresh = QShortcut(QKeySequence("R"), self) - self.shortcut_refresh.activated.connect(self.refresh_table) - guiutils.center_to_parent(self) - - def refresh_table(self) -> None: - memory_regions = utils.get_regions(debugcore.currentpid) - region_dict = utils.get_region_dict(debugcore.currentpid) - self.tableWidget_MemoryRegions.setSortingEnabled(False) - self.tableWidget_MemoryRegions.setRowCount(0) - self.tableWidget_MemoryRegions.setRowCount(len(memory_regions)) - # The shown [index] is this region's position within get_region_dict's per name list, matching - # utils.get_region_info so it lines up with the index bookmarks store and resolve against. - for row, (start, end, perms, offset, _, _, path) in enumerate(memory_regions): - file_name = os.path.split(path)[1] - address_list = region_dict.get(file_name, []) - try: - region_index = address_list.index("0x" + start) - except ValueError: - region_index = 0 - address = start + "-" + end - self.tableWidget_MemoryRegions.setItem(row, MEMORY_REGIONS_ADDR_COL, QTableWidgetItem(address)) - self.tableWidget_MemoryRegions.setItem(row, MEMORY_REGIONS_PERM_COL, QTableWidgetItem(perms)) - self.tableWidget_MemoryRegions.setItem(row, MEMORY_REGIONS_OFFSET_COL, QTableWidgetItem(offset)) - self.tableWidget_MemoryRegions.setItem(row, MEMORY_REGIONS_PATH_COL, QTableWidgetItem(path + f"[{region_index}]")) - - self.tableWidget_MemoryRegions.setSortingEnabled(True) - guiutils.resize_to_contents(self.tableWidget_MemoryRegions) - self.filter_table() - - def filter_table(self) -> None: - search_text = self.lineEdit_Search.text().lower() - for row in range(self.tableWidget_MemoryRegions.rowCount()): - path = self.tableWidget_MemoryRegions.item(row, MEMORY_REGIONS_PATH_COL).text() - self.tableWidget_MemoryRegions.setRowHidden(row, search_text not in path.lower()) - - def tableWidget_MemoryRegions_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - QApplication.clipboard().setText(self.tableWidget_MemoryRegions.item(row, column).text()) - - selected_row = guiutils.get_current_row(self.tableWidget_MemoryRegions) - - menu = QMenu() - refresh = menu.addAction(f"{tr.REFRESH}[R]") - menu.addSeparator() - copy_addresses = menu.addAction(tr.COPY_ADDRESSES) - copy_offset = menu.addAction(tr.COPY_OFFSET) - copy_path = menu.addAction(tr.COPY_PATH) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_addresses, copy_offset, copy_path]) - font_size = self.tableWidget_MemoryRegions.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - refresh: self.refresh_table, - copy_addresses: lambda: copy_to_clipboard(selected_row, MEMORY_REGIONS_ADDR_COL), - copy_offset: lambda: copy_to_clipboard(selected_row, MEMORY_REGIONS_OFFSET_COL), - copy_path: lambda: copy_to_clipboard(selected_row, MEMORY_REGIONS_PATH_COL), - } - try: - actions[action]() - except KeyError: - pass - - def tableWidget_MemoryRegions_item_double_clicked(self, index: QTableWidgetItem) -> None: - row = index.row() - address = self.tableWidget_MemoryRegions.item(row, MEMORY_REGIONS_ADDR_COL).text() - address_int = utils.safe_str_to_int(address.split("-")[0], 16) - self.parent().hex_dump_address(address_int) diff --git a/GUI/Widgets/MemoryView/Form/MemoryViewWindow.py b/GUI/Widgets/MemoryView/Form/MemoryViewWindow.py deleted file mode 100644 index e19a9d3e..00000000 --- a/GUI/Widgets/MemoryView/Form/MemoryViewWindow.py +++ /dev/null @@ -1,945 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/MemoryView/Form/MemoryViewWindow.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_MainWindow_MemoryView(object): - def setupUi(self, MainWindow_MemoryView): - MainWindow_MemoryView.setObjectName("MainWindow_MemoryView") - MainWindow_MemoryView.resize(800, 600) - self.centralwidget = QtWidgets.QWidget(parent=MainWindow_MemoryView) - self.centralwidget.setObjectName("centralwidget") - self.gridLayout_5 = QtWidgets.QGridLayout(self.centralwidget) - self.gridLayout_5.setContentsMargins(0, 0, 0, 0) - self.gridLayout_5.setSpacing(0) - self.gridLayout_5.setObjectName("gridLayout_5") - self.splitter_MainMiddle = QtWidgets.QSplitter(parent=self.centralwidget) - self.splitter_MainMiddle.setLineWidth(1) - self.splitter_MainMiddle.setOrientation(QtCore.Qt.Orientation.Vertical) - self.splitter_MainMiddle.setOpaqueResize(True) - self.splitter_MainMiddle.setHandleWidth(10) - self.splitter_MainMiddle.setChildrenCollapsible(True) - self.splitter_MainMiddle.setObjectName("splitter_MainMiddle") - self.splitter_Disassemble_Registers = QtWidgets.QSplitter(parent=self.splitter_MainMiddle) - self.splitter_Disassemble_Registers.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter_Disassemble_Registers.setHandleWidth(10) - self.splitter_Disassemble_Registers.setObjectName("splitter_Disassemble_Registers") - self.widget_Disassemble = QtWidgets.QWidget(parent=self.splitter_Disassemble_Registers) - self.widget_Disassemble.setObjectName("widget_Disassemble") - self.gridLayout_2 = QtWidgets.QGridLayout(self.widget_Disassemble) - self.gridLayout_2.setContentsMargins(0, 0, 0, 0) - self.gridLayout_2.setSpacing(0) - self.gridLayout_2.setObjectName("gridLayout_2") - self.tableWidget_Disassemble = QtWidgets.QTableWidget(parent=self.widget_Disassemble) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_Disassemble.setFont(font) - self.tableWidget_Disassemble.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.tableWidget_Disassemble.setAutoScroll(False) - self.tableWidget_Disassemble.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Disassemble.setAlternatingRowColors(True) - self.tableWidget_Disassemble.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection) - self.tableWidget_Disassemble.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Disassemble.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollMode.ScrollPerPixel) - self.tableWidget_Disassemble.setShowGrid(False) - self.tableWidget_Disassemble.setWordWrap(False) - self.tableWidget_Disassemble.setObjectName("tableWidget_Disassemble") - self.tableWidget_Disassemble.setColumnCount(4) - self.tableWidget_Disassemble.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Disassemble.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Disassemble.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Disassemble.setHorizontalHeaderItem(2, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Disassemble.setHorizontalHeaderItem(3, item) - self.tableWidget_Disassemble.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Disassemble.verticalHeader().setVisible(False) - self.tableWidget_Disassemble.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Disassemble.verticalHeader().setMinimumSectionSize(16) - self.tableWidget_Disassemble.verticalHeader().setStretchLastSection(False) - self.gridLayout_2.addWidget(self.tableWidget_Disassemble, 0, 0, 1, 1) - self.verticalScrollBar_Disassemble = QtWidgets.QScrollBar(parent=self.widget_Disassemble) - self.verticalScrollBar_Disassemble.setOrientation(QtCore.Qt.Orientation.Vertical) - self.verticalScrollBar_Disassemble.setObjectName("verticalScrollBar_Disassemble") - self.gridLayout_2.addWidget(self.verticalScrollBar_Disassemble, 0, 1, 1, 1) - self.widget_Registers = QtWidgets.QWidget(parent=self.splitter_Disassemble_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.widget_Registers.setFont(font) - self.widget_Registers.setObjectName("widget_Registers") - self.gridLayout_4 = QtWidgets.QGridLayout(self.widget_Registers) - self.gridLayout_4.setContentsMargins(0, 0, 0, 0) - self.gridLayout_4.setSpacing(0) - self.gridLayout_4.setObjectName("gridLayout_4") - self.scrollArea_Registers = QtWidgets.QScrollArea(parent=self.widget_Registers) - self.scrollArea_Registers.setWidgetResizable(True) - self.scrollArea_Registers.setObjectName("scrollArea_Registers") - self.scrollAreaWidgetContents_Registers = QtWidgets.QWidget() - self.scrollAreaWidgetContents_Registers.setGeometry(QtCore.QRect(0, 0, 373, 373)) - self.scrollAreaWidgetContents_Registers.setObjectName("scrollAreaWidgetContents_Registers") - self.gridLayout_8 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_Registers) - self.gridLayout_8.setContentsMargins(0, 0, 0, 0) - self.gridLayout_8.setSpacing(0) - self.gridLayout_8.setObjectName("gridLayout_8") - self.horizontalLayout_4 = QtWidgets.QHBoxLayout() - self.horizontalLayout_4.setSpacing(0) - self.horizontalLayout_4.setObjectName("horizontalLayout_4") - self.verticalLayout_19 = QtWidgets.QVBoxLayout() - self.verticalLayout_19.setSpacing(0) - self.verticalLayout_19.setObjectName("verticalLayout_19") - self.label_3 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_3.setFont(font) - self.label_3.setObjectName("label_3") - self.verticalLayout_19.addWidget(self.label_3) - self.line = QtWidgets.QFrame(parent=self.scrollAreaWidgetContents_Registers) - self.line.setFrameShape(QtWidgets.QFrame.Shape.HLine) - self.line.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line.setObjectName("line") - self.verticalLayout_19.addWidget(self.line) - self.stackedWidget = QtWidgets.QStackedWidget(parent=self.scrollAreaWidgetContents_Registers) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.stackedWidget.sizePolicy().hasHeightForWidth()) - self.stackedWidget.setSizePolicy(sizePolicy) - self.stackedWidget.setMinimumSize(QtCore.QSize(0, 145)) - self.stackedWidget.setMaximumSize(QtCore.QSize(16777215, 145)) - self.stackedWidget.setObjectName("stackedWidget") - self.registers_64 = QtWidgets.QWidget() - self.registers_64.setObjectName("registers_64") - self.gridLayout_7 = QtWidgets.QGridLayout(self.registers_64) - self.gridLayout_7.setContentsMargins(0, 0, 0, 0) - self.gridLayout_7.setSpacing(0) - self.gridLayout_7.setObjectName("gridLayout_7") - self.verticalLayout_17 = QtWidgets.QVBoxLayout() - self.verticalLayout_17.setSpacing(0) - self.verticalLayout_17.setObjectName("verticalLayout_17") - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setSpacing(0) - self.horizontalLayout.setObjectName("horizontalLayout") - self.verticalLayout_16 = QtWidgets.QVBoxLayout() - self.verticalLayout_16.setSpacing(0) - self.verticalLayout_16.setObjectName("verticalLayout_16") - self.RAX = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RAX.setFont(font) - self.RAX.setText("RAX=") - self.RAX.setObjectName("RAX") - self.verticalLayout_16.addWidget(self.RAX) - self.RBX = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RBX.setFont(font) - self.RBX.setText("RBX=") - self.RBX.setObjectName("RBX") - self.verticalLayout_16.addWidget(self.RBX) - self.RCX = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RCX.setFont(font) - self.RCX.setText("RCX=") - self.RCX.setObjectName("RCX") - self.verticalLayout_16.addWidget(self.RCX) - self.RDX = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RDX.setFont(font) - self.RDX.setText("RDX=") - self.RDX.setObjectName("RDX") - self.verticalLayout_16.addWidget(self.RDX) - self.RSI = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RSI.setFont(font) - self.RSI.setText("RSI=") - self.RSI.setObjectName("RSI") - self.verticalLayout_16.addWidget(self.RSI) - self.RDI = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RDI.setFont(font) - self.RDI.setText("RDI=") - self.RDI.setObjectName("RDI") - self.verticalLayout_16.addWidget(self.RDI) - self.RBP = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RBP.setFont(font) - self.RBP.setText("RBP=") - self.RBP.setObjectName("RBP") - self.verticalLayout_16.addWidget(self.RBP) - self.RSP = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RSP.setFont(font) - self.RSP.setText("RSP=") - self.RSP.setObjectName("RSP") - self.verticalLayout_16.addWidget(self.RSP) - self.horizontalLayout.addLayout(self.verticalLayout_16) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.verticalLayout_3 = QtWidgets.QVBoxLayout() - self.verticalLayout_3.setSpacing(0) - self.verticalLayout_3.setObjectName("verticalLayout_3") - self.R8 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R8.setFont(font) - self.R8.setText("R8=") - self.R8.setObjectName("R8") - self.verticalLayout_3.addWidget(self.R8) - self.R9 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R9.setFont(font) - self.R9.setText("R9=") - self.R9.setObjectName("R9") - self.verticalLayout_3.addWidget(self.R9) - self.R10 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R10.setFont(font) - self.R10.setText("R10=") - self.R10.setObjectName("R10") - self.verticalLayout_3.addWidget(self.R10) - self.R11 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R11.setFont(font) - self.R11.setText("R11=") - self.R11.setObjectName("R11") - self.verticalLayout_3.addWidget(self.R11) - self.R12 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R12.setFont(font) - self.R12.setText("R12=") - self.R12.setObjectName("R12") - self.verticalLayout_3.addWidget(self.R12) - self.R13 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R13.setFont(font) - self.R13.setText("R13=") - self.R13.setObjectName("R13") - self.verticalLayout_3.addWidget(self.R13) - self.R14 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R14.setFont(font) - self.R14.setText("R14=") - self.R14.setObjectName("R14") - self.verticalLayout_3.addWidget(self.R14) - self.R15 = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.R15.setFont(font) - self.R15.setText("R15=") - self.R15.setObjectName("R15") - self.verticalLayout_3.addWidget(self.R15) - self.horizontalLayout.addLayout(self.verticalLayout_3) - self.verticalLayout_17.addLayout(self.horizontalLayout) - self.horizontalLayout_18 = QtWidgets.QHBoxLayout() - self.horizontalLayout_18.setSpacing(0) - self.horizontalLayout_18.setObjectName("horizontalLayout_18") - self.RIP = RegisterLabel(parent=self.registers_64) - font = QtGui.QFont() - font.setFamily("Monospace") - self.RIP.setFont(font) - self.RIP.setText("RIP=") - self.RIP.setObjectName("RIP") - self.horizontalLayout_18.addWidget(self.RIP) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_18.addItem(spacerItem1) - self.verticalLayout_17.addLayout(self.horizontalLayout_18) - spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_17.addItem(spacerItem2) - self.gridLayout_7.addLayout(self.verticalLayout_17, 0, 0, 1, 1) - self.stackedWidget.addWidget(self.registers_64) - self.registers_32 = QtWidgets.QWidget() - self.registers_32.setObjectName("registers_32") - self.gridLayout_6 = QtWidgets.QGridLayout(self.registers_32) - self.gridLayout_6.setContentsMargins(0, 0, 0, 0) - self.gridLayout_6.setSpacing(0) - self.gridLayout_6.setObjectName("gridLayout_6") - self.verticalLayout_14 = QtWidgets.QVBoxLayout() - self.verticalLayout_14.setSpacing(0) - self.verticalLayout_14.setObjectName("verticalLayout_14") - self.horizontalLayout_3 = QtWidgets.QHBoxLayout() - self.horizontalLayout_3.setSpacing(0) - self.horizontalLayout_3.setObjectName("horizontalLayout_3") - self.verticalLayout_2 = QtWidgets.QVBoxLayout() - self.verticalLayout_2.setSpacing(0) - self.verticalLayout_2.setObjectName("verticalLayout_2") - self.EAX = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.EAX.setFont(font) - self.EAX.setText("EAX=") - self.EAX.setObjectName("EAX") - self.verticalLayout_2.addWidget(self.EAX) - self.EBX = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.EBX.setFont(font) - self.EBX.setText("EBX=") - self.EBX.setObjectName("EBX") - self.verticalLayout_2.addWidget(self.EBX) - self.ECX = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.ECX.setFont(font) - self.ECX.setText("ECX=") - self.ECX.setObjectName("ECX") - self.verticalLayout_2.addWidget(self.ECX) - self.EDX = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.EDX.setFont(font) - self.EDX.setText("EDX=") - self.EDX.setObjectName("EDX") - self.verticalLayout_2.addWidget(self.EDX) - self.ESI = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.ESI.setFont(font) - self.ESI.setText("ESI=") - self.ESI.setObjectName("ESI") - self.verticalLayout_2.addWidget(self.ESI) - self.EDI = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.EDI.setFont(font) - self.EDI.setText("EDI=") - self.EDI.setObjectName("EDI") - self.verticalLayout_2.addWidget(self.EDI) - self.EBP = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.EBP.setFont(font) - self.EBP.setText("EBP=") - self.EBP.setObjectName("EBP") - self.verticalLayout_2.addWidget(self.EBP) - self.ESP = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.ESP.setFont(font) - self.ESP.setText("ESP=") - self.ESP.setObjectName("ESP") - self.verticalLayout_2.addWidget(self.ESP) - self.EIP = RegisterLabel(parent=self.registers_32) - font = QtGui.QFont() - font.setFamily("Monospace") - self.EIP.setFont(font) - self.EIP.setText("EIP=") - self.EIP.setObjectName("EIP") - self.verticalLayout_2.addWidget(self.EIP) - self.horizontalLayout_3.addLayout(self.verticalLayout_2) - spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_3.addItem(spacerItem3) - self.verticalLayout_14.addLayout(self.horizontalLayout_3) - self.gridLayout_6.addLayout(self.verticalLayout_14, 0, 0, 1, 1) - self.stackedWidget.addWidget(self.registers_32) - self.verticalLayout_19.addWidget(self.stackedWidget) - self.label_29 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_29.setFont(font) - self.label_29.setObjectName("label_29") - self.verticalLayout_19.addWidget(self.label_29) - self.line_2 = QtWidgets.QFrame(parent=self.scrollAreaWidgetContents_Registers) - self.line_2.setFrameShape(QtWidgets.QFrame.Shape.HLine) - self.line_2.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line_2.setObjectName("line_2") - self.verticalLayout_19.addWidget(self.line_2) - self.horizontalLayout_21 = QtWidgets.QHBoxLayout() - self.horizontalLayout_21.setSpacing(0) - self.horizontalLayout_21.setObjectName("horizontalLayout_21") - self.verticalLayout_5 = QtWidgets.QVBoxLayout() - self.verticalLayout_5.setSpacing(0) - self.verticalLayout_5.setObjectName("verticalLayout_5") - self.label_31 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_31.setFont(font) - self.label_31.setText("CF") - self.label_31.setObjectName("label_31") - self.verticalLayout_5.addWidget(self.label_31) - self.CF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.CF.setFont(font) - self.CF.setText("0") - self.CF.setObjectName("CF") - self.verticalLayout_5.addWidget(self.CF) - self.horizontalLayout_21.addLayout(self.verticalLayout_5) - self.verticalLayout_6 = QtWidgets.QVBoxLayout() - self.verticalLayout_6.setSpacing(0) - self.verticalLayout_6.setObjectName("verticalLayout_6") - self.label_35 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_35.setFont(font) - self.label_35.setText("PF") - self.label_35.setObjectName("label_35") - self.verticalLayout_6.addWidget(self.label_35) - self.PF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.PF.setFont(font) - self.PF.setText("0") - self.PF.setObjectName("PF") - self.verticalLayout_6.addWidget(self.PF) - self.horizontalLayout_21.addLayout(self.verticalLayout_6) - self.verticalLayout_7 = QtWidgets.QVBoxLayout() - self.verticalLayout_7.setSpacing(0) - self.verticalLayout_7.setObjectName("verticalLayout_7") - self.label_37 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_37.setFont(font) - self.label_37.setText("AF") - self.label_37.setObjectName("label_37") - self.verticalLayout_7.addWidget(self.label_37) - self.AF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.AF.setFont(font) - self.AF.setText("0") - self.AF.setObjectName("AF") - self.verticalLayout_7.addWidget(self.AF) - self.horizontalLayout_21.addLayout(self.verticalLayout_7) - self.verticalLayout_8 = QtWidgets.QVBoxLayout() - self.verticalLayout_8.setSpacing(0) - self.verticalLayout_8.setObjectName("verticalLayout_8") - self.label_39 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_39.setFont(font) - self.label_39.setText("ZF") - self.label_39.setObjectName("label_39") - self.verticalLayout_8.addWidget(self.label_39) - self.ZF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.ZF.setFont(font) - self.ZF.setText("0") - self.ZF.setObjectName("ZF") - self.verticalLayout_8.addWidget(self.ZF) - self.horizontalLayout_21.addLayout(self.verticalLayout_8) - self.verticalLayout_9 = QtWidgets.QVBoxLayout() - self.verticalLayout_9.setSpacing(0) - self.verticalLayout_9.setObjectName("verticalLayout_9") - self.label_41 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_41.setFont(font) - self.label_41.setText("SF") - self.label_41.setObjectName("label_41") - self.verticalLayout_9.addWidget(self.label_41) - self.SF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.SF.setFont(font) - self.SF.setText("0") - self.SF.setObjectName("SF") - self.verticalLayout_9.addWidget(self.SF) - self.horizontalLayout_21.addLayout(self.verticalLayout_9) - self.verticalLayout_10 = QtWidgets.QVBoxLayout() - self.verticalLayout_10.setSpacing(0) - self.verticalLayout_10.setObjectName("verticalLayout_10") - self.label_43 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_43.setFont(font) - self.label_43.setText("TF") - self.label_43.setObjectName("label_43") - self.verticalLayout_10.addWidget(self.label_43) - self.TF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.TF.setFont(font) - self.TF.setText("0") - self.TF.setObjectName("TF") - self.verticalLayout_10.addWidget(self.TF) - self.horizontalLayout_21.addLayout(self.verticalLayout_10) - self.verticalLayout_11 = QtWidgets.QVBoxLayout() - self.verticalLayout_11.setSpacing(0) - self.verticalLayout_11.setObjectName("verticalLayout_11") - self.label_45 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_45.setFont(font) - self.label_45.setText("IF") - self.label_45.setObjectName("label_45") - self.verticalLayout_11.addWidget(self.label_45) - self.IF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.IF.setFont(font) - self.IF.setText("0") - self.IF.setObjectName("IF") - self.verticalLayout_11.addWidget(self.IF) - self.horizontalLayout_21.addLayout(self.verticalLayout_11) - self.verticalLayout_12 = QtWidgets.QVBoxLayout() - self.verticalLayout_12.setSpacing(0) - self.verticalLayout_12.setObjectName("verticalLayout_12") - self.label_47 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_47.setFont(font) - self.label_47.setText("DF") - self.label_47.setObjectName("label_47") - self.verticalLayout_12.addWidget(self.label_47) - self.DF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.DF.setFont(font) - self.DF.setText("0") - self.DF.setObjectName("DF") - self.verticalLayout_12.addWidget(self.DF) - self.horizontalLayout_21.addLayout(self.verticalLayout_12) - self.verticalLayout_13 = QtWidgets.QVBoxLayout() - self.verticalLayout_13.setSpacing(0) - self.verticalLayout_13.setObjectName("verticalLayout_13") - self.label_49 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_49.setFont(font) - self.label_49.setText("OF") - self.label_49.setObjectName("label_49") - self.verticalLayout_13.addWidget(self.label_49) - self.OF = FlagRegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.OF.setFont(font) - self.OF.setText("0") - self.OF.setObjectName("OF") - self.verticalLayout_13.addWidget(self.OF) - self.horizontalLayout_21.addLayout(self.verticalLayout_13) - self.verticalLayout_19.addLayout(self.horizontalLayout_21) - spacerItem4 = QtWidgets.QSpacerItem(20, 15, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Fixed) - self.verticalLayout_19.addItem(spacerItem4) - self.label_30 = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_30.setFont(font) - self.label_30.setObjectName("label_30") - self.verticalLayout_19.addWidget(self.label_30) - self.line_3 = QtWidgets.QFrame(parent=self.scrollAreaWidgetContents_Registers) - self.line_3.setFrameShape(QtWidgets.QFrame.Shape.HLine) - self.line_3.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line_3.setObjectName("line_3") - self.verticalLayout_19.addWidget(self.line_3) - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setSpacing(0) - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.verticalLayout_4 = QtWidgets.QVBoxLayout() - self.verticalLayout_4.setSpacing(0) - self.verticalLayout_4.setObjectName("verticalLayout_4") - self.CS = RegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.CS.setFont(font) - self.CS.setText("CS=") - self.CS.setObjectName("CS") - self.verticalLayout_4.addWidget(self.CS) - self.ES = RegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.ES.setFont(font) - self.ES.setText("ES=") - self.ES.setObjectName("ES") - self.verticalLayout_4.addWidget(self.ES) - self.horizontalLayout_2.addLayout(self.verticalLayout_4) - spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_2.addItem(spacerItem5) - self.verticalLayout_15 = QtWidgets.QVBoxLayout() - self.verticalLayout_15.setSpacing(0) - self.verticalLayout_15.setObjectName("verticalLayout_15") - self.SS = RegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.SS.setFont(font) - self.SS.setText("SS=") - self.SS.setObjectName("SS") - self.verticalLayout_15.addWidget(self.SS) - self.GS = RegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.GS.setFont(font) - self.GS.setText("GS=") - self.GS.setObjectName("GS") - self.verticalLayout_15.addWidget(self.GS) - self.horizontalLayout_2.addLayout(self.verticalLayout_15) - spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_2.addItem(spacerItem6) - self.verticalLayout_18 = QtWidgets.QVBoxLayout() - self.verticalLayout_18.setSpacing(0) - self.verticalLayout_18.setObjectName("verticalLayout_18") - self.DS = RegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.DS.setFont(font) - self.DS.setText("DS=") - self.DS.setObjectName("DS") - self.verticalLayout_18.addWidget(self.DS) - self.FS = RegisterLabel(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.FS.setFont(font) - self.FS.setText("FS=") - self.FS.setObjectName("FS") - self.verticalLayout_18.addWidget(self.FS) - self.horizontalLayout_2.addLayout(self.verticalLayout_18) - self.verticalLayout_19.addLayout(self.horizontalLayout_2) - self.pushButton_ShowFloatRegisters = QtWidgets.QPushButton(parent=self.scrollAreaWidgetContents_Registers) - font = QtGui.QFont() - font.setFamily("Monospace") - self.pushButton_ShowFloatRegisters.setFont(font) - self.pushButton_ShowFloatRegisters.setObjectName("pushButton_ShowFloatRegisters") - self.verticalLayout_19.addWidget(self.pushButton_ShowFloatRegisters) - spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_19.addItem(spacerItem7) - self.horizontalLayout_4.addLayout(self.verticalLayout_19) - spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_4.addItem(spacerItem8) - self.gridLayout_8.addLayout(self.horizontalLayout_4, 0, 0, 1, 1) - self.scrollArea_Registers.setWidget(self.scrollAreaWidgetContents_Registers) - self.gridLayout_4.addWidget(self.scrollArea_Registers, 0, 0, 1, 1) - self.splitter_HexView_StackView = QtWidgets.QSplitter(parent=self.splitter_MainMiddle) - self.splitter_HexView_StackView.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter_HexView_StackView.setHandleWidth(10) - self.splitter_HexView_StackView.setObjectName("splitter_HexView_StackView") - self.widget_HexView = QtWidgets.QWidget(parent=self.splitter_HexView_StackView) - self.widget_HexView.setObjectName("widget_HexView") - self.gridLayout = QtWidgets.QGridLayout(self.widget_HexView) - self.gridLayout.setContentsMargins(0, 0, 0, 0) - self.gridLayout.setHorizontalSpacing(0) - self.gridLayout.setVerticalSpacing(4) - self.gridLayout.setObjectName("gridLayout") - self.scrollArea_Hex = QtWidgets.QScrollArea(parent=self.widget_HexView) - self.scrollArea_Hex.setWidgetResizable(True) - self.scrollArea_Hex.setObjectName("scrollArea_Hex") - self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() - self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 490, 181)) - self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2") - self.gridLayout_11 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents_2) - self.gridLayout_11.setContentsMargins(0, 0, 0, 0) - self.gridLayout_11.setSpacing(0) - self.gridLayout_11.setObjectName("gridLayout_11") - self.horizontalLayout_5 = QtWidgets.QHBoxLayout() - self.horizontalLayout_5.setSpacing(0) - self.horizontalLayout_5.setObjectName("horizontalLayout_5") - self.tableWidget_HexView_Address = QtWidgets.QTableWidget(parent=self.scrollAreaWidgetContents_2) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_HexView_Address.setFont(font) - self.tableWidget_HexView_Address.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_HexView_Address.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_HexView_Address.setShowGrid(False) - self.tableWidget_HexView_Address.setWordWrap(False) - self.tableWidget_HexView_Address.setObjectName("tableWidget_HexView_Address") - self.tableWidget_HexView_Address.setColumnCount(1) - self.tableWidget_HexView_Address.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_HexView_Address.setHorizontalHeaderItem(0, item) - self.tableWidget_HexView_Address.horizontalHeader().setVisible(False) - self.tableWidget_HexView_Address.verticalHeader().setVisible(False) - self.horizontalLayout_5.addWidget(self.tableWidget_HexView_Address) - self.line_5 = QtWidgets.QFrame(parent=self.scrollAreaWidgetContents_2) - self.line_5.setFrameShape(QtWidgets.QFrame.Shape.VLine) - self.line_5.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line_5.setObjectName("line_5") - self.horizontalLayout_5.addWidget(self.line_5) - self.tableView_HexView_Hex = HexView(parent=self.scrollAreaWidgetContents_2) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableView_HexView_Hex.setFont(font) - self.tableView_HexView_Hex.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.SizeAdjustPolicy.AdjustToContents) - self.tableView_HexView_Hex.setObjectName("tableView_HexView_Hex") - self.horizontalLayout_5.addWidget(self.tableView_HexView_Hex) - self.line_4 = QtWidgets.QFrame(parent=self.scrollAreaWidgetContents_2) - self.line_4.setFrameShape(QtWidgets.QFrame.Shape.VLine) - self.line_4.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line_4.setObjectName("line_4") - self.horizontalLayout_5.addWidget(self.line_4) - self.tableView_HexView_Ascii = AsciiView(parent=self.scrollAreaWidgetContents_2) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableView_HexView_Ascii.setFont(font) - self.tableView_HexView_Ascii.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.SizeAdjustPolicy.AdjustToContents) - self.tableView_HexView_Ascii.setObjectName("tableView_HexView_Ascii") - self.horizontalLayout_5.addWidget(self.tableView_HexView_Ascii) - spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_5.addItem(spacerItem9) - self.gridLayout_11.addLayout(self.horizontalLayout_5, 2, 0, 1, 1) - self.label_HexView_Information = QtWidgets.QLabel(parent=self.scrollAreaWidgetContents_2) - self.label_HexView_Information.setText("") - self.label_HexView_Information.setObjectName("label_HexView_Information") - self.gridLayout_11.addWidget(self.label_HexView_Information, 0, 0, 1, 1) - self.line_6 = QtWidgets.QFrame(parent=self.scrollAreaWidgetContents_2) - self.line_6.setFrameShape(QtWidgets.QFrame.Shape.HLine) - self.line_6.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - self.line_6.setObjectName("line_6") - self.gridLayout_11.addWidget(self.line_6, 1, 0, 1, 1) - self.label_HexView_Information.raise_() - self.line_6.raise_() - self.scrollArea_Hex.setWidget(self.scrollAreaWidgetContents_2) - self.gridLayout.addWidget(self.scrollArea_Hex, 0, 0, 1, 1) - self.verticalScrollBar_HexView = QtWidgets.QScrollBar(parent=self.widget_HexView) - self.verticalScrollBar_HexView.setOrientation(QtCore.Qt.Orientation.Vertical) - self.verticalScrollBar_HexView.setObjectName("verticalScrollBar_HexView") - self.gridLayout.addWidget(self.verticalScrollBar_HexView, 0, 1, 1, 1) - self.widget_StackView = QtWidgets.QWidget(parent=self.splitter_HexView_StackView) - self.widget_StackView.setObjectName("widget_StackView") - self.gridLayout_3 = QtWidgets.QGridLayout(self.widget_StackView) - self.gridLayout_3.setContentsMargins(0, 0, 0, 0) - self.gridLayout_3.setSpacing(0) - self.gridLayout_3.setObjectName("gridLayout_3") - self.stackedWidget_StackScreens = QtWidgets.QStackedWidget(parent=self.widget_StackView) - self.stackedWidget_StackScreens.setObjectName("stackedWidget_StackScreens") - self.StackTrace = QtWidgets.QWidget() - self.StackTrace.setObjectName("StackTrace") - self.gridLayout_9 = QtWidgets.QGridLayout(self.StackTrace) - self.gridLayout_9.setContentsMargins(0, 0, 0, 0) - self.gridLayout_9.setSpacing(0) - self.gridLayout_9.setObjectName("gridLayout_9") - self.tableWidget_StackTrace = QtWidgets.QTableWidget(parent=self.StackTrace) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_StackTrace.setFont(font) - self.tableWidget_StackTrace.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_StackTrace.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_StackTrace.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_StackTrace.setWordWrap(False) - self.tableWidget_StackTrace.setObjectName("tableWidget_StackTrace") - self.tableWidget_StackTrace.setColumnCount(2) - self.tableWidget_StackTrace.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_StackTrace.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_StackTrace.setHorizontalHeaderItem(1, item) - self.tableWidget_StackTrace.horizontalHeader().setStretchLastSection(True) - self.tableWidget_StackTrace.verticalHeader().setVisible(False) - self.tableWidget_StackTrace.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_StackTrace.verticalHeader().setMinimumSectionSize(16) - self.gridLayout_9.addWidget(self.tableWidget_StackTrace, 0, 0, 1, 1) - self.stackedWidget_StackScreens.addWidget(self.StackTrace) - self.Stack = QtWidgets.QWidget() - self.Stack.setObjectName("Stack") - self.gridLayout_10 = QtWidgets.QGridLayout(self.Stack) - self.gridLayout_10.setContentsMargins(0, 0, 0, 0) - self.gridLayout_10.setSpacing(0) - self.gridLayout_10.setObjectName("gridLayout_10") - self.tableWidget_Stack = QtWidgets.QTableWidget(parent=self.Stack) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_Stack.setFont(font) - self.tableWidget_Stack.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Stack.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_Stack.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Stack.setObjectName("tableWidget_Stack") - self.tableWidget_Stack.setColumnCount(3) - self.tableWidget_Stack.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Stack.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Stack.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Stack.setHorizontalHeaderItem(2, item) - self.tableWidget_Stack.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Stack.verticalHeader().setVisible(False) - self.tableWidget_Stack.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Stack.verticalHeader().setMinimumSectionSize(16) - self.gridLayout_10.addWidget(self.tableWidget_Stack, 0, 0, 1, 1) - self.stackedWidget_StackScreens.addWidget(self.Stack) - self.gridLayout_3.addWidget(self.stackedWidget_StackScreens, 0, 0, 1, 1) - self.gridLayout_5.addWidget(self.splitter_MainMiddle, 0, 0, 1, 1) - MainWindow_MemoryView.setCentralWidget(self.centralwidget) - self.menubar = QtWidgets.QMenuBar(parent=MainWindow_MemoryView) - self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 32)) - self.menubar.setObjectName("menubar") - self.menuView = QtWidgets.QMenu(parent=self.menubar) - self.menuView.setObjectName("menuView") - self.menuDebug = QtWidgets.QMenu(parent=self.menubar) - self.menuDebug.setObjectName("menuDebug") - self.menuTools = QtWidgets.QMenu(parent=self.menubar) - self.menuTools.setObjectName("menuTools") - self.menuFile = QtWidgets.QMenu(parent=self.menubar) - self.menuFile.setObjectName("menuFile") - self.menuHelp = QtWidgets.QMenu(parent=self.menubar) - self.menuHelp.setObjectName("menuHelp") - MainWindow_MemoryView.setMenuBar(self.menubar) - self.statusbar = QtWidgets.QStatusBar(parent=MainWindow_MemoryView) - self.statusbar.setObjectName("statusbar") - MainWindow_MemoryView.setStatusBar(self.statusbar) - self.actionBookmarks = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionBookmarks.setObjectName("actionBookmarks") - self.actionStackTrace_Info = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionStackTrace_Info.setObjectName("actionStackTrace_Info") - self.actionInject_so_file = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionInject_so_file.setObjectName("actionInject_so_file") - self.actionInject_DLL_file = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionInject_DLL_file.setObjectName("actionInject_DLL_file") - self.actionRun = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionRun.setObjectName("actionRun") - self.actionBreak = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionBreak.setObjectName("actionBreak") - self.actionStep = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionStep.setObjectName("actionStep") - self.actionStep_Over = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionStep_Over.setObjectName("actionStep_Over") - self.actionExecute_Till_Return = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionExecute_Till_Return.setObjectName("actionExecute_Till_Return") - self.actionToggle_Breakpoint = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionToggle_Breakpoint.setObjectName("actionToggle_Breakpoint") - self.actionBreakpoints = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionBreakpoints.setObjectName("actionBreakpoints") - self.actionFunctions = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionFunctions.setObjectName("actionFunctions") - self.actionSet_Address = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionSet_Address.setObjectName("actionSet_Address") - self.actionCall_Function = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionCall_Function.setObjectName("actionCall_Function") - self.actionLoad_Trace = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionLoad_Trace.setObjectName("actionLoad_Trace") - self.actionLibpince = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionLibpince.setObjectName("actionLibpince") - self.actionGDB_Log_File = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionGDB_Log_File.setObjectName("actionGDB_Log_File") - self.actionSearch_Instructions = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionSearch_Instructions.setObjectName("actionSearch_Instructions") - self.actionMemory_Regions = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionMemory_Regions.setObjectName("actionMemory_Regions") - self.actionDissect_Code = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionDissect_Code.setObjectName("actionDissect_Code") - self.actionDissect_Mono = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionDissect_Mono.setObjectName("actionDissect_Mono") - self.actionReferenced_Strings = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionReferenced_Strings.setObjectName("actionReferenced_Strings") - self.actionReferenced_Calls = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionReferenced_Calls.setObjectName("actionReferenced_Calls") - self.actionToggle_Attach = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionToggle_Attach.setObjectName("actionToggle_Attach") - self.actionRestore_Instructions = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionRestore_Instructions.setObjectName("actionRestore_Instructions") - self.actionLibpince_Engine = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionLibpince_Engine.setObjectName("actionLibpince_Engine") - self.actionStructures = QtGui.QAction(parent=MainWindow_MemoryView) - self.actionStructures.setObjectName("actionStructures") - self.menuView.addAction(self.actionBookmarks) - self.menuView.addAction(self.actionStackTrace_Info) - self.menuView.addAction(self.actionBreakpoints) - self.menuView.addAction(self.actionFunctions) - self.menuView.addAction(self.actionGDB_Log_File) - self.menuView.addAction(self.actionMemory_Regions) - self.menuView.addAction(self.actionRestore_Instructions) - self.menuView.addSeparator() - self.menuView.addAction(self.actionReferenced_Strings) - self.menuView.addAction(self.actionReferenced_Calls) - self.menuDebug.addAction(self.actionRun) - self.menuDebug.addAction(self.actionBreak) - self.menuDebug.addSeparator() - self.menuDebug.addAction(self.actionStep) - self.menuDebug.addAction(self.actionStep_Over) - self.menuDebug.addAction(self.actionExecute_Till_Return) - self.menuDebug.addAction(self.actionToggle_Breakpoint) - self.menuDebug.addAction(self.actionSet_Address) - self.menuDebug.addSeparator() - self.menuDebug.addAction(self.actionToggle_Attach) - self.menuTools.addAction(self.actionInject_so_file) - self.menuTools.addAction(self.actionInject_DLL_file) - self.menuTools.addAction(self.actionCall_Function) - self.menuTools.addAction(self.actionSearch_Instructions) - self.menuTools.addAction(self.actionDissect_Code) - self.menuTools.addAction(self.actionDissect_Mono) - self.menuTools.addAction(self.actionStructures) - self.menuTools.addAction(self.actionLibpince_Engine) - self.menuFile.addAction(self.actionLoad_Trace) - self.menuHelp.addAction(self.actionLibpince) - self.menubar.addAction(self.menuFile.menuAction()) - self.menubar.addAction(self.menuView.menuAction()) - self.menubar.addAction(self.menuDebug.menuAction()) - self.menubar.addAction(self.menuTools.menuAction()) - self.menubar.addAction(self.menuHelp.menuAction()) - - self.retranslateUi(MainWindow_MemoryView) - self.stackedWidget.setCurrentIndex(1) - self.stackedWidget_StackScreens.setCurrentIndex(0) - QtCore.QMetaObject.connectSlotsByName(MainWindow_MemoryView) - - def retranslateUi(self, MainWindow_MemoryView): - _translate = QtCore.QCoreApplication.translate - MainWindow_MemoryView.setWindowTitle(_translate("MainWindow_MemoryView", "Memory Viewer")) - item = self.tableWidget_Disassemble.horizontalHeaderItem(0) - item.setText(_translate("MainWindow_MemoryView", "Address")) - item = self.tableWidget_Disassemble.horizontalHeaderItem(1) - item.setText(_translate("MainWindow_MemoryView", "Opcodes")) - item = self.tableWidget_Disassemble.horizontalHeaderItem(2) - item.setText(_translate("MainWindow_MemoryView", "Instruction")) - item = self.tableWidget_Disassemble.horizontalHeaderItem(3) - item.setText(_translate("MainWindow_MemoryView", "Comment")) - self.label_3.setText(_translate("MainWindow_MemoryView", "Registers")) - self.label_29.setText(_translate("MainWindow_MemoryView", "Flags")) - self.label_30.setText(_translate("MainWindow_MemoryView", "Segment Registers")) - self.pushButton_ShowFloatRegisters.setText(_translate("MainWindow_MemoryView", "Show Float Registers")) - item = self.tableWidget_HexView_Address.horizontalHeaderItem(0) - item.setText(_translate("MainWindow_MemoryView", "Address")) - item = self.tableWidget_StackTrace.horizontalHeaderItem(0) - item.setText(_translate("MainWindow_MemoryView", "Return Address")) - item = self.tableWidget_StackTrace.horizontalHeaderItem(1) - item.setText(_translate("MainWindow_MemoryView", "Frame Address")) - item = self.tableWidget_Stack.horizontalHeaderItem(0) - item.setText(_translate("MainWindow_MemoryView", "Address")) - item = self.tableWidget_Stack.horizontalHeaderItem(1) - item.setText(_translate("MainWindow_MemoryView", "Value")) - item = self.tableWidget_Stack.horizontalHeaderItem(2) - item.setText(_translate("MainWindow_MemoryView", "Points to")) - self.menuView.setTitle(_translate("MainWindow_MemoryView", "V&iew")) - self.menuDebug.setTitle(_translate("MainWindow_MemoryView", "&Debug")) - self.menuTools.setTitle(_translate("MainWindow_MemoryView", "&Tools")) - self.menuFile.setTitle(_translate("MainWindow_MemoryView", "Fi&le")) - self.menuHelp.setTitle(_translate("MainWindow_MemoryView", "Help")) - self.actionBookmarks.setText(_translate("MainWindow_MemoryView", "&Bookmarks")) - self.actionStackTrace_Info.setText(_translate("MainWindow_MemoryView", "&StackTrace Info")) - self.actionInject_so_file.setText(_translate("MainWindow_MemoryView", "&Inject .so file")) - self.actionInject_DLL_file.setText(_translate("MainWindow_MemoryView", "Inject D&LL file")) - self.actionRun.setText(_translate("MainWindow_MemoryView", "&Break")) - self.actionBreak.setText(_translate("MainWindow_MemoryView", "&Run")) - self.actionStep.setText(_translate("MainWindow_MemoryView", "&Step[F7]")) - self.actionStep_Over.setText(_translate("MainWindow_MemoryView", "Step &Over[F8]")) - self.actionExecute_Till_Return.setText(_translate("MainWindow_MemoryView", "&Execute Till Return[Shift+F8]")) - self.actionToggle_Breakpoint.setText(_translate("MainWindow_MemoryView", "&Toggle Breakpoint[F5]")) - self.actionBreakpoints.setText(_translate("MainWindow_MemoryView", "B&reakpoints")) - self.actionFunctions.setText(_translate("MainWindow_MemoryView", "&Functions")) - self.actionSet_Address.setText(_translate("MainWindow_MemoryView", "Set Address[Shift+F4]")) - self.actionCall_Function.setText(_translate("MainWindow_MemoryView", "&Call Function")) - self.actionLoad_Trace.setText(_translate("MainWindow_MemoryView", "&Load Trace")) - self.actionLibpince.setText(_translate("MainWindow_MemoryView", "&Libpince")) - self.actionGDB_Log_File.setText(_translate("MainWindow_MemoryView", "&GDB Log File")) - self.actionSearch_Instructions.setText(_translate("MainWindow_MemoryView", "&Search Instructions")) - self.actionMemory_Regions.setText(_translate("MainWindow_MemoryView", "&Memory Regions")) - self.actionDissect_Code.setText(_translate("MainWindow_MemoryView", "&Dissect Code")) - self.actionDissect_Mono.setText(_translate("MainWindow_MemoryView", "Dissect &Mono/IL2CPP")) - self.actionReferenced_Strings.setText(_translate("MainWindow_MemoryView", "R&eferenced Strings")) - self.actionReferenced_Calls.setText(_translate("MainWindow_MemoryView", "Referenced &Calls")) - self.actionToggle_Attach.setText(_translate("MainWindow_MemoryView", "To&ggle Attach")) - self.actionRestore_Instructions.setText(_translate("MainWindow_MemoryView", "Restore Instructions")) - self.actionLibpince_Engine.setText(_translate("MainWindow_MemoryView", "Libpince Engine")) - self.actionStructures.setText(_translate("MainWindow_MemoryView", "Structures")) -from GUI.Labels.FlagRegisterLabel import FlagRegisterLabel -from GUI.Labels.RegisterLabel import RegisterLabel -from GUI.TableViews.AsciiView import AsciiView -from GUI.TableViews.HexView import HexView diff --git a/GUI/Widgets/MemoryView/MemoryView.py b/GUI/Widgets/MemoryView/MemoryView.py deleted file mode 100644 index 857cafde..00000000 --- a/GUI/Widgets/MemoryView/MemoryView.py +++ /dev/null @@ -1,1834 +0,0 @@ -from PyQt6.QtWidgets import QMainWindow, QWidget, QTableWidgetItem, QMenu, QMessageBox, QFileDialog, QAbstractItemView, QAbstractSlider, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QKeyEvent, QWheelEvent, QContextMenuEvent, QColor, QColorConstants -from PyQt6.QtCore import Qt, QEvent, QObject, QTimer, QKeyCombination, QSignalBlocker, QItemSelection, QItemSelectionModel -from GUI.AbstractTableModels.AsciiModel import AsciiModel -from GUI.AbstractTableModels.HexModel import HexModel -from GUI.Labels.RegisterLabel import RegisterLabel -from GUI.Overlays.DisassembleArrowOverlay import DisassembleArrowOverlay -from GUI.Session.session import SessionDataChanged, SessionManager, StructureManager -from GUI.States import states -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.Bookmark.Bookmark import BookmarkWidget -from GUI.Widgets.BreakpointInfo.BreakpointInfo import BreakpointInfoWidget -from GUI.Widgets.DissectCode.DissectCode import DissectCodeDialog -from GUI.Widgets.EditInstruction.EditInstruction import EditInstructionDialog -from GUI.Widgets.ExamineReferrers.ExamineReferrers import ExamineReferrersWidget -from GUI.Widgets.FloatRegister.FloatRegister import FloatRegisterWidget -from GUI.Widgets.FunctionsInfo.FunctionsInfo import FunctionsInfoWidget -from GUI.Widgets.HexEdit.HexEdit import HexEditDialog -from GUI.Widgets.LogFile.LogFile import LogFileWidget -from GUI.Widgets.ManualAddress.ManualAddress import ManualAddressDialog -from GUI.Widgets.MemoryRegions.MemoryRegions import MemoryRegionsWidget -from GUI.Widgets.MemoryView.Form.MemoryViewWindow import Ui_MainWindow_MemoryView -from GUI.Widgets.MonoDissect.MonoDissect import MonoDissectDialog -from GUI.Widgets.ReferencedCalls.ReferencedCalls import ReferencedCallsWidget -from GUI.Widgets.ReferencedStrings.ReferencedStrings import ReferencedStringsWidget -from GUI.Widgets.RestoreInstructions.RestoreInstructions import RestoreInstructionsWidget -from GUI.Widgets.SearchInstructions.SearchInstructions import SearchInstructionsWidget -from GUI.Widgets.StackTraceInfo.StackTraceInfo import StackTraceInfoWidget -from GUI.Widgets.Structures import mono_export -from GUI.Widgets.Structures.StructureEditorDialog import StructureEditorDialog -from GUI.Widgets.Structures.StructureViewDialog import StructureViewDialog -from GUI.Widgets.TraceInstructions.TraceInstructionsWindow import TraceInstructionsWindow -from GUI.Widgets.TrackBreakpoint.TrackBreakpoint import TrackBreakpointWidget -from libpince import debugcore, monocore, typedefs, utils -from libpince.utils import logger -from tr.tr import TranslationConstants as tr -from time import time -import os - -# row colors for disassemble qtablewidget -PC_COLOR = QColorConstants.Blue -BOOKMARK_COLOR = QColorConstants.Cyan -BREAKPOINT_COLOR = QColorConstants.Red - -# jmp/call references are drawn as arrows overlaid left of the instruction column (see DisassembleArrowOverlay) -DISAS_MAX_REFS_PER_TARGET = 12 # cap referrer arrows converging on a single visible target to avoid clutter -DISAS_MAX_ARROWS = 240 # overall safety cap on the number of arrows drawn for one view -DISAS_BYTES_PER_ROW = 15 # maximum x86 instruction length - -# represents the index of columns in disassemble table -DISAS_ADDR_COL = 0 -DISAS_OPCODES_COL = 1 -DISAS_INSTR_COL = 2 -DISAS_COMMENT_COL = 3 - -# represents the index of columns in stacktrace table -STACKTRACE_RETURN_ADDRESS_COL = 0 -STACKTRACE_FRAME_ADDRESS_COL = 1 - -# represents the index of columns in stack table -STACK_POINTER_ADDRESS_COL = 0 -STACK_VALUE_COL = 1 -STACK_POINTS_TO_COL = 2 - -# represents row and column counts of Hex table -HEX_VIEW_COL_COUNT = 16 -HEX_VIEW_ROW_COUNT = 42 # J-JUST A COINCIDENCE, I SWEAR! - - -class MemoryViewWindow(QMainWindow, Ui_MainWindow_MemoryView): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.updating_memoryview = False - self.stack_from_base_pointer = False - self.stacktrace_info_widget = StackTraceInfoWidget(self) - self.float_registers_widget = FloatRegisterWidget(self) - # Created lazily on first open and reused afterwards, so we don't leak on each open. - self.bookmark_widget = None - self.breakpoint_widget = None - self.functions_info_widget = None - self.memory_regions_widget = None - self.restore_instructions_widget = None - states.status_thread.process_stopped.connect(self.on_process_stop) - states.status_thread.process_running.connect(self.on_process_running) - states.setting_signals.changed.connect(self.set_dynamic_debug_hotkeys) - states.session_signals.new_session.connect(self.on_new_session) - self.session = SessionManager.get_session() - self.set_debug_menu_shortcuts() - self.set_dynamic_debug_hotkeys() - self.initialize_file_context_menu() - self.initialize_view_context_menu() - self.initialize_debug_context_menu() - self.initialize_tools_context_menu() - self.initialize_help_context_menu() - self.initialize_disassemble_view() - self.initialize_register_view() - self.initialize_stack_view() - self.initialize_hex_view() - - self.label_HexView_Information.contextMenuEvent = self.label_HexView_Information_context_menu_event - - self.splitter_Disassemble_Registers.setStretchFactor(0, 1) - # Keep the disassembler/registers pane and the hex/stack pane at a 3:2 ratio, both on first show and on later window resizes. - self.splitter_MainMiddle.setStretchFactor(0, 3) - self.splitter_MainMiddle.setStretchFactor(1, 2) - self.splitter_MainMiddle.setSizes([3000, 2000]) - self.widget_StackView.resize(660, self.widget_StackView.height()) - self.widget_Registers.resize(330, self.widget_Registers.height()) - guiutils.center(self) - - def set_dynamic_debug_hotkeys(self) -> None: - self.actionBreak.setText(tr.BREAK.format(states.hotkeys.break_hotkey.get_active_key())) - self.actionRun.setText(tr.RUN.format(states.hotkeys.continue_hotkey.get_active_key())) - self.actionToggle_Attach.setText(tr.TOGGLE_ATTACH.format(states.hotkeys.toggle_attach_hotkey.get_active_key())) - - def set_debug_menu_shortcuts(self) -> None: - self.shortcut_step = QShortcut(QKeySequence("F7"), self) - self.shortcut_step.activated.connect(self.step_instruction) - self.shortcut_step_over = QShortcut(QKeySequence("F8"), self) - self.shortcut_step_over.activated.connect(self.step_over_instruction) - self.shortcut_execute_till_return = QShortcut(QKeySequence("Shift+F8"), self) - self.shortcut_execute_till_return.activated.connect(self.execute_till_return) - self.shortcut_toggle_breakpoint = QShortcut(QKeySequence("F5"), self) - self.shortcut_toggle_breakpoint.activated.connect(self.toggle_breakpoint) - self.shortcut_set_address = QShortcut(QKeySequence("Shift+F4"), self) - self.shortcut_set_address.activated.connect(self.set_address) - - def initialize_file_context_menu(self) -> None: - self.actionLoad_Trace.triggered.connect(self.show_trace_window) - - def initialize_debug_context_menu(self) -> None: - self.actionBreak.triggered.connect(debugcore.interrupt_inferior) - self.actionRun.triggered.connect(debugcore.continue_inferior) - self.actionToggle_Attach.triggered.connect(lambda: self.parent().toggle_attach_hotkey_pressed()) - self.actionStep.triggered.connect(self.step_instruction) - self.actionStep_Over.triggered.connect(self.step_over_instruction) - self.actionExecute_Till_Return.triggered.connect(self.execute_till_return) - - # Ignore the "checked" bool param as we don't make use of it - self.actionToggle_Breakpoint.triggered.connect(lambda checked: self.toggle_breakpoint()) - self.actionSet_Address.triggered.connect(self.set_address) - - def initialize_view_context_menu(self) -> None: - self.actionBookmarks.triggered.connect(self.actionBookmarks_triggered) - self.actionStackTrace_Info.triggered.connect(self.actionStackTrace_Info_triggered) - self.actionBreakpoints.triggered.connect(self.actionBreakpoints_triggered) - self.actionFunctions.triggered.connect(self.actionFunctions_triggered) - self.actionGDB_Log_File.triggered.connect(self.actionGDB_Log_File_triggered) - self.actionMemory_Regions.triggered.connect(self.actionMemory_Regions_triggered) - self.actionRestore_Instructions.triggered.connect(self.actionRestore_Instructions_triggered) - self.actionReferenced_Strings.triggered.connect(self.actionReferenced_Strings_triggered) - self.actionReferenced_Calls.triggered.connect(self.actionReferenced_Calls_triggered) - - def initialize_tools_context_menu(self) -> None: - self.actionInject_so_file.triggered.connect(self.actionInject_so_file_triggered) - self.actionInject_DLL_file.triggered.connect(self.actionInject_DLL_file_triggered) - self.actionCall_Function.triggered.connect(self.actionCall_Function_triggered) - self.actionSearch_Instructions.triggered.connect(self.actionSearch_Instructions_triggered) - self.actionDissect_Code.triggered.connect(self.actionDissect_Code_triggered) - self.actionDissect_Mono.triggered.connect(self.actionDissect_Mono_triggered) - self.actionStructures.triggered.connect(self.actionStructures_triggered) - self.actionLibpince_Engine.triggered.connect(self.actionLibpince_Engine_triggered) - - def initialize_help_context_menu(self) -> None: - self.actionLibpince.triggered.connect(self.actionLibpince_triggered) - - def initialize_register_view(self) -> None: - self.pushButton_ShowFloatRegisters.clicked.connect(self.pushButton_ShowFloatRegisters_clicked) - for register_label in self.findChildren(RegisterLabel): - register_label.hex_view_requested.connect(lambda address: self.hex_dump_address(utils.safe_str_to_int(address, 16))) - register_label.disassemble_requested.connect(self.disassemble_expression) - if guiutils.check_inferior_running(self, show_message=False): - self.pushButton_ShowFloatRegisters.setEnabled(False) - - def initialize_stack_view(self) -> None: - self.stackedWidget_StackScreens.setCurrentWidget(self.StackTrace) - self.tableWidget_StackTrace.setColumnWidth(STACKTRACE_RETURN_ADDRESS_COL, 350) - - self.tableWidget_Stack.contextMenuEvent = self.tableWidget_Stack_context_menu_event - self.tableWidget_StackTrace.contextMenuEvent = self.tableWidget_StackTrace_context_menu_event - self.tableWidget_Stack.itemDoubleClicked.connect(self.tableWidget_Stack_double_click) - self.tableWidget_StackTrace.itemDoubleClicked.connect(self.tableWidget_StackTrace_double_click) - - # Saving the original function because super() doesn't work when we override functions like this - self.tableWidget_Stack_keyPressEvent_original = self.tableWidget_Stack.keyPressEvent - self.tableWidget_Stack.keyPressEvent = self.tableWidget_Stack_key_press_event - - # Saving the original function because super() doesn't work when we override functions like this - self.tableWidget_StackTrace_keyPressEvent_original = self.tableWidget_StackTrace.keyPressEvent - self.tableWidget_StackTrace.keyPressEvent = self.tableWidget_StackTrace_key_press_event - - def initialize_disassemble_view(self) -> None: - self.tableWidget_Disassemble.setColumnWidth(DISAS_ADDR_COL, 400) - self.tableWidget_Disassemble.setColumnWidth(DISAS_OPCODES_COL, 350) - self.tableWidget_Disassemble.setColumnWidth(DISAS_INSTR_COL, 450) - - # Draw jmp/call references as arrows overlaid on the left of the instruction column. - self.disassemble_arrow_overlay = DisassembleArrowOverlay(self.tableWidget_Disassemble, DISAS_INSTR_COL) - self.disassemble_arrow_overlay.follow_requested.connect(self.disassemble_arrow_follow) - # The most rows any viewport could ever need, computed once from the desktop resolution. - # Sizing for the largest possible screen keeps a later resize or splitter drag from underfilling the table. - row_height = max(1, self.tableWidget_Disassemble.verticalHeader().defaultSectionSize()) - screen_height = max(screen.size().height() for screen in QApplication.screens()) - self.disassemble_screen_rows = max(20, screen_height // row_height) - - self.disassemble_last_selected_address_int = 0 - self.disassemble_selected_addresses: set[int] = set() - self.disassemble_currently_displayed_address = "0" - self.widget_Disassemble.wheelEvent = self.widget_Disassemble_wheel_event - - self.bDisassemblyScrolling = False # rejects new scroll requests while scrolling - self.tableWidget_Disassemble_wheelEvent_original = self.tableWidget_Disassemble.wheelEvent - self.tableWidget_Disassemble.wheelEvent = QEvent.ignore - self.verticalScrollBar_Disassemble.wheelEvent = QEvent.ignore - self.verticalScrollBar_Disassemble.sliderChange = self.disassemble_scrollbar_sliderchanged - guiutils.center_scroll_bar(self.verticalScrollBar_Disassemble) - - # Format: [address1, address2, ...] - self.tableWidget_Disassemble.travel_history = [] - - # Saving the original function because super() doesn't work when we override functions like this - self.tableWidget_Disassemble_keyPressEvent_original = self.tableWidget_Disassemble.keyPressEvent - self.tableWidget_Disassemble.keyPressEvent = self.tableWidget_Disassemble_key_press_event - self.tableWidget_Disassemble.contextMenuEvent = self.tableWidget_Disassemble_context_menu_event - - self.tableWidget_Disassemble.itemDoubleClicked.connect(self.tableWidget_Disassemble_item_double_clicked) - self.tableWidget_Disassemble.itemSelectionChanged.connect(self.tableWidget_Disassemble_item_selection_changed) - - def initialize_hex_view(self) -> None: - # Determines where selection starts and ends - self.hex_selection_start = 0 - self.hex_selection_end = 0 - # Actual start and end addresses of the selection - self.hex_selection_address_begin = 0 - self.hex_selection_address_end = 0 - self.hex_view_current_region = typedefs.tuple_region_info(0, 0, None, None, None) - # Number of rows shown is recomputed from the viewport height (see adjust_hex_view_rows). - self.hex_row_count = HEX_VIEW_ROW_COUNT - self.hex_model = HexModel(self.hex_row_count, HEX_VIEW_COL_COUNT) - self.ascii_model = AsciiModel(self.hex_row_count, HEX_VIEW_COL_COUNT) - self.tableView_HexView_Hex.setModel(self.hex_model) - self.tableView_HexView_Ascii.setModel(self.ascii_model) - # Adjust cell sizes after setting model to ensure correct size - self.tableView_HexView_Hex.adjust_cell_size(2) - self.tableView_HexView_Ascii.adjust_cell_size(1) - - self.widget_HexView.wheelEvent = self.widget_HexView_wheel_event - # Saving the original function because super() doesn't work when we override functions like this - self.widget_HexView_keyPressEvent_original = self.widget_HexView.keyPressEvent - self.widget_HexView.keyPressEvent = self.widget_HexView_key_press_event - - self.tableView_HexView_Hex.contextMenuEvent = self.widget_HexView_context_menu_event - self.tableView_HexView_Ascii.contextMenuEvent = self.widget_HexView_context_menu_event - - self.bHexViewScrolling = False # rejects new scroll requests while scrolling - self.verticalScrollBar_HexView.wheelEvent = QEvent.ignore - self.verticalScrollBar_HexView.sliderChange = self.hex_view_scrollbar_sliderchanged - guiutils.center_scroll_bar(self.verticalScrollBar_HexView) - - self.tableWidget_HexView_Address.wheelEvent = QEvent.ignore - self.tableWidget_HexView_Address.setAutoScroll(False) - self.tableWidget_HexView_Address.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) - - self.tableView_HexView_Hex.selectionModel().selectionChanged.connect(self.hex_view_selection_changed) - self.tableView_HexView_Ascii.selectionModel().selectionChanged.connect(self.hex_view_selection_changed) - self.tableView_HexView_Hex.scroll_requested.connect(self.hex_view_scroll_by_row) - self.tableView_HexView_Ascii.scroll_requested.connect(self.hex_view_scroll_by_row) - self.tableView_HexView_Hex.page_scroll_requested.connect(self.hex_view_page_scroll) - self.tableView_HexView_Ascii.page_scroll_requested.connect(self.hex_view_page_scroll) - - self.scrollArea_Hex.viewport().installEventFilter(self) - self.scrollArea_Hex.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.scrollArea_Hex.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.tableWidget_HexView_Address.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.tableWidget_HexView_Address.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.tableWidget_HexView_Address.verticalHeader().setMinimumSectionSize(self.tableView_HexView_Hex.verticalHeader().minimumSectionSize()) - self.tableWidget_HexView_Address.verticalHeader().setDefaultSectionSize(self.tableView_HexView_Hex.verticalHeader().defaultSectionSize()) - self.tableWidget_HexView_Address.verticalHeader().setMaximumSectionSize(self.tableView_HexView_Hex.verticalHeader().maximumSectionSize()) - - self.hex_update_timer = QTimer(self, timeout=self.hex_update_loop) - self.hex_update_timer.start(200) - - def show_trace_window(self) -> None: - TraceInstructionsWindow(self, prompt_dialog=False) - - def step_instruction(self) -> None: - if not ( - debugcore.currentpid == -1 - or debugcore.driving_inferior - or debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING - or self.updating_memoryview - ): - debugcore.step_instruction() - - def step_over_instruction(self) -> None: - if not ( - debugcore.currentpid == -1 - or debugcore.driving_inferior - or debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING - or self.updating_memoryview - ): - debugcore.step_over_instruction() - - def execute_till_return(self) -> None: - if not ( - debugcore.currentpid == -1 - or debugcore.driving_inferior - or debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING - or self.updating_memoryview - ): - debugcore.execute_till_return() - - def get_disassemble_row(self, no_selection_row: int = -1) -> int: - selected_rows = self.tableWidget_Disassemble.selectionModel().selectedRows() - if not selected_rows: - return no_selection_row - return selected_rows[0].row() if len(selected_rows) == 1 else -1 - - def set_address(self) -> None: - if guiutils.check_inferior_running(self): - return - selected_row = self.get_disassemble_row() - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - debugcore.set_convenience_variable("pc", current_address) - self.refresh_disassemble_view() - - def edit_instruction(self) -> None: - selected_row = self.get_disassemble_row() - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - bytes_aob = self.tableWidget_Disassemble.item(selected_row, DISAS_OPCODES_COL).text() - EditInstructionDialog(self, current_address, bytes_aob).exec() - - def nop_instruction(self) -> None: - if debugcore.currentpid == -1: - return - selected_row = self.get_disassemble_row() - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - current_address_int = utils.safe_str_to_int(current_address, 16) - if current_address_int == 0: - return - array_of_bytes = self.tableWidget_Disassemble.item(selected_row, DISAS_OPCODES_COL).text() - debugcore.nop_instruction(current_address_int, len(array_of_bytes.split())) - self.refresh_disassemble_view() - - def toggle_breakpoint(self) -> None: - if debugcore.currentpid == -1: - return - selected_row = self.get_disassemble_row() - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - current_address_int = utils.safe_str_to_int(current_address, 16) - if current_address_int == 0: - return - breakpoints = debugcore.get_breakpoints_in_range(current_address_int) - if breakpoints: - for breakpoint in breakpoints: - debugcore.delete_breakpoint(utils.safe_int_cast(breakpoint.number)) - else: - if not debugcore.add_breakpoint(current_address): - QMessageBox.information(self, tr.ERROR, tr.BREAKPOINT_FAILED.format(current_address)) - self.refresh_disassemble_view() - - def toggle_watchpoint(self, address: int, length: int, watchpoint_type: int = typedefs.WATCHPOINT_TYPE.BOTH) -> None: - if debugcore.currentpid == -1: - return - breakpoints = debugcore.get_breakpoints_in_range(address, length) - if not breakpoints: - created_watchpoints = debugcore.add_watchpoint(hex(address), length, watchpoint_type) - if not created_watchpoints: - QMessageBox.information(self, tr.ERROR, tr.WATCHPOINT_FAILED.format(hex(address))) - else: - for bp in breakpoints: - debugcore.delete_breakpoint(utils.safe_int_cast(bp.number)) - self.refresh_hex_view() - - def label_HexView_Information_context_menu_event(self, event: QContextMenuEvent) -> None: - if debugcore.currentpid == -1: - return - - def copy_to_clipboard() -> None: - QApplication.clipboard().setText(self.label_HexView_Information.text()) - - menu = QMenu() - copy_label = menu.addAction(tr.COPY_CLIPBOARD) - font_size = self.label_HexView_Information.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {copy_label: copy_to_clipboard} - try: - actions[action]() - except KeyError: - pass - - def widget_HexView_context_menu_event(self, event: QContextMenuEvent) -> None: - if debugcore.currentpid == -1: - return - addr = self.hex_selection_address_begin - length = self.get_hex_selection_length() - menu = QMenu() - edit = menu.addAction(tr.EDIT) - menu.addSeparator() - go_to = menu.addAction(f"{tr.GO_TO_EXPRESSION}[Ctrl+G]") - disassemble = menu.addAction(f"{tr.DISASSEMBLE_ADDRESS}[Ctrl+D]") - menu.addSeparator() - add_address = menu.addAction(f"{tr.ADD_TO_ADDRESS_LIST}[Ctrl+A]") - menu.addSeparator() - copy_selection = menu.addAction(f"{tr.COPY}[Ctrl+C]") - refresh = menu.addAction(f"{tr.REFRESH}[R]") - menu.addSeparator() - watchpoint_menu = menu.addMenu(tr.SET_WATCHPOINT) - watchpoint_write = watchpoint_menu.addAction(tr.WRITE_ONLY) - watchpoint_read = watchpoint_menu.addAction(tr.READ_ONLY) - watchpoint_both = watchpoint_menu.addAction(tr.BOTH) - add_condition = menu.addAction(tr.CHANGE_BREAKPOINT_CONDITION) - delete_breakpoint = menu.addAction(tr.DELETE_BREAKPOINT) - if not debugcore.get_breakpoints_in_range(addr, length): - guiutils.delete_menu_entries(menu, [add_condition, delete_breakpoint]) - else: - guiutils.delete_menu_entries(menu, [watchpoint_menu.menuAction()]) - font_size = self.widget_HexView.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - edit: self.exec_hex_view_edit_dialog, - go_to: self.exec_hex_view_go_to_dialog, - disassemble: lambda: self.disassemble_expression(hex(addr)), - add_address: self.exec_hex_view_add_address_dialog, - copy_selection: self.copy_hex_view_selection, - refresh: self.refresh_hex_view, - watchpoint_write: lambda: self.toggle_watchpoint(addr, length, typedefs.WATCHPOINT_TYPE.WRITE_ONLY), - watchpoint_read: lambda: self.toggle_watchpoint(addr, length, typedefs.WATCHPOINT_TYPE.READ_ONLY), - watchpoint_both: lambda: self.toggle_watchpoint(addr, length, typedefs.WATCHPOINT_TYPE.BOTH), - add_condition: lambda: self.add_breakpoint_condition(addr, length), - delete_breakpoint: lambda: self.toggle_watchpoint(addr, length), - } - try: - actions[action]() - except KeyError: - pass - - def exec_hex_view_edit_dialog(self) -> None: - if debugcore.currentpid == -1: - return - HexEditDialog(self, self.hex_selection_address_begin, self.get_hex_selection_length()).exec() - self.refresh_hex_view() - - def exec_hex_view_go_to_dialog(self) -> None: - if debugcore.currentpid == -1: - return - go_to_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_EXPRESSION, hex(self.hex_selection_address_begin))]) - if go_to_dialog.exec(): - expression = go_to_dialog.get_values()[0] - dest_address = debugcore.examine_expression(expression).address - if not dest_address: - QMessageBox.information(self, tr.ERROR, tr.INVALID.format(expression)) - return - self.hex_dump_address(int(dest_address, 16)) - - def exec_hex_view_add_address_dialog(self) -> None: - if debugcore.currentpid == -1: - return - vt = typedefs.ByteArrayValueType(self.get_hex_selection_length()) - address_dialog = ManualAddressDialog(self, address=hex(self.hex_selection_address_begin), value_type=vt) - if address_dialog.exec(): - desc, address, vt = address_dialog.get_values() - self.parent().add_entry_to_addresstable(desc, address, vt) - self.parent().update_address_table() - - def copy_hex_view_selection(self) -> None: - data = debugcore.hex_dump(self.hex_selection_address_begin, self.get_hex_selection_length()) - if self.focusWidget() == self.tableView_HexView_Ascii: - display_text = utils.aob_to_str(data) - else: - display_text = " ".join(data) - QApplication.clipboard().setText(display_text) - - def hex_view_scroll_up(self) -> None: - self.verticalScrollBar_HexView.setValue(self.verticalScrollBar_HexView.minimum()) - - def hex_view_scroll_down(self) -> None: - self.verticalScrollBar_HexView.setValue(self.verticalScrollBar_HexView.maximum()) - - def hex_view_page_scroll(self, direction: int) -> None: - if direction < 0: - self.hex_view_scroll_up() - else: - self.hex_view_scroll_down() - - def hex_view_scroll_by_row(self, direction: int) -> None: - if debugcore.currentpid == -1: - return - offset = direction * HEX_VIEW_COL_COUNT - self.hex_selection_start += offset - self.hex_selection_end += offset - self.hex_selection_address_begin += offset - self.hex_selection_address_end += offset - self.hex_dump_address(self.hex_model.current_address + offset) - - def hex_view_scrollbar_sliderchanged(self, event: QAbstractSlider.SliderChange) -> None: - if self.bHexViewScrolling: - return - self.bHexViewScrolling = True - maximum = self.verticalScrollBar_HexView.maximum() - minimum = self.verticalScrollBar_HexView.minimum() - midst = (maximum + minimum) / 2 - current_value = self.verticalScrollBar_HexView.value() - current_address = self.hex_model.current_address - if current_value < midst: - next_address = current_address - states.bytes_per_scroll - else: - next_address = current_address + states.bytes_per_scroll - self.hex_dump_address(next_address) - guiutils.center_scroll_bar(self.verticalScrollBar_HexView) - self.bHexViewScrolling = False - - def disassemble_scroll_up(self) -> None: - self.verticalScrollBar_Disassemble.setValue(self.verticalScrollBar_Disassemble.minimum()) - - def disassemble_scroll_down(self) -> None: - self.verticalScrollBar_Disassemble.setValue(self.verticalScrollBar_Disassemble.maximum()) - - def disassemble_scrollbar_sliderchanged(self, even: QAbstractSlider.SliderChange) -> None: - if self.bDisassemblyScrolling: - return - self.bDisassemblyScrolling = True - maximum = self.verticalScrollBar_Disassemble.maximum() - minimum = self.verticalScrollBar_Disassemble.minimum() - midst = (maximum + minimum) / 2 - current_value = self.verticalScrollBar_Disassemble.value() - if current_value < midst: - self.tableWidget_Disassemble_scroll("previous", states.instructions_per_scroll) - else: - self.tableWidget_Disassemble_scroll("next", states.instructions_per_scroll) - guiutils.center_scroll_bar(self.verticalScrollBar_Disassemble) - self.bDisassemblyScrolling = False - - def hex_view_selection_changed(self, selected: QItemSelection, deselected: QItemSelection) -> None: - sender_selection_model: QItemSelectionModel = self.sender() - sender_selection = sorted([(idx.row(), idx.column()) for idx in sender_selection_model.selectedIndexes()]) - if not sender_selection: - return - first_selection = sender_selection[0] - last_selection = sender_selection[-1] - hex_start = self.address_to_hex_point(self.hex_selection_start) - hex_end = self.address_to_hex_point(self.hex_selection_end) - hex_start, hex_end = self.fix_selection_at_borders(hex_start, hex_end) - if len(sender_selection) == 1: - hex_start = first_selection - hex_end = first_selection - else: - # Selection ends in top left - if last_selection == hex_start: - hex_end = first_selection - # Selection ends in top right - elif last_selection[0] == hex_start[0]: - hex_end = (first_selection[0], last_selection[1]) - # Selection ends in bottom left - elif last_selection[1] == hex_start[1]: - hex_end = (last_selection[0], first_selection[1]) - # Selection ends in bottom right - else: - hex_end = last_selection - if hex_start < hex_end: - address_begin = hex_start - address_end = hex_end - else: - address_begin = hex_end - address_end = hex_start - self.hex_selection_start = self.hex_point_to_address(hex_start) - self.hex_selection_end = self.hex_point_to_address(hex_end) - self.hex_selection_address_begin = self.hex_point_to_address(address_begin) - self.hex_selection_address_end = self.hex_point_to_address(address_end) - self.handle_hex_selection() - - def handle_hex_selection(self) -> None: - hex_view = self.tableView_HexView_Hex - ascii_view = self.tableView_HexView_Ascii - addr_view = self.tableWidget_HexView_Address - hex_enabled = hex_view.updatesEnabled() - ascii_enabled = ascii_view.updatesEnabled() - addr_enabled = addr_view.updatesEnabled() - hex_view.setUpdatesEnabled(False) - ascii_view.setUpdatesEnabled(False) - addr_view.setUpdatesEnabled(False) - hex_selection_model = hex_view.selectionModel() - ascii_selection_model = ascii_view.selectionModel() - start_point = self.address_to_hex_point(self.hex_selection_address_begin) - end_point = self.address_to_hex_point(self.hex_selection_address_end) - with QSignalBlocker(hex_selection_model), QSignalBlocker(ascii_selection_model): - hex_selection_model.clearSelection() - ascii_selection_model.clearSelection() - addr_view.clearSelection() - if start_point or end_point: - start_point, end_point = self.fix_selection_at_borders(start_point, end_point) - model = hex_selection_model.model() - selection = QItemSelection() - if start_point[0] == end_point[0]: - selection.select(model.index(*start_point), model.index(*end_point)) - else: - # First line - selection.select(model.index(*start_point), model.index(start_point[0], HEX_VIEW_COL_COUNT - 1)) - # Middle - if end_point[0] - start_point[0] > 1: - selection.select( - model.index(start_point[0] + 1, 0), - model.index(end_point[0] - 1, HEX_VIEW_COL_COUNT - 1), - ) - # Last line - selection.select(model.index(end_point[0], 0), model.index(*end_point)) - hex_selection_model.select(selection, QItemSelectionModel.SelectionFlag.Select) - ascii_selection_model.select(selection, QItemSelectionModel.SelectionFlag.Select) - addr_view.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection) - for row in range(start_point[0], end_point[0] + 1): - addr_view.selectRow(row) - addr_view.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) - hex_view.setUpdatesEnabled(hex_enabled) - ascii_view.setUpdatesEnabled(ascii_enabled) - addr_view.setUpdatesEnabled(addr_enabled) - - def hex_point_to_address(self, point: tuple[int, int]) -> int: - address = self.hex_model.current_address + point[0] * HEX_VIEW_COL_COUNT + point[1] - return utils.modulo_address(address, debugcore.inferior_arch) - - def address_to_hex_point(self, address: int) -> tuple[int, int] | None: - diff = address - self.hex_model.current_address - if 0 <= diff < self.hex_row_count * HEX_VIEW_COL_COUNT: - return diff // HEX_VIEW_COL_COUNT, diff % HEX_VIEW_COL_COUNT - - def get_hex_selection_length(self) -> int: - return self.hex_selection_address_end - self.hex_selection_address_begin + 1 - - def fix_selection_at_borders( - self, start_point: tuple[int, int] | None, end_point: tuple[int, int] | None - ) -> tuple[tuple[int, int], tuple[int, int]]: - if not start_point: - start_point = (0, 0) - if not end_point: - end_point = (self.hex_row_count - 1, HEX_VIEW_COL_COUNT - 1) - return start_point, end_point - - def eventFilter(self, obj: QObject | None, event: QEvent | None) -> bool: - if obj is self.scrollArea_Hex.viewport() and event.type() == QEvent.Type.Resize: - self.adjust_hex_view_rows() - return super().eventFilter(obj, event) - - def adjust_hex_view_rows(self) -> None: - row_height = self.tableView_HexView_Hex.verticalHeader().defaultSectionSize() - if row_height <= 0: - return - available = self.scrollArea_Hex.viewport().height() - self.tableView_HexView_Hex.y() - new_count = max(1, available // row_height) - if new_count == self.hex_row_count: - return - self.hex_row_count = new_count - self.hex_model.set_row_count(new_count) - self.ascii_model.set_row_count(new_count) - self.hex_dump_address(self.hex_model.current_address) - - def hex_update_loop(self) -> None: - offset = self.hex_row_count * HEX_VIEW_COL_COUNT - if debugcore.currentpid == -1 or states.exiting: - updated_array = ["??"] * offset - else: - updated_array = debugcore.hex_dump(self.hex_model.current_address, offset) - self.hex_model.update_loop(updated_array) - self.ascii_model.update_loop(updated_array) - - # TODO: Consider merging HexView_Address, HexView_Hex and HexView_Ascii into one UI class - # TODO: Move this function to that class if that happens - # TODO: Also consider moving shared fields of HexView and HexModel to that class(such as HexModel.current_address) - def hex_dump_address(self, int_address: int, offset: int | None = None) -> None: - if debugcore.currentpid == -1: - return - if offset is None: - offset = self.hex_row_count * HEX_VIEW_COL_COUNT - self.tableView_HexView_Hex.setUpdatesEnabled(False) - self.tableView_HexView_Ascii.setUpdatesEnabled(False) - self.tableWidget_HexView_Address.setUpdatesEnabled(False) - int_address = utils.modulo_address(int_address, debugcore.inferior_arch) - if not (self.hex_view_current_region.start <= int_address < self.hex_view_current_region.end): - info = utils.get_region_info(debugcore.currentpid, int_address) - if info: - self.hex_view_current_region = info - self.label_HexView_Information.setText(tr.REGION_INFO.format(info.perms, hex(info.start), hex(info.end), info.file_name)) - else: - self.hex_view_current_region = typedefs.tuple_region_info(0, 0, None, None, None) - self.label_HexView_Information.setText(tr.INVALID_REGION) - self.tableWidget_HexView_Address.setRowCount(0) - self.tableWidget_HexView_Address.setRowCount(self.hex_row_count) - for row, current_offset in enumerate(range(self.hex_row_count)): - row_address = hex(utils.modulo_address(int_address + current_offset * 16, debugcore.inferior_arch)) - self.tableWidget_HexView_Address.setItem(row, 0, QTableWidgetItem(utils.upper_hex(row_address))) - tableWidget_HexView_column_size = self.tableWidget_HexView_Address.sizeHintForColumn(0) + 5 - self.tableWidget_HexView_Address.setMaximumWidth(tableWidget_HexView_column_size) - self.tableWidget_HexView_Address.setMinimumWidth(tableWidget_HexView_column_size) - self.tableWidget_HexView_Address.setColumnWidth(0, tableWidget_HexView_column_size) - data_array = debugcore.hex_dump(int_address, offset) - breakpoint_info = debugcore.get_breakpoint_info() - self.hex_model.refresh(int_address, offset, data_array, breakpoint_info) - self.ascii_model.refresh(int_address, offset, data_array, breakpoint_info) - self.handle_hex_selection() - self.tableWidget_HexView_Address.setUpdatesEnabled(True) - self.tableView_HexView_Ascii.setUpdatesEnabled(True) - self.tableView_HexView_Hex.setUpdatesEnabled(True) - - def refresh_hex_view(self) -> None: - if debugcore.currentpid == -1: - return - if self.tableWidget_HexView_Address.rowCount() == 0: - entry_point = debugcore.find_entry_point() - if not entry_point: - # **Shrugs** - entry_point = "0x00400000" - self.hex_dump_address(int(entry_point, 16)) - self.tableView_HexView_Hex.resize_to_contents() - self.tableView_HexView_Ascii.resize_to_contents() - else: - self.hex_dump_address(self.hex_model.current_address) - - # returns True if the given expression is disassembled correctly, False if not - def disassemble_expression(self, expression: str, append_history: bool = True) -> bool | None: - if debugcore.currentpid == -1: - return - # We ask for a generous byte span that decodes to at least a screenful of rows at any instruction density, - # because gdb sizes disassembly by byte length, not by row count. - # One forward call spares us find_closest counting rows, keeps the target on row 0 and lets disas_data[0] double as the examine_expression. - span = self.disassemble_screen_rows * DISAS_BYTES_PER_ROW - disas_data = debugcore.disassemble(expression, "+" + str(span)) - if not disas_data: - QMessageBox.information(QApplication.focusWidget(), tr.ERROR, tr.EXPRESSION_ACCESS_ERROR.format(expression)) - return False - # In dense code that span decodes to many more rows than fit. - # We keep only screen_rows, the most any viewport could show, to avoid building rows that would never be visible. - disas_data = disas_data[: self.disassemble_screen_rows] - program_counter = debugcore.examine_expression("$pc").address - program_counter_int = int(program_counter, 16) if program_counter else None - row_color = {} - breakpoint_info = debugcore.get_breakpoint_info() - - # TODO: Change this nonsense when the huge refactorization happens - current_first_address = utils.extract_hex_address(disas_data[0][0]) # address of first list entry - try: - previous_first_address = utils.extract_hex_address(self.tableWidget_Disassemble.item(0, DISAS_ADDR_COL).text()) - except AttributeError: - previous_first_address = current_first_address - - jmp_dict, call_dict = debugcore.get_dissect_code_data(False, True, True) - # Reference arrows are only meaningful within a local range, so we bound the endpoints to the displayed window - # and let DisassembleArrowOverlay clamp what's off-screen. - window_first_int = utils.safe_str_to_int(current_first_address, 16) - window_last_int = utils.safe_str_to_int(utils.extract_hex_address(disas_data[-1][0]), 16) - arrow_span = max(window_last_int - window_first_int, 0) - near_lo = window_first_int - arrow_span - 1 - near_hi = window_last_int + arrow_span + 1 - arrows: set[tuple[int, int, str]] = set() # (source_address, target_address, kind) - address_to_row: dict[int, int] = {} - self.tableWidget_Disassemble.blockSignals(True) - try: - self.tableWidget_Disassemble.setRowCount(0) - self.tableWidget_Disassemble.setRowCount(len(disas_data)) - self.tableWidget_Disassemble.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection) - for row, (address_info, bytes_aob, instruction) in enumerate(disas_data): - comment = "" - current_address_str = utils.extract_hex_address(address_info) - current_address = utils.safe_str_to_int(current_address_str, 16) - address_to_row[current_address] = row - # dissect stores keys as unpadded hex but extract_hex_address keeps gdb's leading zeros, normalize first - referrer_key = hex(current_address) - jmp_ref_exists = False - call_ref_exists = False - try: - jmp_referrers = jmp_dict[referrer_key] - jmp_ref_exists = True - except KeyError: - pass - try: - call_referrers = call_dict[referrer_key] - call_ref_exists = True - except KeyError: - pass - if jmp_ref_exists or call_ref_exists: - tooltip_text = f"{tr.REFERENCED_BY}\n" - ref_count = 0 - if jmp_ref_exists: - for referrer in jmp_referrers: - if ref_count > 30: - break - tooltip_text += "\n" + hex(referrer) + "(" + jmp_referrers[referrer] + ")" - ref_count += 1 - if call_ref_exists: - for referrer in call_referrers: - if ref_count > 30: - break - tooltip_text += "\n" + hex(referrer) + "(call)" - ref_count += 1 - if ref_count > 30: - tooltip_text += "\n..." - tooltip_text += f"\n\n{tr.SEE_REFERRERS}" - # An arrow is drawn from each nearby referrer (caller) into this row (the target). - # Referrers that are out of sight get clamped to the viewport edge by DisassembleArrowOverlay. - arrow_refs = 0 - if jmp_ref_exists: - for referrer in jmp_referrers: - if arrow_refs >= DISAS_MAX_REFS_PER_TARGET: - break - if near_lo <= referrer <= near_hi: - arrows.add((referrer, current_address, "jmp")) - arrow_refs += 1 - if call_ref_exists: - for referrer in call_referrers: - if arrow_refs >= DISAS_MAX_REFS_PER_TARGET: - break - if near_lo <= referrer <= near_hi: - arrows.add((referrer, current_address, "call")) - arrow_refs += 1 - real_ref_count = 0 - if jmp_ref_exists: - real_ref_count += len(jmp_referrers) - if call_ref_exists: - real_ref_count += len(call_referrers) - address_info = "{" + str(real_ref_count) + "}" + address_info - # An arrow is also drawn from this row (the caller) to its target when the instruction is a direct jmp/call. - # The target may be out of sight, the overlay clamps it to an edge if so. - followed_address = utils.instruction_follow_address(instruction) - if followed_address: - target_int = utils.safe_str_to_int(followed_address, 16) - if target_int != current_address and near_lo <= target_int <= near_hi: - arrows.add((current_address, target_int, "call" if instruction.startswith("call") else "jmp")) - if current_address == program_counter_int: - address_info = ">>>" + address_info - try: - row_color[row].append(PC_COLOR) - except KeyError: - row_color[row] = [PC_COLOR] - - for bookmark_item in self.session.pct_bookmarks.keys(): - if current_address == bookmark_item: - try: - row_color[row].append(BOOKMARK_COLOR) - except KeyError: - row_color[row] = [BOOKMARK_COLOR] - address_info = "(M)" + address_info - comment = self.session.pct_bookmarks[bookmark_item]["comment"] - break - for breakpoint in breakpoint_info: - # Catchpoints won't have an address - if type(breakpoint.address) != str: - continue - int_breakpoint_address = utils.safe_str_to_int(breakpoint.address, 16) - if current_address == int_breakpoint_address: - try: - row_color[row].append(BREAKPOINT_COLOR) - except KeyError: - row_color[row] = [BREAKPOINT_COLOR] - breakpoint_mark = "(B" - if breakpoint.enabled == "n": - breakpoint_mark += "-disabled" - else: - if breakpoint.disp != "keep": - breakpoint_mark += "-" + breakpoint.disp - if breakpoint.enable_count: - breakpoint_mark += "-" + breakpoint.enable_count - breakpoint_mark += ")" - address_info = breakpoint_mark + address_info - break - if current_address in self.disassemble_selected_addresses: - self.tableWidget_Disassemble.selectRow(row) - addr_item = QTableWidgetItem(address_info) - bytes_item = QTableWidgetItem(bytes_aob) - instruction_item = QTableWidgetItem(instruction) - comment_item = QTableWidgetItem(comment) - if jmp_ref_exists or call_ref_exists: - addr_item.setToolTip(tooltip_text) - bytes_item.setToolTip(tooltip_text) - instruction_item.setToolTip(tooltip_text) - comment_item.setToolTip(tooltip_text) - self.tableWidget_Disassemble.setItem(row, DISAS_ADDR_COL, addr_item) - self.tableWidget_Disassemble.setItem(row, DISAS_OPCODES_COL, bytes_item) - self.tableWidget_Disassemble.setItem(row, DISAS_INSTR_COL, instruction_item) - self.tableWidget_Disassemble.setItem(row, DISAS_COMMENT_COL, comment_item) - finally: - jmp_dict.close() - call_dict.close() - self.tableWidget_Disassemble.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) - self.tableWidget_Disassemble.blockSignals(False) - self.handle_colors(row_color) - # Sorting keeps the per-arrow shade assignment stable across repaints and groups nearby paths. - sorted_arrows = sorted(arrows)[:DISAS_MAX_ARROWS] - self.disassemble_arrow_overlay.set_arrows(sorted_arrows, address_to_row, window_first_int, window_last_int) - - # We append the old record to travel history as last action because we wouldn't like to see unnecessary - # addresses in travel history if any error occurs while displaying the next location - if append_history: - self.tableWidget_Disassemble.travel_history.append(previous_first_address) - self.disassemble_currently_displayed_address = current_first_address - return True - - def refresh_disassemble_view(self) -> None: - if debugcore.currentpid == -1: - return - self.disassemble_expression(self.disassemble_currently_displayed_address, append_history=False) - - # Set color of a row if a specific address is encountered(e.g $pc, a bookmarked address etc.) - def handle_colors(self, row_color: dict[int, list[QColor]]) -> None: - if debugcore.currentpid == -1: - return - for row in row_color: - current_row = row_color[row] - if PC_COLOR in current_row: - if BREAKPOINT_COLOR in current_row: - color = QColorConstants.Green - elif BOOKMARK_COLOR in current_row: - color = QColorConstants.Yellow - else: - color = PC_COLOR - self.set_row_color(row, color) - continue - if BREAKPOINT_COLOR in current_row: - if BOOKMARK_COLOR in current_row: - color = QColorConstants.Magenta - else: - color = BREAKPOINT_COLOR - self.set_row_color(row, color) - continue - if BOOKMARK_COLOR in current_row: - self.set_row_color(row, BOOKMARK_COLOR) - - def set_row_color(self, row: int, color: QColor) -> None: - if debugcore.currentpid == -1: - return - for col in range(self.tableWidget_Disassemble.columnCount()): - color = QColor(color) - color.setAlpha(96) - self.tableWidget_Disassemble.item(row, col).setData(Qt.ItemDataRole.BackgroundRole, color) - - def on_process_stop(self) -> None: - if debugcore.stop_reason == typedefs.STOP_REASON.PAUSE: - self.setWindowTitle(tr.MV_PAUSED) - return - self.updating_memoryview = True - try: - time0 = time() - self.setWindowTitle(tr.MV_DEBUGGING.format(debugcore.get_thread_info())) - self.disassemble_expression("$pc", append_history=False) - self.update_registers() - if self.stackedWidget_StackScreens.currentWidget() == self.StackTrace: - self.update_stacktrace() - elif self.stackedWidget_StackScreens.currentWidget() == self.Stack: - self.update_stack() - - # These tableWidgets are never emptied but initially both are empty, so this runs only once - if self.tableWidget_StackTrace.rowCount() == 0: - self.update_stacktrace() - if self.tableWidget_Stack.rowCount() == 0: - self.update_stack() - self.refresh_hex_view() - if states.show_memory_view_on_stop: - self.showMaximized() - self.activateWindow() - if self.stacktrace_info_widget.isVisible(): - self.stacktrace_info_widget.update_stacktrace() - self.pushButton_ShowFloatRegisters.setEnabled(True) - if self.float_registers_widget.isVisible(): - self.float_registers_widget.update_registers() - QApplication.processEvents() - time1 = time() - logger.debug(f"Updated memory view in: {str(time1 - time0)}") - finally: - self.updating_memoryview = False - - def on_process_running(self) -> None: - self.setWindowTitle(tr.MV_RUNNING) - self.pushButton_ShowFloatRegisters.setEnabled(False) - - def add_breakpoint_condition(self, int_address: int, length: int = 1, dialog_parent: QWidget | None = None) -> None: - if debugcore.currentpid == -1: - return - breakpoints = debugcore.get_breakpoints_in_range(int_address, length) - if breakpoints: - condition_line_edit_text = breakpoints[0].condition - else: - condition_line_edit_text = "" - items = [(tr.ENTER_BP_CONDITION, condition_line_edit_text)] - condition_dialog = utilwidgets.InputDialog(dialog_parent or self, items, Qt.AlignmentFlag.AlignLeft) - if condition_dialog.exec(): - condition = condition_dialog.get_values()[0] - for bp in breakpoints: - if not debugcore.modify_breakpoint(utils.safe_int_cast(bp.number), typedefs.BREAKPOINT_MODIFY.CONDITION, condition): - QMessageBox.information(QApplication.focusWidget(), tr.ERROR, tr.BP_CONDITION_FAILED.format(bp.address)) - - def update_registers(self) -> None: - if debugcore.currentpid == -1: - return - registers = debugcore.read_registers() - if not registers: - return - if debugcore.inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64: - self.stackedWidget.setCurrentWidget(self.registers_64) - self.RAX.set_value(registers["rax"]) - self.RBX.set_value(registers["rbx"]) - self.RCX.set_value(registers["rcx"]) - self.RDX.set_value(registers["rdx"]) - self.RSI.set_value(registers["rsi"]) - self.RDI.set_value(registers["rdi"]) - self.RBP.set_value(registers["rbp"]) - self.RSP.set_value(registers["rsp"]) - self.RIP.set_value(registers["rip"]) - self.R8.set_value(registers["r8"]) - self.R9.set_value(registers["r9"]) - self.R10.set_value(registers["r10"]) - self.R11.set_value(registers["r11"]) - self.R12.set_value(registers["r12"]) - self.R13.set_value(registers["r13"]) - self.R14.set_value(registers["r14"]) - self.R15.set_value(registers["r15"]) - elif debugcore.inferior_arch == typedefs.INFERIOR_ARCH.ARCH_32: - self.stackedWidget.setCurrentWidget(self.registers_32) - self.EAX.set_value(registers["eax"]) - self.EBX.set_value(registers["ebx"]) - self.ECX.set_value(registers["ecx"]) - self.EDX.set_value(registers["edx"]) - self.ESI.set_value(registers["esi"]) - self.EDI.set_value(registers["edi"]) - self.EBP.set_value(registers["ebp"]) - self.ESP.set_value(registers["esp"]) - self.EIP.set_value(registers["eip"]) - self.CF.set_value(registers["cf"]) - self.PF.set_value(registers["pf"]) - self.AF.set_value(registers["af"]) - self.ZF.set_value(registers["zf"]) - self.SF.set_value(registers["sf"]) - self.TF.set_value(registers["tf"]) - self.IF.set_value(registers["if"]) - self.DF.set_value(registers["df"]) - self.OF.set_value(registers["of"]) - self.CS.set_value(registers["cs"]) - self.SS.set_value(registers["ss"]) - self.DS.set_value(registers["ds"]) - self.ES.set_value(registers["es"]) - self.GS.set_value(registers["gs"]) - self.FS.set_value(registers["fs"]) - - def update_stacktrace(self) -> None: - if guiutils.check_inferior_running(self, show_message=False): - return - stack_trace_info = debugcore.get_stacktrace_info() - self.tableWidget_StackTrace.setRowCount(0) - self.tableWidget_StackTrace.setRowCount(len(stack_trace_info)) - for row, item in enumerate(stack_trace_info): - self.tableWidget_StackTrace.setItem(row, STACKTRACE_RETURN_ADDRESS_COL, QTableWidgetItem(item[0])) - self.tableWidget_StackTrace.setItem(row, STACKTRACE_FRAME_ADDRESS_COL, QTableWidgetItem(item[1])) - - def set_stack_widget(self, stack_widget: QWidget) -> None: - if debugcore.currentpid == -1: - return - self.stackedWidget_StackScreens.setCurrentWidget(stack_widget) - if stack_widget == self.Stack: - self.update_stack() - elif stack_widget == self.StackTrace: - self.update_stacktrace() - - def tableWidget_StackTrace_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - item = self.tableWidget_StackTrace.item(row, column) - if item is None: - return - QApplication.clipboard().setText(item.text()) - - selected_row = guiutils.get_current_row(self.tableWidget_StackTrace) - menu = QMenu() - switch_to_stack = menu.addAction(tr.FULL_STACK) - menu.addSeparator() - clipboard_menu = menu.addMenu(tr.COPY_CLIPBOARD) - copy_return = clipboard_menu.addAction(tr.COPY_RETURN_ADDRESS) - copy_frame = clipboard_menu.addAction(tr.COPY_FRAME_ADDRESS) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [clipboard_menu.menuAction()]) - refresh = menu.addAction(f"{tr.REFRESH}[R]") - if guiutils.check_inferior_running(self, show_message=False): - refresh.setEnabled(False) - if debugcore.currentpid == -1: - menu.clear() - menu.addMenu(clipboard_menu) - font_size = self.tableWidget_StackTrace.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - switch_to_stack: lambda: self.set_stack_widget(self.Stack), - copy_return: lambda: copy_to_clipboard(selected_row, STACKTRACE_RETURN_ADDRESS_COL), - copy_frame: lambda: copy_to_clipboard(selected_row, STACKTRACE_FRAME_ADDRESS_COL), - refresh: self.update_stacktrace, - } - try: - actions[action]() - except KeyError: - pass - - def update_stack(self) -> None: - if guiutils.check_inferior_running(self, show_message=False): - return - stack_info: list[str] = debugcore.get_stack_info(from_base_pointer=self.stack_from_base_pointer) - self.tableWidget_Stack.setRowCount(0) - self.tableWidget_Stack.setRowCount(len(stack_info)) - for row, item in enumerate(stack_info): - self.tableWidget_Stack.setItem(row, STACK_POINTER_ADDRESS_COL, QTableWidgetItem(item[0])) - self.tableWidget_Stack.setItem(row, STACK_VALUE_COL, QTableWidgetItem(item[1])) - self.tableWidget_Stack.setItem(row, STACK_POINTS_TO_COL, QTableWidgetItem(item[2])) - self.tableWidget_Stack.resizeColumnToContents(STACK_POINTER_ADDRESS_COL) - self.tableWidget_Stack.resizeColumnToContents(STACK_VALUE_COL) - - def toggle_stack_from_sp_bp(self) -> None: - self.stack_from_base_pointer = not self.stack_from_base_pointer - self.update_stack() - - def tableWidget_Stack_key_press_event(self, event: QKeyEvent) -> None: - if debugcore.currentpid == -1: - return - selected_row = guiutils.get_current_row(self.tableWidget_Stack) - if selected_row == -1: - actions = {QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_R): self.update_stack} - else: - current_address_text = self.tableWidget_Stack.item(selected_row, STACK_VALUE_COL).text() - current_address = utils.extract_hex_address(current_address_text) - - actions = { - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_R): self.update_stack, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_D): lambda: self.disassemble_expression(current_address), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_H): lambda: self.hex_dump_address( - utils.safe_str_to_int(current_address, 16) - ), - } - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - pass - self.tableWidget_Stack_keyPressEvent_original(event) - - def tableWidget_Stack_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - item = self.tableWidget_Stack.item(row, column) - if item is None: - return - QApplication.clipboard().setText(item.text()) - - selected_row = guiutils.get_current_row(self.tableWidget_Stack) - if selected_row == -1: - current_address = None - else: - current_address_text = self.tableWidget_Stack.item(selected_row, STACK_VALUE_COL).text() - current_address = utils.extract_hex_address(current_address_text) - menu = QMenu() - switch_to_stacktrace = menu.addAction(tr.STACKTRACE) - toggle_stack_pointer = menu.addAction(tr.TOGGLE_STACK_FROM_SP_BP) - if guiutils.check_inferior_running(self, show_message=False): - toggle_stack_pointer.setEnabled(False) - menu.addSeparator() - clipboard_menu = menu.addMenu(tr.COPY_CLIPBOARD) - copy_address = clipboard_menu.addAction(tr.COPY_ADDRESS) - copy_value = clipboard_menu.addAction(tr.COPY_VALUE) - copy_points_to = clipboard_menu.addAction(tr.COPY_POINTS_TO) - refresh = menu.addAction(f"{tr.REFRESH}[R]") - if guiutils.check_inferior_running(self, show_message=False): - refresh.setEnabled(False) - menu.addSeparator() - show_in_disas = menu.addAction(f"{tr.DISASSEMBLE_VALUE_POINTER}[Ctrl+D]") - show_in_hex = menu.addAction(f"{tr.HEXVIEW_VALUE_POINTER}[Ctrl+H]") - if selected_row == -1 or current_address is None: - guiutils.delete_menu_entries(menu, [clipboard_menu.menuAction(), show_in_disas, show_in_hex]) - if debugcore.currentpid == -1: - menu.clear() - menu.addMenu(clipboard_menu) - font_size = self.tableWidget_Stack.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - switch_to_stacktrace: lambda: self.set_stack_widget(self.StackTrace), - toggle_stack_pointer: self.toggle_stack_from_sp_bp, - copy_address: lambda: copy_to_clipboard(selected_row, STACK_POINTER_ADDRESS_COL), - copy_value: lambda: copy_to_clipboard(selected_row, STACK_VALUE_COL), - copy_points_to: lambda: copy_to_clipboard(selected_row, STACK_POINTS_TO_COL), - refresh: self.update_stack, - show_in_disas: lambda: self.disassemble_expression(current_address), - show_in_hex: lambda: self.hex_dump_address(utils.safe_str_to_int(current_address, 16)), - } - try: - actions[action]() - except KeyError: - pass - - def tableWidget_Stack_double_click(self, index: QTableWidgetItem) -> None: - if debugcore.currentpid == -1: - return - selected_row = guiutils.get_current_row(self.tableWidget_Stack) - if index.column() == STACK_POINTER_ADDRESS_COL: - current_address_text = self.tableWidget_Stack.item(selected_row, STACK_POINTER_ADDRESS_COL).text() - current_address = utils.extract_hex_address(current_address_text) - self.hex_dump_address(utils.safe_str_to_int(current_address, 16)) - else: - points_to_text = self.tableWidget_Stack.item(selected_row, STACK_POINTS_TO_COL).text() - current_address_text = self.tableWidget_Stack.item(selected_row, STACK_VALUE_COL).text() - current_address = utils.extract_hex_address(current_address_text) - if points_to_text.startswith("(str)"): - self.hex_dump_address(utils.safe_str_to_int(current_address, 16)) - else: - self.disassemble_expression(current_address) - - def tableWidget_StackTrace_double_click(self, index: QTableWidgetItem) -> None: - if debugcore.currentpid == -1: - return - selected_row = guiutils.get_current_row(self.tableWidget_StackTrace) - if index.column() == STACKTRACE_RETURN_ADDRESS_COL: - current_address_text = self.tableWidget_StackTrace.item(selected_row, STACKTRACE_RETURN_ADDRESS_COL).text() - current_address = utils.extract_hex_address(current_address_text) - self.disassemble_expression(current_address) - if index.column() == STACKTRACE_FRAME_ADDRESS_COL: - current_address_text = self.tableWidget_StackTrace.item(selected_row, STACKTRACE_FRAME_ADDRESS_COL).text() - current_address = utils.extract_hex_address(current_address_text) - self.hex_dump_address(utils.safe_str_to_int(current_address, 16)) - - def tableWidget_StackTrace_key_press_event(self, event: QKeyEvent) -> None: - if debugcore.currentpid == -1: - return - actions = {QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_R): self.update_stacktrace} - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - pass - self.tableWidget_StackTrace_keyPressEvent_original(event) - - def widget_Disassemble_wheel_event(self, event: QWheelEvent) -> None: - steps = event.angleDelta() - if steps.x() != 0: - self.tableWidget_Disassemble_wheelEvent_original(event) - if debugcore.currentpid == -1: - return - if steps.y() > 0: - self.tableWidget_Disassemble_scroll("previous", states.instructions_per_scroll) - elif steps.y() < 0: - self.tableWidget_Disassemble_scroll("next", states.instructions_per_scroll) - - def disassemble_check_viewport(self, where: str, instruction_count: int) -> None: - if debugcore.currentpid == -1: - return - current_row = guiutils.get_current_row(self.tableWidget_Disassemble) - if current_row == -1: - return - current_row_height = self.tableWidget_Disassemble.rowViewportPosition(current_row) - row_height = self.tableWidget_Disassemble.verticalHeader().defaultSectionSize() - max_height = self.tableWidget_Disassemble.maximumViewportSize().height() - # visible_height = max_height - row_height - height = max_height - row_height * 3 # lets us see the next 2 instructions after the last visible row - if current_row_height > max_height: - last_visible_row = 0 - for row in range(self.tableWidget_Disassemble.rowCount()): - if self.tableWidget_Disassemble.rowViewportPosition(row) > height: - break - last_visible_row += 1 - current_address = utils.extract_hex_address(self.tableWidget_Disassemble.item(current_row, DISAS_ADDR_COL).text()) - new_address = debugcore.find_closest_instruction_address(current_address, "previous", last_visible_row) - if not new_address: - return - self.disassemble_expression(new_address, append_history=False) - elif (where == "previous" and current_row == 0) or (where == "next" and current_row_height > height): - self.tableWidget_Disassemble_scroll(where, instruction_count) - - def tableWidget_Disassemble_scroll(self, where: str, instruction_count: int) -> None: - if debugcore.currentpid == -1: - return - current_address = self.disassemble_currently_displayed_address - new_address = debugcore.find_closest_instruction_address(current_address, where, instruction_count) - if not new_address: - return - self.disassemble_expression(new_address, append_history=False) - - def widget_HexView_wheel_event(self, event: QWheelEvent) -> None: - if debugcore.currentpid == -1: - return - steps = event.angleDelta() - current_address = self.hex_model.current_address - if steps.y() > 0: - next_address = current_address - states.bytes_per_scroll - else: - next_address = current_address + states.bytes_per_scroll - self.hex_dump_address(next_address) - - def widget_HexView_key_press_event(self, event: QKeyEvent) -> None: - if debugcore.currentpid == -1: - return - actions = { - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_G): self.exec_hex_view_go_to_dialog, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_D): lambda: self.disassemble_expression( - hex(self.hex_selection_address_begin) - ), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_A): self.exec_hex_view_add_address_dialog, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_C): self.copy_hex_view_selection, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_R): self.refresh_hex_view, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_PageUp): self.hex_view_scroll_up, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_PageDown): self.hex_view_scroll_down, - } - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - pass - self.widget_HexView_keyPressEvent_original(event) - - def tableWidget_Disassemble_key_press_event(self, event: QKeyEvent) -> None: - if debugcore.currentpid == -1: - return - if not self.tableWidget_Disassemble.rowCount(): - return - if event.matches(QKeySequence.StandardKey.SelectAll): - last_row = self.tableWidget_Disassemble.rowAt(self.tableWidget_Disassemble.viewport().height() - 1) - if last_row == -1: - last_row = self.tableWidget_Disassemble.rowCount() - 1 - model = self.tableWidget_Disassemble.model() - selection = QItemSelection(model.index(0, 0), model.index(last_row, self.tableWidget_Disassemble.columnCount() - 1)) - self.tableWidget_Disassemble.selectionModel().select(selection, QItemSelectionModel.SelectionFlag.ClearAndSelect) - return - selected_row = self.get_disassemble_row(no_selection_row=0) - if selected_row == -1: - return self.tableWidget_Disassemble_keyPressEvent_original(event) - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - current_address_int = utils.safe_str_to_int(current_address, 16) - - actions = { - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Space): lambda: self.follow_instruction(selected_row), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_E): lambda: self.exec_examine_referrers_widget(current_address_text), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_G): self.exec_disassemble_go_to_dialog, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_H): lambda: self.hex_dump_address(current_address_int), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_B): lambda: self.bookmark_address(current_address_int), - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_D): self.dissect_current_region, - QKeyCombination(Qt.KeyboardModifier.ControlModifier, Qt.Key.Key_T): self.exec_trace_instructions_dialog, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_R): self.refresh_disassemble_view, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Down): lambda: self.disassemble_check_viewport("next", 1), - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_Up): lambda: self.disassemble_check_viewport("previous", 1), - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_PageUp): self.disassemble_scroll_up, - QKeyCombination(Qt.KeyboardModifier.NoModifier, Qt.Key.Key_PageDown): self.disassemble_scroll_down, - } - try: - actions[QKeyCombination(event.modifiers(), Qt.Key(event.key()))]() - except KeyError: - pass - self.tableWidget_Disassemble_keyPressEvent_original(event) - - def tableWidget_Disassemble_item_double_clicked(self, index: QTableWidgetItem) -> None: - if debugcore.currentpid == -1: - return - if index.column() == DISAS_COMMENT_COL: - selected_row = guiutils.get_current_row(self.tableWidget_Disassemble) - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.safe_str_to_int(utils.extract_hex_address(current_address_text), 16) - if current_address in self.session.pct_bookmarks: - self.change_bookmark_comment(current_address) - else: - self.bookmark_address(current_address) - - def tableWidget_Disassemble_item_selection_changed(self) -> None: - if debugcore.currentpid == -1: - return - try: - selected_rows = self.tableWidget_Disassemble.selectionModel().selectedRows() - address_texts = [self.tableWidget_Disassemble.item(index.row(), DISAS_ADDR_COL).text() for index in selected_rows] - self.disassemble_selected_addresses = {utils.safe_str_to_int(utils.extract_hex_address(text), 16) for text in address_texts} - selected_row = guiutils.get_current_row(self.tableWidget_Disassemble) - selected_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - self.disassemble_last_selected_address_int = int(utils.extract_hex_address(selected_address_text), 16) - except (TypeError, ValueError, AttributeError): - pass - - # Search the item in given row for location changing instructions - # Go to the address pointed by that instruction if it contains any - def follow_instruction(self, selected_row: int) -> None: - if debugcore.currentpid == -1: - return - address = utils.instruction_follow_address(self.tableWidget_Disassemble.item(selected_row, DISAS_INSTR_COL).text()) - if address: - self.disassemble_expression(address) - - # Follows a clicked reference arrow. - # Normally jumps to the target address, but if the target is already the selected row we follow the caller instead so the arrow acts as a toggle. - def disassemble_arrow_follow(self, source: int, target: int) -> None: - if debugcore.currentpid == -1: - return - follow_address = source if self.disassemble_last_selected_address_int == target else target - # Select the followed address so repeated clicks keep toggling between caller and target. - self.disassemble_last_selected_address_int = follow_address - self.disassemble_selected_addresses = {follow_address} - self.disassemble_expression(hex(follow_address)) - - def disassemble_go_back(self) -> None: - if debugcore.currentpid == -1: - return - if self.tableWidget_Disassemble.travel_history: - last_location = self.tableWidget_Disassemble.travel_history[-1] - self.disassemble_expression(last_location, append_history=False) - self.tableWidget_Disassemble.travel_history.pop() - - def tableWidget_Disassemble_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(*columns: int, extract_address: bool = False) -> None: - rows = ["\t".join(self.tableWidget_Disassemble.item(row, column).text() for column in columns) for row in selected_rows] - QApplication.clipboard().setText("\n".join(utils.extract_hex_address(text) if extract_address else text for text in rows)) - - selected_rows = sorted({index.row() for index in self.tableWidget_Disassemble.selectionModel().selectedRows()}) - if not selected_rows: - return - selected_row = selected_rows[0] - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - current_address_int = utils.safe_str_to_int(current_address, 16) - - menu = QMenu() - go_to = menu.addAction(f"{tr.GO_TO_EXPRESSION}[Ctrl+G]") - back = menu.addAction(tr.BACK) - show_in_hex_view = menu.addAction(f"{tr.HEXVIEW_ADDRESS}[Ctrl+H]") - menu.addSeparator() - followable = utils.instruction_follow_address(self.tableWidget_Disassemble.item(selected_row, DISAS_INSTR_COL).text()) - follow = menu.addAction(f"{tr.FOLLOW}[Space]") - if not followable: - guiutils.delete_menu_entries(menu, [follow]) - examine_referrers = menu.addAction(f"{tr.EXAMINE_REFERRERS}[Ctrl+E]") - if not guiutils.contains_reference_mark(current_address_text): - guiutils.delete_menu_entries(menu, [examine_referrers]) - bookmark = menu.addAction(f"{tr.BOOKMARK_ADDRESS}[Ctrl+B]") - delete_bookmark = menu.addAction(tr.DELETE_BOOKMARK) - change_comment = menu.addAction(tr.CHANGE_COMMENT) - is_bookmarked = current_address_int in self.session.pct_bookmarks - if not is_bookmarked: - guiutils.delete_menu_entries(menu, [delete_bookmark, change_comment]) - else: - guiutils.delete_menu_entries(menu, [bookmark]) - go_to_bookmark = menu.addMenu(tr.GO_TO_BOOKMARK_ADDRESS) - address_list = [hex(address) for address in self.session.pct_bookmarks.keys()] - bookmark_actions = [go_to_bookmark.addAction(item.all) for item in debugcore.examine_expressions(address_list)] - menu.addSeparator() - toggle_breakpoint = menu.addAction(f"{tr.TOGGLE_BREAKPOINT}[F5]") - add_condition = menu.addAction(tr.CHANGE_BREAKPOINT_CONDITION) - if not debugcore.get_breakpoints_in_range(current_address_int): - guiutils.delete_menu_entries(menu, [add_condition]) - menu.addSeparator() - edit_instruction = menu.addAction(tr.EDIT_INSTRUCTION) - nop_instruction = menu.addAction(tr.REPLACE_WITH_NOPS) - if self.tableWidget_Disassemble.item(selected_row, DISAS_OPCODES_COL).text() == "90": - guiutils.delete_menu_entries(menu, [nop_instruction]) - menu.addSeparator() - track_breakpoint = menu.addAction(tr.WHAT_ACCESSES_INSTRUCTION) - trace_instructions = menu.addAction(f"{tr.TRACE_INSTRUCTION}[Ctrl+T]") - dissect_region = menu.addAction(f"{tr.DISSECT_REGION}[Ctrl+D]") - menu.addSeparator() - refresh = menu.addAction(f"{tr.REFRESH}[R]") - menu.addSeparator() - if debugcore.currentpid == -1: - menu.clear() - clipboard_menu = menu.addMenu(tr.COPY_CLIPBOARD) - copy_address = clipboard_menu.addAction(tr.COPY_ADDRESS) - copy_bytes = clipboard_menu.addAction(tr.COPY_BYTES) - copy_instr = clipboard_menu.addAction(tr.COPY_INSTR) - copy_comment = clipboard_menu.addAction(tr.COPY_COMMENT) - copy_all = clipboard_menu.addAction(tr.COPY_ALL) - if len(selected_rows) > 1: - for entry in menu.actions(): - entry.setEnabled(entry.menu() is not None or entry in (go_to, back, dissect_region, refresh)) - font_size = self.tableWidget_Disassemble.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - go_to: self.exec_disassemble_go_to_dialog, - back: self.disassemble_go_back, - show_in_hex_view: lambda: self.hex_dump_address(current_address_int), - follow: lambda: self.follow_instruction(selected_row), - examine_referrers: lambda: self.exec_examine_referrers_widget(current_address_text), - bookmark: lambda: self.bookmark_address(current_address_int), - delete_bookmark: lambda: self.delete_bookmark(current_address_int), - change_comment: lambda: self.change_bookmark_comment(current_address_int), - toggle_breakpoint: self.toggle_breakpoint, - add_condition: lambda: self.add_breakpoint_condition(current_address_int), - edit_instruction: self.edit_instruction, - nop_instruction: self.nop_instruction, - track_breakpoint: self.exec_track_breakpoint_dialog, - trace_instructions: self.exec_trace_instructions_dialog, - dissect_region: self.dissect_current_region, - refresh: self.refresh_disassemble_view, - copy_address: lambda: copy_to_clipboard(DISAS_ADDR_COL, extract_address=True), - copy_bytes: lambda: copy_to_clipboard(DISAS_OPCODES_COL), - copy_instr: lambda: copy_to_clipboard(DISAS_INSTR_COL), - copy_comment: lambda: copy_to_clipboard(DISAS_COMMENT_COL), - copy_all: lambda: copy_to_clipboard(*range(self.tableWidget_Disassemble.columnCount())), - } - try: - actions[action]() - except KeyError: - pass - if action in bookmark_actions: - self.disassemble_expression(utils.extract_hex_address(action.text())) - - def dissect_current_region(self) -> None: - if debugcore.currentpid == -1: - return - if not self.tableWidget_Disassemble.rowCount(): - return - selected_row = guiutils.get_current_row(self.tableWidget_Disassemble) - if selected_row == -1: - selected_row = 0 - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - dissect_code_dialog = DissectCodeDialog(self, utils.safe_str_to_int(current_address, 16)) - dissect_code_dialog.scan_finished_signal.connect(dissect_code_dialog.accept) - dissect_code_dialog.exec() - self.refresh_disassemble_view() - - def exec_examine_referrers_widget(self, current_address_text: str) -> None: - if debugcore.currentpid == -1: - return - if not guiutils.contains_reference_mark(current_address_text): - return - current_address = utils.extract_hex_address(current_address_text) - current_address_int = utils.safe_str_to_int(current_address, 16) - examine_referrers_widget = ExamineReferrersWidget(self, current_address_int) - examine_referrers_widget.show() - - def exec_trace_instructions_dialog(self) -> None: - if debugcore.currentpid == -1: - return - if not self.tableWidget_Disassemble.rowCount(): - return - selected_row = self.get_disassemble_row(no_selection_row=0) - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - TraceInstructionsWindow(self, current_address) - - def exec_track_breakpoint_dialog(self) -> None: - if debugcore.currentpid == -1: - return - selected_row = self.get_disassemble_row() - if selected_row == -1: - return - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - current_instruction = self.tableWidget_Disassemble.item(selected_row, DISAS_INSTR_COL).text() - register_expression_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_TRACK_BP_EXPRESSION, "")]) - if register_expression_dialog.exec(): - exp = register_expression_dialog.get_values()[0] - TrackBreakpointWidget(self, current_address, current_instruction, exp) - - def exec_disassemble_go_to_dialog(self) -> None: - if debugcore.currentpid == -1: - return - if not self.tableWidget_Disassemble.rowCount(): - return - selected_row = guiutils.get_current_row(self.tableWidget_Disassemble) - if selected_row == -1: - selected_row = 0 - current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - - go_to_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_EXPRESSION, current_address)]) - if go_to_dialog.exec(): - traveled_exp = go_to_dialog.get_values()[0] - self.disassemble_expression(traveled_exp) - - def bookmark_address(self, address: int) -> None: - if debugcore.currentpid == -1: - return - if address in self.session.pct_bookmarks: - QMessageBox.information(QApplication.focusWidget(), tr.ERROR, tr.ALREADY_BOOKMARKED) - return - comment_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_BOOKMARK_COMMENT, "")]) - if comment_dialog.exec(): - comment_data = comment_dialog.get_values() - comment = comment_data[0] if comment_data else "" - else: - return - exam_result = debugcore.examine_expression(hex(address)) - symbol = utils.extract_symbol_name(exam_result.symbol) if exam_result.symbol else "" - - region_info = utils.get_region_info(debugcore.currentpid, address) - - if not region_info: - logger.error("Address does not belong to any mapped region, aborting") - return - - if region_info.file_name == "[heap]" or region_info.file_name == "[stack]": - logger.warning("Address belongs to the heap or stack, cannot bookmark") - return - - address_region_details = { - "region_name": region_info.file_name, - "offset_in_region": hex(address - region_info.start), - "region_index": region_info.region_index, - } - self.session.pct_bookmarks[address] = { - "symbol": symbol, - "comment": comment, - "address_region_details": address_region_details, - } - self.session.data_changed |= SessionDataChanged.BOOKMARKS - states.session_signals.bookmarks_changed.emit() - logger.info(self.session.pct_bookmarks) - self.refresh_disassemble_view() - - def change_bookmark_comment(self, address: int) -> None: - if debugcore.currentpid == -1: - return - current_comment = self.session.pct_bookmarks[address]["comment"] - comment_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_BOOKMARK_COMMENT, current_comment)]) - if comment_dialog.exec(): - new_comment = comment_dialog.get_values()[0] - else: - return - self.session.pct_bookmarks[address]["comment"] = new_comment - self.session.data_changed |= SessionDataChanged.BOOKMARKS - states.session_signals.bookmarks_changed.emit() - self.refresh_disassemble_view() - - def delete_bookmark(self, address: int) -> None: - if debugcore.currentpid == -1: - return - if address in self.session.pct_bookmarks: - del self.session.pct_bookmarks[address] - self.session.data_changed |= SessionDataChanged.BOOKMARKS - states.session_signals.bookmarks_changed.emit() - self.refresh_disassemble_view() - - def actionBookmarks_triggered(self) -> None: - if self.bookmark_widget is None: - self.bookmark_widget = BookmarkWidget(self) - self.bookmark_widget.bookmarked.connect(self.bookmark_address) - self.bookmark_widget.comment_changed.connect(self.change_bookmark_comment) - self.bookmark_widget.double_clicked.connect(self.disassemble_expression) - self.bookmark_widget.deleted.connect(self.delete_bookmark) - else: - self.bookmark_widget.refresh_table() - self.bookmark_widget.show() - self.bookmark_widget.activateWindow() - - def actionStackTrace_Info_triggered(self) -> None: - if debugcore.currentpid == -1: - return - self.stacktrace_info_widget.update_stacktrace() - guiutils.center_to_parent(self.stacktrace_info_widget) - self.stacktrace_info_widget.show() - self.stacktrace_info_widget.activateWindow() - - def actionBreakpoints_triggered(self) -> None: - if debugcore.currentpid == -1: - return - if self.breakpoint_widget is None: - self.breakpoint_widget = BreakpointInfoWidget(self) - else: - self.breakpoint_widget.refresh() - self.breakpoint_widget.show() - self.breakpoint_widget.activateWindow() - - def actionFunctions_triggered(self) -> None: - if debugcore.currentpid == -1: - return - if self.functions_info_widget is None: - self.functions_info_widget = FunctionsInfoWidget(self) - self.functions_info_widget.show() - - def actionGDB_Log_File_triggered(self) -> None: - log_file_widget = LogFileWidget(self) - log_file_widget.showMaximized() - - def actionMemory_Regions_triggered(self) -> None: - if debugcore.currentpid == -1: - return - if self.memory_regions_widget is None: - self.memory_regions_widget = MemoryRegionsWidget(self) - else: - self.memory_regions_widget.refresh_table() - self.memory_regions_widget.show() - - def actionRestore_Instructions_triggered(self) -> None: - if debugcore.currentpid == -1: - return - if self.restore_instructions_widget is None: - self.restore_instructions_widget = RestoreInstructionsWidget(self) - self.restore_instructions_widget.restored.connect(self.refresh_hex_view) - self.restore_instructions_widget.restored.connect(self.refresh_disassemble_view) - self.restore_instructions_widget.double_clicked.connect(self.disassemble_expression) - else: - self.restore_instructions_widget.refresh() - self.restore_instructions_widget.show() - self.restore_instructions_widget.activateWindow() - - def actionReferenced_Strings_triggered(self) -> None: - if debugcore.currentpid == -1: - return - ref_str_widget = ReferencedStringsWidget(self) - ref_str_widget.show() - - def actionReferenced_Calls_triggered(self) -> None: - if debugcore.currentpid == -1: - return - ref_call_widget = ReferencedCallsWidget(self) - ref_call_widget.show() - - def actionInject_so_file_triggered(self) -> None: - if debugcore.currentpid == -1: - return - file_path, _ = QFileDialog.getOpenFileName(self, tr.SELECT_SO_FILE, os.path.expanduser("~"), tr.SHARED_OBJECT_TYPE) - if file_path: - if debugcore.inject_so(file_path): - QMessageBox.information(self, tr.SUCCESS, tr.SO_INJECTED) - else: - QMessageBox.information(self, tr.ERROR, tr.SO_INJECT_FAILED) - - def actionInject_DLL_file_triggered(self) -> None: - if debugcore.currentpid == -1: - return - if not utils.is_wine_process(debugcore.currentpid): - QMessageBox.information(self, tr.ERROR, tr.DLL_INJECT_WINE_ONLY) - return - file_path, _ = QFileDialog.getOpenFileName(self, tr.SELECT_DLL_FILE, os.path.expanduser("~"), tr.DLL_TYPE) - if file_path: - if debugcore.inject_dll(file_path): - QMessageBox.information(self, tr.SUCCESS, tr.DLL_INJECT_STARTED) - else: - QMessageBox.information(self, tr.ERROR, tr.DLL_INJECT_FAILED) - - def actionCall_Function_triggered(self) -> None: - if debugcore.currentpid == -1: - return - call_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_CALL_EXPRESSION, "")]) - if call_dialog.exec(): - result = debugcore.call_function_from_inferior(call_dialog.get_values()[0]) - if result[0]: - QMessageBox.information(self, tr.SUCCESS, result[0] + " = " + result[1]) - else: - QMessageBox.information(self, tr.ERROR, tr.CALL_EXPRESSION_FAILED.format(call_dialog.get_values()[0])) - - def actionSearch_Instructions_triggered(self) -> None: - if debugcore.currentpid == -1: - return - start_address = utils.safe_str_to_int(self.disassemble_currently_displayed_address, 16) - end_address = start_address + 0x30000 - region_info = utils.get_region_info(debugcore.currentpid, start_address) - if region_info: - start_address = region_info.start - end_address = region_info.end - search_instr_widget = SearchInstructionsWidget(self, hex(start_address), hex(end_address)) - search_instr_widget.show() - - def actionDissect_Code_triggered(self) -> None: - if debugcore.currentpid == -1: - return - dissect_code_dialog = DissectCodeDialog(self) - dissect_code_dialog.exec() - self.refresh_disassemble_view() - - def actionDissect_Mono_triggered(self) -> None: - if debugcore.currentpid == -1: - return - info = monocore.detect_runtime(debugcore.currentpid) - if info is None: - QMessageBox.information(self, tr.ERROR, tr.MONO_NO_RUNTIME) - return - if not monocore.init_mono(): - QMessageBox.information(self, tr.ERROR, tr.MONO_NOT_READY) - return - mono_dialog = MonoDissectDialog(self) - mono_dialog.disassemble_requested.connect(lambda address: self.disassemble_expression(hex(int(address)))) - mono_dialog.breakpoint_requested.connect(self._mono_breakpoint) - mono_dialog.add_to_table_requested.connect(lambda description, address: self.parent().add_entry_to_addresstable(description, address)) - mono_dialog.export_structure_requested.connect(self._export_mono_structure) - mono_dialog.view_structure_requested.connect(self._view_mono_structure) - mono_dialog.show() - - def _mono_breakpoint(self, address: object) -> None: - if not debugcore.add_breakpoint(hex(int(address))): - QMessageBox.information(self, tr.ERROR, tr.BREAKPOINT_FAILED.format(hex(int(address)))) - self.refresh_disassemble_view() - - def _export_mono_structure(self, class_data: object) -> None: - client = monocore.get_client() - if client is None: - return - existing = set(StructureManager.list_names()) - try: - struct = mono_export.structure_from_class(client, class_data) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_NOT_READY) - return - created = set(StructureManager.list_names()) - existing - if not StructureEditorDialog(self, struct.name).exec(): - for name in created: - StructureManager.delete(name) - if self.parent().structures_window: - self.parent().structures_window.refresh() - - def _view_mono_structure(self, structure_name: str, address: object) -> None: - view = StructureViewDialog(self, structure_name, hex(int(address))) - view.add_to_table_requested.connect(self.parent()._add_structure_records_to_table) - view.show() - if self.parent().structures_window: - self.parent().structures_window.refresh() - - def actionLibpince_Engine_triggered(self) -> None: - # The engine is owned by the main form since it integrates with the address table - self.parent().show_libpince_engine() - - def actionStructures_triggered(self) -> None: - self.parent().show_structures_window() - - def actionLibpince_triggered(self) -> None: - utils.execute_command_as_user('python3 -m webbrowser "https://korcankaraokcu.github.io/PINCE/"') - - def pushButton_ShowFloatRegisters_clicked(self) -> None: - if guiutils.check_inferior_running(self): - return - self.float_registers_widget.update_registers() - guiutils.center_to_parent(self.float_registers_widget) - self.float_registers_widget.show() - self.float_registers_widget.activateWindow() - - def on_new_session(self) -> None: - self.session = SessionManager.get_session() diff --git a/GUI/Widgets/MonoDissect/Form/MonoDissectDialog.py b/GUI/Widgets/MonoDissect/Form/MonoDissectDialog.py deleted file mode 100644 index d7ad79b5..00000000 --- a/GUI/Widgets/MonoDissect/Form/MonoDissectDialog.py +++ /dev/null @@ -1,47 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/MonoDissect/Form/MonoDissectDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(700, 550) - self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) - self.verticalLayout.setObjectName("verticalLayout") - self.lineEdit_Search = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Search.setObjectName("lineEdit_Search") - self.verticalLayout.addWidget(self.lineEdit_Search) - self.checkBox_ShowInherited = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_ShowInherited.setObjectName("checkBox_ShowInherited") - self.verticalLayout.addWidget(self.checkBox_ShowInherited) - self.treeWidget_Mono = QtWidgets.QTreeWidget(parent=Dialog) - font = QtGui.QFont() - font.setFamily("Monospace") - self.treeWidget_Mono.setFont(font) - self.treeWidget_Mono.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.treeWidget_Mono.setWordWrap(False) - self.treeWidget_Mono.setObjectName("treeWidget_Mono") - self.verticalLayout.addWidget(self.treeWidget_Mono) - self.label_Status = QtWidgets.QLabel(parent=Dialog) - self.label_Status.setText("") - self.label_Status.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_Status.setObjectName("label_Status") - self.verticalLayout.addWidget(self.label_Status) - - self.retranslateUi(Dialog) - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Dissect Mono/IL2CPP")) - self.lineEdit_Search.setPlaceholderText(_translate("Dialog", "Search")) - self.checkBox_ShowInherited.setText(_translate("Dialog", "Show inherited members")) - self.treeWidget_Mono.headerItem().setText(0, _translate("Dialog", "Name")) - self.treeWidget_Mono.headerItem().setText(1, _translate("Dialog", "Value")) diff --git a/GUI/Widgets/MonoDissect/Form/MonoDissectDialog.ui b/GUI/Widgets/MonoDissect/Form/MonoDissectDialog.ui deleted file mode 100644 index 271a86d6..00000000 --- a/GUI/Widgets/MonoDissect/Form/MonoDissectDialog.ui +++ /dev/null @@ -1,70 +0,0 @@ - - - Dialog - - - - 0 - 0 - 700 - 550 - - - - Dissect Mono/IL2CPP - - - - - - Search - - - - - - - Show inherited members - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - false - - - - Name - - - - - Value - - - - - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - diff --git a/GUI/Widgets/MonoDissect/MonoDissect.py b/GUI/Widgets/MonoDissect/MonoDissect.py deleted file mode 100644 index e468692a..00000000 --- a/GUI/Widgets/MonoDissect/MonoDissect.py +++ /dev/null @@ -1,480 +0,0 @@ -from PyQt6.QtCore import Qt, pyqtSignal -from PyQt6.QtGui import QBrush, QColor -from PyQt6.QtWidgets import QApplication, QDialog, QMenu, QMessageBox, QTreeWidgetItem, QWidget - -from GUI.Widgets.MonoDissect.Form.MonoDissectDialog import Ui_Dialog -from GUI.Widgets.MonoInvoke.MonoInvoke import MonoInvokeDialog -from GUI.Widgets.MonoFindInstances.MonoFindInstances import MonoFindInstancesDialog -from GUI.Widgets.Structures import mono_export -from GUI.Utils import guiutils -from libpince import debugcore, monocore, utils, typedefs -from tr.tr import TranslationConstants as tr - -ROLE_KIND = Qt.ItemDataRole.UserRole # "image" | "class" | "fields" | "methods" | "field" | "method" | "ref_field" -ROLE_DATA = Qt.ItemDataRole.UserRole + 1 # the dict from monocore -ROLE_LOADED = Qt.ItemDataRole.UserRole + 2 # bool, children populated - -_INHERITED_BRUSH = QBrush(QColor(140, 140, 140)) -_MAX_INHERIT_DEPTH = 32 -_MAX_DRILL_DEPTH = 16 - - -class MonoDissectDialog(QDialog, Ui_Dialog): - disassemble_requested = pyqtSignal(object) # native address (int) - breakpoint_requested = pyqtSignal(object) # native address (int) - add_to_table_requested = pyqtSignal(str, object) # description, address-expr (str | PointerChainRequest) - export_structure_requested = pyqtSignal(object) # class_data dict - view_structure_requested = pyqtSignal(str, object) # structure name, base address (int) - - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.treeWidget_Mono.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.lineEdit_Search.textChanged.connect(self.search_text_changed) - self.treeWidget_Mono.itemExpanded.connect(self.tree_item_expanded) - self.treeWidget_Mono.itemExpanded.connect(self.resize_columns) - self.treeWidget_Mono.customContextMenuRequested.connect(self.tree_context_menu) - self.checkBox_ShowInherited.toggled.connect(self._on_inherited_toggled) - guiutils.center_to_parent(self) - self.populate_assemblies() - - def populate_assemblies(self) -> None: - client = monocore.get_client() - if client is None: - self.label_Status.setText(tr.MONO_NOT_READY) - return - self.treeWidget_Mono.clear() - try: - for assembly in client.assemblies(): - item = QTreeWidgetItem([assembly["name"], ""]) - item.setData(0, ROLE_KIND, "image") - item.setData(0, ROLE_DATA, assembly) - item.setData(0, ROLE_LOADED, False) - item.addChild(QTreeWidgetItem(["", ""])) # placeholder for the expand arrow - self.treeWidget_Mono.addTopLevelItem(item) - except monocore.MonoError: - self.label_Status.setText(tr.MONO_NOT_READY) - return - self.resize_columns() - - def _on_inherited_toggled(self, checked: bool) -> None: - self.populate_assemblies() - - def _add_field_node( - self, - parent: QTreeWidgetItem, - fld: dict, - class_data: dict, - offsets: list[int], - root_class: dict, - suffix: str = "", - instance_base: int | None = None, - ) -> None: - if fld["flags"] & 0x40: # FIELD_ATTRIBUTE_LITERAL: const, no runtime address - value = f"const {fld['type']}" - else: - marker = "static " if fld["is_static"] else "" - value = f"{marker}{fld['type']} @ {utils.upper_hex(hex(fld['offset']))}" - is_ref = not fld["is_static"] and fld.get("tag") == "object" - child = QTreeWidgetItem([fld["name"], value + suffix]) - child.setData(0, ROLE_KIND, "ref_field" if is_ref else "field") - # instance_base roots the path at a concrete object (Find Instances) vs the singleton static - child.setData( - 0, - ROLE_DATA, - { - "field": fld, - "class": class_data, - "offsets": offsets, - "root_class": root_class, - "instance_base": instance_base, - }, - ) - if is_ref: # drillable: lazily expand into the referenced type's fields - child.setData(0, ROLE_LOADED, False) - child.addChild(QTreeWidgetItem(["", ""])) - parent.addChild(child) - - def _add_inherited_fields(self, client: monocore.MonoClient, parent_item: QTreeWidgetItem, class_data: dict) -> None: - ptr = class_data.get("parent", 0) - depth = 0 - while ptr != 0 and depth < _MAX_INHERIT_DEPTH: - try: - info = client.class_info(ptr) - except monocore.MonoError: - break - owner_label = f"({info['name']})" - for fld in client.fields(ptr): - if fld["flags"] & 0x40: - value = f"const {fld['type']}" - else: - marker = "static " if fld["is_static"] else "" - value = f"{marker}{fld['type']} @ {utils.upper_hex(hex(fld['offset']))}" - child = QTreeWidgetItem([fld["name"], f"{value} {owner_label}"]) - child.setData(0, ROLE_KIND, "field") - child.setData( - 0, - ROLE_DATA, - {"field": fld, "class": {"klass": ptr, "name": info["name"], "namespace": info["namespace"]}}, - ) - for col in range(parent_item.columnCount()): - child.setForeground(col, _INHERITED_BRUSH) - parent_item.addChild(child) - ptr = info.get("parent", 0) - depth += 1 - - def _add_inherited_methods(self, client: monocore.MonoClient, parent_item: QTreeWidgetItem, class_data: dict) -> None: - ptr = class_data.get("parent", 0) - depth = 0 - while ptr != 0 and depth < _MAX_INHERIT_DEPTH: - try: - info = client.class_info(ptr) - except monocore.MonoError: - break - owner_label = f"({info['name']})" - for meth in client.methods(ptr): - label = f"{meth['full_name'] or meth['name']} {owner_label}" - child = QTreeWidgetItem([label, ""]) - child.setData(0, ROLE_KIND, "method") - child.setData(0, ROLE_DATA, meth) - for col in range(parent_item.columnCount()): - child.setForeground(col, _INHERITED_BRUSH) - parent_item.addChild(child) - ptr = info.get("parent", 0) - depth += 1 - - def _drill_depth(self, item: QTreeWidgetItem) -> int: - depth = 0 - node = item - while node is not None: - if node.data(0, ROLE_KIND) == "ref_field": - depth += 1 - node = node.parent() - return depth - - def resize_columns(self) -> None: - for column in range(self.treeWidget_Mono.columnCount()): - self.treeWidget_Mono.resizeColumnToContents(column) - - def tree_item_expanded(self, item: QTreeWidgetItem) -> None: - if item.data(0, ROLE_LOADED): - return - kind = item.data(0, ROLE_KIND) - item.takeChildren() # drop placeholder - client = monocore.get_client() - if client is None: - return - try: - if kind == "image": - data = item.data(0, ROLE_DATA) - for klass in client.classes(data["image"]): - ns = klass["namespace"] - label = f"{ns}.{klass['name']}" if ns else klass["name"] - child = QTreeWidgetItem([label, ""]) - child.setData(0, ROLE_KIND, "class") - child.setData(0, ROLE_DATA, klass) - child.setData(0, ROLE_LOADED, False) - child.addChild(QTreeWidgetItem(["", ""])) - item.addChild(child) - elif kind == "class": - data = item.data(0, ROLE_DATA) - fields_node = QTreeWidgetItem([tr.FIELDS, ""]) - fields_node.setData(0, ROLE_KIND, "fields") - fields_node.setData(0, ROLE_DATA, data) - fields_node.setData(0, ROLE_LOADED, False) - fields_node.addChild(QTreeWidgetItem(["", ""])) - methods_node = QTreeWidgetItem([tr.METHODS, ""]) - methods_node.setData(0, ROLE_KIND, "methods") - methods_node.setData(0, ROLE_DATA, data) - methods_node.setData(0, ROLE_LOADED, False) - methods_node.addChild(QTreeWidgetItem(["", ""])) - item.addChild(fields_node) - item.addChild(methods_node) - elif kind == "fields": - class_data = item.data(0, ROLE_DATA) - klass = class_data["klass"] - for fld in client.fields(klass): - self._add_field_node(item, fld, class_data, [fld["offset"]], class_data) - if self.checkBox_ShowInherited.isChecked(): - self._add_inherited_fields(client, item, class_data) - elif kind == "methods": - class_data = item.data(0, ROLE_DATA) - klass = class_data["klass"] - for meth in client.methods(klass): - child = QTreeWidgetItem([meth["full_name"] or meth["name"], ""]) - child.setData(0, ROLE_KIND, "method") - child.setData(0, ROLE_DATA, meth) - item.addChild(child) - if self.checkBox_ShowInherited.isChecked(): - self._add_inherited_methods(client, item, class_data) - elif kind == "ref_field": - self._expand_ref_field(item, client) - return - except monocore.MonoError: - return - item.setData(0, ROLE_LOADED, True) - - def _expand_ref_field(self, item: QTreeWidgetItem, client: monocore.MonoClient) -> None: - """Expand a reference field into its type's fields (shared by both trees). - - Children accumulate the offset path and inherit instance_base (None when singleton). - """ - payload = item.data(0, ROLE_DATA) - fld = payload["field"] - parent_offsets = payload.get("offsets", []) - root_class = payload.get("root_class", payload["class"]) - instance_base = payload.get("instance_base") - if self._drill_depth(item) >= _MAX_DRILL_DEPTH: - item.addChild(QTreeWidgetItem([tr.MONO_DRILL_MAX_DEPTH, ""])) - item.setData(0, ROLE_LOADED, True) - return - try: - ref_klass = client.type_klass(fld["field"]) - except monocore.MonoError: - ref_klass = 0 - if ref_klass == 0: - item.addChild(QTreeWidgetItem([tr.MONO_DRILL_UNRESOLVABLE, ""])) - else: - try: - ref_info = client.class_info(ref_klass) - except monocore.MonoError: - ref_info = {"name": "?", "namespace": ""} - ns = ref_info.get("namespace") - type_label = f"{ns}.{ref_info['name']}" if ns else ref_info.get("name", "?") - ref_class = {**ref_info, "klass": ref_klass} - for sub_fld in client.fields(ref_klass): - offsets = parent_offsets + [sub_fld["offset"]] - self._add_field_node(item, sub_fld, ref_class, offsets, root_class, f" [{type_label}]", instance_base) - item.setData(0, ROLE_LOADED, True) - - def search_text_changed(self, text: str) -> None: - text = text.lower() - - def filter_item(item: QTreeWidgetItem) -> bool: - visible_child = False - for i in range(item.childCount()): - if filter_item(item.child(i)): - visible_child = True - match = text in item.text(0).lower() - item.setHidden(not (match or visible_child) if text else False) - return match or visible_child - - for i in range(self.treeWidget_Mono.topLevelItemCount()): - filter_item(self.treeWidget_Mono.topLevelItem(i)) - - def tree_context_menu(self, position) -> None: - item = self.treeWidget_Mono.itemAt(position) - if item is None: - return - client = monocore.get_client() - if client is None: - return - kind = item.data(0, ROLE_KIND) - global_pos = self.treeWidget_Mono.viewport().mapToGlobal(position) - if kind == "method": - self._method_context_menu(client, item, global_pos) - elif kind in ("field", "ref_field"): - self._field_context_menu(client, item, global_pos) - elif kind == "class": - self._class_context_menu(client, item, global_pos) - - def _method_context_menu(self, client: monocore.MonoClient, item: QTreeWidgetItem, global_pos) -> None: - method = item.data(0, ROLE_DATA)["method"] - menu = QMenu(self) - action_disas = menu.addAction(tr.DISASSEMBLE) - action_break = menu.addAction(tr.SET_BREAKPOINT) - action_copy = menu.addAction(tr.COPY_ADDRESS) - action_invoke = menu.addAction(tr.MONO_INVOKE) - chosen = menu.exec(global_pos) - if chosen is None: - return - if chosen == action_invoke: - methods_node = item.parent() - class_info = methods_node.data(0, ROLE_DATA) if methods_node is not None else None - self.open_invoke_for_method(client, item.data(0, ROLE_DATA), class_info) - return - try: - address = client.compile_method(method) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_NOT_READY) - return - if chosen == action_disas: - self.disassemble_requested.emit(address) - elif chosen == action_break: - self.breakpoint_requested.emit(address) - elif chosen == action_copy: - QApplication.clipboard().setText(utils.upper_hex(hex(address))) - - def _class_context_menu(self, client: monocore.MonoClient, item: QTreeWidgetItem, global_pos) -> None: - class_data = item.data(0, ROLE_DATA) - menu = QMenu(self) - action_find = menu.addAction(tr.MONO_FIND_INSTANCES) - action_export = menu.addAction(tr.EXPORT_AS_STRUCTURE) - singleton = self._singleton_root(client, class_data) - action_dissect_singleton = None - if singleton is not None: - action_dissect_singleton = menu.addAction(tr.DISSECT_AS_STRUCTURE) - chosen = menu.exec(global_pos) - if chosen is None: - return - if chosen == action_find: - self._find_instances(class_data) - elif chosen == action_export: - self.export_structure_requested.emit(class_data) - elif chosen == action_dissect_singleton: - self._dissect_singleton_as_structure(client, class_data, singleton) - - def _field_context_menu(self, client: monocore.MonoClient, item: QTreeWidgetItem, global_pos) -> None: - """Build the field/ref_field context menu. Shared with the Find Instances tree.""" - payload = item.data(0, ROLE_DATA) - fld = payload["field"] - menu = QMenu(item.treeWidget()) # parent to the clicked tree's window, not always this dialog - if fld["is_static"]: - if fld["flags"] & 0x40: # FIELD_ATTRIBUTE_LITERAL: const, no runtime address - return - # Static field: resolve to an absolute address. - action_table = menu.addAction(tr.ADD_TO_ADDRESS_LIST) - action_copy = menu.addAction(tr.COPY_ADDRESS) - chosen = menu.exec(global_pos) - if chosen is None: - return - try: - address = client.static_field_address(payload["class"]["klass"], fld["field"]) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_STATIC_UNAVAILABLE) - return - if chosen == action_table: - self.add_to_table_requested.emit(fld["name"], hex(address)) - elif chosen == action_copy: - QApplication.clipboard().setText(utils.upper_hex(hex(address))) - return - offsets = payload.get("offsets", [fld["offset"]]) - instance_base = payload.get("instance_base") - if instance_base is not None: - # Concrete instance (Find Instances): the path always resolves. - action_table = menu.addAction(tr.ADD_TO_ADDRESS_LIST) - action_copy = menu.addAction(tr.COPY_OFFSET) - chosen = menu.exec(global_pos) - if chosen is None: - return - if chosen == action_table: - expr = self._instance_address_expr(instance_base, offsets) - self.add_to_table_requested.emit(f"{payload['root_class'].get('name', '?')}.{fld['name']}", expr) - elif chosen == action_copy: - QApplication.clipboard().setText(utils.upper_hex(hex(fld["offset"]))) - return - # Instance field -> no absolute address. - # If the dissect root has a self-referential static (the singleton / Instance pattern), - # resolve via a pointer chain whose offsets are the full drilled path, - # so deep leaves still hit the live object. - root_class = payload.get("root_class", payload["class"]) - root = self._singleton_root(client, root_class) - action_table = menu.addAction(tr.ADD_TO_ADDRESS_LIST) if root is not None else None - action_copy = menu.addAction(tr.COPY_OFFSET) - chosen = menu.exec(global_pos) - if chosen is None: - return - if action_table is not None and chosen == action_table: - try: - base = client.static_field_address(root_class["klass"], root["field"]) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_STATIC_UNAVAILABLE) - return - # hex base keeps read_pointer_chain on its fast path (an int base forces a GDB lookup) - pointer = typedefs.PointerChainRequest(hex(base), offsets) - self.add_to_table_requested.emit(f"{root_class.get('name', '?')}.{fld['name']}", pointer) - elif chosen == action_copy: - QApplication.clipboard().setText(utils.upper_hex(hex(fld["offset"]))) - - def _instance_address_expr(self, instance_base: int, offsets: list[int]) -> "str | typedefs.PointerChainRequest": - """Address for a drilled field on a concrete instance: one hop is absolute, - deeper hops chain through the intermediate reference fields.""" - if len(offsets) == 1: - return hex(instance_base + offsets[0]) - # hex base keeps read_pointer_chain on its fast path (an int base forces a GDB lookup) - return typedefs.PointerChainRequest(hex(instance_base + offsets[0]), offsets[1:]) - - def _find_instances(self, class_data: dict) -> None: - QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor) - try: - addresses = monocore.find_instances(class_data["klass"]) - except monocore.MonoError: - addresses = None # marker unavailable - finally: - QApplication.restoreOverrideCursor() - if addresses is None: - QMessageBox.information(self, tr.ERROR, tr.MONO_INSTANCE_MARKER_UNAVAILABLE) - return - if not addresses: - QMessageBox.information(self, tr.MONO_FIND_INSTANCES, tr.MONO_NO_INSTANCES) - return - ns = class_data.get("namespace") - type_label = f"{ns}.{class_data['name']}" if ns else class_data.get("name", "?") - MonoFindInstancesDialog(self, class_data, type_label, addresses).show() - - def open_invoke_for_method( - self, client: monocore.MonoClient, method_info: dict, class_info: dict | None, instance_ptr: int | None = None - ) -> None: - """Open the Invoke dialog for a method.""" - try: - signature = client.signature(method_info["method"]) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_NOT_READY) - return - klass = class_info["klass"] if class_info else 0 - if instance_ptr is None and not signature.get("static", True) and class_info is not None: - # No concrete instance given: try the class' self-referential static (singleton pattern). - root = self._singleton_root(client, class_info) - if root is not None: - try: - slot = client.static_field_address(klass, root["field"]) - pointer_bits = 32 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64 - instance_ptr = debugcore.read_memory(slot, typedefs.IntegerValueType(pointer_bits)) - except monocore.MonoError: - instance_ptr = None - MonoInvokeDialog(self, method_info, signature, instance_ptr=instance_ptr, klass=klass).show() - - def _singleton_root(self, client: monocore.MonoClient, klass_info: dict) -> dict | None: - """Return the class' self-referential static field (singleton / Instance pattern), if any. - - Such a field (e.g. Player.Current : Player) holds a pointer to a live instance, so it can - root a pointer chain that resolves the class's instance fields to that object automatically. - """ - full_name = f"{klass_info['namespace']}.{klass_info['name']}" if klass_info["namespace"] else klass_info["name"] - try: - fields = client.fields(klass_info["klass"]) - except monocore.MonoError: - return None - for candidate in fields: - if candidate["is_static"] and candidate["type"] == full_name: - return candidate - return None - - def _dissect_instance_as_structure(self, class_data: dict, address: int) -> None: - client = monocore.get_client() - if client is None: - return - try: - struct = mono_export.structure_from_class(client, class_data, force_new=False) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_NOT_READY) - return - self.view_structure_requested.emit(struct.name, address) - - def _dissect_singleton_as_structure(self, client: monocore.MonoClient, class_data: dict, singleton: dict) -> None: - try: - slot = client.static_field_address(class_data["klass"], singleton["field"]) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_STATIC_UNAVAILABLE) - return - pointer_bits = 32 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64 - address = debugcore.read_memory(slot, typedefs.IntegerValueType(pointer_bits)) - if not address: - QMessageBox.information(self, tr.MONO_FIND_INSTANCES, tr.MONO_NO_INSTANCES) - return - try: - struct = mono_export.structure_from_class(client, class_data, force_new=False) - except monocore.MonoError: - QMessageBox.information(self, tr.ERROR, tr.MONO_NOT_READY) - return - self.view_structure_requested.emit(struct.name, address) diff --git a/GUI/Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.py b/GUI/Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.py deleted file mode 100644 index 814a6fee..00000000 --- a/GUI/Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.py +++ /dev/null @@ -1,39 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(640, 480) - self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) - self.verticalLayout.setObjectName("verticalLayout") - self.label_Header = QtWidgets.QLabel(parent=Dialog) - self.label_Header.setText("") - self.label_Header.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_Header.setObjectName("label_Header") - self.verticalLayout.addWidget(self.label_Header) - self.treeWidget_Instances = QtWidgets.QTreeWidget(parent=Dialog) - font = QtGui.QFont() - font.setFamily("Monospace") - self.treeWidget_Instances.setFont(font) - self.treeWidget_Instances.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.treeWidget_Instances.setWordWrap(False) - self.treeWidget_Instances.setObjectName("treeWidget_Instances") - self.verticalLayout.addWidget(self.treeWidget_Instances) - - self.retranslateUi(Dialog) - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Find Instances")) - self.treeWidget_Instances.headerItem().setText(0, _translate("Dialog", "Name")) - self.treeWidget_Instances.headerItem().setText(1, _translate("Dialog", "Value")) diff --git a/GUI/Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.ui b/GUI/Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.ui deleted file mode 100644 index 1a7dc4da..00000000 --- a/GUI/Widgets/MonoFindInstances/Form/MonoFindInstancesDialog.ui +++ /dev/null @@ -1,56 +0,0 @@ - - - Dialog - - - - 0 - 0 - 640 - 480 - - - - Find Instances - - - - - - - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - false - - - - Name - - - - - Value - - - - - - - - - diff --git a/GUI/Widgets/MonoFindInstances/MonoFindInstances.py b/GUI/Widgets/MonoFindInstances/MonoFindInstances.py deleted file mode 100644 index 86a4e4a7..00000000 --- a/GUI/Widgets/MonoFindInstances/MonoFindInstances.py +++ /dev/null @@ -1,106 +0,0 @@ -from typing import TYPE_CHECKING - -from PyQt6.QtCore import Qt -from PyQt6.QtWidgets import QApplication, QDialog, QMenu, QTreeWidgetItem - -from GUI.Widgets.MonoFindInstances.Form.MonoFindInstancesDialog import Ui_Dialog -from GUI.Utils import guiutils -from libpince import monocore, utils -from tr.tr import TranslationConstants as tr - -if TYPE_CHECKING: - from GUI.Widgets.MonoDissect.MonoDissect import MonoDissectDialog - -# Tree roles, mirrored from MonoDissect (the shared field-node helpers read these). -ROLE_KIND = Qt.ItemDataRole.UserRole -ROLE_DATA = Qt.ItemDataRole.UserRole + 1 -ROLE_LOADED = Qt.ItemDataRole.UserRole + 2 - -_MAX_INSTANCES = 2000 # cap the results tree so a huge heap can't build an unwieldy list - - -class MonoFindInstancesDialog(QDialog, Ui_Dialog): - """A class' live instances, each drillable into its fields at live addresses. - - Tree building, drill down and the field menu come from the owning MonoDissectDialog, - rooted here at a concrete instance address rather than the class' singleton static. - """ - - def __init__(self, owner: "MonoDissectDialog", class_data: dict, type_label: str, addresses: list[int]) -> None: - super().__init__(owner) - self.setupUi(self) - self.owner = owner - self.setWindowTitle(tr.MONO_FIND_INSTANCES_TITLE.format(type_label)) - shown = addresses[:_MAX_INSTANCES] - header = tr.MONO_INSTANCES_FOUND.format(len(addresses)) - if len(shown) < len(addresses): - header += " " + tr.MONO_INSTANCES_TRUNCATED.format(len(shown)) - self.label_Header.setText(header) - self.treeWidget_Instances.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.treeWidget_Instances.itemExpanded.connect(self.tree_item_expanded) - self.treeWidget_Instances.customContextMenuRequested.connect(self.tree_context_menu) - for i, address in enumerate(shown): - node = QTreeWidgetItem([f"#{i}", utils.upper_hex(hex(address))]) - node.setData(0, ROLE_KIND, "instance") - node.setData(0, ROLE_DATA, {"address": address, "class": class_data}) - node.setData(0, ROLE_LOADED, False) - node.addChild(QTreeWidgetItem(["", ""])) # placeholder for the expand arrow - self.treeWidget_Instances.addTopLevelItem(node) - guiutils.center_to_parent(self) - - def tree_item_expanded(self, item: QTreeWidgetItem) -> None: - if item.data(0, ROLE_LOADED): - return - kind = item.data(0, ROLE_KIND) - item.takeChildren() # drop placeholder - client = monocore.get_client() - if client is None: - return - try: - if kind == "instance": - payload = item.data(0, ROLE_DATA) - base = payload["address"] - class_data = payload["class"] - for fld in client.fields(class_data["klass"]): - self.owner._add_field_node(item, fld, class_data, [fld["offset"]], class_data, instance_base=base) - item.setData(0, ROLE_LOADED, True) - elif kind == "ref_field": - self.owner._expand_ref_field(item, client) - except monocore.MonoError: - return - for column in range(self.treeWidget_Instances.columnCount()): - self.treeWidget_Instances.resizeColumnToContents(column) - - def tree_context_menu(self, position) -> None: - item = self.treeWidget_Instances.itemAt(position) - if item is None: - return - client = monocore.get_client() - if client is None: - return - kind = item.data(0, ROLE_KIND) - global_pos = self.treeWidget_Instances.viewport().mapToGlobal(position) - if kind in ("field", "ref_field"): - self.owner._field_context_menu(client, item, global_pos) - elif kind == "instance": - payload = item.data(0, ROLE_DATA) - menu = QMenu(self) - action_table = menu.addAction(tr.ADD_TO_ADDRESS_LIST) - action_dissect = menu.addAction(tr.DISSECT_AS_STRUCTURE) - action_copy = menu.addAction(tr.COPY_ADDRESS) - invoke_menu = menu.addMenu(tr.MONO_INVOKE) - try: - methods = client.methods(payload["class"]["klass"]) - except monocore.MonoError: - methods = [] - method_actions = {invoke_menu.addAction(m["full_name"] or m["name"]): m for m in methods} - invoke_menu.setEnabled(bool(method_actions)) - chosen = menu.exec(global_pos) - if chosen == action_table: - self.owner.add_to_table_requested.emit(f"{payload['class'].get('name', '?')} {item.text(0)}", hex(payload["address"])) - elif chosen == action_dissect: - self.owner._dissect_instance_as_structure(payload["class"], payload["address"]) - elif chosen == action_copy: - QApplication.clipboard().setText(utils.upper_hex(hex(payload["address"]))) - elif chosen in method_actions: - self.owner.open_invoke_for_method(client, method_actions[chosen], payload["class"], instance_ptr=payload["address"]) diff --git a/GUI/Widgets/MonoInvoke/Form/MonoInvokeDialog.py b/GUI/Widgets/MonoInvoke/Form/MonoInvokeDialog.py deleted file mode 100644 index cbfad1ac..00000000 --- a/GUI/Widgets/MonoInvoke/Form/MonoInvokeDialog.py +++ /dev/null @@ -1,53 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/MonoInvoke/Form/MonoInvokeDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(480, 320) - self.verticalLayout = QtWidgets.QVBoxLayout(Dialog) - self.verticalLayout.setObjectName("verticalLayout") - self.label_Method = QtWidgets.QLabel(parent=Dialog) - font = QtGui.QFont() - font.setFamily("Monospace") - self.label_Method.setFont(font) - self.label_Method.setText("") - self.label_Method.setWordWrap(True) - self.label_Method.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_Method.setObjectName("label_Method") - self.verticalLayout.addWidget(self.label_Method) - self.formLayout = QtWidgets.QFormLayout() - self.formLayout.setObjectName("formLayout") - self.verticalLayout.addLayout(self.formLayout) - spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout.addItem(spacerItem) - self.label_Result = QtWidgets.QLabel(parent=Dialog) - self.label_Result.setText("") - self.label_Result.setWordWrap(True) - self.label_Result.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.LinksAccessibleByMouse|QtCore.Qt.TextInteractionFlag.TextSelectableByMouse) - self.label_Result.setObjectName("label_Result") - self.verticalLayout.addWidget(self.label_Result) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem1) - self.pushButton_Call = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Call.setObjectName("pushButton_Call") - self.horizontalLayout.addWidget(self.pushButton_Call) - self.verticalLayout.addLayout(self.horizontalLayout) - - self.retranslateUi(Dialog) - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Invoke")) - self.pushButton_Call.setText(_translate("Dialog", "Call")) diff --git a/GUI/Widgets/MonoInvoke/Form/MonoInvokeDialog.ui b/GUI/Widgets/MonoInvoke/Form/MonoInvokeDialog.ui deleted file mode 100644 index 6b74db7e..00000000 --- a/GUI/Widgets/MonoInvoke/Form/MonoInvokeDialog.ui +++ /dev/null @@ -1,92 +0,0 @@ - - - Dialog - - - - 0 - 0 - 480 - 320 - - - - Invoke - - - - - - - Monospace - - - - - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Call - - - - - - - - - - diff --git a/GUI/Widgets/MonoInvoke/MonoInvoke.py b/GUI/Widgets/MonoInvoke/MonoInvoke.py deleted file mode 100644 index fed4967c..00000000 --- a/GUI/Widgets/MonoInvoke/MonoInvoke.py +++ /dev/null @@ -1,183 +0,0 @@ -from typing import Any - -from PyQt6.QtCore import Qt -from PyQt6.QtWidgets import ( - QApplication, - QDialog, - QHBoxLayout, - QInputDialog, - QLabel, - QLineEdit, - QMessageBox, - QPushButton, - QWidget, -) - -from GUI.Widgets.MonoInvoke.Form.MonoInvokeDialog import Ui_Dialog -from GUI.Utils import guiutils -from libpince import monocore, utils -from tr.tr import TranslationConstants as tr - -_MAX_PICK = 2000 # cap the instance picker list, same as the Find Instances tree - - -class MonoInvokeDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, method_info: dict, signature: dict, instance_ptr: int | None = None, klass: int = 0) -> None: - super().__init__(parent) - self.setupUi(self) - self.method = method_info["method"] - self.signature = signature - self.klass = klass # declaring class, for the "Find instance" picker - self.label_Method.setText(method_info["full_name"] or method_info["name"]) - self.params: list[dict] = [] # one descriptor per parameter (see _add_param) - - # Instance ("this") pointer. Disabled for static methods, prefilled/pickable for instance ones. - self.instance_input = QLineEdit(self) - if signature.get("static", True): - self.instance_input.setText("0") - self.instance_input.setEnabled(False) - self.formLayout.addRow(tr.MONO_INVOKE_INSTANCE, self.instance_input) - else: - if instance_ptr: - self.instance_input.setText(utils.upper_hex(hex(instance_ptr))) - row = QHBoxLayout() - row.addWidget(self.instance_input) - find_button = QPushButton(tr.MONO_INVOKE_FIND_INSTANCE, self) - find_button.setEnabled(bool(klass)) - find_button.clicked.connect(self._pick_instance) - row.addWidget(find_button) - self.formLayout.addRow(tr.MONO_INVOKE_INSTANCE, row) - - client = monocore.get_client() - for param in signature.get("params", []): - self.params.append(self._add_param(client, param)) - - self.pushButton_Call.clicked.connect(self.call) - guiutils.center_to_parent(self) - - def _pick_instance(self) -> None: - """Scan for live instances of the class and fill the instance field with a chosen one.""" - if monocore.get_client() is None: - self.label_Result.setText(tr.MONO_NOT_READY) - return - QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor) - try: - addresses = monocore.find_instances(self.klass) - except monocore.MonoError: - addresses = None # marker unavailable - finally: - QApplication.restoreOverrideCursor() - if addresses is None: - QMessageBox.information(self, tr.MONO_FIND_INSTANCES, tr.MONO_INSTANCE_MARKER_UNAVAILABLE) - return - if not addresses: - QMessageBox.information(self, tr.MONO_FIND_INSTANCES, tr.MONO_NO_INSTANCES) - return - items = [utils.upper_hex(hex(a)) for a in addresses[:_MAX_PICK]] - label = tr.MONO_INVOKE_PICK_INSTANCE - if len(addresses) > _MAX_PICK: - label = f"{label} {tr.MONO_INSTANCES_TRUNCATED.format(_MAX_PICK)}" - choice, ok = QInputDialog.getItem(self, tr.MONO_FIND_INSTANCES, label, items, 0, False) - if ok and choice: - self.instance_input.setText(choice) - - def _add_param(self, client: "monocore.MonoClient | None", param: dict) -> dict: - """Add a parameter's inputs and return a descriptor used to build its invoke arg. - - A struct expands into one input per primitive field. - A struct whose fields aren't all primitive falls back to a single raw hex bytes input. - """ - tag, name = param["tag"], param["name"] - if tag == "struct": - layout = client.struct_fields(param["klass"]) if client and param.get("klass") else None - if layout: - self.formLayout.addRow(QLabel(f"{name} ({param['type']})")) - fields = [] - for fld in layout: - edit = QLineEdit(self) - self.formLayout.addRow(f"{fld['name']} ({fld['type']})", edit) - fields.append({**fld, "edit": edit}) - return {"kind": "struct", "size": param["size"], "fields": fields} - edit = QLineEdit(self) - if param.get("size"): - edit.setPlaceholderText(tr.MONO_INVOKE_STRUCT_HINT.format(param["size"])) - kind = "struct_raw" - else: # collector couldn't resolve the value size so we can't marshal it by value - edit.setEnabled(False) - edit.setPlaceholderText(param["type"]) - kind = "unsupported" - self.formLayout.addRow(f"{name} ({param['type']})", edit) - return {"kind": kind, "size": param.get("size", 0), "edit": edit} - edit = QLineEdit(self) - if tag == "unsupported": - edit.setEnabled(False) - edit.setPlaceholderText(param["type"]) - self.formLayout.addRow(f"{name} ({param['type']})", edit) - return {"kind": "unsupported" if tag == "unsupported" else "scalar", "tag": tag, "edit": edit} - - def call(self) -> None: - client = monocore.get_client() - if client is None: - self.label_Result.setText(tr.MONO_NOT_READY) - return - if any(p["kind"] == "unsupported" for p in self.params): - self.label_Result.setText(tr.MONO_INVOKE_UNSUPPORTED) - return - try: - obj = int(self.instance_input.text().strip() or "0", 0) - except ValueError: - self.label_Result.setText(tr.MONO_INVOKE_BAD_INSTANCE) - return - try: - args = [self._param_arg(p) for p in self.params] - except (ValueError, monocore.MonoError): - self.label_Result.setText(tr.MONO_INVOKE_BAD_ARG) - return - try: - response = client.invoke(self.method, obj, args) - except monocore.MonoError as error: - self.label_Result.setText(str(error)) - return - if response["exception"]: - self.label_Result.setText(tr.MONO_INVOKE_EXCEPTION.format(utils.upper_hex(hex(response["exception"])))) - elif response["tag"] is None: - self.label_Result.setText(tr.MONO_INVOKE_VOID) - elif response["tag"] == "struct": - self.label_Result.setText(tr.MONO_INVOKE_RESULT.format(self._format_struct(client, response["result"]))) - else: - self.label_Result.setText(tr.MONO_INVOKE_RESULT.format(response["result"])) - - def _param_arg(self, p: dict) -> tuple[str, Any]: - """Build one (tag, value) invoke arg from a parameter descriptor.""" - if p["kind"] == "scalar": - return (p["tag"], self.parse_value(p["tag"], p["edit"].text().strip())) - if p["kind"] == "struct": - buf = bytearray(p["size"]) # gaps (padding) stay zero - for fld in p["fields"]: - raw = monocore.pack_value(fld["tag"], self.parse_value(fld["tag"], fld["edit"].text().strip())) - buf[fld["offset"] : fld["offset"] + len(raw)] = raw - return ("struct", bytes(buf)) - raw = bytes.fromhex(p["edit"].text().strip().replace(" ", "")) # struct_raw fallback - if len(raw) != p["size"]: - raise ValueError("struct byte length mismatch") - return ("struct", raw) - - def _format_struct(self, client: "monocore.MonoClient", raw: bytes) -> str: - """Render a returned struct as "field=value, ..." or hex bytes if its fields aren't primitive.""" - ret_klass = self.signature["ret"].get("klass", 0) - try: - layout = client.struct_fields(ret_klass) if ret_klass else None - except monocore.MonoError: - layout = None - if not layout: - return raw.hex() - return ", ".join(f"{fld['name']}={monocore.unpack_value(fld['tag'], raw[fld['offset'] : fld['offset'] + fld['width']])}" for fld in layout) - - def parse_value(self, tag: str, text: str) -> Any: - if tag in ("str", "char"): - return text - if tag == "bool": - return text.lower() in ("1", "true", "yes") - if tag in ("r4", "r8"): - return float(text) - return int(text, 0) diff --git a/GUI/Widgets/PointerScan/Form/PointerScanWindow.py b/GUI/Widgets/PointerScan/Form/PointerScanWindow.py deleted file mode 100644 index a8257761..00000000 --- a/GUI/Widgets/PointerScan/Form/PointerScanWindow.py +++ /dev/null @@ -1,67 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/PointerScan/Form/PointerScanWindow.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.resize(783, 693) - self.centralwidget = QtWidgets.QWidget(parent=MainWindow) - self.centralwidget.setObjectName("centralwidget") - self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) - self.gridLayout.setObjectName("gridLayout") - self.tableView = QtWidgets.QTableView(parent=self.centralwidget) - self.tableView.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableView.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection) - self.tableView.setAlternatingRowColors(True) - self.tableView.setWordWrap(False) - self.tableView.setObjectName("tableView") - self.gridLayout.addWidget(self.tableView, 0, 0, 1, 1) - MainWindow.setCentralWidget(self.centralwidget) - self.menubar = QtWidgets.QMenuBar(parent=MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 783, 32)) - self.menubar.setObjectName("menubar") - self.menuFile = QtWidgets.QMenu(parent=self.menubar) - self.menuFile.setObjectName("menuFile") - self.menuActions = QtWidgets.QMenu(parent=self.menubar) - self.menuActions.setObjectName("menuActions") - MainWindow.setMenuBar(self.menubar) - self.statusbar = QtWidgets.QStatusBar(parent=MainWindow) - self.statusbar.setSizeGripEnabled(True) - self.statusbar.setObjectName("statusbar") - MainWindow.setStatusBar(self.statusbar) - self.actionOpen = QtGui.QAction(parent=MainWindow) - self.actionOpen.setObjectName("actionOpen") - self.actionSaveAs = QtGui.QAction(parent=MainWindow) - self.actionSaveAs.setObjectName("actionSaveAs") - self.actionScan = QtGui.QAction(parent=MainWindow) - self.actionScan.setObjectName("actionScan") - self.actionFilter = QtGui.QAction(parent=MainWindow) - self.actionFilter.setObjectName("actionFilter") - self.menuFile.addAction(self.actionOpen) - self.menuFile.addAction(self.actionSaveAs) - self.menuActions.addAction(self.actionScan) - self.menuActions.addAction(self.actionFilter) - self.menubar.addAction(self.menuFile.menuAction()) - self.menubar.addAction(self.menuActions.menuAction()) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - _translate = QtCore.QCoreApplication.translate - MainWindow.setWindowTitle(_translate("MainWindow", "Pointer Scanner")) - self.menuFile.setTitle(_translate("MainWindow", "Fi&le")) - self.menuActions.setTitle(_translate("MainWindow", "Actio&ns")) - self.actionOpen.setText(_translate("MainWindow", "&Open")) - self.actionSaveAs.setText(_translate("MainWindow", "&Save As...")) - self.actionScan.setText(_translate("MainWindow", "&Scan")) - self.actionFilter.setText(_translate("MainWindow", "&Filter")) diff --git a/GUI/Widgets/PointerScan/Form/PointerScanWindow.ui b/GUI/Widgets/PointerScan/Form/PointerScanWindow.ui deleted file mode 100644 index 57ce4bb5..00000000 --- a/GUI/Widgets/PointerScan/Form/PointerScanWindow.ui +++ /dev/null @@ -1,93 +0,0 @@ - - - MainWindow - - - - 0 - 0 - 783 - 693 - - - - Pointer Scanner - - - - - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - QAbstractItemView::SelectionBehavior::SelectRows - - - QAbstractItemView::SelectionMode::ExtendedSelection - - - true - - - false - - - - - - - - - 0 - 0 - 783 - 32 - - - - - Fi&le - - - - - - - Actio&ns - - - - - - - - - - true - - - - - &Open - - - - - &Save As... - - - - - &Scan - - - - - &Filter - - - - - - diff --git a/GUI/Widgets/PointerScan/PointerScan.py b/GUI/Widgets/PointerScan/PointerScan.py deleted file mode 100644 index 104fa5b6..00000000 --- a/GUI/Widgets/PointerScan/PointerScan.py +++ /dev/null @@ -1,129 +0,0 @@ -from PyQt6.QtCore import Qt, QModelIndex -from PyQt6.QtGui import QCloseEvent, QKeySequence, QShortcut -from PyQt6.QtWidgets import QMainWindow, QFileDialog, QLabel, QWidget, QMessageBox -from GUI.Widgets.PointerScan.Form.PointerScanWindow import Ui_MainWindow -from GUI.Widgets.PointerScanFilter.PointerScanFilter import PointerScanFilterDialog -from GUI.Widgets.PointerScanSearch.PointerScanSearch import PointerScanSearchDialog -from GUI.AbstractTableModels.PointerScanModel import PointerScanModel -from GUI.Utils import guiutils, guitypedefs -from GUI.States import states -from libpince import debugcore, typedefs, utils -from libpince.scancore import memscan -from tr.tr import TranslationConstants as tr -import os - - -class PointerScanWindow(QMainWindow, Ui_MainWindow): - def __init__(self, parent: QWidget, default_scan_address: str) -> None: - super().__init__(parent) - self.setupUi(self) - self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) - states.process_signals.attach.connect(self.on_process_changed) - states.process_signals.exit.connect(self.on_process_changed) - self.actionOpen.triggered.connect(self.actionOpen_triggered) - self.actionSaveAs.triggered.connect(self.actionSaveAs_triggered) - self.actionScan.triggered.connect(self.scan_triggered) - self.actionFilter.triggered.connect(self.filter_triggered) - self.model = PointerScanModel(self) - self.tableView.setModel(self.model) - self.tableView.setSortingEnabled(True) - self.tableView.horizontalHeader().setSortIndicator(-1, Qt.SortOrder.AscendingOrder) - self.tableView.doubleClicked.connect(self.tableView_double_clicked) - # Enter/Return adds every selected row (a double-click collapses multi-selection, so it can't) - self.add_selected_shortcuts: list[QShortcut] = [] - for key in (Qt.Key.Key_Return, Qt.Key.Key_Enter): - shortcut = QShortcut(QKeySequence(key), self.tableView) - shortcut.setContext(Qt.ShortcutContext.WidgetWithChildrenShortcut) - shortcut.activated.connect(self.add_selected_to_address_table) - self.add_selected_shortcuts.append(shortcut) - self.path_count_label = QLabel() - self.path_count_label.setContentsMargins(0, 0, 6, 0) - self.menubar.setCornerWidget(self.path_count_label, Qt.Corner.TopRightCorner) - self.default_scan_address = default_scan_address - self.load_thread: guitypedefs.InterruptibleWorker | None = None - if debugcore.currentpid == -1: - self.actionScan.setEnabled(False) - guiutils.center_to_parent(self) - - def on_process_changed(self) -> None: - self.actionScan.setEnabled(debugcore.currentpid != -1) - - def closeEvent(self, event: QCloseEvent) -> None: - if self.load_thread is not None: - self.load_thread.terminate() - self.load_thread.wait() - self.model.clear() - return super().closeEvent(event) - - def actionOpen_triggered(self) -> None: - file_path, _ = QFileDialog.getOpenFileName(self, tr.SELECT_POINTER_MAP, os.path.expanduser("~"), tr.FILE_TYPES_POINTER_MAP) - if file_path != "": - self.load_map(file_path) - - def load_map(self, file_path: str) -> None: - if self.load_thread is not None: - self.load_thread.terminate() - self.load_thread.wait() - self.model.clear() - self.tableView.horizontalHeader().setSortIndicator(-1, Qt.SortOrder.AscendingOrder) - self.load_thread = guitypedefs.InterruptibleWorker(self._read_pointer_map, file_path) - self.load_thread.signals.finished.connect(self._on_map_loaded) - self.load_thread.signals.error.connect(self._on_map_error) - self.load_thread.start() - - @staticmethod - def _read_pointer_map(file_path: str) -> tuple[list[tuple[str, list[int]]], int]: - rows = [] - offset_columns = 0 - for base, offsets in memscan.iter_pointer_map(file_path): - rows.append((base, offsets)) - if len(offsets) > offset_columns: - offset_columns = len(offsets) - return rows, offset_columns - - def _on_map_loaded(self, result: tuple[list[tuple[str, list[int]]], int]) -> None: - self.load_thread.wait() - self.load_thread = None - rows, offset_columns = result - self.model.set_data(rows, offset_columns) - self.tableView.resizeColumnsToContents() - self.path_count_label.setText(tr.POINTER_PATH_COUNT.format(len(rows))) - # Re-set widget to re-align it after text change. - self.menubar.setCornerWidget(self.path_count_label, Qt.Corner.TopRightCorner) - - def _on_map_error(self, error: Exception) -> None: - self.load_thread.wait() - self.load_thread = None - QMessageBox.information(self, tr.ERROR, str(error)) - - def actionSaveAs_triggered(self) -> None: - with guiutils.save_dialog_as_user(self, tr.SELECT_POINTER_MAP, os.path.expanduser("~"), "") as file_path: - if file_path: - with open(file_path, "w") as file: - file.write("".join(self.model.format_row(row) + "\n" for row in range(self.model.rowCount()))) - - def tableView_double_clicked(self, index: QModelIndex) -> None: - self.add_rows_to_address_table([index.row()]) - - def add_selected_to_address_table(self) -> None: - selected_rows = sorted({index.row() for index in self.tableView.selectionModel().selectedRows()}) - self.add_rows_to_address_table(selected_rows) - - def add_rows_to_address_table(self, rows: list[int]) -> None: - if not rows: - return - main_window = self.parent() - for row in rows: - request = self.model.pointer_chain_request(row) - main_window.add_entry_to_addresstable(tr.NO_DESCRIPTION, request, typedefs.IntegerValueType()) - main_window.update_address_table() - - def scan_triggered(self) -> None: - dialog = PointerScanSearchDialog(self, self.default_scan_address) - if dialog.exec() and dialog.result_map_path: - self.load_map(dialog.result_map_path) - - def filter_triggered(self) -> None: - dialog = PointerScanFilterDialog(self) - if dialog.exec() and dialog.result_map_path: - self.load_map(dialog.result_map_path) diff --git a/GUI/Widgets/PointerScanFilter/Form/PointerScanFilterDialog.py b/GUI/Widgets/PointerScanFilter/Form/PointerScanFilterDialog.py deleted file mode 100644 index 7820e2cf..00000000 --- a/GUI/Widgets/PointerScanFilter/Form/PointerScanFilterDialog.py +++ /dev/null @@ -1,88 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/PointerScanFilter/Form/PointerScanFilterDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(400, 190) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth()) - Dialog.setSizePolicy(sizePolicy) - Dialog.setMinimumSize(QtCore.QSize(400, 190)) - Dialog.setMaximumSize(QtCore.QSize(400, 190)) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout_Main = QtWidgets.QVBoxLayout() - self.verticalLayout_Main.setContentsMargins(0, -1, -1, -1) - self.verticalLayout_Main.setObjectName("verticalLayout_Main") - self.horizontalLayout_PrevFile = QtWidgets.QHBoxLayout() - self.horizontalLayout_PrevFile.setObjectName("horizontalLayout_PrevFile") - self.label_PrevFile = QtWidgets.QLabel(parent=Dialog) - self.label_PrevFile.setScaledContents(False) - self.label_PrevFile.setObjectName("label_PrevFile") - self.horizontalLayout_PrevFile.addWidget(self.label_PrevFile) - self.lineEdit_PrevFile = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_PrevFile.setReadOnly(True) - self.lineEdit_PrevFile.setObjectName("lineEdit_PrevFile") - self.horizontalLayout_PrevFile.addWidget(self.lineEdit_PrevFile) - self.pushButton_PrevFile = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_PrevFile.setObjectName("pushButton_PrevFile") - self.horizontalLayout_PrevFile.addWidget(self.pushButton_PrevFile) - self.verticalLayout_Main.addLayout(self.horizontalLayout_PrevFile) - self.horizontalLayout_CurrentFile = QtWidgets.QHBoxLayout() - self.horizontalLayout_CurrentFile.setObjectName("horizontalLayout_CurrentFile") - self.label_CurrentFile = QtWidgets.QLabel(parent=Dialog) - self.label_CurrentFile.setObjectName("label_CurrentFile") - self.horizontalLayout_CurrentFile.addWidget(self.label_CurrentFile) - self.lineEdit_CurrentFile = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_CurrentFile.setReadOnly(True) - self.lineEdit_CurrentFile.setObjectName("lineEdit_CurrentFile") - self.horizontalLayout_CurrentFile.addWidget(self.lineEdit_CurrentFile) - self.pushButton_CurrentFile = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_CurrentFile.setObjectName("pushButton_CurrentFile") - self.horizontalLayout_CurrentFile.addWidget(self.pushButton_CurrentFile) - self.verticalLayout_Main.addLayout(self.horizontalLayout_CurrentFile) - self.horizontalLayout_NewFile = QtWidgets.QHBoxLayout() - self.horizontalLayout_NewFile.setObjectName("horizontalLayout_NewFile") - self.label_NewFile = QtWidgets.QLabel(parent=Dialog) - self.label_NewFile.setObjectName("label_NewFile") - self.horizontalLayout_NewFile.addWidget(self.label_NewFile) - self.lineEdit_NewFile = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_NewFile.setReadOnly(True) - self.lineEdit_NewFile.setObjectName("lineEdit_NewFile") - self.horizontalLayout_NewFile.addWidget(self.lineEdit_NewFile) - self.pushButton_NewFile = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_NewFile.setObjectName("pushButton_NewFile") - self.horizontalLayout_NewFile.addWidget(self.pushButton_NewFile) - self.verticalLayout_Main.addLayout(self.horizontalLayout_NewFile) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel) - self.buttonBox.setObjectName("buttonBox") - self.verticalLayout_Main.addWidget(self.buttonBox) - self.gridLayout.addLayout(self.verticalLayout_Main, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Compare & Filter Pointers")) - self.label_PrevFile.setText(_translate("Dialog", "Previous Map:")) - self.pushButton_PrevFile.setText(_translate("Dialog", "Browse")) - self.label_CurrentFile.setText(_translate("Dialog", "Current Map:")) - self.pushButton_CurrentFile.setText(_translate("Dialog", "Browse")) - self.label_NewFile.setText(_translate("Dialog", "New Output Map:")) - self.pushButton_NewFile.setText(_translate("Dialog", "Browse")) diff --git a/GUI/Widgets/PointerScanFilter/Form/PointerScanFilterDialog.ui b/GUI/Widgets/PointerScanFilter/Form/PointerScanFilterDialog.ui deleted file mode 100644 index b0ef8bc4..00000000 --- a/GUI/Widgets/PointerScanFilter/Form/PointerScanFilterDialog.ui +++ /dev/null @@ -1,167 +0,0 @@ - - - Dialog - - - - 0 - 0 - 400 - 190 - - - - - 0 - 0 - - - - - 400 - 190 - - - - - 400 - 190 - - - - Compare & Filter Pointers - - - - - - 0 - - - - - - - Previous Map: - - - false - - - - - - - true - - - - - - - Browse - - - - - - - - - - - Current Map: - - - - - - - true - - - - - - - Browse - - - - - - - - - - - New Output Map: - - - - - - - true - - - - - - - Browse - - - - - - - - - Qt::Orientation::Horizontal - - - QDialogButtonBox::StandardButton::Cancel - - - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/GUI/Widgets/PointerScanFilter/PointerScanFilter.py b/GUI/Widgets/PointerScanFilter/PointerScanFilter.py deleted file mode 100644 index e8573788..00000000 --- a/GUI/Widgets/PointerScanFilter/PointerScanFilter.py +++ /dev/null @@ -1,83 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QFileDialog, QPushButton, QLineEdit, QMessageBox, QWidget -from GUI.Widgets.PointerScanFilter.Form.PointerScanFilterDialog import Ui_Dialog -from GUI.Utils import guiutils, guitypedefs -from tr.tr import TranslationConstants as tr -from libpince import utils -from libpince.scancore import memscan -import os - - -class PointerScanFilterDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - guiutils.center_to_parent(self) - self.pushButton_PrevFile.clicked.connect(self.pushButton_PrevFile_clicked) - self.pushButton_CurrentFile.clicked.connect(self.pushButton_CurrentFile_clicked) - self.pushButton_NewFile.clicked.connect(self.pushButton_NewFile_clicked) - self.filter_button: QPushButton = self.buttonBox.addButton(tr.FILTER, QDialogButtonBox.ButtonRole.ActionRole) - self.filter_button.clicked.connect(self.filter_button_clicked) - self.filter_button.setEnabled(False) - self.filter_thread: guitypedefs.InterruptibleWorker | None = None - self.result_map_path = "" - - def pointer_map_file_prompt(self, file_path_field: QLineEdit, is_open: bool) -> None: - if is_open: - file_path, _ = QFileDialog.getOpenFileName(self, tr.SELECT_POINTER_MAP, os.path.expanduser("~"), tr.FILE_TYPES_POINTER_MAP) - else: - file_path, _ = QFileDialog.getSaveFileName(self, tr.SELECT_POINTER_MAP, os.path.expanduser("~"), tr.FILE_TYPES_POINTER_MAP) - if file_path != "": - if not is_open: - file_path = utils.append_file_extension(file_path, "lmptr") - file_path_field.setText(file_path) - if self.is_filterable_state(): - self.filter_button.setEnabled(True) - - def is_filterable_state(self) -> bool: - return self.lineEdit_PrevFile.text() != "" and self.lineEdit_CurrentFile.text() != "" and self.lineEdit_NewFile.text() != "" - - def reject(self) -> None: - if self.filter_thread is not None: - self.filter_thread.terminate() - self.filter_thread.wait() - self.filter_thread = None - return super().reject() - - def pushButton_PrevFile_clicked(self) -> None: - self.pointer_map_file_prompt(self.lineEdit_PrevFile, True) - - def pushButton_CurrentFile_clicked(self) -> None: - self.pointer_map_file_prompt(self.lineEdit_CurrentFile, True) - - def pushButton_NewFile_clicked(self) -> None: - self.pointer_map_file_prompt(self.lineEdit_NewFile, False) - - def filter_button_clicked(self) -> None: - if not self.is_filterable_state(): - return - self.filter_button.setEnabled(False) - self.filter_button.setText(tr.FILTERING) - self.filter_thread = guitypedefs.InterruptibleWorker( - memscan.compare_pointer_maps, - self.lineEdit_PrevFile.text(), - self.lineEdit_CurrentFile.text(), - self.lineEdit_NewFile.text(), - ) - self.filter_thread.signals.finished.connect(self.filter_finished) - self.filter_thread.signals.error.connect(self.filter_error) - self.filter_thread.start() - - def filter_finished(self, new_paths: int) -> None: - self.filter_thread.wait() - self.filter_thread = None - self.result_map_path = self.lineEdit_NewFile.text() - guiutils.own_path_as_user(self.result_map_path) - self.accept() - QMessageBox.information(self, tr.SUCCESS, tr.POINTER_FILTER_SUCCESS.format(new_paths)) - - def filter_error(self, error: Exception) -> None: - self.filter_thread.wait() - self.filter_thread = None - self.filter_button.setText(tr.FILTER) - self.filter_button.setEnabled(True) - QMessageBox.information(self, tr.ERROR, str(error)) diff --git a/GUI/Widgets/PointerScanSearch/Form/PointerScanSearchDialog.py b/GUI/Widgets/PointerScanSearch/Form/PointerScanSearchDialog.py deleted file mode 100644 index ba85a248..00000000 --- a/GUI/Widgets/PointerScanSearch/Form/PointerScanSearchDialog.py +++ /dev/null @@ -1,233 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/PointerScanSearch/Form/PointerScanSearchDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(404, 468) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Fixed) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth()) - Dialog.setSizePolicy(sizePolicy) - Dialog.setMinimumSize(QtCore.QSize(404, 468)) - Dialog.setMaximumSize(QtCore.QSize(404, 468)) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout_Main = QtWidgets.QVBoxLayout() - self.verticalLayout_Main.setObjectName("verticalLayout_Main") - self.horizontalLayout_Address = QtWidgets.QHBoxLayout() - self.horizontalLayout_Address.setObjectName("horizontalLayout_Address") - self.label_Address = QtWidgets.QLabel(parent=Dialog) - self.label_Address.setObjectName("label_Address") - self.horizontalLayout_Address.addWidget(self.label_Address) - self.lineEdit_Address = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Address.setObjectName("lineEdit_Address") - self.horizontalLayout_Address.addWidget(self.lineEdit_Address) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_Address.addItem(spacerItem) - self.verticalLayout_Main.addLayout(self.horizontalLayout_Address) - self.horizontalLayout_Path = QtWidgets.QHBoxLayout() - self.horizontalLayout_Path.setObjectName("horizontalLayout_Path") - self.label_Path = QtWidgets.QLabel(parent=Dialog) - self.label_Path.setObjectName("label_Path") - self.horizontalLayout_Path.addWidget(self.label_Path) - self.lineEdit_Path = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Path.setEnabled(True) - self.lineEdit_Path.setText("") - self.lineEdit_Path.setDragEnabled(False) - self.lineEdit_Path.setReadOnly(True) - self.lineEdit_Path.setClearButtonEnabled(False) - self.lineEdit_Path.setObjectName("lineEdit_Path") - self.horizontalLayout_Path.addWidget(self.lineEdit_Path) - self.pushButton_Path = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Path.setEnabled(True) - self.pushButton_Path.setObjectName("pushButton_Path") - self.horizontalLayout_Path.addWidget(self.pushButton_Path) - self.verticalLayout_Main.addLayout(self.horizontalLayout_Path) - self.horizontalLayout_CheckAdvOptions = QtWidgets.QHBoxLayout() - self.horizontalLayout_CheckAdvOptions.setObjectName("horizontalLayout_CheckAdvOptions") - self.checkBox_CheckAdvOptions = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_CheckAdvOptions.setChecked(False) - self.checkBox_CheckAdvOptions.setObjectName("checkBox_CheckAdvOptions") - self.horizontalLayout_CheckAdvOptions.addWidget(self.checkBox_CheckAdvOptions) - self.verticalLayout_Main.addLayout(self.horizontalLayout_CheckAdvOptions) - self.verticalWidget_AdvOptions = QtWidgets.QWidget(parent=Dialog) - self.verticalWidget_AdvOptions.setEnabled(False) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Maximum) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.verticalWidget_AdvOptions.sizePolicy().hasHeightForWidth()) - self.verticalWidget_AdvOptions.setSizePolicy(sizePolicy) - self.verticalWidget_AdvOptions.setObjectName("verticalWidget_AdvOptions") - self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalWidget_AdvOptions) - self.verticalLayout.setObjectName("verticalLayout") - self.horizontalLayout_ScanScope = QtWidgets.QHBoxLayout() - self.horizontalLayout_ScanScope.setObjectName("horizontalLayout_ScanScope") - self.label_ScanScope = QtWidgets.QLabel(parent=self.verticalWidget_AdvOptions) - self.label_ScanScope.setObjectName("label_ScanScope") - self.horizontalLayout_ScanScope.addWidget(self.label_ScanScope) - self.comboBox_ScanScope = QtWidgets.QComboBox(parent=self.verticalWidget_AdvOptions) - self.comboBox_ScanScope.setObjectName("comboBox_ScanScope") - self.horizontalLayout_ScanScope.addWidget(self.comboBox_ScanScope) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_ScanScope.addItem(spacerItem1) - self.verticalLayout.addLayout(self.horizontalLayout_ScanScope) - self.horizontalLayout_Endian = QtWidgets.QHBoxLayout() - self.horizontalLayout_Endian.setObjectName("horizontalLayout_Endian") - self.label_Endian = QtWidgets.QLabel(parent=self.verticalWidget_AdvOptions) - self.label_Endian.setObjectName("label_Endian") - self.horizontalLayout_Endian.addWidget(self.label_Endian) - self.comboBox_Endian = QtWidgets.QComboBox(parent=self.verticalWidget_AdvOptions) - self.comboBox_Endian.setObjectName("comboBox_Endian") - self.horizontalLayout_Endian.addWidget(self.comboBox_Endian) - spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_Endian.addItem(spacerItem2) - self.verticalLayout.addLayout(self.horizontalLayout_Endian) - self.horizontalLayout_PointerSize = QtWidgets.QHBoxLayout() - self.horizontalLayout_PointerSize.setObjectName("horizontalLayout_PointerSize") - self.label_PointerSize = QtWidgets.QLabel(parent=self.verticalWidget_AdvOptions) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.label_PointerSize.sizePolicy().hasHeightForWidth()) - self.label_PointerSize.setSizePolicy(sizePolicy) - self.label_PointerSize.setObjectName("label_PointerSize") - self.horizontalLayout_PointerSize.addWidget(self.label_PointerSize) - self.comboBox_PointerSize = QtWidgets.QComboBox(parent=self.verticalWidget_AdvOptions) - self.comboBox_PointerSize.setEditable(False) - self.comboBox_PointerSize.setMaxVisibleItems(2) - self.comboBox_PointerSize.setObjectName("comboBox_PointerSize") - self.horizontalLayout_PointerSize.addWidget(self.comboBox_PointerSize) - spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_PointerSize.addItem(spacerItem3) - self.verticalLayout.addLayout(self.horizontalLayout_PointerSize) - self.horizontalLayout_Depth = QtWidgets.QHBoxLayout() - self.horizontalLayout_Depth.setObjectName("horizontalLayout_Depth") - self.label_Depth = QtWidgets.QLabel(parent=self.verticalWidget_AdvOptions) - self.label_Depth.setObjectName("label_Depth") - self.horizontalLayout_Depth.addWidget(self.label_Depth) - self.spinBox_Depth = QtWidgets.QSpinBox(parent=self.verticalWidget_AdvOptions) - self.spinBox_Depth.setMinimum(1) - self.spinBox_Depth.setProperty("value", 5) - self.spinBox_Depth.setObjectName("spinBox_Depth") - self.horizontalLayout_Depth.addWidget(self.spinBox_Depth) - spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_Depth.addItem(spacerItem4) - self.verticalLayout.addLayout(self.horizontalLayout_Depth) - self.horizontalLayout_MaxOffset = QtWidgets.QHBoxLayout() - self.horizontalLayout_MaxOffset.setObjectName("horizontalLayout_MaxOffset") - self.label_MaxOffset = QtWidgets.QLabel(parent=self.verticalWidget_AdvOptions) - self.label_MaxOffset.setObjectName("label_MaxOffset") - self.horizontalLayout_MaxOffset.addWidget(self.label_MaxOffset) - self.spinBox_MaxOffset = QtWidgets.QSpinBox(parent=self.verticalWidget_AdvOptions) - self.spinBox_MaxOffset.setMaximum(999999999) - self.spinBox_MaxOffset.setSingleStep(4) - self.spinBox_MaxOffset.setProperty("value", 2048) - self.spinBox_MaxOffset.setDisplayIntegerBase(16) - self.spinBox_MaxOffset.setObjectName("spinBox_MaxOffset") - self.horizontalLayout_MaxOffset.addWidget(self.spinBox_MaxOffset) - spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_MaxOffset.addItem(spacerItem5) - self.verticalLayout.addLayout(self.horizontalLayout_MaxOffset) - self.horizontalLayout_MinOffset = QtWidgets.QHBoxLayout() - self.horizontalLayout_MinOffset.setObjectName("horizontalLayout_MinOffset") - self.label_MinOffset = QtWidgets.QLabel(parent=self.verticalWidget_AdvOptions) - self.label_MinOffset.setObjectName("label_MinOffset") - self.horizontalLayout_MinOffset.addWidget(self.label_MinOffset) - self.spinBox_MinOffset = QtWidgets.QSpinBox(parent=self.verticalWidget_AdvOptions) - self.spinBox_MinOffset.setMaximum(999999999) - self.spinBox_MinOffset.setSingleStep(4) - self.spinBox_MinOffset.setDisplayIntegerBase(16) - self.spinBox_MinOffset.setObjectName("spinBox_MinOffset") - self.horizontalLayout_MinOffset.addWidget(self.spinBox_MinOffset) - spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_MinOffset.addItem(spacerItem6) - self.verticalLayout.addLayout(self.horizontalLayout_MinOffset) - self.horizontalLayout_LastOffset = QtWidgets.QHBoxLayout() - self.horizontalLayout_LastOffset.setObjectName("horizontalLayout_LastOffset") - self.checkBox_LastOffset = QtWidgets.QCheckBox(parent=self.verticalWidget_AdvOptions) - self.checkBox_LastOffset.setChecked(False) - self.checkBox_LastOffset.setObjectName("checkBox_LastOffset") - self.horizontalLayout_LastOffset.addWidget(self.checkBox_LastOffset) - self.spinBox_LastOffset = QtWidgets.QSpinBox(parent=self.verticalWidget_AdvOptions) - self.spinBox_LastOffset.setMaximum(2048) - self.spinBox_LastOffset.setSingleStep(4) - self.spinBox_LastOffset.setDisplayIntegerBase(16) - self.spinBox_LastOffset.setObjectName("spinBox_LastOffset") - self.horizontalLayout_LastOffset.addWidget(self.spinBox_LastOffset) - spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_LastOffset.addItem(spacerItem7) - self.verticalLayout.addLayout(self.horizontalLayout_LastOffset) - self.horizontalLayout_MaxResults = QtWidgets.QHBoxLayout() - self.horizontalLayout_MaxResults.setObjectName("horizontalLayout_MaxResults") - self.checkBox_MaxResults = QtWidgets.QCheckBox(parent=self.verticalWidget_AdvOptions) - self.checkBox_MaxResults.setChecked(False) - self.checkBox_MaxResults.setObjectName("checkBox_MaxResults") - self.horizontalLayout_MaxResults.addWidget(self.checkBox_MaxResults) - self.spinBox_MaxResults = QtWidgets.QSpinBox(parent=self.verticalWidget_AdvOptions) - self.spinBox_MaxResults.setSuffix("") - self.spinBox_MaxResults.setMinimum(1) - self.spinBox_MaxResults.setMaximum(999999999) - self.spinBox_MaxResults.setObjectName("spinBox_MaxResults") - self.horizontalLayout_MaxResults.addWidget(self.spinBox_MaxResults) - spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_MaxResults.addItem(spacerItem8) - self.verticalLayout.addLayout(self.horizontalLayout_MaxResults) - self.horizontalLayout_Module = QtWidgets.QHBoxLayout() - self.horizontalLayout_Module.setObjectName("horizontalLayout_Module") - self.checkBox_Module = QtWidgets.QCheckBox(parent=self.verticalWidget_AdvOptions) - self.checkBox_Module.setChecked(True) - self.checkBox_Module.setObjectName("checkBox_Module") - self.horizontalLayout_Module.addWidget(self.checkBox_Module) - self.verticalLayout.addLayout(self.horizontalLayout_Module) - self.verticalLayout_Main.addWidget(self.verticalWidget_AdvOptions) - spacerItem9 = QtWidgets.QSpacerItem(20, 0, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_Main.addItem(spacerItem9) - self.progressBar = QtWidgets.QProgressBar(parent=Dialog) - self.progressBar.setVisible(False) - self.progressBar.setProperty("value", 0) - self.progressBar.setInvertedAppearance(False) - self.progressBar.setObjectName("progressBar") - self.verticalLayout_Main.addWidget(self.progressBar) - spacerItem10 = QtWidgets.QSpacerItem(20, 16, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Fixed) - self.verticalLayout_Main.addItem(spacerItem10) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel) - self.buttonBox.setObjectName("buttonBox") - self.verticalLayout_Main.addWidget(self.buttonBox) - self.gridLayout.addLayout(self.verticalLayout_Main, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Scan for Pointers")) - self.label_Address.setText(_translate("Dialog", "Target Address:")) - self.label_Path.setText(_translate("Dialog", "Pointer Map File Path:")) - self.pushButton_Path.setText(_translate("Dialog", "Browse")) - self.checkBox_CheckAdvOptions.setText(_translate("Dialog", "Advanced Options")) - self.label_ScanScope.setText(_translate("Dialog", "Scan Scope:")) - self.label_Endian.setText(_translate("Dialog", "Endianness:")) - self.label_PointerSize.setText(_translate("Dialog", "Pointer Size:")) - self.label_Depth.setText(_translate("Dialog", "Max Depth:")) - self.label_MaxOffset.setText(_translate("Dialog", "Max Positive Offset:")) - self.spinBox_MaxOffset.setPrefix(_translate("Dialog", "0x")) - self.label_MinOffset.setText(_translate("Dialog", "Max Negative Offset:")) - self.spinBox_MinOffset.setPrefix(_translate("Dialog", "0x")) - self.checkBox_LastOffset.setText(_translate("Dialog", "Last Offset")) - self.spinBox_LastOffset.setPrefix(_translate("Dialog", "0x")) - self.checkBox_MaxResults.setText(_translate("Dialog", "Max Results")) - self.checkBox_Module.setText(_translate("Dialog", "Module Bases Only")) diff --git a/GUI/Widgets/PointerScanSearch/Form/PointerScanSearchDialog.ui b/GUI/Widgets/PointerScanSearch/Form/PointerScanSearchDialog.ui deleted file mode 100644 index 9ba20af4..00000000 --- a/GUI/Widgets/PointerScanSearch/Form/PointerScanSearchDialog.ui +++ /dev/null @@ -1,535 +0,0 @@ - - - Dialog - - - - 0 - 0 - 404 - 468 - - - - - 0 - 0 - - - - - 404 - 468 - - - - - 404 - 468 - - - - Scan for Pointers - - - - - - - - - - Target Address: - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Pointer Map File Path: - - - - - - - true - - - - - - false - - - true - - - false - - - - - - - true - - - Browse - - - - - - - - - - - Advanced Options - - - false - - - - - - - - - false - - - - 0 - 0 - - - - - - - - - Scan Scope: - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Endianness: - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - 0 - 0 - - - - Pointer Size: - - - - - - - false - - - 2 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Max Depth: - - - - - - - 1 - - - 5 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Max Positive Offset: - - - - - - - 0x - - - 999999999 - - - 4 - - - 2048 - - - 16 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Max Negative Offset: - - - - - - - 0x - - - 999999999 - - - 4 - - - 16 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Last Offset - - - false - - - - - - - 0x - - - 2048 - - - 4 - - - 16 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Max Results - - - false - - - - - - - - - - 1 - - - 999999999 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Module Bases Only - - - true - - - - - - - - - - - - Qt::Orientation::Vertical - - - QSizePolicy::Policy::Expanding - - - - 20 - 0 - - - - - - - - false - - - 0 - - - false - - - - - - - Qt::Orientation::Vertical - - - QSizePolicy::Policy::Fixed - - - - 20 - 16 - - - - - - - - Qt::Orientation::Horizontal - - - QDialogButtonBox::StandardButton::Cancel - - - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/GUI/Widgets/PointerScanSearch/PointerScanSearch.py b/GUI/Widgets/PointerScanSearch/PointerScanSearch.py deleted file mode 100644 index 99cd8f4e..00000000 --- a/GUI/Widgets/PointerScanSearch/PointerScanSearch.py +++ /dev/null @@ -1,158 +0,0 @@ -from PyQt6.QtCore import QTimer -from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QFileDialog, QPushButton, QMessageBox, QWidget -from GUI.Widgets.PointerScanSearch.Form.PointerScanSearchDialog import Ui_Dialog -from GUI.Utils import guiutils, guitypedefs -from libpince import debugcore, typedefs, utils -from libpince.libmemscan.memscan import Libmemscan, PointerEndianness, PointerScanOptions, ScanLevel -from tr.tr import TranslationConstants as tr -import os - - -class PointerScanSearchDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, address: str) -> None: - super().__init__(parent) - self.setupUi(self) - for endian, text in ( - (PointerEndianness.NATIVE, tr.HOST), - (PointerEndianness.LITTLE, tr.LITTLE), - (PointerEndianness.BIG, tr.BIG), - ): - self.comboBox_Endian.addItem(text, endian) - for width in (8, 4): - self.comboBox_PointerSize.addItem(f"{width} Bytes", width) - guiutils.fill_scope_combobox(self.comboBox_ScanScope) - effective_pointer_width = 4 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 8 - pointer_size_index = self.comboBox_PointerSize.findData(effective_pointer_width) - if pointer_size_index != -1: - self.comboBox_PointerSize.setCurrentIndex(pointer_size_index) - guiutils.center_to_parent(self) - self.lineEdit_Address.setText(address) - self.lineEdit_Path.setText(os.path.expanduser("~") + f"/{utils.get_process_name(debugcore.currentpid)}.lmptr") - self.pushButton_Path.clicked.connect(self.pushButton_Path_clicked) - self.checkBox_CheckAdvOptions.toggled.connect(self.checkBox_CheckAdvOptions_checked) - self.spinBox_LastOffset.setEnabled(self.checkBox_LastOffset.isChecked()) - self.checkBox_LastOffset.toggled.connect(self.spinBox_LastOffset.setEnabled) - self.spinBox_LastOffset.setRange(-self.spinBox_MinOffset.value(), self.spinBox_MaxOffset.value()) - self.spinBox_MinOffset.valueChanged.connect(lambda value: self.spinBox_LastOffset.setMinimum(-value)) - self.spinBox_MaxOffset.valueChanged.connect(self.spinBox_LastOffset.setMaximum) - self.spinBox_MaxResults.setEnabled(self.checkBox_MaxResults.isChecked()) - self.checkBox_MaxResults.toggled.connect(self.checkBox_MaxResults_checked) - self.scan_button: QPushButton | None = self.buttonBox.addButton(tr.SCAN, QDialogButtonBox.ButtonRole.ActionRole) - if self.scan_button: - self.scan_button.clicked.connect(self.scan_button_clicked) - self.cancel_button: QPushButton | None = self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel) - self.memscan_thread: guitypedefs.InterruptibleWorker | None = None - self.memscan: Libmemscan | None = None - self.progress_bar_timer: QTimer | None = None - self.started_path_resolve = False - self.result_map_path = "" - - def checkBox_CheckAdvOptions_checked(self, checked: bool) -> None: - self.verticalWidget_AdvOptions.setEnabled(checked) - - def checkBox_MaxResults_checked(self, checked: bool) -> None: - self.spinBox_MaxResults.setEnabled(checked) - - def pushButton_Path_clicked(self) -> None: - file_path, _ = QFileDialog.getSaveFileName(self, tr.SELECT_POINTER_MAP, os.path.expanduser("~"), tr.FILE_TYPES_POINTER_MAP) - if file_path != "": - file_path = utils.append_file_extension(file_path, "lmptr") - self.lineEdit_Path.setText(file_path) - - def reject(self) -> None: - if self.memscan_thread is None: - self.cleanup() - return super().reject() - if self.memscan is not None: - self.memscan.set_stop_flag(True) - if self.cancel_button: - self.cancel_button.setText(tr.STOPPING) - self.cancel_button.setEnabled(False) - - def cleanup(self) -> None: - if self.progress_bar_timer: - self.progress_bar_timer.stop() - self.progress_bar_timer = None - if self.memscan is not None: - self.memscan.close() - self.memscan = None - - def scan_button_clicked(self) -> None: - if debugcore.currentpid == -1 or self.scan_button == None or self.memscan_thread is not None: - return - addr_val = utils.safe_str_to_int(self.lineEdit_Address.text(), 16) - ptrmap_file_path = self.lineEdit_Path.text() - scan_level = ScanLevel.HEAP_STACK_EXE_BSS - if self.checkBox_CheckAdvOptions.isChecked(): - scan_level = self.comboBox_ScanScope.currentData() - ptr_opts = PointerScanOptions(pointer_width=self.comboBox_PointerSize.currentData()) - ptr_opts.endianness = self.comboBox_Endian.currentData() - ptr_opts.max_depth = self.spinBox_Depth.value() - ptr_opts.max_positive_offset = self.spinBox_MaxOffset.value() - ptr_opts.max_negative_offset = self.spinBox_MinOffset.value() - ptr_opts.last_offset = self.spinBox_LastOffset.value() if self.checkBox_LastOffset.isChecked() else None - ptr_opts.max_results = self.spinBox_MaxResults.value() if self.checkBox_MaxResults.isChecked() else None - ptr_opts.module_base_only = self.checkBox_Module.isChecked() - else: - ptr_opts = PointerScanOptions(pointer_width=4 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 8) - self.cleanup() - scanner = Libmemscan(os.path.join(utils.get_libpince_directory(), "libmemscan", "libmemscan.so")) - try: - scanner.set_scan_level(scan_level) - scanner.attach(debugcore.currentpid) - except Exception as error: - scanner.close() - QMessageBox.information(self, tr.ERROR, str(error)) - return - self.memscan = scanner - self.parent().default_scan_address = hex(addr_val) - self.scan_button.setText(tr.SCANNING) - self.scan_button.setEnabled(False) - self.pushButton_Path.setEnabled(False) - if self.cancel_button: - self.cancel_button.setText(tr.STOP) - self.memscan_thread = guitypedefs.InterruptibleWorker(self.memscan.pointer_scan, addr_val, ptrmap_file_path, ptr_opts) - self.memscan_thread.signals.finished.connect(self.memscan_callback) - self.memscan_thread.signals.error.connect(self.memscan_error) - self.memscan_thread.start() - self.started_path_resolve = False - self.progressBar.setValue(0) - self.progressBar.setFormat(f"{tr.SCANNING_POINTERS} - %p%") - self.progressBar.setVisible(True) - self.progress_bar_timer = QTimer(self, timeout=self.update_progress_bar) - self.progress_bar_timer.start(100) - - def update_progress_bar(self) -> None: - if self.memscan is None: - return - if self.started_path_resolve is False: - scan_progress = int(round(self.memscan.get_scan_progress() * 100)) - self.progressBar.setValue(scan_progress) - self.started_path_resolve = scan_progress == 100 - if self.started_path_resolve: - self.progressBar.setFormat(f"{tr.RESOLVING_POINTERS} - %p%") - else: - resolve_progress = int(round(self.memscan.get_pointer_resolve_progress() * 100)) - self.progressBar.setValue(resolve_progress) - - def memscan_callback(self, paths_found: int) -> None: - self.memscan_thread.wait() - self.memscan_thread = None - self.cleanup() - self.result_map_path = self.lineEdit_Path.text() - guiutils.own_path_as_user(self.result_map_path) - self.accept() - QMessageBox.information(self, tr.SUCCESS, tr.POINTER_SCAN_SUCCESS.format(paths_found)) - - def memscan_error(self, error: Exception) -> None: - self.memscan_thread.wait() - self.memscan_thread = None - self.cleanup() - if self.scan_button: - self.scan_button.setText(tr.SCAN) - self.scan_button.setEnabled(True) - self.pushButton_Path.setEnabled(True) - if self.cancel_button: - self.cancel_button.setText(tr.CANCEL) - self.cancel_button.setEnabled(True) - QMessageBox.information(self, tr.ERROR, str(error)) diff --git a/GUI/Widgets/ReferencedCalls/Form/ReferencedCallsWidget.py b/GUI/Widgets/ReferencedCalls/Form/ReferencedCallsWidget.py deleted file mode 100644 index 57d0e085..00000000 --- a/GUI/Widgets/ReferencedCalls/Form/ReferencedCallsWidget.py +++ /dev/null @@ -1,86 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/ReferencedCalls/Form/ReferencedCallsWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(1025, 530) - Form.setToolTip("") - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=Form) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter.setObjectName("splitter") - self.layoutWidget = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget.setObjectName("layoutWidget") - self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) - self.verticalLayout.setContentsMargins(0, 0, 0, 0) - self.verticalLayout.setObjectName("verticalLayout") - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.lineEdit_Regex = QtWidgets.QLineEdit(parent=self.layoutWidget) - self.lineEdit_Regex.setObjectName("lineEdit_Regex") - self.horizontalLayout_2.addWidget(self.lineEdit_Regex) - self.checkBox_CaseSensitive = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_CaseSensitive.setObjectName("checkBox_CaseSensitive") - self.horizontalLayout_2.addWidget(self.checkBox_CaseSensitive) - self.checkBox_Regex = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_Regex.setObjectName("checkBox_Regex") - self.horizontalLayout_2.addWidget(self.checkBox_Regex) - self.pushButton_Search = QtWidgets.QPushButton(parent=self.layoutWidget) - self.pushButton_Search.setObjectName("pushButton_Search") - self.horizontalLayout_2.addWidget(self.pushButton_Search) - self.verticalLayout.addLayout(self.horizontalLayout_2) - self.tableWidget_References = QtWidgets.QTableWidget(parent=self.layoutWidget) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_References.setFont(font) - self.tableWidget_References.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_References.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_References.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_References.setWordWrap(False) - self.tableWidget_References.setObjectName("tableWidget_References") - self.tableWidget_References.setColumnCount(2) - self.tableWidget_References.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_References.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_References.setHorizontalHeaderItem(1, item) - self.tableWidget_References.horizontalHeader().setStretchLastSection(True) - self.tableWidget_References.verticalHeader().setVisible(False) - self.tableWidget_References.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_References.verticalHeader().setMinimumSectionSize(16) - self.verticalLayout.addWidget(self.tableWidget_References) - self.listWidget_Referrers = QtWidgets.QListWidget(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.listWidget_Referrers.setFont(font) - self.listWidget_Referrers.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.listWidget_Referrers.setObjectName("listWidget_Referrers") - self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Referenced Calls")) - self.lineEdit_Regex.setPlaceholderText(_translate("Form", "Enter a string or a python regex")) - self.checkBox_CaseSensitive.setToolTip(_translate("Form", "Ignore case if checked")) - self.checkBox_CaseSensitive.setText(_translate("Form", "Case sensitive")) - self.checkBox_Regex.setToolTip(_translate("Form", "Your string will be treated as a regex if checked")) - self.checkBox_Regex.setText(_translate("Form", "Regex")) - self.pushButton_Search.setText(_translate("Form", "Search(Enter)")) - self.tableWidget_References.setSortingEnabled(True) - item = self.tableWidget_References.horizontalHeaderItem(0) - item.setText(_translate("Form", "Address")) - item = self.tableWidget_References.horizontalHeaderItem(1) - item.setText(_translate("Form", "Refcount")) diff --git a/GUI/Widgets/ReferencedCalls/Form/ReferencedCallsWidget.ui b/GUI/Widgets/ReferencedCalls/Form/ReferencedCallsWidget.ui deleted file mode 100644 index b629b72c..00000000 --- a/GUI/Widgets/ReferencedCalls/Form/ReferencedCallsWidget.ui +++ /dev/null @@ -1,129 +0,0 @@ - - - Form - - - - 0 - 0 - 1025 - 530 - - - - Referenced Calls - - - - - - - - - Qt::Horizontal - - - - - - - - - Enter a string or a python regex - - - - - - - Ignore case if checked - - - Case sensitive - - - - - - - Your string will be treated as a regex if checked - - - Regex - - - - - - - Search(Enter) - - - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - true - - - false - - - true - - - false - - - 16 - - - 16 - - - - Address - - - - - Refcount - - - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - - - - - - - diff --git a/GUI/Widgets/ReferencedCalls/ReferencedCalls.py b/GUI/Widgets/ReferencedCalls/ReferencedCalls.py deleted file mode 100644 index f2377255..00000000 --- a/GUI/Widgets/ReferencedCalls/ReferencedCalls.py +++ /dev/null @@ -1,133 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMenu, QMessageBox, QListWidgetItem, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QContextMenuEvent -from PyQt6.QtCore import Qt, QModelIndex -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.DissectCode.DissectCode import DissectCodeDialog -from GUI.Widgets.ReferencedCalls.Form.ReferencedCallsWidget import Ui_Form -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - -# represents the index of columns in referenced calls table -REF_CALL_ADDR_COL = 0 -REF_CALL_COUNT_COL = 1 - - -class ReferencedCallsWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.tableWidget_References.setColumnWidth(REF_CALL_ADDR_COL, 480) - self.splitter.setStretchFactor(0, 1) - self.listWidget_Referrers.resize(400, self.listWidget_Referrers.height()) - guiutils.center_to_parent(self) - self.hex_len = 16 if debugcore.inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 else 8 - str_dict, jmp_dict, call_dict = debugcore.get_dissect_code_data() - try: - str_dict_len, jmp_dict_len, call_dict_len = len(str_dict), len(jmp_dict), len(call_dict) - finally: - str_dict.close() - jmp_dict.close() - call_dict.close() - if str_dict_len == 0 and jmp_dict_len == 0 and call_dict_len == 0: - if utilwidgets.InputDialog(self, tr.DISSECT_CODE).exec(): - dissect_code_dialog = DissectCodeDialog(self) - dissect_code_dialog.scan_finished_signal.connect(dissect_code_dialog.accept) - dissect_code_dialog.exec() - self.refresh_table() - self.tableWidget_References.sortByColumn(REF_CALL_ADDR_COL, Qt.SortOrder.AscendingOrder) - self.tableWidget_References.selectionModel().currentChanged.connect(self.tableWidget_References_current_changed) - self.listWidget_Referrers.itemDoubleClicked.connect(self.listWidget_Referrers_item_double_clicked) - self.tableWidget_References.itemDoubleClicked.connect(self.tableWidget_References_item_double_clicked) - self.tableWidget_References.contextMenuEvent = self.tableWidget_References_context_menu_event - self.listWidget_Referrers.contextMenuEvent = self.listWidget_Referrers_context_menu_event - self.pushButton_Search.clicked.connect(self.refresh_table) - self.shortcut_search = QShortcut(QKeySequence("Return"), self) - self.shortcut_search.activated.connect(self.refresh_table) - - def pad_hex(self, hex_str: str) -> str: - index = hex_str.find(" ") - if index == -1: - self_len = 0 - else: - self_len = len(hex_str) - index - return "0x" + hex_str[2:].zfill(self.hex_len + self_len) - - def refresh_table(self) -> None: - item_list = debugcore.search_referenced_calls( - self.lineEdit_Regex.text(), self.checkBox_CaseSensitive.isChecked(), self.checkBox_Regex.isChecked() - ) - if item_list is None: - QMessageBox.information(self, tr.ERROR, tr.INVALID_REGEX) - return - self.tableWidget_References.setSortingEnabled(False) - self.tableWidget_References.setRowCount(0) - self.tableWidget_References.setRowCount(len(item_list)) - for row, item in enumerate(item_list): - self.tableWidget_References.setItem(row, REF_CALL_ADDR_COL, QTableWidgetItem(self.pad_hex(item[0]))) - table_widget_item = QTableWidgetItem() - table_widget_item.setData(Qt.ItemDataRole.EditRole, item[1]) - self.tableWidget_References.setItem(row, REF_CALL_COUNT_COL, table_widget_item) - self.tableWidget_References.setSortingEnabled(True) - - def tableWidget_References_current_changed(self, QModelIndex_current: QModelIndex) -> None: - if QModelIndex_current.row() < 0: - return - self.listWidget_Referrers.clear() - call_dict = debugcore.get_dissect_code_data(False, False, True)[0] - try: - addr = self.tableWidget_References.item(QModelIndex_current.row(), REF_CALL_ADDR_COL).text() - referrers = call_dict.get(hex(int(utils.extract_hex_address(addr), 16))) - if referrers is None: - return - addrs = [hex(address) for address in referrers] - self.listWidget_Referrers.addItems([self.pad_hex(item.all) for item in debugcore.examine_expressions(addrs) if item.all]) - self.listWidget_Referrers.sortItems(Qt.SortOrder.AscendingOrder) - finally: - call_dict.close() - - def tableWidget_References_item_double_clicked(self, index: QTableWidgetItem) -> None: - row = index.row() - address = self.tableWidget_References.item(row, REF_CALL_ADDR_COL).text() - self.parent().disassemble_expression(utils.extract_hex_address(address)) - - def listWidget_Referrers_item_double_clicked(self, item: QListWidgetItem) -> None: - self.parent().disassemble_expression(utils.extract_hex_address(item.text())) - - def tableWidget_References_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - QApplication.clipboard().setText(self.tableWidget_References.item(row, column).text()) - - selected_row = guiutils.get_current_row(self.tableWidget_References) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address]) - font_size = self.tableWidget_References.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {copy_address: lambda: copy_to_clipboard(selected_row, REF_CALL_ADDR_COL)} - try: - actions[action]() - except KeyError: - pass - - def listWidget_Referrers_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int) -> None: - QApplication.clipboard().setText(self.listWidget_Referrers.item(row).text()) - - selected_row = guiutils.get_current_row(self.listWidget_Referrers) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address]) - font_size = self.listWidget_Referrers.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {copy_address: lambda: copy_to_clipboard(selected_row)} - try: - actions[action]() - except KeyError: - pass diff --git a/GUI/Widgets/ReferencedStrings/Form/ReferencedStringsWidget.py b/GUI/Widgets/ReferencedStrings/Form/ReferencedStringsWidget.py deleted file mode 100644 index 6c9c36cb..00000000 --- a/GUI/Widgets/ReferencedStrings/Form/ReferencedStringsWidget.py +++ /dev/null @@ -1,100 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/ReferencedStrings/Form/ReferencedStringsWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(1025, 530) - Form.setToolTip("") - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=Form) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter.setObjectName("splitter") - self.layoutWidget = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget.setObjectName("layoutWidget") - self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) - self.verticalLayout.setContentsMargins(0, 0, 0, 0) - self.verticalLayout.setObjectName("verticalLayout") - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.lineEdit_Regex = QtWidgets.QLineEdit(parent=self.layoutWidget) - self.lineEdit_Regex.setObjectName("lineEdit_Regex") - self.horizontalLayout_2.addWidget(self.lineEdit_Regex) - self.checkBox_CaseSensitive = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_CaseSensitive.setObjectName("checkBox_CaseSensitive") - self.horizontalLayout_2.addWidget(self.checkBox_CaseSensitive) - self.checkBox_Regex = QtWidgets.QCheckBox(parent=self.layoutWidget) - self.checkBox_Regex.setObjectName("checkBox_Regex") - self.horizontalLayout_2.addWidget(self.checkBox_Regex) - self.pushButton_Search = QtWidgets.QPushButton(parent=self.layoutWidget) - self.pushButton_Search.setObjectName("pushButton_Search") - self.horizontalLayout_2.addWidget(self.pushButton_Search) - self.verticalLayout.addLayout(self.horizontalLayout_2) - self.tableWidget_References = QtWidgets.QTableWidget(parent=self.layoutWidget) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_References.setFont(font) - self.tableWidget_References.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_References.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_References.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_References.setWordWrap(False) - self.tableWidget_References.setObjectName("tableWidget_References") - self.tableWidget_References.setColumnCount(3) - self.tableWidget_References.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_References.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_References.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_References.setHorizontalHeaderItem(2, item) - self.tableWidget_References.horizontalHeader().setStretchLastSection(True) - self.tableWidget_References.verticalHeader().setVisible(False) - self.tableWidget_References.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_References.verticalHeader().setMinimumSectionSize(16) - self.verticalLayout.addWidget(self.tableWidget_References) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.comboBox_ValueType = QtWidgets.QComboBox(parent=self.layoutWidget) - self.comboBox_ValueType.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToContents) - self.comboBox_ValueType.setObjectName("comboBox_ValueType") - self.horizontalLayout.addWidget(self.comboBox_ValueType) - self.verticalLayout.addLayout(self.horizontalLayout) - self.listWidget_Referrers = QtWidgets.QListWidget(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.listWidget_Referrers.setFont(font) - self.listWidget_Referrers.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.listWidget_Referrers.setObjectName("listWidget_Referrers") - self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) - - self.retranslateUi(Form) - self.comboBox_ValueType.setCurrentIndex(-1) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Referenced Strings and Values")) - self.lineEdit_Regex.setPlaceholderText(_translate("Form", "Enter a string or a python regex")) - self.checkBox_CaseSensitive.setToolTip(_translate("Form", "Ignore case if checked")) - self.checkBox_CaseSensitive.setText(_translate("Form", "Case sensitive")) - self.checkBox_Regex.setToolTip(_translate("Form", "Your string will be treated as a regex if checked")) - self.checkBox_Regex.setText(_translate("Form", "Regex")) - self.pushButton_Search.setText(_translate("Form", "Search(Enter)")) - self.tableWidget_References.setSortingEnabled(True) - item = self.tableWidget_References.horizontalHeaderItem(0) - item.setText(_translate("Form", "Address")) - item = self.tableWidget_References.horizontalHeaderItem(1) - item.setText(_translate("Form", "Refcount")) - item = self.tableWidget_References.horizontalHeaderItem(2) - item.setText(_translate("Form", "Value")) diff --git a/GUI/Widgets/ReferencedStrings/Form/ReferencedStringsWidget.ui b/GUI/Widgets/ReferencedStrings/Form/ReferencedStringsWidget.ui deleted file mode 100644 index 3384c90d..00000000 --- a/GUI/Widgets/ReferencedStrings/Form/ReferencedStringsWidget.ui +++ /dev/null @@ -1,161 +0,0 @@ - - - Form - - - - 0 - 0 - 1025 - 530 - - - - Referenced Strings and Values - - - - - - - - - Qt::Horizontal - - - - - - - - - Enter a string or a python regex - - - - - - - Ignore case if checked - - - Case sensitive - - - - - - - Your string will be treated as a regex if checked - - - Regex - - - - - - - Search(Enter) - - - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - true - - - false - - - true - - - false - - - 16 - - - 16 - - - - Address - - - - - Refcount - - - - - Value - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - -1 - - - QComboBox::AdjustToContents - - - - - - - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - - - - - - - diff --git a/GUI/Widgets/ReferencedStrings/ReferencedStrings.py b/GUI/Widgets/ReferencedStrings/ReferencedStrings.py deleted file mode 100644 index fb78b489..00000000 --- a/GUI/Widgets/ReferencedStrings/ReferencedStrings.py +++ /dev/null @@ -1,151 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMenu, QMessageBox, QListWidgetItem, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QContextMenuEvent -from PyQt6.QtCore import Qt, QModelIndex -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.DissectCode.DissectCode import DissectCodeDialog -from GUI.Widgets.ReferencedStrings.Form.ReferencedStringsWidget import Ui_Form -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - -# represents the index of columns in referenced strings table -REF_STR_ADDR_COL = 0 -REF_STR_COUNT_COL = 1 -REF_STR_VAL_COL = 2 - - -class ReferencedStringsWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - guiutils.fill_value_combobox(self.comboBox_ValueType, typedefs.StringValueType("utf-8")) - self.setWindowFlags(Qt.WindowType.Window) - self.tableWidget_References.setColumnWidth(REF_STR_ADDR_COL, 150) - self.tableWidget_References.setColumnWidth(REF_STR_COUNT_COL, 80) - self.splitter.setStretchFactor(0, 1) - self.listWidget_Referrers.resize(400, self.listWidget_Referrers.height()) - guiutils.center_to_parent(self) - self.hex_len = 16 if debugcore.inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 else 8 - str_dict, jmp_dict, call_dict = debugcore.get_dissect_code_data() - try: - str_dict_len, jmp_dict_len, call_dict_len = len(str_dict), len(jmp_dict), len(call_dict) - finally: - str_dict.close() - jmp_dict.close() - call_dict.close() - if str_dict_len == 0 and jmp_dict_len == 0 and call_dict_len == 0: - if utilwidgets.InputDialog(self, tr.DISSECT_CODE).exec(): - dissect_code_dialog = DissectCodeDialog(self) - dissect_code_dialog.scan_finished_signal.connect(dissect_code_dialog.accept) - dissect_code_dialog.exec() - self.refresh_table() - self.tableWidget_References.sortByColumn(REF_STR_ADDR_COL, Qt.SortOrder.AscendingOrder) - self.tableWidget_References.selectionModel().currentChanged.connect(self.tableWidget_References_current_changed) - self.listWidget_Referrers.itemDoubleClicked.connect(self.listWidget_Referrers_item_double_clicked) - self.tableWidget_References.itemDoubleClicked.connect(self.tableWidget_References_item_double_clicked) - self.tableWidget_References.contextMenuEvent = self.tableWidget_References_context_menu_event - self.listWidget_Referrers.contextMenuEvent = self.listWidget_Referrers_context_menu_event - self.pushButton_Search.clicked.connect(self.refresh_table) - self.comboBox_ValueType.currentIndexChanged.connect(self.refresh_table) - self.shortcut_search = QShortcut(QKeySequence("Return"), self) - self.shortcut_search.activated.connect(self.refresh_table) - - def pad_hex(self, hex_str: str) -> str: - index = hex_str.find(" ") - if index == -1: - self_len = 0 - else: - self_len = len(hex_str) - index - return "0x" + hex_str[2:].zfill(self.hex_len + self_len) - - def refresh_table(self) -> None: - value_type = guiutils.configure_value_type( - self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole), - length=100, - ) - item_list = debugcore.search_referenced_strings( - self.lineEdit_Regex.text(), - value_type, - self.checkBox_CaseSensitive.isChecked(), - self.checkBox_Regex.isChecked(), - ) - if item_list is None: - QMessageBox.information(self, tr.ERROR, tr.INVALID_REGEX) - return - self.tableWidget_References.setSortingEnabled(False) - self.tableWidget_References.setRowCount(0) - self.tableWidget_References.setRowCount(len(item_list)) - for row, item in enumerate(item_list): - self.tableWidget_References.setItem(row, REF_STR_ADDR_COL, QTableWidgetItem(self.pad_hex(item[0]))) - table_widget_item = QTableWidgetItem() - table_widget_item.setData(Qt.ItemDataRole.EditRole, item[1]) - self.tableWidget_References.setItem(row, REF_STR_COUNT_COL, table_widget_item) - table_widget_item = QTableWidgetItem() - table_widget_item.setData(Qt.ItemDataRole.EditRole, item[2]) - self.tableWidget_References.setItem(row, REF_STR_VAL_COL, table_widget_item) - self.tableWidget_References.setSortingEnabled(True) - - def tableWidget_References_current_changed(self, QModelIndex_current: QModelIndex) -> None: - if QModelIndex_current.row() < 0: - return - self.listWidget_Referrers.clear() - str_dict = debugcore.get_dissect_code_data(True, False, False)[0] - try: - addr = self.tableWidget_References.item(QModelIndex_current.row(), REF_STR_ADDR_COL).text() - referrers = str_dict.get(hex(int(addr, 16))) - if referrers is None: - return - addrs = [hex(address) for address in referrers] - self.listWidget_Referrers.addItems([self.pad_hex(item.all) for item in debugcore.examine_expressions(addrs) if item.all]) - self.listWidget_Referrers.sortItems(Qt.SortOrder.AscendingOrder) - finally: - str_dict.close() - - def tableWidget_References_item_double_clicked(self, index: QTableWidgetItem) -> None: - row = index.row() - address = self.tableWidget_References.item(row, REF_STR_ADDR_COL).text() - self.parent().hex_dump_address(utils.safe_str_to_int(address, 16)) - - def listWidget_Referrers_item_double_clicked(self, item: QListWidgetItem) -> None: - self.parent().disassemble_expression(utils.extract_hex_address(item.text())) - - def tableWidget_References_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - QApplication.clipboard().setText(self.tableWidget_References.item(row, column).text()) - - selected_row = guiutils.get_current_row(self.tableWidget_References) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - copy_value = menu.addAction(tr.COPY_VALUE) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address, copy_value]) - font_size = self.tableWidget_References.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - copy_address: lambda: copy_to_clipboard(selected_row, REF_STR_ADDR_COL), - copy_value: lambda: copy_to_clipboard(selected_row, REF_STR_VAL_COL), - } - try: - actions[action]() - except KeyError: - pass - - def listWidget_Referrers_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int) -> None: - QApplication.clipboard().setText(self.listWidget_Referrers.item(row).text()) - - selected_row = guiutils.get_current_row(self.listWidget_Referrers) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address]) - font_size = self.listWidget_Referrers.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {copy_address: lambda: copy_to_clipboard(selected_row)} - try: - actions[action]() - except KeyError: - pass diff --git a/GUI/Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.py b/GUI/Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.py deleted file mode 100644 index dd3bafb0..00000000 --- a/GUI/Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.py +++ /dev/null @@ -1,53 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(429, 420) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.tableWidget_Instructions = QtWidgets.QTableWidget(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_Instructions.setFont(font) - self.tableWidget_Instructions.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Instructions.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_Instructions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Instructions.setWordWrap(False) - self.tableWidget_Instructions.setObjectName("tableWidget_Instructions") - self.tableWidget_Instructions.setColumnCount(3) - self.tableWidget_Instructions.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Instructions.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Instructions.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Instructions.setHorizontalHeaderItem(2, item) - self.tableWidget_Instructions.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Instructions.verticalHeader().setVisible(False) - self.tableWidget_Instructions.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Instructions.verticalHeader().setMinimumSectionSize(16) - self.gridLayout.addWidget(self.tableWidget_Instructions, 0, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Restore Instructions")) - self.tableWidget_Instructions.setSortingEnabled(True) - item = self.tableWidget_Instructions.horizontalHeaderItem(0) - item.setText(_translate("Form", "Address")) - item = self.tableWidget_Instructions.horizontalHeaderItem(1) - item.setText(_translate("Form", "Original Opcodes")) - item = self.tableWidget_Instructions.horizontalHeaderItem(2) - item.setText(_translate("Form", "Original Instruction")) diff --git a/GUI/Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.ui b/GUI/Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.ui deleted file mode 100644 index 03e5f193..00000000 --- a/GUI/Widgets/RestoreInstructions/Form/RestoreInstructionsWidget.ui +++ /dev/null @@ -1,72 +0,0 @@ - - - Form - - - - 0 - 0 - 429 - 420 - - - - Restore Instructions - - - - - - - Monospace - - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - QAbstractItemView::SelectionMode::SingleSelection - - - QAbstractItemView::SelectionBehavior::SelectRows - - - true - - - false - - - true - - - false - - - 16 - - - 16 - - - - Address - - - - - Original Opcodes - - - - - Original Instruction - - - - - - - - - diff --git a/GUI/Widgets/RestoreInstructions/RestoreInstructions.py b/GUI/Widgets/RestoreInstructions/RestoreInstructions.py deleted file mode 100644 index 56a008ac..00000000 --- a/GUI/Widgets/RestoreInstructions/RestoreInstructions.py +++ /dev/null @@ -1,73 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMenu -from PyQt6.QtCore import Qt, pyqtSignal -from PyQt6.QtGui import QContextMenuEvent -from GUI.States import states -from GUI.Utils import guiutils -from GUI.Widgets.RestoreInstructions.Form.RestoreInstructionsWidget import Ui_Form -from tr.tr import TranslationConstants as tr -from libpince import debugcore, utils - -ADDR_COL = 0 -AOB_COL = 1 -NAME_COL = 2 - - -class RestoreInstructionsWidget(QWidget, Ui_Form): - restored = pyqtSignal() - double_clicked = pyqtSignal(str) - - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - - self.tableWidget_Instructions.contextMenuEvent = self.tableWidget_Instructions_context_menu_event - self.tableWidget_Instructions.itemDoubleClicked.connect(self.tableWidget_Instructions_double_clicked) - self.refresh() - states.backend_signals.instructions_changed.connect(self.refresh) - guiutils.center_to_parent(self) - - def tableWidget_Instructions_context_menu_event(self, event: QContextMenuEvent) -> None: - selected_row = guiutils.get_current_row(self.tableWidget_Instructions) - menu = QMenu() - restore_instruction = menu.addAction(tr.RESTORE_INSTRUCTION) - if selected_row != -1: - selected_address_text = self.tableWidget_Instructions.item(selected_row, ADDR_COL).text() - selected_address = int(utils.extract_hex_address(selected_address_text), 16) - else: - guiutils.delete_menu_entries(menu, [restore_instruction]) - selected_address = None - menu.addSeparator() - font_size = self.tableWidget_Instructions.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = {restore_instruction: lambda: self.restore_instruction(selected_address)} - try: - actions[action]() - except KeyError: - pass - - def restore_instruction(self, selected_address: int) -> None: - debugcore.restore_instruction(selected_address) - self.refresh() - self.restored.emit() - - def refresh(self) -> None: - modified_instructions = debugcore.get_modified_instructions() - self.tableWidget_Instructions.setRowCount(len(modified_instructions)) - self.tableWidget_Instructions.setSortingEnabled(False) - for row, (address, aob) in enumerate(modified_instructions.items()): - self.tableWidget_Instructions.setItem(row, ADDR_COL, QTableWidgetItem(hex(address))) - self.tableWidget_Instructions.setItem(row, AOB_COL, QTableWidgetItem(aob)) - instr_name = utils.disassemble(aob, address, debugcore.inferior_arch) - if not instr_name: - instr_name = "??" - self.tableWidget_Instructions.setItem(row, NAME_COL, QTableWidgetItem(instr_name)) - self.tableWidget_Instructions.setSortingEnabled(True) - guiutils.resize_to_contents(self.tableWidget_Instructions) - self.repaint() - - def tableWidget_Instructions_double_clicked(self, index: QTableWidgetItem) -> None: - current_address_text = self.tableWidget_Instructions.item(index.row(), ADDR_COL).text() - current_address = utils.extract_hex_address(current_address_text) - self.double_clicked.emit(current_address) diff --git a/GUI/Widgets/SearchInstructions/Form/SearchInstructionsWidget.py b/GUI/Widgets/SearchInstructions/Form/SearchInstructionsWidget.py deleted file mode 100644 index b5045894..00000000 --- a/GUI/Widgets/SearchInstructions/Form/SearchInstructionsWidget.py +++ /dev/null @@ -1,95 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/SearchInstructions/Form/SearchInstructionsWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(631, 490) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.label_3 = QtWidgets.QLabel(parent=Form) - self.label_3.setObjectName("label_3") - self.horizontalLayout_2.addWidget(self.label_3) - self.lineEdit_Regex = QtWidgets.QLineEdit(parent=Form) - self.lineEdit_Regex.setObjectName("lineEdit_Regex") - self.horizontalLayout_2.addWidget(self.lineEdit_Regex) - self.checkBox_CaseSensitive = QtWidgets.QCheckBox(parent=Form) - self.checkBox_CaseSensitive.setObjectName("checkBox_CaseSensitive") - self.horizontalLayout_2.addWidget(self.checkBox_CaseSensitive) - self.checkBox_Regex = QtWidgets.QCheckBox(parent=Form) - self.checkBox_Regex.setObjectName("checkBox_Regex") - self.horizontalLayout_2.addWidget(self.checkBox_Regex) - self.pushButton_Search = QtWidgets.QPushButton(parent=Form) - self.pushButton_Search.setObjectName("pushButton_Search") - self.horizontalLayout_2.addWidget(self.pushButton_Search) - self.pushButton_Help = QtWidgets.QPushButton(parent=Form) - self.pushButton_Help.setText("") - self.pushButton_Help.setObjectName("pushButton_Help") - self.horizontalLayout_2.addWidget(self.pushButton_Help) - self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.label = QtWidgets.QLabel(parent=Form) - self.label.setObjectName("label") - self.horizontalLayout.addWidget(self.label) - self.lineEdit_Start = QtWidgets.QLineEdit(parent=Form) - self.lineEdit_Start.setObjectName("lineEdit_Start") - self.horizontalLayout.addWidget(self.lineEdit_Start) - self.label_2 = QtWidgets.QLabel(parent=Form) - self.label_2.setObjectName("label_2") - self.horizontalLayout.addWidget(self.label_2) - self.lineEdit_End = QtWidgets.QLineEdit(parent=Form) - self.lineEdit_End.setObjectName("lineEdit_End") - self.horizontalLayout.addWidget(self.lineEdit_End) - self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) - self.tableWidget_Instructions = QtWidgets.QTableWidget(parent=Form) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_Instructions.setFont(font) - self.tableWidget_Instructions.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Instructions.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_Instructions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Instructions.setWordWrap(False) - self.tableWidget_Instructions.setObjectName("tableWidget_Instructions") - self.tableWidget_Instructions.setColumnCount(2) - self.tableWidget_Instructions.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Instructions.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Instructions.setHorizontalHeaderItem(1, item) - self.tableWidget_Instructions.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Instructions.verticalHeader().setVisible(False) - self.tableWidget_Instructions.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Instructions.verticalHeader().setMinimumSectionSize(16) - self.gridLayout.addWidget(self.tableWidget_Instructions, 2, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Search for Instructions")) - self.label_3.setText(_translate("Form", "Search:")) - self.lineEdit_Regex.setPlaceholderText(_translate("Form", "Enter a string or a python regex")) - self.checkBox_CaseSensitive.setToolTip(_translate("Form", "Ignore case if checked")) - self.checkBox_CaseSensitive.setText(_translate("Form", "Case sensitive")) - self.checkBox_Regex.setToolTip(_translate("Form", "Your string will be treated as a regex if checked")) - self.checkBox_Regex.setText(_translate("Form", "Regex")) - self.pushButton_Search.setText(_translate("Form", "Search(Enter)")) - self.label.setText(_translate("Form", "Start")) - self.label_2.setText(_translate("Form", "End")) - self.tableWidget_Instructions.setSortingEnabled(True) - item = self.tableWidget_Instructions.horizontalHeaderItem(0) - item.setText(_translate("Form", "Address")) - item = self.tableWidget_Instructions.horizontalHeaderItem(1) - item.setText(_translate("Form", "Instruction")) diff --git a/GUI/Widgets/SearchInstructions/Form/SearchInstructionsWidget.ui b/GUI/Widgets/SearchInstructions/Form/SearchInstructionsWidget.ui deleted file mode 100644 index 22be4c46..00000000 --- a/GUI/Widgets/SearchInstructions/Form/SearchInstructionsWidget.ui +++ /dev/null @@ -1,143 +0,0 @@ - - - Form - - - - 0 - 0 - 631 - 490 - - - - Search for Instructions - - - - - - - - Search: - - - - - - - Enter a string or a python regex - - - - - - - Ignore case if checked - - - Case sensitive - - - - - - - Your string will be treated as a regex if checked - - - Regex - - - - - - - Search(Enter) - - - - - - - - - - - - - - - - - - Start - - - - - - - - - - End - - - - - - - - - - - - - Monospace - - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - QAbstractItemView::SelectionMode::SingleSelection - - - QAbstractItemView::SelectionBehavior::SelectRows - - - true - - - false - - - true - - - false - - - 16 - - - 16 - - - - Address - - - - - Instruction - - - - - - - - - diff --git a/GUI/Widgets/SearchInstructions/SearchInstructions.py b/GUI/Widgets/SearchInstructions/SearchInstructions.py deleted file mode 100644 index c0c8a8c5..00000000 --- a/GUI/Widgets/SearchInstructions/SearchInstructions.py +++ /dev/null @@ -1,95 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMenu, QMessageBox, QApplication -from PyQt6.QtGui import QShortcut, QKeySequence, QIcon, QPixmap, QContextMenuEvent -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.LoadingDialog.LoadingDialog import LoadingDialog -from GUI.Widgets.SearchInstructions.Form.SearchInstructionsWidget import Ui_Form -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr -import re - -# represents the index of columns in search instructions table -ADDR_COL = 0 -INSTR_COL = 1 - - -class SearchInstructionsWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget, start: str = "", end: str = "") -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.lineEdit_Start.setText(start) - self.lineEdit_End.setText(end) - self.tableWidget_Instructions.setColumnWidth(ADDR_COL, 250) - icons_directory = guiutils.get_icons_directory() - self.pushButton_Help.setIcon(QIcon(QPixmap(icons_directory + "/help.png"))) - self.pushButton_Help.clicked.connect(self.pushButton_Help_clicked) - self.pushButton_Search.clicked.connect(self.refresh_table) - self.shortcut_search = QShortcut(QKeySequence("Return"), self) - self.shortcut_search.activated.connect(self.refresh_table) - self.tableWidget_Instructions.itemDoubleClicked.connect(self.tableWidget_Instructions_item_double_clicked) - self.tableWidget_Instructions.contextMenuEvent = self.tableWidget_Instructions_context_menu_event - guiutils.center_to_parent(self) - - def refresh_table(self) -> None: - start_address = self.lineEdit_Start.text() - end_address = self.lineEdit_End.text() - regex = self.lineEdit_Regex.text() - case_sensitive = self.checkBox_CaseSensitive.isChecked() - enable_regex = self.checkBox_Regex.isChecked() - if enable_regex: - try: - re.compile(regex) if case_sensitive else re.compile(regex, re.IGNORECASE) - except re.error: - QMessageBox.information(self, tr.ERROR, tr.INVALID_REGEX) - return - self.loading_dialog = LoadingDialog(self) - self.background_thread = self.loading_dialog.background_thread - self.background_thread.overridden_func = lambda: self.process_data(regex, start_address, end_address, case_sensitive, enable_regex) - self.background_thread.output_ready.connect(self.apply_data) - self.loading_dialog.exec() - - def process_data(self, regex: str, start_address: str, end_address: str, case_sensitive: bool, enable_regex: bool) -> list | None: - return debugcore.search_instr(regex, start_address, end_address, case_sensitive, enable_regex) - - def apply_data(self, disas_data: list | None) -> None: - if disas_data is None: - return - self.tableWidget_Instructions.setSortingEnabled(False) - self.tableWidget_Instructions.setRowCount(0) - self.tableWidget_Instructions.setRowCount(len(disas_data)) - for row, item in enumerate(disas_data): - self.tableWidget_Instructions.setItem(row, ADDR_COL, QTableWidgetItem(item[0])) - self.tableWidget_Instructions.setItem(row, INSTR_COL, QTableWidgetItem(item[1])) - self.tableWidget_Instructions.setSortingEnabled(True) - - def pushButton_Help_clicked(self) -> None: - utilwidgets.InputDialog(self, tr.SEARCH_INSTR_HELPER, Qt.AlignmentFlag.AlignLeft, False).exec() - - def tableWidget_Instructions_item_double_clicked(self, index: QTableWidgetItem) -> None: - row = index.row() - address = self.tableWidget_Instructions.item(row, ADDR_COL).text() - self.parent().disassemble_expression(utils.extract_hex_address(address)) - - def tableWidget_Instructions_context_menu_event(self, event: QContextMenuEvent) -> None: - def copy_to_clipboard(row: int, column: int) -> None: - QApplication.clipboard().setText(self.tableWidget_Instructions.item(row, column).text()) - - selected_row = guiutils.get_current_row(self.tableWidget_Instructions) - - menu = QMenu() - copy_address = menu.addAction(tr.COPY_ADDRESS) - copy_instr = menu.addAction(tr.COPY_INSTR) - if selected_row == -1: - guiutils.delete_menu_entries(menu, [copy_address, copy_instr]) - font_size = self.tableWidget_Instructions.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - copy_address: lambda: copy_to_clipboard(selected_row, ADDR_COL), - copy_instr: lambda: copy_to_clipboard(selected_row, INSTR_COL), - } - try: - actions[action]() - except KeyError: - pass diff --git a/GUI/Widgets/SelectProcess/Form/SelectProcess.py b/GUI/Widgets/SelectProcess/Form/SelectProcess.py deleted file mode 100644 index 6571cd93..00000000 --- a/GUI/Widgets/SelectProcess/Form/SelectProcess.py +++ /dev/null @@ -1,100 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/SelectProcess/Form/SelectProcess.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.setWindowModality(QtCore.Qt.WindowModality.WindowModal) - MainWindow.resize(443, 420) - self.centralwidget = QtWidgets.QWidget(parent=MainWindow) - self.centralwidget.setObjectName("centralwidget") - self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget) - self.verticalLayout.setObjectName("verticalLayout") - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.label = QtWidgets.QLabel(parent=self.centralwidget) - self.label.setObjectName("label") - self.horizontalLayout.addWidget(self.label) - self.lineEdit_SearchProcess = QtWidgets.QLineEdit(parent=self.centralwidget) - self.lineEdit_SearchProcess.setObjectName("lineEdit_SearchProcess") - self.horizontalLayout.addWidget(self.lineEdit_SearchProcess) - self.verticalLayout.addLayout(self.horizontalLayout) - self.tableWidget_ProcessTable = QtWidgets.QTableWidget(parent=self.centralwidget) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.tableWidget_ProcessTable.sizePolicy().hasHeightForWidth()) - self.tableWidget_ProcessTable.setSizePolicy(sizePolicy) - self.tableWidget_ProcessTable.setAutoFillBackground(False) - self.tableWidget_ProcessTable.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.SizeAdjustPolicy.AdjustIgnored) - self.tableWidget_ProcessTable.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_ProcessTable.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_ProcessTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_ProcessTable.setWordWrap(False) - self.tableWidget_ProcessTable.setObjectName("tableWidget_ProcessTable") - self.tableWidget_ProcessTable.setColumnCount(3) - self.tableWidget_ProcessTable.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_ProcessTable.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_ProcessTable.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - item.setTextAlignment(QtCore.Qt.AlignmentFlag.AlignLeading|QtCore.Qt.AlignmentFlag.AlignVCenter) - self.tableWidget_ProcessTable.setHorizontalHeaderItem(2, item) - self.tableWidget_ProcessTable.horizontalHeader().setDefaultSectionSize(70) - self.tableWidget_ProcessTable.horizontalHeader().setStretchLastSection(True) - self.tableWidget_ProcessTable.verticalHeader().setVisible(False) - self.tableWidget_ProcessTable.verticalHeader().setStretchLastSection(False) - self.verticalLayout.addWidget(self.tableWidget_ProcessTable) - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_2.addItem(spacerItem) - self.pushButton_Open = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_Open.setObjectName("pushButton_Open") - self.horizontalLayout_2.addWidget(self.pushButton_Open) - self.pushButton_Close = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_Close.setObjectName("pushButton_Close") - self.horizontalLayout_2.addWidget(self.pushButton_Close) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_2.addItem(spacerItem1) - self.verticalLayout.addLayout(self.horizontalLayout_2) - self.horizontalLayout_3 = QtWidgets.QHBoxLayout() - self.horizontalLayout_3.setObjectName("horizontalLayout_3") - spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_3.addItem(spacerItem2) - self.pushButton_CreateProcess = QtWidgets.QPushButton(parent=self.centralwidget) - self.pushButton_CreateProcess.setObjectName("pushButton_CreateProcess") - self.horizontalLayout_3.addWidget(self.pushButton_CreateProcess) - spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_3.addItem(spacerItem3) - self.verticalLayout.addLayout(self.horizontalLayout_3) - MainWindow.setCentralWidget(self.centralwidget) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - _translate = QtCore.QCoreApplication.translate - MainWindow.setWindowTitle(_translate("MainWindow", "Please select a Process")) - self.label.setText(_translate("MainWindow", "Name or PID of the Process:")) - self.tableWidget_ProcessTable.setSortingEnabled(True) - item = self.tableWidget_ProcessTable.horizontalHeaderItem(0) - item.setText(_translate("MainWindow", "PID")) - item = self.tableWidget_ProcessTable.horizontalHeaderItem(1) - item.setText(_translate("MainWindow", "Username")) - item = self.tableWidget_ProcessTable.horizontalHeaderItem(2) - item.setText(_translate("MainWindow", "Process Name")) - self.pushButton_Open.setToolTip(_translate("MainWindow", "Attach to the selected process")) - self.pushButton_Open.setText(_translate("MainWindow", "Open")) - self.pushButton_Close.setText(_translate("MainWindow", "Cancel")) - self.pushButton_CreateProcess.setToolTip(_translate("MainWindow", "Open an executable")) - self.pushButton_CreateProcess.setText(_translate("MainWindow", "Create Process[F1]")) diff --git a/GUI/Widgets/SelectProcess/SelectProcess.py b/GUI/Widgets/SelectProcess/SelectProcess.py deleted file mode 100644 index c29f6825..00000000 --- a/GUI/Widgets/SelectProcess/SelectProcess.py +++ /dev/null @@ -1,80 +0,0 @@ -from PyQt6.QtWidgets import QMainWindow, QWidget, QTableWidget, QTableWidgetItem, QMessageBox, QFileDialog -from PyQt6.QtGui import QKeyEvent, QCursor -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.SelectProcess.Form.SelectProcess import Ui_MainWindow -from libpince import utils -from tr.tr import TranslationConstants as tr -import os - - -class SelectProcessWindow(QMainWindow, Ui_MainWindow): - def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self.setupUi(self) - self.refresh_process_table(self.tableWidget_ProcessTable, utils.get_process_list()) - self.pushButton_Close.clicked.connect(self.close) - self.pushButton_Open.clicked.connect(self.pushButton_Open_clicked) - self.pushButton_CreateProcess.clicked.connect(self.pushButton_CreateProcess_clicked) - self.lineEdit_SearchProcess.textChanged.connect(self.generate_new_list) - self.tableWidget_ProcessTable.itemDoubleClicked.connect(self.pushButton_Open_clicked) - guiutils.center_to_parent(self) - - # refreshes process list - def generate_new_list(self) -> None: - text = self.lineEdit_SearchProcess.text() - processlist = utils.search_processes(text) - self.refresh_process_table(self.tableWidget_ProcessTable, processlist) - - def keyPressEvent(self, event: QKeyEvent) -> None: - if event.key() == Qt.Key.Key_Escape: - self.close() - elif event.key() == Qt.Key.Key_Return or event.key() == Qt.Key.Key_Enter: - self.pushButton_Open_clicked() - elif event.key() == Qt.Key.Key_F1: - self.pushButton_CreateProcess_clicked() - else: - return super().keyPressEvent(event) - - # lists currently working processes to table - def refresh_process_table(self, tablewidget: QTableWidget, processlist: list[tuple[str, str, str]]) -> None: - tablewidget.setSortingEnabled(False) - tablewidget.setRowCount(0) - for pid, user, name in processlist: - current_row = tablewidget.rowCount() - tablewidget.insertRow(current_row) - tablewidget.setItem(current_row, 0, QTableWidgetItem(pid)) - tablewidget.setItem(current_row, 1, QTableWidgetItem(user)) - tablewidget.setItem(current_row, 2, QTableWidgetItem(name)) - tablewidget.setSortingEnabled(True) - - # gets the pid out of the selection to attach - def pushButton_Open_clicked(self) -> None: - index = self.tableWidget_ProcessTable.currentIndex() - row_count = self.tableWidget_ProcessTable.rowCount() - if index.row() == -1 and row_count == 1: - # autoselect first row if there is only one row - self.tableWidget_ProcessTable.setCurrentCell(0, 0) - - current_item = self.tableWidget_ProcessTable.item(self.tableWidget_ProcessTable.currentIndex().row(), 0) - if current_item is None: - QMessageBox.information(self, tr.ERROR, tr.SELECT_PROCESS) - else: - pid = int(current_item.text()) - self.setCursor(QCursor(Qt.CursorShape.WaitCursor)) - if self.parent().attach_to_pid(pid): - self.close() - self.setCursor(QCursor(Qt.CursorShape.ArrowCursor)) - - def pushButton_CreateProcess_clicked(self) -> None: - file_path, _ = QFileDialog.getOpenFileName(self, tr.SELECT_BINARY, os.path.expanduser("~")) - if file_path: - arg_dialog = utilwidgets.InputDialog(self, [(tr.ENTER_OPTIONAL_ARGS, ""), (tr.LD_PRELOAD_OPTIONAL, "")]) - if arg_dialog.exec(): - args, ld_preload_path = arg_dialog.get_values() - else: - return - self.setCursor(QCursor(Qt.CursorShape.WaitCursor)) - if self.parent().create_new_process(file_path, args, ld_preload_path): - self.close() - self.setCursor(QCursor(Qt.CursorShape.ArrowCursor)) diff --git a/GUI/Widgets/SessionNotes/Form/SessionNotes.py b/GUI/Widgets/SessionNotes/Form/SessionNotes.py deleted file mode 100644 index 891586e9..00000000 --- a/GUI/Widgets/SessionNotes/Form/SessionNotes.py +++ /dev/null @@ -1,33 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/SessionNotes/Form/SessionNotes.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_SessionNotes(object): - def setupUi(self, SessionNotes): - SessionNotes.setObjectName("SessionNotes") - SessionNotes.setWindowModality(QtCore.Qt.WindowModality.WindowModal) - SessionNotes.resize(259, 190) - self.gridLayout = QtWidgets.QGridLayout(SessionNotes) - self.gridLayout.setObjectName("gridLayout") - self.textEdit_Notes = QtWidgets.QTextEdit(parent=SessionNotes) - self.textEdit_Notes.setMinimumSize(QtCore.QSize(50, 50)) - self.textEdit_Notes.setObjectName("textEdit_Notes") - self.gridLayout.addWidget(self.textEdit_Notes, 1, 0, 1, 1) - self.label = QtWidgets.QLabel(parent=SessionNotes) - self.label.setObjectName("label") - self.gridLayout.addWidget(self.label, 0, 0, 1, 1) - - self.retranslateUi(SessionNotes) - QtCore.QMetaObject.connectSlotsByName(SessionNotes) - - def retranslateUi(self, SessionNotes): - _translate = QtCore.QCoreApplication.translate - SessionNotes.setWindowTitle(_translate("SessionNotes", "Notes")) - self.label.setText(_translate("SessionNotes", "Session Notes")) diff --git a/GUI/Widgets/SessionNotes/Form/SessionNotes.ui b/GUI/Widgets/SessionNotes/Form/SessionNotes.ui deleted file mode 100644 index 63483b32..00000000 --- a/GUI/Widgets/SessionNotes/Form/SessionNotes.ui +++ /dev/null @@ -1,41 +0,0 @@ - - - SessionNotes - - - Qt::WindowModality::WindowModal - - - - 0 - 0 - 259 - 190 - - - - Notes - - - - - - - 50 - 50 - - - - - - - - Session Notes - - - - - - - - diff --git a/GUI/Widgets/SessionNotes/SessionNotes.py b/GUI/Widgets/SessionNotes/SessionNotes.py deleted file mode 100644 index 8ce9cad3..00000000 --- a/GUI/Widgets/SessionNotes/SessionNotes.py +++ /dev/null @@ -1,28 +0,0 @@ -from GUI.Widgets.SessionNotes.Form.SessionNotes import Ui_SessionNotes -from GUI.Session.session import SessionManager, SessionDataChanged -from PyQt6.QtWidgets import QWidget -from GUI.States import states - - -class SessionNotesWidget(QWidget, Ui_SessionNotes): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.textEdit_Notes.textChanged.connect(self.on_textEdit_notes_textChanged) - states.session_signals.on_load.connect(self.on_load) - states.session_signals.new_session.connect(self.on_new_session) - self.session = SessionManager.get_session() - - def on_new_session(self) -> None: - self.textEdit_Notes.clear() - self.session = SessionManager.get_session() - - def on_load(self) -> None: - self.textEdit_Notes.setText(SessionManager.session.pct_notes) - - def on_textEdit_notes_textChanged(self) -> None: - SessionManager.session.pct_notes = self.textEdit_Notes.toPlainText() - SessionManager.session.data_changed |= SessionDataChanged.NOTES - - def toggle_visibility(self) -> None: - self.setVisible(not self.isVisible()) diff --git a/GUI/Widgets/Settings/Form/SettingsDialog.py b/GUI/Widgets/Settings/Form/SettingsDialog.py deleted file mode 100644 index 11741cee..00000000 --- a/GUI/Widgets/Settings/Form/SettingsDialog.py +++ /dev/null @@ -1,399 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/Settings/Form/SettingsDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(884, 633) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.horizontalLayout_2 = QtWidgets.QHBoxLayout() - self.horizontalLayout_2.setObjectName("horizontalLayout_2") - self.listWidget_Options = QtWidgets.QListWidget(parent=Dialog) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Expanding) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.listWidget_Options.sizePolicy().hasHeightForWidth()) - self.listWidget_Options.setSizePolicy(sizePolicy) - self.listWidget_Options.setMaximumSize(QtCore.QSize(130, 16777215)) - self.listWidget_Options.setObjectName("listWidget_Options") - item = QtWidgets.QListWidgetItem() - self.listWidget_Options.addItem(item) - item = QtWidgets.QListWidgetItem() - self.listWidget_Options.addItem(item) - item = QtWidgets.QListWidgetItem() - self.listWidget_Options.addItem(item) - item = QtWidgets.QListWidgetItem() - self.listWidget_Options.addItem(item) - item = QtWidgets.QListWidgetItem() - self.listWidget_Options.addItem(item) - self.horizontalLayout_2.addWidget(self.listWidget_Options) - self.stackedWidget = QtWidgets.QStackedWidget(parent=Dialog) - self.stackedWidget.setMinimumSize(QtCore.QSize(500, 500)) - self.stackedWidget.setObjectName("stackedWidget") - self.page_General = QtWidgets.QWidget() - self.page_General.setObjectName("page_General") - self.gridLayout_2 = QtWidgets.QGridLayout(self.page_General) - self.gridLayout_2.setObjectName("gridLayout_2") - self.verticalLayout_5 = QtWidgets.QVBoxLayout() - self.verticalLayout_5.setObjectName("verticalLayout_5") - self.horizontalLayout_7 = QtWidgets.QHBoxLayout() - self.horizontalLayout_7.setObjectName("horizontalLayout_7") - self.verticalLayout_3 = QtWidgets.QVBoxLayout() - self.verticalLayout_3.setObjectName("verticalLayout_3") - self.verticalLayout_2 = QtWidgets.QVBoxLayout() - self.verticalLayout_2.setObjectName("verticalLayout_2") - self.checkBox_AutoUpdateAddressTable = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_AutoUpdateAddressTable.setObjectName("checkBox_AutoUpdateAddressTable") - self.verticalLayout_2.addWidget(self.checkBox_AutoUpdateAddressTable) - self.checkBox_CheckUpdatesOnStartup = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_CheckUpdatesOnStartup.setObjectName("checkBox_CheckUpdatesOnStartup") - self.verticalLayout_2.addWidget(self.checkBox_CheckUpdatesOnStartup) - self.verticalLayout_3.addLayout(self.verticalLayout_2) - self.QWidget_UpdateInterval = QtWidgets.QWidget(parent=self.page_General) - self.QWidget_UpdateInterval.setObjectName("QWidget_UpdateInterval") - self.horizontalLayout_UpdateInterval = QtWidgets.QHBoxLayout(self.QWidget_UpdateInterval) - self.horizontalLayout_UpdateInterval.setContentsMargins(-1, 0, -1, -1) - self.horizontalLayout_UpdateInterval.setObjectName("horizontalLayout_UpdateInterval") - self.label = QtWidgets.QLabel(parent=self.QWidget_UpdateInterval) - self.label.setMinimumSize(QtCore.QSize(102, 0)) - self.label.setObjectName("label") - self.horizontalLayout_UpdateInterval.addWidget(self.label) - self.spinBox_UpdateInterval = QtWidgets.QSpinBox(parent=self.QWidget_UpdateInterval) - self.spinBox_UpdateInterval.setMinimum(100) - self.spinBox_UpdateInterval.setMaximum(10000) - self.spinBox_UpdateInterval.setSingleStep(100) - self.spinBox_UpdateInterval.setObjectName("spinBox_UpdateInterval") - self.horizontalLayout_UpdateInterval.addWidget(self.spinBox_UpdateInterval) - self.label_2 = QtWidgets.QLabel(parent=self.QWidget_UpdateInterval) - self.label_2.setText("ms") - self.label_2.setObjectName("label_2") - self.horizontalLayout_UpdateInterval.addWidget(self.label_2) - self.verticalLayout_3.addWidget(self.QWidget_UpdateInterval) - self.LockInterval = QtWidgets.QWidget(parent=self.page_General) - self.LockInterval.setObjectName("LockInterval") - self.horizontalLayout_14 = QtWidgets.QHBoxLayout(self.LockInterval) - self.horizontalLayout_14.setContentsMargins(-1, 0, -1, -1) - self.horizontalLayout_14.setObjectName("horizontalLayout_14") - self.label_12 = QtWidgets.QLabel(parent=self.LockInterval) - sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred) - sizePolicy.setHorizontalStretch(0) - sizePolicy.setVerticalStretch(0) - sizePolicy.setHeightForWidth(self.label_12.sizePolicy().hasHeightForWidth()) - self.label_12.setSizePolicy(sizePolicy) - self.label_12.setMinimumSize(QtCore.QSize(102, 0)) - self.label_12.setBaseSize(QtCore.QSize(0, 0)) - self.label_12.setObjectName("label_12") - self.horizontalLayout_14.addWidget(self.label_12) - self.spinBox_FreezeInterval = QtWidgets.QSpinBox(parent=self.LockInterval) - self.spinBox_FreezeInterval.setMinimum(100) - self.spinBox_FreezeInterval.setMaximum(10000) - self.spinBox_FreezeInterval.setSingleStep(100) - self.spinBox_FreezeInterval.setObjectName("spinBox_FreezeInterval") - self.horizontalLayout_14.addWidget(self.spinBox_FreezeInterval) - self.label_10 = QtWidgets.QLabel(parent=self.LockInterval) - self.label_10.setText("ms") - self.label_10.setObjectName("label_10") - self.horizontalLayout_14.addWidget(self.label_10) - self.verticalLayout_3.addWidget(self.LockInterval) - self.horizontalLayout_7.addLayout(self.verticalLayout_3) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_7.addItem(spacerItem) - self.verticalLayout_5.addLayout(self.horizontalLayout_7) - self.horizontalLayout_3 = QtWidgets.QHBoxLayout() - self.horizontalLayout_3.setObjectName("horizontalLayout_3") - self.label_8 = QtWidgets.QLabel(parent=self.page_General) - self.label_8.setObjectName("label_8") - self.horizontalLayout_3.addWidget(self.label_8) - self.checkBox_OutputModeAsync = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_OutputModeAsync.setObjectName("checkBox_OutputModeAsync") - self.horizontalLayout_3.addWidget(self.checkBox_OutputModeAsync) - self.checkBox_OutputModeCommand = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_OutputModeCommand.setObjectName("checkBox_OutputModeCommand") - self.horizontalLayout_3.addWidget(self.checkBox_OutputModeCommand) - self.checkBox_OutputModeCommandInfo = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_OutputModeCommandInfo.setObjectName("checkBox_OutputModeCommandInfo") - self.horizontalLayout_3.addWidget(self.checkBox_OutputModeCommandInfo) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_3.addItem(spacerItem1) - self.verticalLayout_5.addLayout(self.horizontalLayout_3) - self.horizontalLayout_12 = QtWidgets.QHBoxLayout() - self.horizontalLayout_12.setObjectName("horizontalLayout_12") - self.label_9 = QtWidgets.QLabel(parent=self.page_General) - self.label_9.setObjectName("label_9") - self.horizontalLayout_12.addWidget(self.label_9) - self.lineEdit_AutoAttach = QtWidgets.QLineEdit(parent=self.page_General) - self.lineEdit_AutoAttach.setObjectName("lineEdit_AutoAttach") - self.horizontalLayout_12.addWidget(self.lineEdit_AutoAttach) - self.checkBox_AutoAttachRegex = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_AutoAttachRegex.setObjectName("checkBox_AutoAttachRegex") - self.horizontalLayout_12.addWidget(self.checkBox_AutoAttachRegex) - self.verticalLayout_5.addLayout(self.horizontalLayout_12) - self.horizontalLayout_13 = QtWidgets.QHBoxLayout() - self.horizontalLayout_13.setObjectName("horizontalLayout_13") - self.label_13 = QtWidgets.QLabel(parent=self.page_General) - self.label_13.setObjectName("label_13") - self.horizontalLayout_13.addWidget(self.label_13) - self.comboBox_Language = QtWidgets.QComboBox(parent=self.page_General) - self.comboBox_Language.setObjectName("comboBox_Language") - self.horizontalLayout_13.addWidget(self.comboBox_Language) - spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_13.addItem(spacerItem2) - self.verticalLayout_5.addLayout(self.horizontalLayout_13) - self.horizontalLayout_15 = QtWidgets.QHBoxLayout() - self.horizontalLayout_15.setObjectName("horizontalLayout_15") - self.label_11 = QtWidgets.QLabel(parent=self.page_General) - self.label_11.setObjectName("label_11") - self.horizontalLayout_15.addWidget(self.label_11) - self.comboBox_Logo = QtWidgets.QComboBox(parent=self.page_General) - self.comboBox_Logo.setObjectName("comboBox_Logo") - self.horizontalLayout_15.addWidget(self.comboBox_Logo) - spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_15.addItem(spacerItem3) - self.verticalLayout_5.addLayout(self.horizontalLayout_15) - self.horizontalLayout_17 = QtWidgets.QHBoxLayout() - self.horizontalLayout_17.setObjectName("horizontalLayout_17") - self.label_14 = QtWidgets.QLabel(parent=self.page_General) - self.label_14.setObjectName("label_14") - self.horizontalLayout_17.addWidget(self.label_14) - self.comboBox_Theme = QtWidgets.QComboBox(parent=self.page_General) - self.comboBox_Theme.setObjectName("comboBox_Theme") - self.horizontalLayout_17.addWidget(self.comboBox_Theme) - spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_17.addItem(spacerItem4) - self.verticalLayout_5.addLayout(self.horizontalLayout_17) - self.horizontalLayout_23 = QtWidgets.QHBoxLayout() - self.horizontalLayout_23.setContentsMargins(-1, -1, -1, 0) - self.horizontalLayout_23.setObjectName("horizontalLayout_23") - self.label_5 = QtWidgets.QLabel(parent=self.page_General) - self.label_5.setObjectName("label_5") - self.horizontalLayout_23.addWidget(self.label_5) - self.comboBox_SaveSessionOnExit = QtWidgets.QComboBox(parent=self.page_General) - self.comboBox_SaveSessionOnExit.setObjectName("comboBox_SaveSessionOnExit") - self.horizontalLayout_23.addWidget(self.comboBox_SaveSessionOnExit) - spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_23.addItem(spacerItem5) - self.verticalLayout_5.addLayout(self.horizontalLayout_23) - self.checkBox_RememberLastPctDirectory = QtWidgets.QCheckBox(parent=self.page_General) - self.checkBox_RememberLastPctDirectory.setObjectName("checkBox_RememberLastPctDirectory") - self.verticalLayout_5.addWidget(self.checkBox_RememberLastPctDirectory) - spacerItem6 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_5.addItem(spacerItem6) - self.gridLayout_2.addLayout(self.verticalLayout_5, 0, 0, 1, 1) - self.stackedWidget.addWidget(self.page_General) - self.page_Hotkeys = QtWidgets.QWidget() - self.page_Hotkeys.setObjectName("page_Hotkeys") - self.gridLayout_3 = QtWidgets.QGridLayout(self.page_Hotkeys) - self.gridLayout_3.setObjectName("gridLayout_3") - self.horizontalLayout_5 = QtWidgets.QHBoxLayout() - self.horizontalLayout_5.setObjectName("horizontalLayout_5") - self.verticalLayout_4 = QtWidgets.QVBoxLayout() - self.verticalLayout_4.setObjectName("verticalLayout_4") - self.label_3 = QtWidgets.QLabel(parent=self.page_Hotkeys) - self.label_3.setObjectName("label_3") - self.verticalLayout_4.addWidget(self.label_3) - self.listWidget_Functions = QtWidgets.QListWidget(parent=self.page_Hotkeys) - self.listWidget_Functions.setObjectName("listWidget_Functions") - self.verticalLayout_4.addWidget(self.listWidget_Functions) - self.horizontalLayout_5.addLayout(self.verticalLayout_4) - self.verticalLayout_6 = QtWidgets.QVBoxLayout() - self.verticalLayout_6.setObjectName("verticalLayout_6") - self.verticalLayout_Hotkey = QtWidgets.QVBoxLayout() - self.verticalLayout_Hotkey.setObjectName("verticalLayout_Hotkey") - self.label_4 = QtWidgets.QLabel(parent=self.page_Hotkeys) - self.label_4.setObjectName("label_4") - self.verticalLayout_Hotkey.addWidget(self.label_4) - self.lineEdit_Hotkey = QtWidgets.QLineEdit(parent=self.page_Hotkeys) - self.lineEdit_Hotkey.setReadOnly(True) - self.lineEdit_Hotkey.setObjectName("lineEdit_Hotkey") - self.verticalLayout_Hotkey.addWidget(self.lineEdit_Hotkey) - self.verticalLayout_6.addLayout(self.verticalLayout_Hotkey) - self.horizontalLayout_4 = QtWidgets.QHBoxLayout() - self.horizontalLayout_4.setObjectName("horizontalLayout_4") - spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_4.addItem(spacerItem7) - self.pushButton_ClearHotkey = QtWidgets.QPushButton(parent=self.page_Hotkeys) - self.pushButton_ClearHotkey.setObjectName("pushButton_ClearHotkey") - self.horizontalLayout_4.addWidget(self.pushButton_ClearHotkey) - self.verticalLayout_6.addLayout(self.horizontalLayout_4) - spacerItem8 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_6.addItem(spacerItem8) - self.horizontalLayout_5.addLayout(self.verticalLayout_6) - self.gridLayout_3.addLayout(self.horizontalLayout_5, 0, 0, 1, 1) - self.stackedWidget.addWidget(self.page_Hotkeys) - self.page_MemoryView = QtWidgets.QWidget() - self.page_MemoryView.setObjectName("page_MemoryView") - self.gridLayout_5 = QtWidgets.QGridLayout(self.page_MemoryView) - self.gridLayout_5.setObjectName("gridLayout_5") - self.verticalLayout_10 = QtWidgets.QVBoxLayout() - self.verticalLayout_10.setObjectName("verticalLayout_10") - self.checkBox_ShowMemoryViewOnStop = QtWidgets.QCheckBox(parent=self.page_MemoryView) - self.checkBox_ShowMemoryViewOnStop.setObjectName("checkBox_ShowMemoryViewOnStop") - self.verticalLayout_10.addWidget(self.checkBox_ShowMemoryViewOnStop) - self.horizontalLayout_10 = QtWidgets.QHBoxLayout() - self.horizontalLayout_10.setObjectName("horizontalLayout_10") - self.label_6 = QtWidgets.QLabel(parent=self.page_MemoryView) - self.label_6.setObjectName("label_6") - self.horizontalLayout_10.addWidget(self.label_6) - self.spinBox_InstructionsPerScroll = QtWidgets.QSpinBox(parent=self.page_MemoryView) - self.spinBox_InstructionsPerScroll.setObjectName("spinBox_InstructionsPerScroll") - self.horizontalLayout_10.addWidget(self.spinBox_InstructionsPerScroll) - spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_10.addItem(spacerItem9) - self.verticalLayout_10.addLayout(self.horizontalLayout_10) - self.horizontalLayout_19 = QtWidgets.QHBoxLayout() - self.horizontalLayout_19.setObjectName("horizontalLayout_19") - self.label_16 = QtWidgets.QLabel(parent=self.page_MemoryView) - self.label_16.setObjectName("label_16") - self.horizontalLayout_19.addWidget(self.label_16) - self.spinBox_BytesPerScroll = QtWidgets.QSpinBox(parent=self.page_MemoryView) - self.spinBox_BytesPerScroll.setPrefix("0x") - self.spinBox_BytesPerScroll.setMaximum(4096) - self.spinBox_BytesPerScroll.setSingleStep(16) - self.spinBox_BytesPerScroll.setDisplayIntegerBase(16) - self.spinBox_BytesPerScroll.setObjectName("spinBox_BytesPerScroll") - self.horizontalLayout_19.addWidget(self.spinBox_BytesPerScroll) - spacerItem10 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_19.addItem(spacerItem10) - self.verticalLayout_10.addLayout(self.horizontalLayout_19) - spacerItem11 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_10.addItem(spacerItem11) - self.gridLayout_5.addLayout(self.verticalLayout_10, 0, 0, 1, 1) - self.stackedWidget.addWidget(self.page_MemoryView) - self.page_Debug = QtWidgets.QWidget() - self.page_Debug.setObjectName("page_Debug") - self.gridLayout_6 = QtWidgets.QGridLayout(self.page_Debug) - self.gridLayout_6.setObjectName("gridLayout_6") - self.verticalLayout_11 = QtWidgets.QVBoxLayout() - self.verticalLayout_11.setObjectName("verticalLayout_11") - self.horizontalLayout_11 = QtWidgets.QHBoxLayout() - self.horizontalLayout_11.setObjectName("horizontalLayout_11") - self.horizontalLayout_101 = QtWidgets.QHBoxLayout() - self.horizontalLayout_101.setObjectName("horizontalLayout_101") - self.label_GDBPath = QtWidgets.QLabel(parent=self.page_Debug) - self.label_GDBPath.setObjectName("label_GDBPath") - self.horizontalLayout_101.addWidget(self.label_GDBPath) - self.lineEdit_GDBPath = QtWidgets.QLineEdit(parent=self.page_Debug) - self.lineEdit_GDBPath.setObjectName("lineEdit_GDBPath") - self.horizontalLayout_101.addWidget(self.lineEdit_GDBPath) - self.horizontalLayout_11.addLayout(self.horizontalLayout_101) - self.pushButton_GDBPath = QtWidgets.QPushButton(parent=self.page_Debug) - self.pushButton_GDBPath.setObjectName("pushButton_GDBPath") - self.horizontalLayout_11.addWidget(self.pushButton_GDBPath) - self.verticalLayout_11.addLayout(self.horizontalLayout_11) - self.checkBox_GDBLogging = QtWidgets.QCheckBox(parent=self.page_Debug) - self.checkBox_GDBLogging.setObjectName("checkBox_GDBLogging") - self.verticalLayout_11.addWidget(self.checkBox_GDBLogging) - self.horizontalLayout_18 = QtWidgets.QHBoxLayout() - self.horizontalLayout_18.setObjectName("horizontalLayout_18") - self.label_15 = QtWidgets.QLabel(parent=self.page_Debug) - self.label_15.setObjectName("label_15") - self.horizontalLayout_18.addWidget(self.label_15) - self.comboBox_InterruptSignal = QtWidgets.QComboBox(parent=self.page_Debug) - self.comboBox_InterruptSignal.setObjectName("comboBox_InterruptSignal") - self.horizontalLayout_18.addWidget(self.comboBox_InterruptSignal) - spacerItem12 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_18.addItem(spacerItem12) - self.verticalLayout_11.addLayout(self.horizontalLayout_18) - self.horizontalLayout_16 = QtWidgets.QHBoxLayout() - self.horizontalLayout_16.setObjectName("horizontalLayout_16") - self.pushButton_HandleSignals = QtWidgets.QPushButton(parent=self.page_Debug) - self.pushButton_HandleSignals.setObjectName("pushButton_HandleSignals") - self.horizontalLayout_16.addWidget(self.pushButton_HandleSignals) - spacerItem13 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout_16.addItem(spacerItem13) - self.verticalLayout_11.addLayout(self.horizontalLayout_16) - spacerItem14 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.verticalLayout_11.addItem(spacerItem14) - self.gridLayout_6.addLayout(self.verticalLayout_11, 0, 0, 1, 1) - self.stackedWidget.addWidget(self.page_Debug) - self.page_Java = QtWidgets.QWidget() - self.page_Java.setObjectName("page_Java") - self.gridLayout_7 = QtWidgets.QGridLayout(self.page_Java) - self.gridLayout_7.setObjectName("gridLayout_7") - self.checkBox_JavaSegfault = QtWidgets.QCheckBox(parent=self.page_Java) - self.checkBox_JavaSegfault.setObjectName("checkBox_JavaSegfault") - self.gridLayout_7.addWidget(self.checkBox_JavaSegfault, 0, 0, 1, 1) - spacerItem15 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Expanding) - self.gridLayout_7.addItem(spacerItem15, 1, 0, 1, 1) - self.stackedWidget.addWidget(self.page_Java) - self.horizontalLayout_2.addWidget(self.stackedWidget) - self.verticalLayout.addLayout(self.horizontalLayout_2) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.pushButton_ResetSettings = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_ResetSettings.setObjectName("pushButton_ResetSettings") - self.horizontalLayout.addWidget(self.pushButton_ResetSettings) - spacerItem16 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem16) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.horizontalLayout.addWidget(self.buttonBox) - self.verticalLayout.addLayout(self.horizontalLayout) - self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - self.stackedWidget.setCurrentIndex(0) - self.listWidget_Functions.setCurrentRow(-1) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Settings")) - __sortingEnabled = self.listWidget_Options.isSortingEnabled() - self.listWidget_Options.setSortingEnabled(False) - item = self.listWidget_Options.item(0) - item.setText(_translate("Dialog", "General")) - item = self.listWidget_Options.item(1) - item.setText(_translate("Dialog", "Hotkeys")) - item = self.listWidget_Options.item(2) - item.setText(_translate("Dialog", "Memory View")) - item = self.listWidget_Options.item(3) - item.setText(_translate("Dialog", "Debug")) - item = self.listWidget_Options.item(4) - item.setText(_translate("Dialog", "Java")) - self.listWidget_Options.setSortingEnabled(__sortingEnabled) - self.checkBox_AutoUpdateAddressTable.setText(_translate("Dialog", "Auto-update address table")) - self.checkBox_CheckUpdatesOnStartup.setText(_translate("Dialog", "Check for AppImage updates on startup")) - self.label.setText(_translate("Dialog", "Update Interval")) - self.label_12.setText(_translate("Dialog", "Freeze Interval")) - self.label_8.setText(_translate("Dialog", "GDB output:")) - self.checkBox_OutputModeAsync.setText(_translate("Dialog", "Async")) - self.checkBox_OutputModeCommand.setText(_translate("Dialog", "Command")) - self.checkBox_OutputModeCommandInfo.setText(_translate("Dialog", "Command info")) - self.label_9.setToolTip(_translate("Dialog", "On start, automatically attach to processes with name matching one of the entries\n" -"Patterns at former positions have higher priority if regex is off")) - self.label_9.setText(_translate("Dialog", "Auto-attach to processes named")) - self.checkBox_AutoAttachRegex.setText(_translate("Dialog", "Regex")) - self.label_13.setText(_translate("Dialog", "Language")) - self.label_11.setText(_translate("Dialog", "Logo")) - self.label_14.setText(_translate("Dialog", "Theme")) - self.label_5.setText(_translate("Dialog", "Save session when exiting PINCE")) - self.checkBox_RememberLastPctDirectory.setText(_translate("Dialog", "Remember last file save/open across restarts")) - self.label_3.setText(_translate("Dialog", "Functions")) - self.label_4.setText(_translate("Dialog", "Hotkey")) - self.lineEdit_Hotkey.setPlaceholderText(_translate("Dialog", "Press shortcut")) - self.pushButton_ClearHotkey.setText(_translate("Dialog", "Clear")) - self.checkBox_ShowMemoryViewOnStop.setText(_translate("Dialog", "Bring Memory View to front when the inferior is stopped")) - self.label_6.setText(_translate("Dialog", "Instructions shown per scroll in Disassembly View")) - self.label_16.setText(_translate("Dialog", "Bytes shown per scroll in Hex View")) - self.label_GDBPath.setText(_translate("Dialog", "GDB Path")) - self.checkBox_GDBLogging.setText(_translate("Dialog", "GDB Logging")) - self.label_15.setText(_translate("Dialog", "Interruption signal")) - self.pushButton_HandleSignals.setText(_translate("Dialog", "Handle Signals")) - self.checkBox_JavaSegfault.setText(_translate("Dialog", "Ignore SIGSEGV for Java processes (overrides signal settings if enabled)")) - self.pushButton_ResetSettings.setText(_translate("Dialog", "Reset Settings")) diff --git a/GUI/Widgets/Settings/Form/SettingsDialog.ui b/GUI/Widgets/Settings/Form/SettingsDialog.ui deleted file mode 100644 index f8116e06..00000000 --- a/GUI/Widgets/Settings/Form/SettingsDialog.ui +++ /dev/null @@ -1,818 +0,0 @@ - - - Dialog - - - - 0 - 0 - 884 - 633 - - - - Settings - - - - - - - - - - - 0 - 0 - - - - - 130 - 16777215 - - - - - General - - - - - Hotkeys - - - - - Memory View - - - - - Debug - - - - - Java - - - - - - - - - 500 - 500 - - - - 0 - - - - - - - - - - - - - - - Auto-update address table - - - - - - - Check for AppImage updates on startup - - - - - - - - - - 0 - - - - - - 102 - 0 - - - - Update Interval - - - - - - - 100 - - - 10000 - - - 100 - - - - - - - ms - - - - - - - - - - - 0 - - - - - - 0 - 0 - - - - - 102 - 0 - - - - - 0 - 0 - - - - Freeze Interval - - - - - - - 100 - - - 10000 - - - 100 - - - - - - - ms - - - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - GDB output: - - - - - - - Async - - - - - - - Command - - - - - - - Command info - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - On start, automatically attach to processes with name matching one of the entries -Patterns at former positions have higher priority if regex is off - - - Auto-attach to processes named - - - - - - - - - - Regex - - - - - - - - - - - Language - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Logo - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Theme - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - 0 - - - - - Save session when exiting PINCE - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - Remember last file save/open across restarts - - - - - - - Qt::Orientation::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - - - Functions - - - - - - - -1 - - - - - - - - - - - - - Hotkey - - - - - - - true - - - Press shortcut - - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - Clear - - - - - - - - - Qt::Orientation::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - - - Bring Memory View to front when the inferior is stopped - - - - - - - - - Instructions shown per scroll in Disassembly View - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Bytes shown per scroll in Hex View - - - - - - - 0x - - - 4096 - - - 16 - - - 16 - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Orientation::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - - - - - GDB Path - - - - - - - - - - - - - - - - - GDB Logging - - - - - - - - - Interruption signal - - - - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - - - Handle Signals - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Orientation::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - Ignore SIGSEGV for Java processes (overrides signal settings if enabled) - - - - - - - Qt::Orientation::Vertical - - - - 20 - 40 - - - - - - - - - - - - - - - - Reset Settings - - - - - - - Qt::Orientation::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Orientation::Horizontal - - - QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok - - - - - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - - - 5 - - - 5 - - - true - - - true - - - true - - - diff --git a/GUI/Widgets/Settings/Settings.py b/GUI/Widgets/Settings/Settings.py deleted file mode 100644 index 1935b667..00000000 --- a/GUI/Widgets/Settings/Settings.py +++ /dev/null @@ -1,259 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QMessageBox, QFileDialog, QApplication, QWidget -from PyQt6.QtCore import Qt, QSettings, QSignalBlocker -from PyQt6.QtGui import QKeyEvent, QIcon, QPixmap, QStandardItemModel, QStandardItem -from GUI.States import states -from GUI.Settings import settings, themes -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.Settings.Form.SettingsDialog import Ui_Dialog -from GUI.Widgets.HandleSignals.HandleSignals import HandleSignalsDialog -from tr.tr import TranslationConstants as tr -from tr.tr import language_list -from libpince import debugcore, utils, typedefs -from keyboard import KeyboardEvent, _pressed_events -from keyboard._nixkeyboard import to_name -import os, signal, json, re - - -class SettingsDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.settings = QSettings() - self.hotkey_to_value: dict[str, str] = {} # Dict[str:str]-->Dict[Hotkey.name:settings_value] - self.handle_signals_data = "" - icons_directory = guiutils.get_icons_directory() - self.pushButton_GDBPath.setIcon(QIcon(QPixmap(icons_directory + "/folder.png"))) - locale_model = QStandardItemModel() - for loc, name in language_list.items(): - item = QStandardItem() - item.setData(name, Qt.ItemDataRole.DisplayRole) - item.setData(loc, Qt.ItemDataRole.UserRole) - locale_model.appendRow(item) - self.comboBox_Language.setModel(locale_model) - self.comboBox_InterruptSignal.addItem("SIGINT") - self.comboBox_InterruptSignal.addItems([f"SIG{x}" for x in range(signal.SIGRTMIN, signal.SIGRTMAX + 1)]) - self.comboBox_InterruptSignal.setStyleSheet("combobox-popup: 0;") # maxVisibleItems doesn't work otherwise - for theme_value, theme_name in themes.theme_strings.items(): - self.comboBox_Theme.addItem(theme_name, theme_value) - logo_directory = utils.get_logo_directory() - logo_list = utils.search_files(logo_directory, r"\.(png|jpg|jpeg|svg)$") - for logo in logo_list: - self.comboBox_Logo.addItem(QIcon(os.path.join(logo_directory, logo)), logo) - for hotkey in states.hotkeys.get_hotkeys(): - self.listWidget_Functions.addItem(hotkey.desc) - save_on_exit_combobox_items = ( - (tr.ALWAYS_ASK, None), - (tr.ALWAYS_SAVE, True), - (tr.ALWAYS_DISCARD, False), - ) - for translation, data in save_on_exit_combobox_items: - self.comboBox_SaveSessionOnExit.addItem(translation, data) - self.config_gui() - - self.listWidget_Options.currentRowChanged.connect(self.change_display) - self.listWidget_Functions.currentRowChanged.connect(self.listWidget_Functions_current_row_changed) - self.pushButton_ClearHotkey.clicked.connect(self.pushButton_ClearHotkey_clicked) - self.pushButton_ResetSettings.clicked.connect(self.pushButton_ResetSettings_clicked) - self.pushButton_GDBPath.clicked.connect(self.pushButton_GDBPath_clicked) - self.checkBox_AutoUpdateAddressTable.stateChanged.connect(self.checkBox_AutoUpdateAddressTable_state_changed) - self.checkBox_AutoAttachRegex.stateChanged.connect(self.checkBox_AutoAttachRegex_state_changed) - self.comboBox_Logo.currentIndexChanged.connect(self.comboBox_Logo_current_index_changed) - self.comboBox_Theme.currentIndexChanged.connect(self.comboBox_Theme_current_index_changed) - self.pushButton_HandleSignals.clicked.connect(self.pushButton_HandleSignals_clicked) - self.lineEdit_Hotkey.keyPressEvent = self.lineEdit_Hotkey_key_pressed_event - guiutils.center_to_parent(self) - - def accept(self) -> None: - if self.checkBox_AutoAttachRegex.isChecked(): - try: - re.compile(self.lineEdit_AutoAttach.text()) - except re.error: - QMessageBox.information(self, tr.ERROR, tr.IS_INVALID_REGEX.format(self.lineEdit_AutoAttach.text())) - return - if not os.environ.get("APPDIR"): - selected_gdb_path = self.lineEdit_GDBPath.text() - if selected_gdb_path != states.gdb_path and utilwidgets.InputDialog(self, tr.GDB_RESET).exec(): - if not debugcore.init_gdb(selected_gdb_path): - QMessageBox.information(self, tr.ERROR, tr.GDB_INIT_ERROR) - return - self.settings.setValue("Debug/gdb_path", selected_gdb_path) - self.settings.setValue("General/auto_update_address_table", self.checkBox_AutoUpdateAddressTable.isChecked()) - if os.environ.get("APPDIR"): - self.settings.setValue(settings.CHECK_UPDATES_ON_STARTUP, self.checkBox_CheckUpdatesOnStartup.isChecked()) - if self.checkBox_AutoUpdateAddressTable.isChecked(): - self.settings.setValue("General/address_table_update_interval", self.spinBox_UpdateInterval.value()) - self.settings.setValue("General/freeze_interval", self.spinBox_FreezeInterval.value()) - output_mode = [ - self.checkBox_OutputModeAsync.isChecked(), - self.checkBox_OutputModeCommand.isChecked(), - self.checkBox_OutputModeCommandInfo.isChecked(), - ] - self.settings.setValue("General/gdb_output_mode", json.dumps(output_mode)) - self.settings.setValue("General/auto_attach", self.lineEdit_AutoAttach.text()) - self.settings.setValue("General/auto_attach_regex", self.checkBox_AutoAttachRegex.isChecked()) - new_locale = self.comboBox_Language.currentData(Qt.ItemDataRole.UserRole) - current_locale = self.settings.value("General/locale", type=str) - if new_locale != current_locale: - QMessageBox.information(self, tr.INFO, tr.LANG_RESET) - self.settings.setValue("General/locale", new_locale) - self.settings.setValue("General/logo_path", self.comboBox_Logo.currentText()) - self.settings.setValue("General/theme", self.comboBox_Theme.currentData()) - for hotkey in states.hotkeys.get_hotkeys(): - self.settings.setValue("Hotkeys/" + hotkey.name, self.hotkey_to_value[hotkey.name]) - self.settings.setValue("MemoryView/show_memory_view_on_stop", self.checkBox_ShowMemoryViewOnStop.isChecked()) - self.settings.setValue("MemoryView/instructions_per_scroll", self.spinBox_InstructionsPerScroll.value()) - self.settings.setValue("MemoryView/bytes_per_scroll", self.spinBox_BytesPerScroll.value()) - self.settings.setValue("Debug/gdb_logging", self.checkBox_GDBLogging.isChecked()) - self.settings.setValue("Debug/interrupt_signal", self.comboBox_InterruptSignal.currentText()) - self.settings.setValue("Java/ignore_segfault", self.checkBox_JavaSegfault.isChecked()) - if self.handle_signals_data: - self.settings.setValue("Debug/handle_signals", self.handle_signals_data) - save_on_exit: bool | None = self.comboBox_SaveSessionOnExit.currentData() - if save_on_exit is None: - self.settings.remove(settings.SAVE_SESSION_ON_EXIT) - else: - self.settings.setValue(settings.SAVE_SESSION_ON_EXIT, save_on_exit) - if not self.checkBox_RememberLastPctDirectory.isChecked(): - self.settings.remove(settings.LAST_PCT_DIRECTORY) - elif not self.settings.contains(settings.LAST_PCT_DIRECTORY): - self.settings.setValue(settings.LAST_PCT_DIRECTORY, "") - settings.apply_settings() - super().accept() - - def reject(self) -> None: - logo_path = self.settings.value("General/logo_path", type=str) - QApplication.setWindowIcon(QIcon(os.path.join(utils.get_logo_directory(), logo_path))) - theme = self.settings.value("General/theme", type=str) - QApplication.setPalette(themes.get_theme(theme)) - super().reject() - - def config_gui(self) -> None: - self.checkBox_AutoUpdateAddressTable.setChecked(self.settings.value("General/auto_update_address_table", type=bool)) - self.checkBox_CheckUpdatesOnStartup.setChecked(self.settings.value(settings.CHECK_UPDATES_ON_STARTUP, False, type=bool)) - if not os.environ.get("APPDIR"): - self.checkBox_CheckUpdatesOnStartup.hide() - self.spinBox_UpdateInterval.setValue(self.settings.value("General/address_table_update_interval", type=int)) - self.spinBox_FreezeInterval.setValue(self.settings.value("General/freeze_interval", type=int)) - output_mode = json.loads(self.settings.value("General/gdb_output_mode", type=str)) - output_mode = typedefs.gdb_output_mode(*output_mode) - self.checkBox_OutputModeAsync.setChecked(output_mode.async_output) - self.checkBox_OutputModeCommand.setChecked(output_mode.command_output) - self.checkBox_OutputModeCommandInfo.setChecked(output_mode.command_info) - self.lineEdit_AutoAttach.setText(self.settings.value("General/auto_attach", type=str)) - self.checkBox_AutoAttachRegex.setChecked(self.settings.value("General/auto_attach_regex", type=bool)) - current_locale = self.settings.value("General/locale", type=str) - self.comboBox_Language.setCurrentText(language_list.get(current_locale, language_list["en_US"])) - with QSignalBlocker(self.comboBox_Theme): - self.comboBox_Theme.setCurrentIndex(self.comboBox_Theme.findData(self.settings.value("General/theme", type=str))) - with QSignalBlocker(self.comboBox_Logo): - self.comboBox_Logo.setCurrentText(self.settings.value("General/logo_path", type=str)) - self.hotkey_to_value.clear() - for hotkey in states.hotkeys.get_hotkeys(): - self.hotkey_to_value[hotkey.name] = self.settings.value("Hotkeys/" + hotkey.name) - self.listWidget_Functions_current_row_changed(self.listWidget_Functions.currentRow()) - self.checkBox_ShowMemoryViewOnStop.setChecked(self.settings.value("MemoryView/show_memory_view_on_stop", type=bool)) - self.spinBox_InstructionsPerScroll.setValue(self.settings.value("MemoryView/instructions_per_scroll", type=int)) - self.spinBox_BytesPerScroll.setValue(self.settings.value("MemoryView/bytes_per_scroll", type=int)) - self.lineEdit_GDBPath.setText(str(self.settings.value("Debug/gdb_path", type=str))) - if os.environ.get("APPDIR"): - self.label_GDBPath.setDisabled(True) - self.label_GDBPath.setToolTip(tr.UNUSED_APPIMAGE_SETTING) - self.lineEdit_GDBPath.setDisabled(True) - self.lineEdit_GDBPath.setToolTip(tr.UNUSED_APPIMAGE_SETTING) - self.pushButton_GDBPath.setDisabled(True) - self.pushButton_GDBPath.setToolTip(tr.UNUSED_APPIMAGE_SETTING) - self.checkBox_GDBLogging.setChecked(self.settings.value("Debug/gdb_logging", type=bool)) - self.comboBox_InterruptSignal.setCurrentText(self.settings.value("Debug/interrupt_signal", type=str)) - self.checkBox_JavaSegfault.setChecked(self.settings.value("Java/ignore_segfault", type=bool)) - save_on_exit: bool | None = ( - self.settings.value(settings.SAVE_SESSION_ON_EXIT, type=bool) if self.settings.contains(settings.SAVE_SESSION_ON_EXIT) else None - ) - self.comboBox_SaveSessionOnExit.setCurrentIndex(self.comboBox_SaveSessionOnExit.findData(save_on_exit)) - self.checkBox_RememberLastPctDirectory.setChecked(self.settings.contains(settings.LAST_PCT_DIRECTORY)) - - def change_display(self, index: int) -> None: - self.stackedWidget.setCurrentIndex(index) - - def listWidget_Functions_current_row_changed(self, index: int) -> None: - if index == -1: - self.lineEdit_Hotkey.clear() - else: - self.lineEdit_Hotkey.setText(self.hotkey_to_value[states.hotkeys.get_hotkeys()[index].name]) - - def pushButton_ClearHotkey_clicked(self) -> None: - self.lineEdit_Hotkey.clear() - index = self.listWidget_Functions.currentIndex().row() - if index != -1: - self.hotkey_to_value[states.hotkeys.get_hotkeys()[index].name] = self.lineEdit_Hotkey.text() - - def pushButton_ResetSettings_clicked(self) -> None: - if utilwidgets.InputDialog(self, tr.RESET_DEFAULT_SETTINGS).exec(): - settings.set_default_settings() - self.handle_signals_data = "" - self.config_gui() - - def checkBox_AutoUpdateAddressTable_state_changed(self) -> None: - if self.checkBox_AutoUpdateAddressTable.isChecked(): - self.QWidget_UpdateInterval.setEnabled(True) - else: - self.QWidget_UpdateInterval.setEnabled(False) - - def checkBox_AutoAttachRegex_state_changed(self) -> None: - if self.checkBox_AutoAttachRegex.isChecked(): - self.lineEdit_AutoAttach.setPlaceholderText(tr.MOUSE_OVER_EXAMPLES) - self.lineEdit_AutoAttach.setToolTip(tr.AUTO_ATTACH_TOOLTIP) - else: - self.lineEdit_AutoAttach.setPlaceholderText(tr.SEPARATE_PROCESSES_WITH.format(";")) - self.lineEdit_AutoAttach.setToolTip("") - - def comboBox_Logo_current_index_changed(self) -> None: - logo_path = self.comboBox_Logo.currentText() - QApplication.setWindowIcon(QIcon(os.path.join(utils.get_logo_directory(), logo_path))) - - def comboBox_Theme_current_index_changed(self, index: int) -> None: - QApplication.setPalette(themes.get_theme(self.comboBox_Theme.itemData(index))) - - def pushButton_GDBPath_clicked(self) -> None: - current_path = self.lineEdit_GDBPath.text() - file_path, _ = QFileDialog.getOpenFileName(self, tr.SELECT_GDB_BINARY, os.path.dirname(current_path)) - if file_path: - self.lineEdit_GDBPath.setText(file_path) - - def pushButton_HandleSignals_clicked(self) -> None: - if not self.handle_signals_data: - self.handle_signals_data = self.settings.value("Debug/handle_signals", type=str) - signal_dialog = HandleSignalsDialog(self, self.handle_signals_data) - if signal_dialog.exec(): - self.handle_signals_data = signal_dialog.get_values() - - def lineEdit_Hotkey_key_pressed_event(self, event: QKeyEvent) -> None: - """ - Instead of relying on the QT Event, we grab input from keyboard lib directly. - This reduces the amount of parsing from keys necessary and catches some more edge cases. - - One final caveat exists: system hotkeys or system wide defined hotkeys (xserver) - take precedence over the keyboard lib and are not caught completely. - """ - pressed_events: list[KeyboardEvent] = list(_pressed_events.values()) - if len(pressed_events) == 0: - # the keypress time was so short its not recognized by keyboard lib. - return - hotkey_string = "" - for ev in pressed_events: - # replacing keys with their respective base key, e.g "!" --> "1" - ev.name = to_name.get((ev.scan_code, ()), [ev.name])[-1] - # keyboard does recognize meta key (win key) as alt, setting manually - if ev.scan_code == 125 or ev.scan_code == 126: - ev.name = "windows" - hotkey_string += ev.name + "+" - - # remove the last plus - hotkey_string = hotkey_string[:-1] - - # moved from old keySequenceChanged event - self.lineEdit_Hotkey.setText(hotkey_string) - index = self.listWidget_Functions.currentIndex().row() - if index == -1: - self.lineEdit_Hotkey.clear() - else: - self.hotkey_to_value[states.hotkeys.get_hotkeys()[index].name] = self.lineEdit_Hotkey.text() diff --git a/GUI/Widgets/StackTraceInfo/StackTraceInfo.py b/GUI/Widgets/StackTraceInfo/StackTraceInfo.py deleted file mode 100644 index 31cf864c..00000000 --- a/GUI/Widgets/StackTraceInfo/StackTraceInfo.py +++ /dev/null @@ -1,40 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QListWidgetItem -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils -from GUI.Widgets.StackTraceInfo.Form.StackTraceInfoWidget import Ui_Form -from libpince import debugcore, utils - - -class StackTraceInfoWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.listWidget_ReturnAddresses.currentRowChanged.connect(self.update_frame_info) - self.listWidget_ReturnAddresses.itemDoubleClicked.connect(self.listWidget_ReturnAddresses_item_double_clicked) - - def update_stacktrace(self) -> None: - self.listWidget_ReturnAddresses.clear() - self.textBrowser_Info.clear() - error_message = guiutils.check_inferior_running(self, show_message=False) - if error_message: - self.textBrowser_Info.setText(error_message) - return - return_addresses = debugcore.get_stack_frame_return_addresses() - self.listWidget_ReturnAddresses.addItems(return_addresses) - - def update_frame_info(self, index: int) -> None: - self.textBrowser_Info.clear() - error_message = guiutils.check_inferior_running(self, show_message=False) - if error_message: - self.textBrowser_Info.setText(error_message) - return - frame_info = debugcore.get_stack_frame_info(index) - self.textBrowser_Info.setText(frame_info) - - def listWidget_ReturnAddresses_item_double_clicked(self, item: QListWidgetItem) -> None: - if debugcore.currentpid == -1: - return - address = utils.extract_hex_address(item.text()) - if address: - self.parent().disassemble_expression(address) diff --git a/GUI/Widgets/Structures/Form/MemberEditorDialog.py b/GUI/Widgets/Structures/Form/MemberEditorDialog.py deleted file mode 100644 index b438a339..00000000 --- a/GUI/Widgets/Structures/Form/MemberEditorDialog.py +++ /dev/null @@ -1,95 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/Structures/Form/MemberEditorDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(340, 406) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.label_Name = QtWidgets.QLabel(parent=Dialog) - self.label_Name.setObjectName("label_Name") - self.gridLayout.addWidget(self.label_Name, 0, 0, 1, 1) - self.lineEdit_Name = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Name.setObjectName("lineEdit_Name") - self.gridLayout.addWidget(self.lineEdit_Name, 0, 1, 1, 1) - self.label_Offset = QtWidgets.QLabel(parent=Dialog) - self.label_Offset.setObjectName("label_Offset") - self.gridLayout.addWidget(self.label_Offset, 1, 0, 1, 1) - self.lineEdit_Offset = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Offset.setObjectName("lineEdit_Offset") - self.gridLayout.addWidget(self.lineEdit_Offset, 1, 1, 1, 1) - self.label_Kind = QtWidgets.QLabel(parent=Dialog) - self.label_Kind.setObjectName("label_Kind") - self.gridLayout.addWidget(self.label_Kind, 2, 0, 1, 1) - self.comboBox_Kind = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_Kind.setObjectName("comboBox_Kind") - self.gridLayout.addWidget(self.comboBox_Kind, 2, 1, 1, 1) - self.label_Type = QtWidgets.QLabel(parent=Dialog) - self.label_Type.setObjectName("label_Type") - self.gridLayout.addWidget(self.label_Type, 3, 0, 1, 1) - self.comboBox_Type = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_Type.setObjectName("comboBox_Type") - self.gridLayout.addWidget(self.comboBox_Type, 3, 1, 1, 1) - self.label_Length = QtWidgets.QLabel(parent=Dialog) - self.label_Length.setObjectName("label_Length") - self.gridLayout.addWidget(self.label_Length, 4, 0, 1, 1) - self.lineEdit_Length = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Length.setObjectName("lineEdit_Length") - self.gridLayout.addWidget(self.lineEdit_Length, 4, 1, 1, 1) - self.label_StartBit = QtWidgets.QLabel(parent=Dialog) - self.label_StartBit.setObjectName("label_StartBit") - self.gridLayout.addWidget(self.label_StartBit, 5, 0, 1, 1) - self.spinBox_StartBit = QtWidgets.QSpinBox(parent=Dialog) - self.spinBox_StartBit.setMaximum(7) - self.spinBox_StartBit.setObjectName("spinBox_StartBit") - self.gridLayout.addWidget(self.spinBox_StartBit, 5, 1, 1, 1) - self.label_Repr = QtWidgets.QLabel(parent=Dialog) - self.label_Repr.setObjectName("label_Repr") - self.gridLayout.addWidget(self.label_Repr, 6, 0, 1, 1) - self.comboBox_Repr = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_Repr.setObjectName("comboBox_Repr") - self.gridLayout.addWidget(self.comboBox_Repr, 6, 1, 1, 1) - self.label_Endian = QtWidgets.QLabel(parent=Dialog) - self.label_Endian.setObjectName("label_Endian") - self.gridLayout.addWidget(self.label_Endian, 7, 0, 1, 1) - self.comboBox_Endian = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_Endian.setObjectName("comboBox_Endian") - self.gridLayout.addWidget(self.comboBox_Endian, 7, 1, 1, 1) - self.label_StructRef = QtWidgets.QLabel(parent=Dialog) - self.label_StructRef.setObjectName("label_StructRef") - self.gridLayout.addWidget(self.label_StructRef, 8, 0, 1, 1) - self.comboBox_StructRef = QtWidgets.QComboBox(parent=Dialog) - self.comboBox_StructRef.setObjectName("comboBox_StructRef") - self.gridLayout.addWidget(self.comboBox_StructRef, 8, 1, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 9, 0, 1, 2) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Member")) - self.label_Name.setText(_translate("Dialog", "Name")) - self.label_Offset.setText(_translate("Dialog", "Offset (hex)")) - self.label_Kind.setText(_translate("Dialog", "Kind")) - self.label_Type.setText(_translate("Dialog", "Value type")) - self.label_Length.setText(_translate("Dialog", "Length")) - self.label_StartBit.setText(_translate("Dialog", "Start bit")) - self.label_Repr.setText(_translate("Dialog", "Repr")) - self.label_Endian.setText(_translate("Dialog", "Endianness")) - self.label_StructRef.setText(_translate("Dialog", "Structure")) diff --git a/GUI/Widgets/Structures/Form/MemberEditorDialog.ui b/GUI/Widgets/Structures/Form/MemberEditorDialog.ui deleted file mode 100644 index e7af1d61..00000000 --- a/GUI/Widgets/Structures/Form/MemberEditorDialog.ui +++ /dev/null @@ -1,158 +0,0 @@ - - - Dialog - - - - 0 - 0 - 340 - 406 - - - - Member - - - - - - Name - - - - - - - - - - Offset (hex) - - - - - - - - - - Kind - - - - - - - - - - Value type - - - - - - - - - - Length - - - - - - - - - - Start bit - - - - - - - 7 - - - - - - - Repr - - - - - - - - - - Endianness - - - - - - - - - - Structure - - - - - - - - - - Qt::Orientation::Horizontal - - - QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 20 - 20 - - - 20 - 20 - - - - - buttonBox - rejected() - Dialog - reject() - - - 20 - 20 - - - 20 - 20 - - - - - diff --git a/GUI/Widgets/Structures/Form/StructureEditorDialog.py b/GUI/Widgets/Structures/Form/StructureEditorDialog.py deleted file mode 100644 index ae5abf0a..00000000 --- a/GUI/Widgets/Structures/Form/StructureEditorDialog.py +++ /dev/null @@ -1,68 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/Structures/Form/StructureEditorDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(460, 460) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.label_Name = QtWidgets.QLabel(parent=Dialog) - self.label_Name.setObjectName("label_Name") - self.gridLayout.addWidget(self.label_Name, 0, 0, 1, 1) - self.lineEdit_Name = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Name.setObjectName("lineEdit_Name") - self.gridLayout.addWidget(self.lineEdit_Name, 0, 1, 1, 1) - self.treeWidget_Members = QtWidgets.QTreeWidget(parent=Dialog) - self.treeWidget_Members.setRootIsDecorated(False) - self.treeWidget_Members.setObjectName("treeWidget_Members") - self.gridLayout.addWidget(self.treeWidget_Members, 1, 0, 1, 2) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.pushButton_Add = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Add.setObjectName("pushButton_Add") - self.horizontalLayout.addWidget(self.pushButton_Add) - self.pushButton_Edit = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Edit.setObjectName("pushButton_Edit") - self.horizontalLayout.addWidget(self.pushButton_Edit) - self.pushButton_Remove = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Remove.setObjectName("pushButton_Remove") - self.horizontalLayout.addWidget(self.pushButton_Remove) - self.pushButton_Up = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Up.setObjectName("pushButton_Up") - self.horizontalLayout.addWidget(self.pushButton_Up) - self.pushButton_Down = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Down.setObjectName("pushButton_Down") - self.horizontalLayout.addWidget(self.pushButton_Down) - self.gridLayout.addLayout(self.horizontalLayout, 2, 0, 1, 2) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 3, 0, 1, 2) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Edit structure")) - self.label_Name.setText(_translate("Dialog", "Name")) - self.treeWidget_Members.headerItem().setText(0, _translate("Dialog", "Offset")) - self.treeWidget_Members.headerItem().setText(1, _translate("Dialog", "Name")) - self.treeWidget_Members.headerItem().setText(2, _translate("Dialog", "Type")) - self.pushButton_Add.setText(_translate("Dialog", "Add")) - self.pushButton_Edit.setText(_translate("Dialog", "Edit")) - self.pushButton_Remove.setText(_translate("Dialog", "Remove")) - self.pushButton_Up.setText(_translate("Dialog", "Up")) - self.pushButton_Down.setText(_translate("Dialog", "Down")) diff --git a/GUI/Widgets/Structures/Form/StructureEditorDialog.ui b/GUI/Widgets/Structures/Form/StructureEditorDialog.ui deleted file mode 100644 index 16cf649d..00000000 --- a/GUI/Widgets/Structures/Form/StructureEditorDialog.ui +++ /dev/null @@ -1,135 +0,0 @@ - - - Dialog - - - - 0 - 0 - 460 - 460 - - - - Edit structure - - - - - - Name - - - - - - - - - - false - - - - Offset - - - - - Name - - - - - Type - - - - - - - - - - Add - - - - - - - Edit - - - - - - - Remove - - - - - - - Up - - - - - - - Down - - - - - - - - - Qt::Orientation::Horizontal - - - QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 20 - 20 - - - 20 - 20 - - - - - buttonBox - rejected() - Dialog - reject() - - - 20 - 20 - - - 20 - 20 - - - - - diff --git a/GUI/Widgets/Structures/Form/StructureViewDialog.py b/GUI/Widgets/Structures/Form/StructureViewDialog.py deleted file mode 100644 index 18aa3f1b..00000000 --- a/GUI/Widgets/Structures/Form/StructureViewDialog.py +++ /dev/null @@ -1,52 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/Structures/Form/StructureViewDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(560, 460) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.horizontalLayout_Base = QtWidgets.QHBoxLayout() - self.horizontalLayout_Base.setObjectName("horizontalLayout_Base") - self.label_Base = QtWidgets.QLabel(parent=Dialog) - self.label_Base.setObjectName("label_Base") - self.horizontalLayout_Base.addWidget(self.label_Base) - self.lineEdit_Base = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_Base.setReadOnly(True) - self.lineEdit_Base.setObjectName("lineEdit_Base") - self.horizontalLayout_Base.addWidget(self.lineEdit_Base) - self.gridLayout.addLayout(self.horizontalLayout_Base, 0, 0, 1, 2) - self.treeWidget_View = QtWidgets.QTreeWidget(parent=Dialog) - self.treeWidget_View.setObjectName("treeWidget_View") - self.gridLayout.addWidget(self.treeWidget_View, 1, 0, 1, 2) - self.pushButton_AddToTable = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_AddToTable.setObjectName("pushButton_AddToTable") - self.gridLayout.addWidget(self.pushButton_AddToTable, 2, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Close) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 2, 1, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Structure view")) - self.label_Base.setText(_translate("Dialog", "Base address")) - self.treeWidget_View.headerItem().setText(0, _translate("Dialog", "Offset")) - self.treeWidget_View.headerItem().setText(1, _translate("Dialog", "Name")) - self.treeWidget_View.headerItem().setText(2, _translate("Dialog", "Type")) - self.treeWidget_View.headerItem().setText(3, _translate("Dialog", "Value")) - self.pushButton_AddToTable.setText(_translate("Dialog", "Add to address table")) diff --git a/GUI/Widgets/Structures/Form/StructureViewDialog.ui b/GUI/Widgets/Structures/Form/StructureViewDialog.ui deleted file mode 100644 index b9cee1b5..00000000 --- a/GUI/Widgets/Structures/Form/StructureViewDialog.ui +++ /dev/null @@ -1,97 +0,0 @@ - - - Dialog - - - - 0 - 0 - 560 - 460 - - - - Structure view - - - - - - - - Base address - - - - - - - true - - - - - - - - - - Offset - - - - - Name - - - - - Type - - - - - Value - - - - - - - - Add to address table - - - - - - - Qt::Orientation::Horizontal - - - QDialogButtonBox::StandardButton::Close - - - - - - - - - buttonBox - rejected() - Dialog - reject() - - - 20 - 20 - - - 20 - 20 - - - - - diff --git a/GUI/Widgets/Structures/Form/StructuresWindow.py b/GUI/Widgets/Structures/Form/StructuresWindow.py deleted file mode 100644 index 74a29d81..00000000 --- a/GUI/Widgets/Structures/Form/StructuresWindow.py +++ /dev/null @@ -1,52 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/Structures/Form/StructuresWindow.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(611, 450) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.treeWidget_Structures = QtWidgets.QTreeWidget(parent=Form) - self.treeWidget_Structures.setRootIsDecorated(False) - self.treeWidget_Structures.setObjectName("treeWidget_Structures") - self.gridLayout.addWidget(self.treeWidget_Structures, 0, 0, 1, 1) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.pushButton_New = QtWidgets.QPushButton(parent=Form) - self.pushButton_New.setObjectName("pushButton_New") - self.horizontalLayout.addWidget(self.pushButton_New) - self.pushButton_Edit = QtWidgets.QPushButton(parent=Form) - self.pushButton_Edit.setObjectName("pushButton_Edit") - self.horizontalLayout.addWidget(self.pushButton_Edit) - self.pushButton_Delete = QtWidgets.QPushButton(parent=Form) - self.pushButton_Delete.setObjectName("pushButton_Delete") - self.horizontalLayout.addWidget(self.pushButton_Delete) - self.pushButton_ViewAtAddress = QtWidgets.QPushButton(parent=Form) - self.pushButton_ViewAtAddress.setObjectName("pushButton_ViewAtAddress") - self.horizontalLayout.addWidget(self.pushButton_ViewAtAddress) - self.pushButton_AddToTable = QtWidgets.QPushButton(parent=Form) - self.pushButton_AddToTable.setObjectName("pushButton_AddToTable") - self.horizontalLayout.addWidget(self.pushButton_AddToTable) - self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Structures")) - self.treeWidget_Structures.headerItem().setText(0, _translate("Form", "Name")) - self.pushButton_New.setText(_translate("Form", "New")) - self.pushButton_Edit.setText(_translate("Form", "Edit")) - self.pushButton_Delete.setText(_translate("Form", "Delete")) - self.pushButton_ViewAtAddress.setText(_translate("Form", "View at address…")) - self.pushButton_AddToTable.setText(_translate("Form", "Add to address table")) diff --git a/GUI/Widgets/Structures/Form/StructuresWindow.ui b/GUI/Widgets/Structures/Form/StructuresWindow.ui deleted file mode 100644 index 2c581ab7..00000000 --- a/GUI/Widgets/Structures/Form/StructuresWindow.ui +++ /dev/null @@ -1,72 +0,0 @@ - - - Form - - - - 0 - 0 - 611 - 450 - - - - Structures - - - - - - false - - - - Name - - - - - - - - - - New - - - - - - - Edit - - - - - - - Delete - - - - - - - View at address… - - - - - - - Add to address table - - - - - - - - - - diff --git a/GUI/Widgets/Structures/MemberEditorDialog.py b/GUI/Widgets/Structures/MemberEditorDialog.py deleted file mode 100644 index a7c548ed..00000000 --- a/GUI/Widgets/Structures/MemberEditorDialog.py +++ /dev/null @@ -1,151 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QMessageBox, QWidget - -from GUI.Utils import guiutils -from GUI.Session.session import StructureManager -from GUI.Widgets.Structures.Form.MemberEditorDialog import Ui_Dialog -from libpince import typedefs, utils -from tr.tr import TranslationConstants as tr - -KIND_VALUE = 0 -KIND_POINTER = 1 -KIND_INLINE = 2 - - -class MemberEditorDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, member: typedefs.StructureMember | None = None) -> None: - super().__init__(parent) - self.setupUi(self) - - self.comboBox_Kind.addItem(tr.VALUE_MEMBER, KIND_VALUE) - self.comboBox_Kind.addItem(tr.POINTER_MEMBER, KIND_POINTER) - self.comboBox_Kind.addItem(tr.INLINE_MEMBER, KIND_INLINE) - - guiutils.fill_value_combobox(self.comboBox_Type, member.value_type if member else None, include_bit_field=True) - guiutils.fill_endianness_combobox(self.comboBox_Endian) - - self.comboBox_Repr.addItem(tr.REPR_UNSIGNED, typedefs.VALUE_REPR.UNSIGNED) - self.comboBox_Repr.addItem(tr.REPR_SIGNED, typedefs.VALUE_REPR.SIGNED) - self.comboBox_Repr.addItem(tr.REPR_HEX, typedefs.VALUE_REPR.HEX) - - struct_names = StructureManager.list_names() - for name in struct_names: - self.comboBox_StructRef.addItem(name) - if not struct_names: - # Nothing to link to yet so only value members are valid. - kind_model = self.comboBox_Kind.model() - kind_model.item(KIND_POINTER).setEnabled(False) - kind_model.item(KIND_INLINE).setEnabled(False) - - self.comboBox_Kind.currentIndexChanged.connect(self._kind_changed) - self.comboBox_Type.currentIndexChanged.connect(self._type_changed) - - if member is not None: - self._load_member(member) - else: - self.comboBox_Kind.setCurrentIndex(self.comboBox_Kind.findData(KIND_VALUE)) - - self._kind_changed() - guiutils.center_to_parent(self) - - def _load_member(self, member: typedefs.StructureMember) -> None: - self.lineEdit_Name.setText(member.name) - self.lineEdit_Offset.setText(hex(member.offset)) - if member.value_type is not None: - self.comboBox_Kind.setCurrentIndex(self.comboBox_Kind.findData(KIND_VALUE)) - if hasattr(member.value_type, "length"): - self.lineEdit_Length.setText(str(member.value_type.length)) - elif isinstance(member.value_type, typedefs.BitFieldValueType): - self.lineEdit_Length.setText(str(member.value_type.bits)) - self.spinBox_StartBit.setValue(member.value_type.start_bit) - idx = self.comboBox_Repr.findData(getattr(member.value_type, "value_repr", typedefs.VALUE_REPR.UNSIGNED)) - if idx >= 0: - self.comboBox_Repr.setCurrentIndex(idx) - else: - self.comboBox_Repr.setCurrentIndex(0) - idx = self.comboBox_Endian.findData(getattr(member.value_type, "endian", typedefs.ENDIANNESS.HOST)) - if idx >= 0: - self.comboBox_Endian.setCurrentIndex(idx) - else: - self.comboBox_Endian.setCurrentIndex(0) - else: - if member.is_pointer: - self.comboBox_Kind.setCurrentIndex(self.comboBox_Kind.findData(KIND_POINTER)) - else: - self.comboBox_Kind.setCurrentIndex(self.comboBox_Kind.findData(KIND_INLINE)) - idx = self.comboBox_StructRef.findText(member.struct_ref) - if idx < 0 and member.struct_ref: - # Keep a link to a structure that's no longer registered instead of silently re-pointing it. - self.comboBox_StructRef.addItem(member.struct_ref) - idx = self.comboBox_StructRef.findText(member.struct_ref) - if idx >= 0: - self.comboBox_StructRef.setCurrentIndex(idx) - - def _kind_changed(self) -> None: - kind = self.comboBox_Kind.currentData() - is_value = kind == KIND_VALUE - self.label_Type.setVisible(is_value) - self.comboBox_Type.setVisible(is_value) - self.label_StructRef.setVisible(not is_value) - self.comboBox_StructRef.setVisible(not is_value) - self._type_changed() - - def _type_changed(self) -> None: - value_type = self.comboBox_Type.currentData() - is_value = self.comboBox_Kind.currentData() == KIND_VALUE - is_bit_field = isinstance(value_type, typedefs.BitFieldValueType) - has_len = is_value and (hasattr(value_type, "length") or is_bit_field) - self.label_Length.setVisible(has_len) - self.lineEdit_Length.setVisible(has_len) - self.label_StartBit.setVisible(is_value and is_bit_field) - self.spinBox_StartBit.setVisible(is_value and is_bit_field) - has_repr = is_value and hasattr(value_type, "value_repr") - self.label_Repr.setVisible(has_repr) - self.comboBox_Repr.setVisible(has_repr) - self.label_Endian.setVisible(is_value and not is_bit_field) - self.comboBox_Endian.setVisible(is_value and not is_bit_field) - - def accept(self) -> None: - try: - int(self.lineEdit_Offset.text(), 16) - except ValueError: - QMessageBox.warning(self, tr.ERROR, tr.PARSE_ERROR) - return - if self.lineEdit_Length.isVisible(): - try: - length = int(self.lineEdit_Length.text(), 0) - except ValueError: - QMessageBox.warning(self, tr.ERROR, tr.LENGTH_NOT_VALID) - return - if length <= 0: - QMessageBox.warning(self, tr.ERROR, tr.LENGTH_GT) - return - if isinstance(self.comboBox_Type.currentData(), typedefs.BitFieldValueType) and length > 64: - QMessageBox.warning(self, tr.ERROR, tr.LENGTH_NOT_VALID) - return - super().accept() - - def get_member(self) -> typedefs.StructureMember: - name = self.lineEdit_Name.text().strip() - offset = utils.safe_str_to_int(self.lineEdit_Offset.text(), 16) - kind = self.comboBox_Kind.currentData() - if kind == KIND_VALUE: - value_type = self.comboBox_Type.currentData() - has_length = hasattr(value_type, "length") or isinstance(value_type, typedefs.BitFieldValueType) - length = utils.safe_str_to_int(self.lineEdit_Length.text(), 0) if has_length else 10 - value_repr = self.comboBox_Repr.currentData() if hasattr(value_type, "value_repr") else typedefs.VALUE_REPR.UNSIGNED - if isinstance(value_type, typedefs.BitFieldValueType): - vt = typedefs.BitFieldValueType(length, self.spinBox_StartBit.value(), value_repr=value_repr) - return typedefs.StructureMember(name, offset, value_type=vt) - endian = self.comboBox_Endian.currentData() - vt = guiutils.configure_value_type( - value_type, - length=length, - zero_terminate=True, - value_repr=value_repr, - endian=endian, - ) - return typedefs.StructureMember(name, offset, value_type=vt) - else: - struct_ref = self.comboBox_StructRef.currentText() - is_pointer = kind == KIND_POINTER - return typedefs.StructureMember(name, offset, struct_ref=struct_ref, is_pointer=is_pointer) diff --git a/GUI/Widgets/Structures/StructureEditorDialog.py b/GUI/Widgets/Structures/StructureEditorDialog.py deleted file mode 100644 index 524dbd03..00000000 --- a/GUI/Widgets/Structures/StructureEditorDialog.py +++ /dev/null @@ -1,112 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QTreeWidgetItem, QMessageBox - -from GUI.Utils import guiutils -from GUI.Session.session import StructureManager -from GUI.Widgets.Structures.Form.StructureEditorDialog import Ui_Dialog -from GUI.Widgets.Structures.MemberEditorDialog import MemberEditorDialog -from libpince import typedefs, utils -from tr.tr import TranslationConstants as tr - - -class StructureEditorDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, structure_name: str | None = None) -> None: - super().__init__(parent) - self.setupUi(self) - - self._members: list[typedefs.StructureMember] = [] - self._original_name: str | None = structure_name - - self.pushButton_Add.clicked.connect(self._add_member) - self.pushButton_Edit.clicked.connect(self._edit_member) - self.pushButton_Remove.clicked.connect(self._remove_member) - self.pushButton_Up.clicked.connect(self._move_up) - self.pushButton_Down.clicked.connect(self._move_down) - - if structure_name is not None: - struct = StructureManager.get(structure_name) - if struct is not None: - self.lineEdit_Name.setText(struct.name) - self._members = list(struct.members) - - self._rebuild_tree() - guiutils.center_to_parent(self) - - def _rebuild_tree(self) -> None: - self.treeWidget_Members.clear() - for m in self._members: - offset_text = utils.upper_hex(hex(m.offset)) - if m.value_type is not None: - type_text = m.value_type.text() - else: - prefix = "ptr → " if m.is_pointer else "inline → " - type_text = prefix + m.struct_ref - item = QTreeWidgetItem([offset_text, m.name, type_text]) - self.treeWidget_Members.addTopLevelItem(item) - for column in range(self.treeWidget_Members.columnCount()): - self.treeWidget_Members.resizeColumnToContents(column) - - def _selected_index(self) -> int: - item = self.treeWidget_Members.currentItem() - if item is None: - return -1 - return self.treeWidget_Members.indexOfTopLevelItem(item) - - def _add_member(self) -> None: - dlg = MemberEditorDialog(self) - if dlg.exec(): - self._members.append(dlg.get_member()) - self._rebuild_tree() - - def _edit_member(self) -> None: - idx = self._selected_index() - if idx < 0: - return - dlg = MemberEditorDialog(self, self._members[idx]) - if dlg.exec(): - self._members[idx] = dlg.get_member() - self._rebuild_tree() - - def _remove_member(self) -> None: - idx = self._selected_index() - if idx < 0: - return - del self._members[idx] - self._rebuild_tree() - - def _move_up(self) -> None: - idx = self._selected_index() - if idx <= 0: - return - self._members[idx - 1], self._members[idx] = self._members[idx], self._members[idx - 1] - self._rebuild_tree() - self.treeWidget_Members.setCurrentItem(self.treeWidget_Members.topLevelItem(idx - 1)) - - def _move_down(self) -> None: - idx = self._selected_index() - if idx < 0 or idx >= len(self._members) - 1: - return - self._members[idx], self._members[idx + 1] = self._members[idx + 1], self._members[idx] - self._rebuild_tree() - self.treeWidget_Members.setCurrentItem(self.treeWidget_Members.topLevelItem(idx + 1)) - - def accept(self) -> None: - name = self.lineEdit_Name.text().strip() - if not name: - QMessageBox.warning(self, tr.ERROR, tr.STRUCTURE_NAME_EMPTY) - return - struct = typedefs.Structure(name, list(self._members)) - if self._original_name is not None and name != self._original_name: - if not StructureManager.rename(self._original_name, name): - QMessageBox.warning(self, tr.ERROR, tr.STRUCTURE_NAME_TAKEN) - return - for member in struct.members: - if member.struct_ref == self._original_name: - member.struct_ref = name - StructureManager.update(struct) - elif self._original_name is None: - if not StructureManager.add(struct): - QMessageBox.warning(self, tr.ERROR, tr.STRUCTURE_NAME_TAKEN) - return - else: - StructureManager.update(struct) - super().accept() diff --git a/GUI/Widgets/Structures/StructureViewDialog.py b/GUI/Widgets/Structures/StructureViewDialog.py deleted file mode 100644 index 7cd26340..00000000 --- a/GUI/Widgets/Structures/StructureViewDialog.py +++ /dev/null @@ -1,168 +0,0 @@ -import io - -from PyQt6.QtCore import Qt, QTimer, pyqtSignal -from PyQt6.QtGui import QShowEvent -from PyQt6.QtWidgets import QDialog, QMessageBox, QTreeWidgetItem, QWidget - -from GUI.Session.session import StructureManager -from GUI.States import states -from GUI.Utils import guiutils, utilwidgets -from GUI.Widgets.Structures.Form.StructureViewDialog import Ui_Dialog -from GUI.Widgets.Structures.materialize import structure_to_group_record -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr - -ROLE_MEMBER = Qt.ItemDataRole.UserRole -ROLE_ADDR = Qt.ItemDataRole.UserRole + 1 -ROLE_CHILD_BASE = Qt.ItemDataRole.UserRole + 2 - -_MAX_DEPTH = 16 - - -class StructureViewDialog(QDialog, Ui_Dialog): - add_to_table_requested = pyqtSignal(list) - - def __init__(self, parent: QWidget, structure_name: str, base_address: str = "") -> None: - super().__init__(parent) - self.setupUi(self) - self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) - states.process_signals.attach.connect(self.close) - states.process_signals.exit.connect(self.close) - - self.structure_name = structure_name - base_address = base_address.strip() - self.base_expr = debugcore.convert_to_hex(base_address) if base_address else "" - resolved = debugcore.examine_expression(self.base_expr).address if self.base_expr else None - self.base = int(resolved, 0) if resolved else 0 - - self.lineEdit_Base.setText(self.base_expr) - self.pushButton_AddToTable.clicked.connect(self._add_to_table) - - self.treeWidget_View.itemExpanded.connect(self._on_item_expanded) - self.treeWidget_View.itemDoubleClicked.connect(self._on_item_double_clicked) - - self._refresh_timer = QTimer(self) - self._refresh_timer.setSingleShot(True) - self._refresh_timer.timeout.connect(self._refresh_values) - - self._build_tree() - self._start_refresh() - guiutils.center_to_parent(self) - - def _add_to_table(self) -> None: - struct = StructureManager.get(self.structure_name) - if struct is None: - return - self.add_to_table_requested.emit([structure_to_group_record(struct, self.base_expr)]) - - def _build_tree(self) -> None: - self.treeWidget_View.clear() - struct = StructureManager.get(self.structure_name) - if struct is None: - return - self._build_level(self.treeWidget_View.invisibleRootItem(), struct, self.base, 0) - self.treeWidget_View.resizeColumnToContents(0) - self.treeWidget_View.resizeColumnToContents(1) - self.treeWidget_View.resizeColumnToContents(2) - - def _build_level(self, parent: QTreeWidgetItem, struct: typedefs.Structure, base_addr: int, depth: int) -> None: - if depth > _MAX_DEPTH: - return - for member in struct.members: - addr = base_addr + member.offset - offset_text = utils.upper_hex(hex(member.offset)) - if member.value_type is not None: - value = debugcore.read_memory(addr, member.value_type) - value_text = str(value) if value is not None else "??" - type_text = member.value_type.text() - item = QTreeWidgetItem([offset_text, member.name, type_text, value_text]) - item.setData(0, ROLE_MEMBER, member) - item.setData(0, ROLE_ADDR, addr) - parent.addChild(item) - else: - type_text = ("ptr → " if member.is_pointer else "inline → ") + member.struct_ref - item = QTreeWidgetItem([offset_text, member.name, type_text, ""]) - item.setData(0, ROLE_MEMBER, member) - item.setData(0, ROLE_ADDR, addr) - item.addChild(QTreeWidgetItem(["", "", "", ""])) - parent.addChild(item) - - def _on_item_expanded(self, item: QTreeWidgetItem, mem_handle: io.BufferedReader | None = None) -> None: - member: typedefs.StructureMember = item.data(0, ROLE_MEMBER) - if member is None or member.struct_ref is None: - return - child_base = item.data(0, ROLE_ADDR) # already base + member.offset - if member.is_pointer: - pointer_bits = 32 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64 - # One hop deref at the member's address. - child_base = debugcore.read_memory(child_base, typedefs.IntegerValueType(pointer_bits), mem_handle=mem_handle) - if child_base == item.data(0, ROLE_CHILD_BASE): - return - item.takeChildren() - child_struct = StructureManager.get(member.struct_ref) - if child_struct is not None and (child_base or not member.is_pointer): - self._build_level(item, child_struct, child_base, self._get_depth(item) + 1) - item.setData(0, ROLE_CHILD_BASE, child_base) - - def _get_depth(self, item: QTreeWidgetItem) -> int: - depth = 0 - node = item.parent() - while node is not None: - depth += 1 - node = node.parent() - return depth - - def _on_item_double_clicked(self, item: QTreeWidgetItem, column: int) -> None: - if column != 3: - return - member: typedefs.StructureMember = item.data(0, ROLE_MEMBER) - if member is None or member.value_type is None: - return - addr = item.data(0, ROLE_ADDR) - current_value = item.text(3) - dialog = utilwidgets.InputDialog(self, [(tr.ENTER_VALUE, current_value)]) - if dialog.exec(): - new_value = dialog.get_values()[0] - parsed = member.value_type.parse(new_value) - if parsed is None: - QMessageBox.warning(self, tr.ERROR, tr.PARSE_ERROR) - return - debugcore.write_memory(addr, member.value_type, parsed) - self._refresh_single(item, member, addr) - - def _refresh_single(self, item: QTreeWidgetItem, member: typedefs.StructureMember, addr: int) -> None: - value = debugcore.read_memory(addr, member.value_type) - item.setText(3, str(value) if value is not None else "??") - - def _start_refresh(self) -> None: - self._refresh_timer.start(states.table_update_interval) - - def _refresh_values(self) -> None: - if not self.isVisible(): - return # stop polling while hidden, showEvent re-arms on the next show - if debugcore.currentpid == -1: - self._start_refresh() - return - try: - with debugcore.memory_handle() as mem_handle: - self._refresh_item(self.treeWidget_View.invisibleRootItem(), mem_handle) - except OSError: - pass - self._start_refresh() - - def showEvent(self, event: QShowEvent) -> None: - self._start_refresh() - return super().showEvent(event) - - def _refresh_item(self, item: QTreeWidgetItem, mem_handle: io.BufferedReader) -> None: - for i in range(item.childCount()): - child = item.child(i) - member: typedefs.StructureMember = child.data(0, ROLE_MEMBER) - if member is not None and member.value_type is not None: - addr = child.data(0, ROLE_ADDR) - value = debugcore.read_memory(addr, member.value_type, mem_handle=mem_handle) - child.setText(3, str(value) if value is not None else "??") - if child.isExpanded(): - if member is not None and member.is_pointer: - self._on_item_expanded(child, mem_handle) - self._refresh_item(child, mem_handle) diff --git a/GUI/Widgets/Structures/StructuresWindow.py b/GUI/Widgets/Structures/StructuresWindow.py deleted file mode 100644 index 2601fb95..00000000 --- a/GUI/Widgets/Structures/StructuresWindow.py +++ /dev/null @@ -1,94 +0,0 @@ -from PyQt6.QtCore import Qt, pyqtSignal -from PyQt6.QtWidgets import QInputDialog, QMessageBox, QTreeWidgetItem, QWidget - -from GUI.Session.session import StructureManager -from GUI.Utils import guiutils -from GUI.Widgets.Structures.Form.StructuresWindow import Ui_Form -from GUI.Widgets.Structures.StructureEditorDialog import StructureEditorDialog -from GUI.Widgets.Structures.StructureViewDialog import StructureViewDialog -from GUI.Widgets.Structures.materialize import structure_to_group_record -from libpince import debugcore -from tr.tr import TranslationConstants as tr - - -class StructuresWindow(QWidget, Ui_Form): - add_to_table_requested = pyqtSignal(list) - - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - - self.pushButton_New.clicked.connect(self._new_structure) - self.pushButton_Edit.clicked.connect(self._edit_structure) - self.pushButton_Delete.clicked.connect(self._delete_structure) - self.pushButton_ViewAtAddress.clicked.connect(self._view_at_address) - self.pushButton_AddToTable.clicked.connect(self._add_to_table) - self.treeWidget_Structures.itemDoubleClicked.connect(self._edit_structure) - - self._view_windows: list[StructureViewDialog] = [] - self.refresh() - guiutils.center_to_parent(self) - - def refresh(self) -> None: - self.treeWidget_Structures.clear() - for name in StructureManager.list_names(): - item = QTreeWidgetItem([name]) - self.treeWidget_Structures.addTopLevelItem(item) - self.treeWidget_Structures.resizeColumnToContents(0) - - def _selected_name(self) -> str | None: - item = self.treeWidget_Structures.currentItem() - return item.text(0) if item else None - - def _new_structure(self) -> None: - dlg = StructureEditorDialog(self) - if dlg.exec(): - self.refresh() - - def _edit_structure(self) -> None: - name = self._selected_name() - if name is None: - return - dlg = StructureEditorDialog(self, name) - if dlg.exec(): - self.refresh() - - def _delete_structure(self) -> None: - name = self._selected_name() - if name is None: - return - result = QMessageBox.question(self, tr.DELETE_STRUCTURE, tr.DELETE_STRUCTURE_PROMPT.format(name)) - if result == QMessageBox.StandardButton.Yes: - StructureManager.delete(name) - self.refresh() - - def _view_at_address(self) -> None: - name = self._selected_name() - if name is None: - return - address, ok = QInputDialog.getText(self, tr.VIEW_AT_ADDRESS, tr.ENTER_BASE_ADDRESS) - if not ok or not address.strip(): - return - view = StructureViewDialog(self, name, address) - view.add_to_table_requested.connect(self.add_to_table_requested) - self._view_windows.append(view) - view.finished.connect(lambda _result, v=view: self._forget_view(v)) - view.show() - - def _forget_view(self, view: StructureViewDialog) -> None: - if view in self._view_windows: - self._view_windows.remove(view) - - def _add_to_table(self) -> None: - name = self._selected_name() - if name is None: - return - address, ok = QInputDialog.getText(self, tr.ADD_TO_ADDRESS_TABLE, tr.ENTER_BASE_ADDRESS) - if not ok or not address.strip(): - return - struct = StructureManager.get(name) - if struct is None: - return - base_expr = debugcore.convert_to_hex(address.strip()) - self.add_to_table_requested.emit([structure_to_group_record(struct, base_expr)]) diff --git a/GUI/Widgets/Structures/materialize.py b/GUI/Widgets/Structures/materialize.py deleted file mode 100644 index fc90c450..00000000 --- a/GUI/Widgets/Structures/materialize.py +++ /dev/null @@ -1,64 +0,0 @@ -from libpince import debugcore, typedefs -from GUI.Session.session import StructureManager - -_MAX_DEPTH = 16 -_STRUCT_VT = typedefs.StructValueType().serialize() - - -def _rel_off(offset: int) -> str: - return f"+{hex(offset)}" if offset >= 0 else f"-{hex(-offset)}" - - -def _read_string_length(base_addr: int, structure: typedefs.Structure) -> int | None: - if structure.name != "System.String": - return None - for m in structure.members: - if m.name == "length" and m.value_type is not None: - raw_len = debugcore.read_memory(base_addr + m.offset, m.value_type) - if raw_len is not None and 0 <= raw_len <= 4096: - return raw_len - break - return None - - -def structure_to_records( - structure: typedefs.Structure, base_addr: int = 0, _depth: int = 0, _parents: tuple[str, ...] = () -) -> list[tuple[str, str | tuple[str | int, list[int]], tuple[int, ...], list]]: - if _depth > _MAX_DEPTH or structure.name in _parents: - return [] - length_overrides = {} - if structure.name == "System.String" and base_addr > 0: - str_len = _read_string_length(base_addr, structure) - if str_len is not None: - length_overrides["chars"] = str_len - records = [] - for member in structure.members: - if member.value_type is not None: - vt = member.value_type.serialize() - if member.name in length_overrides and isinstance(member.value_type, typedefs.StringValueType): - vt = (vt[0], length_overrides[member.name], vt[2], vt[3], vt[4]) - records.append((member.name, _rel_off(member.offset), vt, [])) - else: - child = StructureManager.get(member.struct_ref) - off = _rel_off(member.offset) - if child is None: - group_expr = typedefs.PointerChainRequest(off, [0]).serialize() if member.is_pointer else off - records.append((member.name, group_expr, _STRUCT_VT, [])) - continue - child_base = base_addr + member.offset - if member.is_pointer and base_addr > 0: - pointer_bits = 32 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64 - ptr_val = debugcore.read_memory(base_addr + member.offset, typedefs.IntegerValueType(pointer_bits)) - if ptr_val is not None: - child_base = ptr_val - children = structure_to_records(child, child_base, _depth + 1, _parents + (structure.name,)) - group_expr = typedefs.PointerChainRequest(off, [0]).serialize() if member.is_pointer else off - records.append((member.name, group_expr, _STRUCT_VT, children)) - return records - - -def structure_to_group_record(structure: typedefs.Structure, base_expr: str) -> tuple[str, str, tuple[int, ...], list]: - address = debugcore.examine_expression(base_expr).address if base_expr else None - base_addr = int(address, 0) if address else 0 - members = structure_to_records(structure, base_addr) - return structure.name, base_expr, _STRUCT_VT, members diff --git a/GUI/Widgets/Structures/mono_export.py b/GUI/Widgets/Structures/mono_export.py deleted file mode 100644 index 72306dd5..00000000 --- a/GUI/Widgets/Structures/mono_export.py +++ /dev/null @@ -1,190 +0,0 @@ -from libpince import debugcore, typedefs, monocore -from GUI.Session.session import StructureManager - -_TAG_TO_VALUE_TYPE = { - "bool": lambda: typedefs.IntegerValueType(8), - "i1": lambda: typedefs.IntegerValueType(8, value_repr=typedefs.VALUE_REPR.SIGNED), - "u1": lambda: typedefs.IntegerValueType(8), - "i2": lambda: typedefs.IntegerValueType(16, value_repr=typedefs.VALUE_REPR.SIGNED), - "u2": lambda: typedefs.IntegerValueType(16), - "char": lambda: typedefs.IntegerValueType(16), - "i4": lambda: typedefs.IntegerValueType(32, value_repr=typedefs.VALUE_REPR.SIGNED), - "u4": lambda: typedefs.IntegerValueType(32), - "i8": lambda: typedefs.IntegerValueType(64, value_repr=typedefs.VALUE_REPR.SIGNED), - "u8": lambda: typedefs.IntegerValueType(64), - "r4": lambda: typedefs.FloatValueType(32), - "r8": lambda: typedefs.FloatValueType(64), -} -_MAX_INHERIT_DEPTH = 32 - - -def _is_instance_field(fld: dict) -> bool: - return not fld["is_static"] and not (fld["flags"] & 0x40) - - -def _ensure_managed_string_structure() -> str: - if StructureManager.get("System.String") is None: - pointer_bits = 32 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64 - pointer_size = pointer_bits // 8 - members = [ - typedefs.StructureMember( - "vtable_ptr", - 0, - typedefs.IntegerValueType(pointer_bits, value_repr=typedefs.VALUE_REPR.HEX), - ), - typedefs.StructureMember("sync", pointer_size, typedefs.IntegerValueType(pointer_bits)), - typedefs.StructureMember("length", pointer_size * 2, typedefs.IntegerValueType()), - # Small preview; address-table export calculates the real length. - typedefs.StructureMember( - "chars", - pointer_size * 2 + 4, - typedefs.StringValueType("utf-16", length=32, zero_terminate=False), - ), - ] - StructureManager.add(typedefs.Structure("System.String", members)) - return "System.String" - - -def member_from_field(fld: dict, pointer_bits: int = 64) -> "typedefs.StructureMember | None": - if not _is_instance_field(fld): - return None - tag = fld.get("tag") - if tag in _TAG_TO_VALUE_TYPE: - return typedefs.StructureMember(fld["name"], fld["offset"], _TAG_TO_VALUE_TYPE[tag]()) - if tag == "str": - return typedefs.StructureMember(fld["name"], fld["offset"], struct_ref=_ensure_managed_string_structure(), is_pointer=True) - if tag == "object": - return typedefs.StructureMember( - fld["name"], - fld["offset"], - typedefs.IntegerValueType(pointer_bits, value_repr=typedefs.VALUE_REPR.HEX), - ) - return typedefs.StructureMember(fld["name"], fld["offset"], typedefs.ByteArrayValueType(0)) - - -def _inherited_instance_fields(client: monocore.MonoClient, class_data: dict) -> list[dict]: - fields = [] - ptr = class_data.get("parent", 0) - depth = 0 - while ptr != 0 and depth < _MAX_INHERIT_DEPTH: - try: - info = client.class_info(ptr) - except monocore.MonoError: - break - fields.extend(client.fields(ptr)) - ptr = info.get("parent", 0) - depth += 1 - return fields - - -def _class_name(class_data: dict) -> str: - name = class_data.get("name", "?") - ns = class_data.get("namespace") - return f"{ns}.{name}" if ns else name - - -def _unique_name(name: str) -> str: - counter = 1 - while StructureManager.get(f"{name}_{counter}") is not None: - counter += 1 - return f"{name}_{counter}" - - -def _leaf_member(fld: dict, instance: list[dict], i: int, pointer_bits: int) -> typedefs.StructureMember: - m = member_from_field(fld, pointer_bits) - if isinstance(m.value_type, typedefs.ByteArrayValueType) and m.value_type.length <= 0: - nxt = instance[i + 1]["offset"] if i + 1 < len(instance) else fld["offset"] + 8 - m.value_type.length = max(1, nxt - fld["offset"]) - return m - - -def _safe_type_klass(client: monocore.MonoClient, fld: dict) -> int: - try: - return client.type_klass(fld["field"]) - except monocore.MonoError: - return 0 - - -def _object_ref_name( - client: monocore.MonoClient, - fld: dict, - seen: set[str], - pointer_bits: int, - include_inherited: bool, -) -> "str | None": - ref_klass = _safe_type_klass(client, fld) - if not ref_klass: - return None - try: - ref_info = client.class_info(ref_klass) - return _build_structure(client, {**ref_info, "klass": ref_klass}, seen, pointer_bits, include_inherited) - except monocore.MonoError: - return None - - -def _inline_value_type(client: monocore.MonoClient, fld: dict) -> "str | None": - vt_klass = _safe_type_klass(client, fld) - if vt_klass == 0: - return None - try: - sub_fields = client.struct_fields(vt_klass) - if sub_fields is None or any(sf["tag"] not in _TAG_TO_VALUE_TYPE for sf in sub_fields): - return None - vt_name = _class_name(client.class_info(vt_klass)) - if StructureManager.get(vt_name) is None: - members = [ - typedefs.StructureMember( - sf["name"], - sf["offset"], - _TAG_TO_VALUE_TYPE[sf["tag"]](), - ) - for sf in sub_fields - ] - StructureManager.add(typedefs.Structure(vt_name, members)) - return vt_name - except monocore.MonoError: - return None - - -def _build_structure( - client: monocore.MonoClient, - class_data: dict, - seen: set[str], - pointer_bits: int, - include_inherited: bool = True, - force_new: bool = False, -) -> str: - name = _class_name(class_data) - if name in seen: - return name - if StructureManager.get(name) is not None: - if not force_new: - return name - name = _unique_name(name) - fields = list(client.fields(class_data["klass"])) # call can fail so do it before registering anything - seen.add(name) - StructureManager.add(typedefs.Structure(name, [])) - if include_inherited: - fields += _inherited_instance_fields(client, class_data) - instance = sorted((f for f in fields if _is_instance_field(f)), key=lambda f: f["offset"]) - members = [] - for i, fld in enumerate(instance): - tag = fld.get("tag") - member = None - if tag == "object": - ref_name = _object_ref_name(client, fld, seen, pointer_bits, include_inherited) - if ref_name is not None: - member = typedefs.StructureMember(fld["name"], fld["offset"], struct_ref=ref_name, is_pointer=True) - elif tag == "struct": - vt_name = _inline_value_type(client, fld) - if vt_name is not None: - member = typedefs.StructureMember(fld["name"], fld["offset"], struct_ref=vt_name, is_pointer=False) - members.append(member if member is not None else _leaf_member(fld, instance, i, pointer_bits)) - StructureManager.update(typedefs.Structure(name, members)) - return name - - -def structure_from_class(client: monocore.MonoClient, class_data: dict, include_inherited: bool = True, force_new: bool = True) -> typedefs.Structure: - pointer_bits = 32 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64 - name = _build_structure(client, class_data, set(), pointer_bits, include_inherited, force_new) - return StructureManager.get(name) diff --git a/GUI/Widgets/TextEdit/Form/TextEditDialog.py b/GUI/Widgets/TextEdit/Form/TextEditDialog.py deleted file mode 100644 index fb725792..00000000 --- a/GUI/Widgets/TextEdit/Form/TextEditDialog.py +++ /dev/null @@ -1,35 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TextEdit/Form/TextEditDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(568, 529) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.textEdit = QtWidgets.QTextEdit(parent=Dialog) - self.textEdit.setObjectName("textEdit") - self.gridLayout.addWidget(self.textEdit, 0, 0, 1, 1) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Dialog")) - self.textEdit.setPlaceholderText(_translate("Dialog", "Hit Esc to cancel and Ctrl+Enter to accept")) diff --git a/GUI/Widgets/TextEdit/TextEdit.py b/GUI/Widgets/TextEdit/TextEdit.py deleted file mode 100644 index 3ef2376b..00000000 --- a/GUI/Widgets/TextEdit/TextEdit.py +++ /dev/null @@ -1,24 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget -from PyQt6.QtGui import QShortcut, QKeySequence, QKeyEvent -from PyQt6.QtCore import Qt -from GUI.Utils import guiutils -from GUI.Widgets.TextEdit.Form.TextEditDialog import Ui_Dialog - - -class TextEditDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget, text: str = "") -> None: - super().__init__(parent) - self.setupUi(self) - self.textEdit.setPlainText(str(text)) - self.accept_shortcut = QShortcut(QKeySequence("Ctrl+Return"), self) - self.accept_shortcut.activated.connect(self.accept) - guiutils.center_to_parent(self) - - def get_values(self) -> str: - return self.textEdit.toPlainText() - - def keyPressEvent(self, QKeyEvent: QKeyEvent) -> None: - if QKeyEvent.key() == Qt.Key.Key_Enter: - pass - else: - super().keyPressEvent(QKeyEvent) diff --git a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.py b/GUI/Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.py deleted file mode 100644 index 00741dc5..00000000 --- a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.py +++ /dev/null @@ -1,72 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(269, 294) - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.verticalLayout.addWidget(self.label) - self.lineEdit_MaxTraceCount = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_MaxTraceCount.setText("1000") - self.lineEdit_MaxTraceCount.setObjectName("lineEdit_MaxTraceCount") - self.verticalLayout.addWidget(self.lineEdit_MaxTraceCount) - self.label_3 = QtWidgets.QLabel(parent=Dialog) - self.label_3.setObjectName("label_3") - self.verticalLayout.addWidget(self.label_3) - self.lineEdit_TriggerCondition = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_TriggerCondition.setObjectName("lineEdit_TriggerCondition") - self.verticalLayout.addWidget(self.lineEdit_TriggerCondition) - self.label_2 = QtWidgets.QLabel(parent=Dialog) - self.label_2.setObjectName("label_2") - self.verticalLayout.addWidget(self.label_2) - self.lineEdit_StopCondition = QtWidgets.QLineEdit(parent=Dialog) - self.lineEdit_StopCondition.setObjectName("lineEdit_StopCondition") - self.verticalLayout.addWidget(self.lineEdit_StopCondition) - self.checkBox_StepOver = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_StepOver.setObjectName("checkBox_StepOver") - self.verticalLayout.addWidget(self.checkBox_StepOver) - self.checkBox_StopAfterTrace = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_StopAfterTrace.setObjectName("checkBox_StopAfterTrace") - self.verticalLayout.addWidget(self.checkBox_StopAfterTrace) - self.checkBox_CollectRegisters = QtWidgets.QCheckBox(parent=Dialog) - self.checkBox_CollectRegisters.setChecked(True) - self.checkBox_CollectRegisters.setObjectName("checkBox_CollectRegisters") - self.verticalLayout.addWidget(self.checkBox_CollectRegisters) - self.buttonBox = QtWidgets.QDialogButtonBox(parent=Dialog) - self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok) - self.buttonBox.setObjectName("buttonBox") - self.verticalLayout.addWidget(self.buttonBox) - self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - self.buttonBox.accepted.connect(Dialog.accept) # type: ignore - self.buttonBox.rejected.connect(Dialog.reject) # type: ignore - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - Dialog.setWindowTitle(_translate("Dialog", "Parameters for tracing")) - self.label.setToolTip(_translate("Dialog", "Number of the instructions that\'ll be traced")) - self.label.setText(_translate("Dialog", "Max trace count(1 or greater):")) - self.label_3.setToolTip(_translate("Dialog", "Tracing will start if this condition is met")) - self.label_3.setText(_translate("Dialog", "Trigger condition(Optional, gdb expression):")) - self.label_2.setToolTip(_translate("Dialog", "Tracing will stop whenever this condition is met")) - self.label_2.setText(_translate("Dialog", "Stop condition(Optional, gdb expression):")) - self.checkBox_StepOver.setText(_translate("Dialog", "Step over instead of single step")) - self.checkBox_StopAfterTrace.setText(_translate("Dialog", "Stop when tracing ends")) - self.checkBox_CollectRegisters.setText(_translate("Dialog", "Collect registers")) diff --git a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.ui b/GUI/Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.ui deleted file mode 100644 index 57d4de78..00000000 --- a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsPromptDialog.ui +++ /dev/null @@ -1,135 +0,0 @@ - - - Dialog - - - - 0 - 0 - 269 - 294 - - - - Parameters for tracing - - - - - - - - Number of the instructions that'll be traced - - - Max trace count(1 or greater): - - - - - - - 1000 - - - - - - - Tracing will start if this condition is met - - - Trigger condition(Optional, gdb expression): - - - - - - - - - - Tracing will stop whenever this condition is met - - - Stop condition(Optional, gdb expression): - - - - - - - - - - Step over instead of single step - - - - - - - Stop when tracing ends - - - - - - - Collect registers - - - true - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.py b/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.py deleted file mode 100644 index 6cdc2c96..00000000 --- a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.py +++ /dev/null @@ -1,46 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(194, 93) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.label_Animated = QtWidgets.QLabel(parent=Form) - self.label_Animated.setText("") - self.label_Animated.setObjectName("label_Animated") - self.verticalLayout.addWidget(self.label_Animated) - self.label_StatusText = QtWidgets.QLabel(parent=Form) - self.label_StatusText.setText("") - self.label_StatusText.setObjectName("label_StatusText") - self.verticalLayout.addWidget(self.label_StatusText) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.pushButton_Cancel = QtWidgets.QPushButton(parent=Form) - self.pushButton_Cancel.setObjectName("pushButton_Cancel") - self.horizontalLayout.addWidget(self.pushButton_Cancel) - spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem1) - self.verticalLayout.addLayout(self.horizontalLayout) - self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Tracer Status")) - self.pushButton_Cancel.setText(_translate("Form", "Cancel")) diff --git a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.ui b/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.ui deleted file mode 100644 index c07e5474..00000000 --- a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWaitWidget.ui +++ /dev/null @@ -1,76 +0,0 @@ - - - Form - - - - 0 - 0 - 194 - 93 - - - - Tracer Status - - - - - - - - - - - - - - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Cancel - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - diff --git a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWindow.py b/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWindow.py deleted file mode 100644 index 6fad9528..00000000 --- a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWindow.py +++ /dev/null @@ -1,66 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TraceInstructions/Form/TraceInstructionsWindow.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.resize(704, 545) - self.centralwidget = QtWidgets.QWidget(parent=MainWindow) - self.centralwidget.setObjectName("centralwidget") - self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) - self.gridLayout.setObjectName("gridLayout") - self.splitter = QtWidgets.QSplitter(parent=self.centralwidget) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter.setObjectName("splitter") - self.treeWidget_InstructionInfo = QtWidgets.QTreeWidget(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.treeWidget_InstructionInfo.setFont(font) - self.treeWidget_InstructionInfo.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.treeWidget_InstructionInfo.setObjectName("treeWidget_InstructionInfo") - self.treeWidget_InstructionInfo.headerItem().setText(0, "1") - self.treeWidget_InstructionInfo.header().setVisible(False) - self.textBrowser_RegisterInfo = QtWidgets.QTextBrowser(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_RegisterInfo.setFont(font) - self.textBrowser_RegisterInfo.setObjectName("textBrowser_RegisterInfo") - self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) - MainWindow.setCentralWidget(self.centralwidget) - self.menubar = QtWidgets.QMenuBar(parent=MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 704, 22)) - self.menubar.setObjectName("menubar") - self.menuFile = QtWidgets.QMenu(parent=self.menubar) - self.menuFile.setObjectName("menuFile") - MainWindow.setMenuBar(self.menubar) - self.statusbar = QtWidgets.QStatusBar(parent=MainWindow) - self.statusbar.setObjectName("statusbar") - MainWindow.setStatusBar(self.statusbar) - self.actionOpen = QtGui.QAction(parent=MainWindow) - self.actionOpen.setObjectName("actionOpen") - self.actionSave = QtGui.QAction(parent=MainWindow) - self.actionSave.setObjectName("actionSave") - self.actionSave_as_a_text_file = QtGui.QAction(parent=MainWindow) - self.actionSave_as_a_text_file.setObjectName("actionSave_as_a_text_file") - self.menuFile.addAction(self.actionOpen) - self.menuFile.addAction(self.actionSave) - self.menubar.addAction(self.menuFile.menuAction()) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - _translate = QtCore.QCoreApplication.translate - MainWindow.setWindowTitle(_translate("MainWindow", "Tracer")) - self.menuFile.setTitle(_translate("MainWindow", "File")) - self.actionOpen.setText(_translate("MainWindow", "Open")) - self.actionSave.setText(_translate("MainWindow", "Save")) - self.actionSave_as_a_text_file.setText(_translate("MainWindow", "Save as a text file")) diff --git a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWindow.ui b/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWindow.ui deleted file mode 100644 index 76fddbdf..00000000 --- a/GUI/Widgets/TraceInstructions/Form/TraceInstructionsWindow.ui +++ /dev/null @@ -1,89 +0,0 @@ - - - MainWindow - - - - 0 - 0 - 704 - 545 - - - - Tracer - - - - - - - Qt::Horizontal - - - - - Monospace - - - - QAbstractItemView::NoEditTriggers - - - false - - - - 1 - - - - - - - Monospace - - - - - - - - - - - 0 - 0 - 704 - 22 - - - - - File - - - - - - - - - - Open - - - - - Save - - - - - Save as a text file - - - - - - diff --git a/GUI/Widgets/TraceInstructions/TraceInstructionsPromptDialog.py b/GUI/Widgets/TraceInstructions/TraceInstructionsPromptDialog.py deleted file mode 100644 index a03d7195..00000000 --- a/GUI/Widgets/TraceInstructions/TraceInstructionsPromptDialog.py +++ /dev/null @@ -1,37 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget, QMessageBox -from GUI.Utils import guiutils -from GUI.Widgets.TraceInstructions.Form.TraceInstructionsPromptDialog import Ui_Dialog -from libpince import typedefs -from tr.tr import TranslationConstants as tr - - -class TraceInstructionsPromptDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - guiutils.center_to_parent(self) - - def get_values(self) -> tuple[int, str, str, int, bool, bool]: - try: - max_trace_count = int(self.lineEdit_MaxTraceCount.text()) - except ValueError: - max_trace_count = 0 - trigger_condition = self.lineEdit_TriggerCondition.text() - stop_condition = self.lineEdit_StopCondition.text() - if self.checkBox_StepOver.isChecked(): - step_mode = typedefs.STEP_MODE.STEP_OVER - else: - step_mode = typedefs.STEP_MODE.SINGLE_STEP - stop_after_trace = self.checkBox_StopAfterTrace.isChecked() - collect_registers = self.checkBox_CollectRegisters.isChecked() - return max_trace_count, trigger_condition, stop_condition, step_mode, stop_after_trace, collect_registers - - def accept(self) -> None: - try: - max_trace_count = int(self.lineEdit_MaxTraceCount.text()) - except ValueError: - max_trace_count = 0 - if max_trace_count >= 1: - super().accept() - else: - QMessageBox.information(self, tr.ERROR, tr.MAX_TRACE_COUNT_ASSERT_GT.format(1)) diff --git a/GUI/Widgets/TraceInstructions/TraceInstructionsWaitWidget.py b/GUI/Widgets/TraceInstructions/TraceInstructionsWaitWidget.py deleted file mode 100644 index ee85e5ca..00000000 --- a/GUI/Widgets/TraceInstructions/TraceInstructionsWaitWidget.py +++ /dev/null @@ -1,61 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QApplication -from PyQt6.QtGui import QMovie, QCloseEvent -from PyQt6.QtCore import Qt, QTimer, QByteArray, QSize, pyqtSignal -from GUI.Utils import guitypedefs, guiutils -from GUI.States import states -from GUI.Widgets.TraceInstructions.Form.TraceInstructionsWaitWidget import Ui_Form -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr -from time import sleep - - -class TraceInstructionsWaitWidget(QWidget, Ui_Form): - widget_closed = pyqtSignal() - - def __init__(self, parent: QWidget, address: str, tracer: debugcore.Tracer) -> None: - super().__init__(parent) - self.setupUi(self) - self.status_to_text = { - typedefs.TRACE_STATUS.IDLE: tr.WAITING_FOR_BREAKPOINT, - typedefs.TRACE_STATUS.FINISHED: tr.TRACING_COMPLETED, - } - self.setWindowFlags(Qt.WindowType.Window) - self.address = address - self.tracer = tracer - media_directory = utils.get_media_directory() - self.movie = QMovie(media_directory + "/TraceInstructionsWaitWidget/ajax-loader.gif", QByteArray()) - self.label_Animated.setMovie(self.movie) - self.movie.setScaledSize(QSize(215, 100)) - self.movie.setCacheMode(QMovie.CacheMode.CacheAll) - self.movie.setSpeed(100) - self.movie.start() - self.pushButton_Cancel.clicked.connect(self.close) - tracer_thread = guitypedefs.Worker(tracer.tracer_loop) - tracer_thread.signals.finished.connect(self.close) - states.threadpool.start(tracer_thread) - self.status_timer = QTimer(self) - self.status_timer.setInterval(50) - self.status_timer.timeout.connect(self.change_status) - self.status_timer.start() - guiutils.center_to_parent(self) - - def change_status(self) -> None: - if self.tracer.trace_status == typedefs.TRACE_STATUS.TRACING: - self.label_StatusText.setText(f"{self.tracer.current_trace_count} / {self.tracer.max_trace_count}") - else: - self.label_StatusText.setText(self.status_to_text[self.tracer.trace_status]) - QApplication.processEvents() - - def closeEvent(self, event: QCloseEvent) -> None: - self.status_timer.stop() - self.label_StatusText.setText(tr.TRACING_COMPLETED) - self.pushButton_Cancel.setVisible(False) - self.adjustSize() - QApplication.processEvents() - if self.tracer.trace_status != typedefs.TRACE_STATUS.FINISHED: - self.tracer.cancel_trace() - while self.tracer.trace_status != typedefs.TRACE_STATUS.FINISHED: - sleep(0.1) - QApplication.processEvents() - self.widget_closed.emit() - super().closeEvent(event) diff --git a/GUI/Widgets/TraceInstructions/TraceInstructionsWindow.py b/GUI/Widgets/TraceInstructions/TraceInstructionsWindow.py deleted file mode 100644 index f512cd35..00000000 --- a/GUI/Widgets/TraceInstructions/TraceInstructionsWindow.py +++ /dev/null @@ -1,120 +0,0 @@ -from PyQt6.QtWidgets import QMainWindow, QWidget, QMessageBox, QMenu, QFileDialog, QTreeWidgetItem -from PyQt6.QtGui import QCloseEvent, QContextMenuEvent -from GUI.Utils import guiutils -from GUI.Widgets.TraceInstructions.Form.TraceInstructionsWindow import Ui_MainWindow -from GUI.Widgets.TraceInstructions.TraceInstructionsPromptDialog import TraceInstructionsPromptDialog -from GUI.Widgets.TraceInstructions.TraceInstructionsWaitWidget import TraceInstructionsWaitWidget -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr -import copy -import os - - -class TraceInstructionsWindow(QMainWindow, Ui_MainWindow): - def __init__(self, parent: QWidget, address: str = "", prompt_dialog: bool = True) -> None: - super().__init__(parent) - self.setupUi(self) - self.address = address - self.tracer = debugcore.Tracer() - self.treeWidget_InstructionInfo.currentItemChanged.connect(self.display_collected_data) - self.treeWidget_InstructionInfo.itemDoubleClicked.connect(self.treeWidget_InstructionInfo_item_double_clicked) - self.treeWidget_InstructionInfo.contextMenuEvent = self.treeWidget_InstructionInfo_context_menu_event - self.actionOpen.triggered.connect(self.load_file) - self.actionSave.triggered.connect(self.save_file) - self.splitter.setStretchFactor(0, 1) - guiutils.center_to_parent(self) - if not prompt_dialog: - self.showMaximized() - return - prompt_dialog = TraceInstructionsPromptDialog(self) - if prompt_dialog.exec(): - params = (address,) + prompt_dialog.get_values() - breakpoint = self.tracer.set_breakpoint(*params) - if not breakpoint: - QMessageBox.information(self, tr.ERROR, tr.BREAKPOINT_FAILED.format(address)) - self.close() - return - self.showMaximized() - self.wait_dialog = TraceInstructionsWaitWidget(self, address, self.tracer) - self.wait_dialog.widget_closed.connect(self.show_trace_info) - self.wait_dialog.show() - else: - self.close() - - def closeEvent(self, event: QCloseEvent) -> None: - wait_dialog = getattr(self, "wait_dialog", None) - if wait_dialog is not None: - wait_dialog.close() - super().closeEvent(event) - - def display_collected_data(self, QTreeWidgetItem_current: QTreeWidgetItem) -> None: - if QTreeWidgetItem_current is None: - return - self.textBrowser_RegisterInfo.clear() - current_dict = QTreeWidgetItem_current.trace_data[1] - if current_dict: - for key in current_dict: - self.textBrowser_RegisterInfo.append(str(key) + " = " + str(current_dict[key])) - self.textBrowser_RegisterInfo.verticalScrollBar().setValue(self.textBrowser_RegisterInfo.verticalScrollBar().minimum()) - - def show_trace_info(self) -> None: - self.treeWidget_InstructionInfo.setStyleSheet("QTreeWidget::item{ height: 16px; }") - parent = QTreeWidgetItem(self.treeWidget_InstructionInfo) - self.treeWidget_InstructionInfo.setRootIndex(self.treeWidget_InstructionInfo.indexFromItem(parent)) - trace_tree, current_root_index = copy.deepcopy(self.tracer.trace_data) - while current_root_index is not None: - try: - current_index = trace_tree[current_root_index][2][0] # Get the first child - current_item = trace_tree[current_index][0] - del trace_tree[current_root_index][2][0] # Delete it - except IndexError: # We've depleted the children - current_root_index = trace_tree[current_root_index][1] # traverse upwards - parent = parent.parent() - continue - child = QTreeWidgetItem(parent) - child.trace_data = current_item - child.setText(0, current_item[0]) - if trace_tree[current_index][2]: # If current item has children, traverse them - current_root_index = current_index # traverse downwards - parent = child - self.treeWidget_InstructionInfo.expandAll() - - def save_file(self) -> None: - with guiutils.save_dialog_as_user(self, tr.SAVE_TRACE_FILE, os.path.expanduser("~"), tr.FILE_TYPES_TRACE, "trace") as file_path: - if file_path and not utils.save_file(self.tracer.trace_data, file_path): - QMessageBox.information(self, tr.ERROR, tr.FILE_SAVE_ERROR) - - def load_file(self) -> None: - file_path, _ = QFileDialog.getOpenFileName(self, tr.OPEN_TRACE_FILE, os.path.expanduser("~"), tr.FILE_TYPES_TRACE) - if file_path: - content = utils.load_file(file_path) - if content is None: - QMessageBox.information(self, tr.ERROR, tr.FILE_LOAD_ERROR.format(file_path)) - return - self.treeWidget_InstructionInfo.clear() - self.tracer.trace_data = content - self.show_trace_info() - - def treeWidget_InstructionInfo_context_menu_event(self, event: QContextMenuEvent) -> None: - menu = QMenu() - expand_all = menu.addAction(tr.EXPAND_ALL) - collapse_all = menu.addAction(tr.COLLAPSE_ALL) - font_size = self.treeWidget_InstructionInfo.font().pointSize() - menu.setStyleSheet("font-size: " + str(font_size) + "pt;") - action = menu.exec(event.globalPos()) - actions = { - expand_all: self.treeWidget_InstructionInfo.expandAll, - collapse_all: self.treeWidget_InstructionInfo.collapseAll, - } - try: - actions[action]() - except KeyError: - pass - - def treeWidget_InstructionInfo_item_double_clicked(self, index: QTreeWidgetItem) -> None: - current_item = guiutils.get_current_item(self.treeWidget_InstructionInfo) - if not current_item: - return - address = utils.extract_hex_address(current_item.trace_data[0]) - if address: - self.parent().disassemble_expression(address) diff --git a/GUI/Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.py b/GUI/Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.py deleted file mode 100644 index afa9400d..00000000 --- a/GUI/Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.py +++ /dev/null @@ -1,69 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(549, 437) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.tableWidget_TrackInfo = QtWidgets.QTableWidget(parent=Form) - self.tableWidget_TrackInfo.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_TrackInfo.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_TrackInfo.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_TrackInfo.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollMode.ScrollPerPixel) - self.tableWidget_TrackInfo.setWordWrap(False) - self.tableWidget_TrackInfo.setObjectName("tableWidget_TrackInfo") - self.tableWidget_TrackInfo.setColumnCount(4) - self.tableWidget_TrackInfo.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_TrackInfo.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_TrackInfo.setHorizontalHeaderItem(1, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_TrackInfo.setHorizontalHeaderItem(2, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_TrackInfo.setHorizontalHeaderItem(3, item) - self.tableWidget_TrackInfo.horizontalHeader().setStretchLastSection(True) - self.tableWidget_TrackInfo.verticalHeader().setVisible(False) - self.tableWidget_TrackInfo.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_TrackInfo.verticalHeader().setMinimumSectionSize(16) - self.gridLayout.addWidget(self.tableWidget_TrackInfo, 0, 0, 1, 1) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.pushButton_Stop = QtWidgets.QPushButton(parent=Form) - self.pushButton_Stop.setObjectName("pushButton_Stop") - self.horizontalLayout.addWidget(self.pushButton_Stop) - spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum) - self.horizontalLayout.addItem(spacerItem) - self.comboBox_ValueType = QtWidgets.QComboBox(parent=Form) - self.comboBox_ValueType.setToolTip("") - self.comboBox_ValueType.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToContents) - self.comboBox_ValueType.setObjectName("comboBox_ValueType") - self.horizontalLayout.addWidget(self.comboBox_ValueType) - self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) - - self.retranslateUi(Form) - self.comboBox_ValueType.setCurrentIndex(-1) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Form")) - item = self.tableWidget_TrackInfo.horizontalHeaderItem(0) - item.setText(_translate("Form", "Count")) - item = self.tableWidget_TrackInfo.horizontalHeaderItem(1) - item.setText(_translate("Form", "Address")) - item = self.tableWidget_TrackInfo.horizontalHeaderItem(2) - item.setText(_translate("Form", "Value")) - item = self.tableWidget_TrackInfo.horizontalHeaderItem(3) - item.setText(_translate("Form", "Source")) - self.pushButton_Stop.setText(_translate("Form", "Stop")) diff --git a/GUI/Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.ui b/GUI/Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.ui deleted file mode 100644 index c525bf20..00000000 --- a/GUI/Widgets/TrackBreakpoint/Form/TrackBreakpointWidget.ui +++ /dev/null @@ -1,109 +0,0 @@ - - - Form - - - - 0 - 0 - 549 - 437 - - - - Form - - - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - QAbstractItemView::ScrollPerPixel - - - false - - - true - - - false - - - 16 - - - 16 - - - - Count - - - - - Address - - - - - Value - - - - - Source - - - - - - - - - - Stop - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - -1 - - - QComboBox::AdjustToContents - - - - - - - - - - diff --git a/GUI/Widgets/TrackBreakpoint/TrackBreakpoint.py b/GUI/Widgets/TrackBreakpoint/TrackBreakpoint.py deleted file mode 100644 index b5695d52..00000000 --- a/GUI/Widgets/TrackBreakpoint/TrackBreakpoint.py +++ /dev/null @@ -1,114 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMessageBox -from PyQt6.QtGui import QCloseEvent -from PyQt6.QtCore import Qt, QTimer, QModelIndex -from GUI.States import states -from GUI.Utils import guiutils -from GUI.Widgets.TrackBreakpoint.Form.TrackBreakpointWidget import Ui_Form -from libpince import debugcore, utils -from tr.tr import TranslationConstants as tr -import os - -# represents the index of columns in track breakpoint table(which addresses this instruction accesses thingy) -TRACK_BREAKPOINT_COUNT_COL = 0 -TRACK_BREAKPOINT_ADDR_COL = 1 -TRACK_BREAKPOINT_VALUE_COL = 2 -TRACK_BREAKPOINT_SOURCE_COL = 3 - - -class TrackBreakpointWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget, address: str, instruction: str, register_expressions: str) -> None: - super().__init__(parent) - self.setupUi(self) - self.update_list_timer = QTimer(self, timeout=self.update_list) - self.update_values_timer = QTimer(self, timeout=self.update_values) - self.stopped = False - self.address = address - self.pid = debugcore.currentpid - self.info = {} - self.last_selected_row = 0 - self.setWindowFlags(Qt.WindowType.Window) - self.setWindowTitle(tr.ACCESSED_BY_INSTRUCTION.format(instruction)) - guiutils.center_to_parent(self) # Called before the QMessageBox to center its position properly - self.breakpoint = debugcore.track_breakpoint(address, register_expressions) - if not self.breakpoint: - QMessageBox.information(self, tr.ERROR, tr.TRACK_BREAKPOINT_FAILED.format(address)) - self.close() - return - states.process_signals.attach.connect(self.close) - states.process_signals.exit.connect(self.close) - guiutils.fill_value_combobox(self.comboBox_ValueType) - self.pushButton_Stop.clicked.connect(self.pushButton_Stop_clicked) - self.tableWidget_TrackInfo.itemDoubleClicked.connect(self.tableWidget_TrackInfo_item_double_clicked) - self.tableWidget_TrackInfo.selectionModel().currentChanged.connect(self.tableWidget_TrackInfo_current_changed) - self.comboBox_ValueType.currentIndexChanged.connect(self.update_values) - self.update_list_timer.start(100) - self.update_values_timer.start(500) - self.parent().refresh_disassemble_view() - self.show() - - def update_list(self) -> None: - if self.pid != debugcore.currentpid: - return - info = debugcore.get_track_breakpoint_info(self.breakpoint) - if not info: - return - if info == self.info: - return - self.info = info - self.tableWidget_TrackInfo.setRowCount(0) - row = 0 - for register_expression in info: - for address in info[register_expression]: - self.tableWidget_TrackInfo.setRowCount(row + 1) - self.tableWidget_TrackInfo.setItem(row, TRACK_BREAKPOINT_COUNT_COL, QTableWidgetItem(str(info[register_expression][address]))) - self.tableWidget_TrackInfo.setItem(row, TRACK_BREAKPOINT_ADDR_COL, QTableWidgetItem(address)) - self.tableWidget_TrackInfo.setItem(row, TRACK_BREAKPOINT_SOURCE_COL, QTableWidgetItem("[" + register_expression + "]")) - row += 1 - self.update_values() - - def update_values(self) -> None: - if self.pid != debugcore.currentpid: - return - with debugcore.memory_handle() as mem_handle: - value_type = self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole) - for row in range(self.tableWidget_TrackInfo.rowCount()): - address = self.tableWidget_TrackInfo.item(row, TRACK_BREAKPOINT_ADDR_COL).text() - value = debugcore.read_memory(address, value_type, mem_handle=mem_handle) - value = "" if value is None else str(value) - self.tableWidget_TrackInfo.setItem(row, TRACK_BREAKPOINT_VALUE_COL, QTableWidgetItem(value)) - guiutils.resize_to_contents(self.tableWidget_TrackInfo) - self.tableWidget_TrackInfo.selectRow(self.last_selected_row) - - def tableWidget_TrackInfo_current_changed(self, QModelIndex_current: QModelIndex) -> None: - current_row = QModelIndex_current.row() - if current_row >= 0: - self.last_selected_row = current_row - - def tableWidget_TrackInfo_item_double_clicked(self, index: QTableWidgetItem) -> None: - address = self.tableWidget_TrackInfo.item(index.row(), TRACK_BREAKPOINT_ADDR_COL).text() - vt = guiutils.configure_value_type(self.comboBox_ValueType.currentData(Qt.ItemDataRole.UserRole)) - self.parent().parent().add_entry_to_addresstable(tr.ACCESSED_BY.format(self.address), address, vt) - self.parent().parent().update_address_table() - - def pushButton_Stop_clicked(self) -> None: - if self.stopped: - self.close() - return - if not debugcore.delete_breakpoint(utils.safe_int_cast(self.breakpoint)): - QMessageBox.information(self, tr.ERROR, tr.DELETE_BREAKPOINT_FAILED.format(self.address)) - return - self.stopped = True - self.pushButton_Stop.setText(tr.CLOSE) - self.parent().refresh_disassemble_view() - - def closeEvent(self, event: QCloseEvent) -> None: - self.update_list_timer.stop() - self.update_values_timer.stop() - if self.breakpoint: - if not self.stopped and self.pid == debugcore.currentpid: - debugcore.delete_breakpoint(utils.safe_int_cast(self.breakpoint)) - breakpoint_file = utils.get_track_breakpoint_file(self.pid, self.breakpoint) - if os.path.exists(breakpoint_file): - os.remove(breakpoint_file) - self.parent().refresh_disassemble_view() - super().closeEvent(event) diff --git a/GUI/Widgets/TrackSelector/Form/TrackSelectorDialog.py b/GUI/Widgets/TrackSelector/Form/TrackSelectorDialog.py deleted file mode 100644 index fc360d1e..00000000 --- a/GUI/Widgets/TrackSelector/Form/TrackSelectorDialog.py +++ /dev/null @@ -1,39 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TrackSelector/Form/TrackSelectorDialog.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.resize(165, 99) - Dialog.setWindowTitle("") - self.gridLayout = QtWidgets.QGridLayout(Dialog) - self.gridLayout.setObjectName("gridLayout") - self.verticalLayout = QtWidgets.QVBoxLayout() - self.verticalLayout.setObjectName("verticalLayout") - self.label = QtWidgets.QLabel(parent=Dialog) - self.label.setObjectName("label") - self.verticalLayout.addWidget(self.label) - self.pushButton_Pointer = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Pointer.setObjectName("pushButton_Pointer") - self.verticalLayout.addWidget(self.pushButton_Pointer) - self.pushButton_Pointed = QtWidgets.QPushButton(parent=Dialog) - self.pushButton_Pointed.setObjectName("pushButton_Pointed") - self.verticalLayout.addWidget(self.pushButton_Pointed) - self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1) - - self.retranslateUi(Dialog) - QtCore.QMetaObject.connectSlotsByName(Dialog) - - def retranslateUi(self, Dialog): - _translate = QtCore.QCoreApplication.translate - self.label.setText(_translate("Dialog", "Select an address to track")) - self.pushButton_Pointer.setText(_translate("Dialog", "Pointer")) - self.pushButton_Pointed.setText(_translate("Dialog", "Pointed Address")) diff --git a/GUI/Widgets/TrackSelector/Form/TrackSelectorDialog.ui b/GUI/Widgets/TrackSelector/Form/TrackSelectorDialog.ui deleted file mode 100644 index a0067453..00000000 --- a/GUI/Widgets/TrackSelector/Form/TrackSelectorDialog.ui +++ /dev/null @@ -1,46 +0,0 @@ - - - Dialog - - - - 0 - 0 - 165 - 99 - - - - - - - - - - - - Select an address to track - - - - - - - Pointer - - - - - - - Pointed Address - - - - - - - - - - diff --git a/GUI/Widgets/TrackSelector/TrackSelector.py b/GUI/Widgets/TrackSelector/TrackSelector.py deleted file mode 100644 index ca292358..00000000 --- a/GUI/Widgets/TrackSelector/TrackSelector.py +++ /dev/null @@ -1,17 +0,0 @@ -from PyQt6.QtWidgets import QDialog, QWidget -from GUI.Utils import guiutils -from GUI.Widgets.TrackSelector.Form.TrackSelectorDialog import Ui_Dialog - - -class TrackSelectorDialog(QDialog, Ui_Dialog): - def __init__(self, parent: QWidget) -> None: - super().__init__(parent) - self.setupUi(self) - self.selection = None - self.pushButton_Pointer.clicked.connect(lambda: self.change_selection("pointer")) - self.pushButton_Pointed.clicked.connect(lambda: self.change_selection("pointed")) - guiutils.center_to_parent(self) - - def change_selection(self, selection: str) -> None: - self.selection = selection - self.close() diff --git a/GUI/Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.py b/GUI/Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.py deleted file mode 100644 index 5d99dc7a..00000000 --- a/GUI/Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.py +++ /dev/null @@ -1,81 +0,0 @@ -# Form implementation generated from reading ui file 'Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.ui' -# -# Created by: PyQt6 UI code generator 6.11.0 -# -# WARNING: Any manual changes made to this file will be lost when pyuic6 is -# run again. Do not edit this file unless you know what you are doing. - - -from PyQt6 import QtCore, QtGui, QtWidgets - - -class Ui_Form(object): - def setupUi(self, Form): - Form.setObjectName("Form") - Form.resize(530, 493) - self.gridLayout = QtWidgets.QGridLayout(Form) - self.gridLayout.setObjectName("gridLayout") - self.splitter_2 = QtWidgets.QSplitter(parent=Form) - self.splitter_2.setOrientation(QtCore.Qt.Orientation.Vertical) - self.splitter_2.setObjectName("splitter_2") - self.splitter = QtWidgets.QSplitter(parent=self.splitter_2) - self.splitter.setOrientation(QtCore.Qt.Orientation.Horizontal) - self.splitter.setObjectName("splitter") - self.layoutWidget = QtWidgets.QWidget(parent=self.splitter) - self.layoutWidget.setObjectName("layoutWidget") - self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) - self.verticalLayout.setContentsMargins(0, 0, 0, 0) - self.verticalLayout.setObjectName("verticalLayout") - self.tableWidget_Addresses = QtWidgets.QTableWidget(parent=self.layoutWidget) - font = QtGui.QFont() - font.setFamily("Monospace") - self.tableWidget_Addresses.setFont(font) - self.tableWidget_Addresses.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) - self.tableWidget_Addresses.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - self.tableWidget_Addresses.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - self.tableWidget_Addresses.setWordWrap(False) - self.tableWidget_Addresses.setObjectName("tableWidget_Addresses") - self.tableWidget_Addresses.setColumnCount(2) - self.tableWidget_Addresses.setRowCount(0) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Addresses.setHorizontalHeaderItem(0, item) - item = QtWidgets.QTableWidgetItem() - self.tableWidget_Addresses.setHorizontalHeaderItem(1, item) - self.tableWidget_Addresses.horizontalHeader().setStretchLastSection(True) - self.tableWidget_Addresses.verticalHeader().setVisible(False) - self.tableWidget_Addresses.verticalHeader().setDefaultSectionSize(16) - self.tableWidget_Addresses.verticalHeader().setMinimumSectionSize(16) - self.verticalLayout.addWidget(self.tableWidget_Addresses) - self.horizontalLayout = QtWidgets.QHBoxLayout() - self.horizontalLayout.setObjectName("horizontalLayout") - self.pushButton_Refresh = QtWidgets.QPushButton(parent=self.layoutWidget) - self.pushButton_Refresh.setObjectName("pushButton_Refresh") - self.horizontalLayout.addWidget(self.pushButton_Refresh) - self.pushButton_Stop = QtWidgets.QPushButton(parent=self.layoutWidget) - self.pushButton_Stop.setObjectName("pushButton_Stop") - self.horizontalLayout.addWidget(self.pushButton_Stop) - self.verticalLayout.addLayout(self.horizontalLayout) - self.textBrowser_Info = QtWidgets.QTextBrowser(parent=self.splitter) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_Info.setFont(font) - self.textBrowser_Info.setObjectName("textBrowser_Info") - self.textBrowser_Disassemble = QtWidgets.QTextBrowser(parent=self.splitter_2) - font = QtGui.QFont() - font.setFamily("Monospace") - self.textBrowser_Disassemble.setFont(font) - self.textBrowser_Disassemble.setObjectName("textBrowser_Disassemble") - self.gridLayout.addWidget(self.splitter_2, 0, 0, 1, 1) - - self.retranslateUi(Form) - QtCore.QMetaObject.connectSlotsByName(Form) - - def retranslateUi(self, Form): - _translate = QtCore.QCoreApplication.translate - Form.setWindowTitle(_translate("Form", "Form")) - item = self.tableWidget_Addresses.horizontalHeaderItem(0) - item.setText(_translate("Form", "Count")) - item = self.tableWidget_Addresses.horizontalHeaderItem(1) - item.setText(_translate("Form", "Address")) - self.pushButton_Refresh.setText(_translate("Form", "Refresh")) - self.pushButton_Stop.setText(_translate("Form", "Stop")) diff --git a/GUI/Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.ui b/GUI/Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.ui deleted file mode 100644 index 82478a19..00000000 --- a/GUI/Widgets/TrackWatchpoint/Form/TrackWatchpointWidget.ui +++ /dev/null @@ -1,112 +0,0 @@ - - - Form - - - - 0 - 0 - 530 - 493 - - - - Form - - - - - - Qt::Orientation::Vertical - - - - Qt::Orientation::Horizontal - - - - - - - - Monospace - - - - QAbstractItemView::EditTrigger::NoEditTriggers - - - QAbstractItemView::SelectionMode::SingleSelection - - - QAbstractItemView::SelectionBehavior::SelectRows - - - false - - - true - - - false - - - 16 - - - 16 - - - - Count - - - - - Address - - - - - - - - - - Refresh - - - - - - - Stop - - - - - - - - - - - Monospace - - - - - - - - Monospace - - - - - - - - - - diff --git a/GUI/Widgets/TrackWatchpoint/TrackWatchpoint.py b/GUI/Widgets/TrackWatchpoint/TrackWatchpoint.py deleted file mode 100644 index 5178591c..00000000 --- a/GUI/Widgets/TrackWatchpoint/TrackWatchpoint.py +++ /dev/null @@ -1,112 +0,0 @@ -from PyQt6.QtWidgets import QWidget, QTableWidgetItem, QMessageBox -from PyQt6.QtGui import QCloseEvent -from PyQt6.QtCore import Qt, QTimer, QModelIndex -from GUI.States import states -from GUI.Utils import guiutils -from GUI.Widgets.TrackWatchpoint.Form.TrackWatchpointWidget import Ui_Form -from libpince import debugcore, typedefs, utils -from tr.tr import TranslationConstants as tr -import os - -# represents the index of columns in track watchpoint table(what accesses this address thingy) -TRACK_WATCHPOINT_COUNT_COL = 0 -TRACK_WATCHPOINT_ADDR_COL = 1 - - -class TrackWatchpointWidget(QWidget, Ui_Form): - def __init__(self, parent: QWidget, address: str, length: int, watchpoint_type: int) -> None: - super().__init__(parent) - self.setupUi(self) - self.setWindowFlags(Qt.WindowType.Window) - self.update_timer = QTimer(self, timeout=self.update_list) - self.stopped = False - self.address = address - self.pid = debugcore.currentpid - self.info = {} - self.last_selected_row = 0 - if watchpoint_type == typedefs.WATCHPOINT_TYPE.WRITE_ONLY: - string = tr.INSTR_WRITING_TO.format(address) - elif watchpoint_type == typedefs.WATCHPOINT_TYPE.READ_ONLY: - string = tr.INSTR_READING_FROM.format(address) - elif watchpoint_type == typedefs.WATCHPOINT_TYPE.BOTH: - string = tr.INSTR_ACCESSING_TO.format(address) - else: - raise Exception("Watchpoint type is invalid: " + str(watchpoint_type)) - self.setWindowTitle(string) - guiutils.center_to_parent(self) # Called before the QMessageBox to center its position properly - self.breakpoints = debugcore.track_watchpoint(address, length, watchpoint_type) - if not self.breakpoints: - QMessageBox.information(self, tr.ERROR, tr.TRACK_WATCHPOINT_FAILED.format(address)) - self.close() - return - states.process_signals.attach.connect(self.close) - states.process_signals.exit.connect(self.close) - self.pushButton_Stop.clicked.connect(self.pushButton_Stop_clicked) - self.pushButton_Refresh.clicked.connect(self.update_list) - self.tableWidget_Addresses.itemDoubleClicked.connect(self.tableWidget_Addresses_item_double_clicked) - self.tableWidget_Addresses.selectionModel().currentChanged.connect(self.tableWidget_Addresses_current_changed) - self.update_timer.start(100) - self.show() - - def update_list(self) -> None: - if self.pid != debugcore.currentpid: - return - info = debugcore.get_track_watchpoint_info(self.breakpoints) - if not info or self.info == info: - return - self.info = info - self.tableWidget_Addresses.setRowCount(0) - self.tableWidget_Addresses.setRowCount(len(info)) - for row, key in enumerate(info): - self.tableWidget_Addresses.setItem(row, TRACK_WATCHPOINT_COUNT_COL, QTableWidgetItem(str(info[key][0]))) - self.tableWidget_Addresses.setItem(row, TRACK_WATCHPOINT_ADDR_COL, QTableWidgetItem(info[key][1])) - guiutils.resize_to_contents(self.tableWidget_Addresses) - self.tableWidget_Addresses.selectRow(self.last_selected_row) - - def tableWidget_Addresses_current_changed(self, QModelIndex_current: QModelIndex) -> None: - current_row = QModelIndex_current.row() - if current_row >= 0: - self.last_selected_row = current_row - - info = self.info - key_list = list(info) - if not key_list: - return - self.last_selected_row = min(self.last_selected_row, len(key_list) - 1) - key = key_list[self.last_selected_row] - self.textBrowser_Info.clear() - for item in info[key][2]: - self.textBrowser_Info.append(item + "=" + str(info[key][2][item])) - self.textBrowser_Info.append(" ") - for item in info[key][3]: - self.textBrowser_Info.append(item + "=" + info[key][3][item]) - self.textBrowser_Info.verticalScrollBar().setValue(self.textBrowser_Info.verticalScrollBar().minimum()) - self.textBrowser_Disassemble.setPlainText(info[key][4]) - - def tableWidget_Addresses_item_double_clicked(self, index: QTableWidgetItem) -> None: - address = self.tableWidget_Addresses.item(index.row(), TRACK_WATCHPOINT_ADDR_COL).text() - self.parent().memory_view_window.disassemble_expression(address) - self.parent().memory_view_window.show() - self.parent().memory_view_window.activateWindow() - - def pushButton_Stop_clicked(self) -> None: - if self.stopped: - self.close() - return - # Internal chained breakpoints check will delete the rest from self.breakpoints - if not debugcore.delete_breakpoint(utils.safe_int_cast(self.breakpoints[0])): - QMessageBox.information(self, tr.ERROR, tr.DELETE_WATCHPOINT_FAILED.format(self.address)) - return - self.stopped = True - self.pushButton_Stop.setText(tr.CLOSE) - - def closeEvent(self, event: QCloseEvent) -> None: - self.update_timer.stop() - if self.breakpoints: - if not self.stopped and self.pid == debugcore.currentpid: - # Internal chained breakpoints check will delete the rest from self.breakpoints - debugcore.delete_breakpoint(utils.safe_int_cast(self.breakpoints[0])) - watchpoint_file = utils.get_track_watchpoint_file(self.pid, self.breakpoints) - if os.path.exists(watchpoint_file): - os.remove(watchpoint_file) - super().closeEvent(event) diff --git a/GUI/__init__.py b/GUI/__init__.py new file mode 100644 index 00000000..8d1c8b69 --- /dev/null +++ b/GUI/__init__.py @@ -0,0 +1 @@ + diff --git a/GUI/ui_to_py.sh b/GUI/ui_to_py.sh deleted file mode 100755 index 6bd320e6..00000000 --- a/GUI/ui_to_py.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh -SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" -cd "$SCRIPT_DIR" || exit - -venv_activator="../.venv/bin/activate" -if [ -f "$venv_activator" ]; then - . "$venv_activator" -else - echo "ERROR: Virtual environment not found, please use install.sh to install PINCE first" - exit -fi - -for uifile in Widgets/*/Form/*.ui -do - pyfile="${uifile%.ui}.py" - pyuic6 "$uifile" -o "$pyfile" -done diff --git a/Notes.txt b/Notes.txt new file mode 100644 index 00000000..1ca99485 --- /dev/null +++ b/Notes.txt @@ -0,0 +1,12 @@ +Code Relocations: + --libPINCE + GuiUtils.py is used to contain GUI related utility functions + SysUtils.py is used to contain all useful but non-GDB related libraries such as psutils + GDB_Engine.py is used to contain all GDB related functions + type_defs.py is used to contain all static&shared variable definitions + All codes that'll be injected to the inferior go to the folder "Injection" + /gdb_python_script/ contains all the python scripts that'll invoked from the gdb + PINCE.py is used to interract with GUI and other utility libraries + /media/ contains all the images, icons n' stuff + /pince-non-stop-files/ contains old codes that made the non-stop mode alive. It'll be re-implemented when the project finishes at basic level, this folder is just a... museum(?) for now +**Don't touch anything in GUI folder, it contains auto-generated codes created by pyuic diff --git a/PINCE.py b/PINCE.py old mode 100755 new mode 100644 index 1e028e48..e54464f4 --- a/PINCE.py +++ b/PINCE.py @@ -1,9 +1,8 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- +# !/usr/bin/env python3 """ -Copyright (C) 2016-2017 Korcan Karaokçu -Copyright (C) 2016-2017 Çağrı Ulaş -Copyright (C) 2016-2017 Jakob Kreuze +Copyright (C) 2016 Korcan Karaokçu +Copyright (C) 2016 Çağrı Ulaş This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -18,112 +17,1748 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ - -import importlib +from PyQt5.QtGui import QIcon, QMovie, QPixmap, QCursor, QKeySequence, QColor +from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QMessageBox, QDialog, QCheckBox, QWidget, \ + QShortcut, QKeySequenceEdit, QTabWidget, QMenu, QFileDialog +from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize, QByteArray, QSettings, QCoreApplication, QEvent, \ + QItemSelectionModel, QTimer +from time import sleep, time +from threading import Thread import os -import signal +import webbrowser import sys import traceback -from types import FrameType, TracebackType - -# Must precede the imports below in case any of the PyQt and other imports want to create bytecodes. -if os.geteuid() == 0: - sys.dont_write_bytecode = True - os.environ["PYTHONDONTWRITEBYTECODE"] = "1" # For GDB and other processes that will inherit environ. - -from PyQt6.QtCore import ( - QLibraryInfo, - QLocale, - QSettings, - QSignalBlocker, - QTranslator, -) -from PyQt6.QtWidgets import ( - QApplication, - QMessageBox, -) - -from GUI.Session.session import SessionManager -from GUI.Settings import themes -from GUI.States import states -from GUI.Widgets.MainWindow.MainWindow import MainWindow -from libpince import typedefs, utils -from tr.tr import TranslationConstants as tr -from tr.tr import get_locale -if __name__ == "__main__": - app = QApplication([]) - app.setApplicationName("PINCE") - app.setOrganizationName("PINCE") - app.setOrganizationDomain("github.io") - app.setDesktopFileName("io.github.korcankaraokcu.PINCE") - QSettings.setPath(QSettings.Format.NativeFormat, QSettings.Scope.UserScope, utils.get_user_path(typedefs.USER_PATHS.CONFIG)) - settings_instance = QSettings() - translator = QTranslator() - qt_translator = QTranslator() - try: - locale = settings_instance.value("General/locale", type=str) - except SystemError: - # We're reading the settings for the first time here - # If there's an error due to python objects, clear settings - settings_instance.clear() - locale = None - if not locale: - locale = get_locale() - # Load Qt's own translations for standard widget strings (file dialog buttons, message box buttons etc...). - # Installed before PINCE's catalog so PINCE's strings take precedence on any overlap. - translations_path = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath) - if qt_translator.load(QLocale(locale), "qtbase", "_", translations_path): - app.installTranslator(qt_translator) - locale_file = utils.get_script_directory() + f"/i18n/qm/{locale}.qm" - translator.load(locale_file) - app.installTranslator(translator) - tr.translate() - # Reload states after QApplication instance to ensure that variables are correctly initiated - # Reloading states after translations also ensures that hotkeys are correctly translated - importlib.reload(states) - importlib.reload(themes) # Needed for correct translations - - -def except_hook(exception_type: type[BaseException], value: BaseException, tb: TracebackType | None) -> None: - focused_widget = app.focusWidget() - if focused_widget and exception_type == typedefs.GDBInitializeException: - QMessageBox.information(focused_widget, tr.ERROR, tr.GDB_INIT) - traceback.print_exception(exception_type, value, tb) +from libPINCE import GuiUtils, SysUtils, GDB_Engine, type_defs + +from GUI.MainWindow import Ui_MainWindow as MainWindow +from GUI.SelectProcess import Ui_MainWindow as ProcessWindow +from GUI.AddAddressManuallyDialog import Ui_Dialog as ManualAddressDialog +from GUI.LoadingWidget import Ui_Form as LoadingWidget +from GUI.DialogWithButtons import Ui_Dialog as DialogWithButtons +from GUI.SettingsDialog import Ui_Dialog as SettingsDialog +from GUI.ConsoleWidget import Ui_Form as ConsoleWidget +from GUI.AboutWidget import Ui_TabWidget as AboutWidget +from GUI.MemoryViewerWindow import Ui_MainWindow as MemoryViewWindow +from GUI.BookmarkWidget import Ui_Form as BookmarkWidget +from GUI.FloatRegisterWidget import Ui_TabWidget as FloatRegisterWidget +from GUI.StackTraceInfoWidget import Ui_Form as StackTraceInfoWidget + +from GUI.CustomAbstractTableModels.HexModel import QHexModel +from GUI.CustomAbstractTableModels.AsciiModel import QAsciiModel + +selfpid = os.getpid() + +# settings +update_table = bool +table_update_interval = float +pause_hotkey = str +continue_hotkey = str +code_injection_method = int +bring_disassemble_to_front = bool +instructions_per_scroll = int + +# row colours for disassemble qtablewidget +PC_COLOUR = Qt.blue +BOOKMARK_COLOUR = Qt.yellow +DEFAULT_COLOUR = Qt.white + +# represents the index of columns in address table +FROZEN_COL = 0 # Frozen +DESC_COL = 1 # Description +ADDR_COL = 2 # Address +TYPE_COL = 3 # Type +VALUE_COL = 4 # Value + +# represents the index of columns in disassemble table +DISAS_ADDR_COL = 0 +DISAS_BYTES_COL = 1 +DISAS_OPCODES_COL = 2 +DISAS_COMMENT_COL = 3 + +# represents the index of columns in floating point table +FLOAT_REGISTERS_NAME_COL = 0 +FLOAT_REGISTERS_VALUE_COL = 1 + +# represents the index of columns in stacktrace table +STACKTRACE_RETURN_ADDRESS_COL = 0 +STACKTRACE_FRAME_ADDRESS_COL = 1 + +# represents the index of columns in stack table +STACK_POINTER_ADDRESS_COL = 0 +STACK_VALUE_COL = 1 +STACK_INT_REPRESENTATION_COL = 2 +STACK_FLOAT_REPRESENTATION_COL = 3 +# represents row and column counts of Hex table +HEX_VIEW_COL_COUNT = 16 +HEX_VIEW_ROW_COUNT = 42 # J-JUST A COINCIDENCE, I SWEAR! + +INDEX_BYTE = type_defs.VALUE_INDEX.INDEX_BYTE +INDEX_2BYTES = type_defs.VALUE_INDEX.INDEX_2BYTES +INDEX_4BYTES = type_defs.VALUE_INDEX.INDEX_4BYTES +INDEX_8BYTES = type_defs.VALUE_INDEX.INDEX_8BYTES +INDEX_FLOAT = type_defs.VALUE_INDEX.INDEX_FLOAT +INDEX_DOUBLE = type_defs.VALUE_INDEX.INDEX_DOUBLE +INDEX_STRING = type_defs.VALUE_INDEX.INDEX_STRING +INDEX_AOB = type_defs.VALUE_INDEX.INDEX_AOB + +INFERIOR_RUNNING = type_defs.INFERIOR_STATUS.INFERIOR_RUNNING +INFERIOR_STOPPED = type_defs.INFERIOR_STATUS.INFERIOR_STOPPED + +SIMPLE_DLOPEN_CALL = type_defs.INJECTION_METHOD.SIMPLE_DLOPEN_CALL +ADVANCED_INJECTION = type_defs.INJECTION_METHOD.ADVANCED_INJECTION + +ARCH_32 = type_defs.INFERIOR_ARCH.ARCH_32 +ARCH_64 = type_defs.INFERIOR_ARCH.ARCH_64 # From version 5.5 and onwards, PyQT calls qFatal() when an exception has been encountered # So, we must override sys.excepthook to avoid calling of qFatal() -sys.excepthook = except_hook +sys.excepthook = traceback.print_exception -# Assigned in __main__ -window: "MainWindow | None" = None +# Checks if the inferior has been terminated +class AwaitProcessExit(QThread): + process_exited = pyqtSignal() + def run(self): + while GDB_Engine.currentpid is 0 or SysUtils.is_process_valid(GDB_Engine.currentpid): + sleep(0.01) + self.process_exited.emit() -def signal_handler(signal: int, frame: FrameType | None) -> None: - with QSignalBlocker(app): - app.quit() +# Await async output from gdb +class AwaitAsyncOutput(QThread): + async_output_ready = pyqtSignal() -signal.signal(signal.SIGINT, signal_handler) -signal.signal(signal.SIGTERM, signal_handler) -signal.signal(signal.SIGHUP, signal_handler) + def run(self): + while True: + with GDB_Engine.gdb_async_condition: + GDB_Engine.gdb_async_condition.wait() + self.async_output_ready.emit() -def handle_exit() -> None: - states.exiting = True - if window is not None and window.update_check_thread is not None: - window.update_check_thread.wait() +class CheckInferiorStatus(QThread): + process_stopped = pyqtSignal() + process_running = pyqtSignal() + def run(self): + while True: + with GDB_Engine.status_changed_condition: + GDB_Engine.status_changed_condition.wait() + if GDB_Engine.inferior_status is INFERIOR_STOPPED: + self.process_stopped.emit() + else: + self.process_running.emit() -if __name__ == "__main__": - app.aboutToQuit.connect(handle_exit) - window = MainWindow() - window.show() - if len(sys.argv) > 1 and sys.argv[1]: - real_path = os.path.realpath(sys.argv[1]) - SessionManager.load_session(real_path) +class UpdateAddressTableThread(QThread): + update_table_signal = pyqtSignal() + + def run(self): + while True: + while not update_table: + sleep(0.1) + if GDB_Engine.inferior_status is INFERIOR_STOPPED: + self.update_table_signal.emit() + sleep(table_update_interval) + + +# the mainwindow +class MainForm(QMainWindow, MainWindow): + def __init__(self): + super().__init__() + self.setupUi(self) + GuiUtils.center(self) + self.tableWidget_addresstable.setColumnWidth(FROZEN_COL, 25) + self.tableWidget_addresstable.setColumnWidth(DESC_COL, 150) + self.tableWidget_addresstable.setColumnWidth(ADDR_COL, 150) + self.tableWidget_addresstable.setColumnWidth(TYPE_COL, 120) + QCoreApplication.setOrganizationName("PINCE") + QCoreApplication.setOrganizationDomain("github.com/korcankaraokcu/PINCE") + QCoreApplication.setApplicationName("PINCE") + self.settings = QSettings() + if not SysUtils.is_path_valid(self.settings.fileName()): + self.set_default_settings() + try: + self.apply_settings() + except Exception as e: + print(e) + self.settings.clear() + self.set_default_settings() + self.memory_view_window = MemoryViewWindowForm() + self.memory_view_window.address_added.connect(self.add_entry_to_addresstable) + self.await_exit_thread = AwaitProcessExit() + self.await_exit_thread.process_exited.connect(self.on_inferior_exit) + self.await_exit_thread.start() + self.check_status_thread = CheckInferiorStatus() + self.check_status_thread.process_stopped.connect(self.on_status_stopped) + self.check_status_thread.process_running.connect(self.on_status_running) + self.check_status_thread.process_stopped.connect(self.memory_view_window.process_stopped) + self.check_status_thread.process_running.connect(self.memory_view_window.process_running) + self.check_status_thread.start() + self.update_address_table_thread = UpdateAddressTableThread() + self.update_address_table_thread.update_table_signal.connect(self.update_address_table_manually) + self.update_address_table_thread.start() + self.shortcut_pause = QShortcut(QKeySequence(pause_hotkey), self) + self.shortcut_pause.activated.connect(self.pause_hotkey_pressed) + self.shortcut_continue = QShortcut(QKeySequence(continue_hotkey), self) + self.shortcut_continue.activated.connect(self.continue_hotkey_pressed) + self.tableWidget_addresstable.keyPressEvent = self.tableWidget_addresstable_keyPressEvent + self.tableWidget_addresstable.contextMenuEvent = self.tableWidget_addresstable_context_menu_event + self.processbutton.clicked.connect(self.processbutton_onclick) + self.pushButton_NewFirstScan.clicked.connect(self.newfirstscan_onclick) + self.pushButton_NextScan.clicked.connect(self.nextscan_onclick) + self.pushButton_Settings.clicked.connect(self.settingsbutton_onclick) + self.pushButton_Console.clicked.connect(self.consolebutton_onclick) + self.pushButton_Wiki.clicked.connect(self.wikibutton_onclick) + self.pushButton_About.clicked.connect(self.aboutbutton_onclick) + self.pushButton_AddAddressManually.clicked.connect(self.addaddressmanually_onclick) + self.pushButton_MemoryView.clicked.connect(self.memoryview_onlick) + self.pushButton_RefreshAdressTable.clicked.connect(self.update_address_table_manually) + self.pushButton_CleanAddressTable.clicked.connect(self.delete_address_table_contents) + self.tableWidget_addresstable.itemDoubleClicked.connect(self.on_address_table_double_click) + icons_directory = SysUtils.get_current_script_directory() + "/media/icons" + self.processbutton.setIcon(QIcon(QPixmap(icons_directory + "/monitor.png"))) + self.pushButton_Open.setIcon(QIcon(QPixmap(icons_directory + "/folder.png"))) + self.pushButton_Save.setIcon(QIcon(QPixmap(icons_directory + "/disk.png"))) + self.pushButton_Settings.setIcon(QIcon(QPixmap(icons_directory + "/wrench.png"))) + self.pushButton_CopyToAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/arrow_down.png"))) + self.pushButton_CleanAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/bin_closed.png"))) + self.pushButton_RefreshAdressTable.setIcon(QIcon(QPixmap(icons_directory + "/table_refresh.png"))) + self.pushButton_Console.setIcon(QIcon(QPixmap(icons_directory + "/application_xp_terminal.png"))) + self.pushButton_Wiki.setIcon(QIcon(QPixmap(icons_directory + "/book_open.png"))) + self.pushButton_About.setIcon(QIcon(QPixmap(icons_directory + "/information.png"))) + + def set_default_settings(self): + self.settings.beginGroup("General") + self.settings.setValue("auto_update_address_table", True) + self.settings.setValue("address_table_update_interval", 0.5) + self.settings.endGroup() + self.settings.beginGroup("Hotkeys") + self.settings.setValue("pause", "F2") + self.settings.setValue("continue", "F3") + self.settings.endGroup() + self.settings.beginGroup("CodeInjection") + self.settings.setValue("code_injection_method", SIMPLE_DLOPEN_CALL) + self.settings.endGroup() + self.settings.beginGroup("Disassemble") + self.settings.setValue("bring_disassemble_to_front", False) + self.settings.setValue("instructions_per_scroll", 2) + self.settings.endGroup() + self.apply_settings() + + def apply_settings(self): + global update_table + global table_update_interval + global pause_hotkey + global continue_hotkey + global code_injection_method + global bring_disassemble_to_front + global instructions_per_scroll + update_table = self.settings.value("General/auto_update_address_table", type=bool) + table_update_interval = self.settings.value("General/address_table_update_interval", type=float) + pause_hotkey = self.settings.value("Hotkeys/pause") + continue_hotkey = self.settings.value("Hotkeys/continue") + try: + self.shortcut_pause.setKey(QKeySequence(pause_hotkey)) + except AttributeError: + pass + try: + self.shortcut_continue.setKey(QKeySequence(continue_hotkey)) + except AttributeError: + pass + try: + self.memory_view_window.set_dynamic_debug_hotkeys() + except AttributeError: + pass + code_injection_method = self.settings.value("CodeInjection/code_injection_method", type=int) + bring_disassemble_to_front = self.settings.value("Disassemble/bring_disassemble_to_front", type=bool) + instructions_per_scroll = self.settings.value("Disassemble/instructions_per_scroll", type=int) + + def pause_hotkey_pressed(self): + GDB_Engine.interrupt_inferior() + + def continue_hotkey_pressed(self): + GDB_Engine.continue_inferior() + + def tableWidget_addresstable_context_menu_event(self, event): + menu = QMenu() + browse_region = menu.addAction("Browse this memory region[B]") + menu.addSeparator() + font_size = self.tableWidget_addresstable.font().pointSize() + menu.setStyleSheet("font-size: " + str(font_size) + "pt;") + action = menu.exec_(event.globalPos()) + if action == browse_region: + self.browse_region_for_selected_row() + + def browse_region_for_selected_row(self): + last_selected_row = self.tableWidget_addresstable.selectionModel().selectedRows()[-1].row() + self.memory_view_window.hex_dump_address( + int(self.tableWidget_addresstable.item(last_selected_row, ADDR_COL).text(), 16)) + self.memory_view_window.show() + self.memory_view_window.activateWindow() + + def tableWidget_addresstable_keyPressEvent(self, e): + if e.key() == Qt.Key_Delete: + selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows() + for item in selected_rows: + self.tableWidget_addresstable.removeRow(item.row()) + if e.key() == Qt.Key_B: + self.browse_region_for_selected_row() + + def update_address_table_manually(self): + table_contents = [] + row_count = self.tableWidget_addresstable.rowCount() + for row in range(row_count): + address = self.tableWidget_addresstable.item(row, ADDR_COL).text() + index, length, unicode, zero_terminate = GuiUtils.text_to_valuetype( + self.tableWidget_addresstable.item(row, TYPE_COL).text()) + table_contents.append([address, index, length, unicode, zero_terminate]) + new_table_contents = GDB_Engine.read_multiple_addresses(table_contents) + for row, item in enumerate(new_table_contents): + self.tableWidget_addresstable.setItem(row, VALUE_COL, QTableWidgetItem(str(item))) + + # gets the information from the dialog then adds it to addresstable + def addaddressmanually_onclick(self): + manual_address_dialog = ManualAddressDialogForm() + if manual_address_dialog.exec_(): + description, address, typeofaddress, length, unicode, zero_terminate = manual_address_dialog.get_values() + self.add_entry_to_addresstable(description=description, address=address, typeofaddress=typeofaddress, + length=length, unicode=unicode, + zero_terminate=zero_terminate) + + def memoryview_onlick(self): + self.memory_view_window.showMaximized() + self.memory_view_window.activateWindow() + + def wikibutton_onclick(self): + webbrowser.open("https://github.com/korcankaraokcu/PINCE/wiki") + + def aboutbutton_onclick(self): + self.about_widget = AboutWidgetForm() + self.about_widget.show() + + def settingsbutton_onclick(self): + settings_dialog = SettingsDialogForm() + settings_dialog.reset_settings.connect(self.set_default_settings) + if settings_dialog.exec_(): + self.apply_settings() + + def consolebutton_onclick(self): + self.console_widget = ConsoleWidgetForm() + self.console_widget.show() + + def newfirstscan_onclick(self): + print("Exception test") + x = 0 / 0 + if self.pushButton_NewFirstScan.text() == "First Scan": + self.pushButton_NextScan.setEnabled(True) + self.pushButton_UndoScan.setEnabled(True) + self.pushButton_NewFirstScan.setText("New Scan") + return + if self.pushButton_NewFirstScan.text() == "New Scan": + self.pushButton_NextScan.setEnabled(False) + self.pushButton_UndoScan.setEnabled(False) + self.pushButton_NewFirstScan.setText("First Scan") + + def nextscan_onclick(self): + # GDB_Engine.send_command('interrupt\nx _start\nc &') # test + GDB_Engine.send_command("x/100x _start") + # t = Thread(target=GDB_Engine.test) # test + # t2=Thread(target=test2) + # t.start() + # t2.start() + if self.tableWidget_valuesearchtable.rowCount() <= 0: + return + + # shows the process select window + def processbutton_onclick(self): + self.processwindow = ProcessForm(self) + self.processwindow.show() + + def delete_address_table_contents(self): + confirm_dialog = DialogWithButtonsForm(label_text="This will clear the contents of address table\n\tProceed?") + if confirm_dialog.exec_(): + self.tableWidget_addresstable.setRowCount(0) + + def on_inferior_exit(self): + GDB_Engine.detach() + self.on_status_running() + self.label_SelectedProcess.setText("No Process Selected") + QMessageBox.information(self, "Warning", "Process has been terminated") + self.await_exit_thread.start() + + def on_status_stopped(self): + self.label_SelectedProcess.setStyleSheet("color: red") + self.label_InferiorStatus.setText("[stopped]") + self.label_InferiorStatus.setVisible(True) + self.label_InferiorStatus.setStyleSheet("color: red") + self.update_address_table_manually() + + def on_status_running(self): + self.label_SelectedProcess.setStyleSheet("") + self.label_InferiorStatus.setVisible(False) + + # closes all windows on exit + def closeEvent(self, event): + if not GDB_Engine.currentpid == 0: + GDB_Engine.detach() + application = QApplication.instance() + application.closeAllWindows() + + def add_entry_to_addresstable(self, description, address, typeofaddress, length=0, unicode=False, + zero_terminate=True): + frozen_checkbox = QCheckBox() + typeofaddress_text = GuiUtils.valuetype_to_text(typeofaddress, length, unicode, zero_terminate) + + # this line lets us take symbols as parameters, pretty rad isn't it? + address_text = GDB_Engine.convert_symbol_to_address(address) + if address_text: + address = address_text + self.tableWidget_addresstable.setRowCount(self.tableWidget_addresstable.rowCount() + 1) + currentrow = self.tableWidget_addresstable.rowCount() - 1 + value = GDB_Engine.read_single_address(address, typeofaddress, length, unicode, zero_terminate) + self.tableWidget_addresstable.setCellWidget(currentrow, FROZEN_COL, frozen_checkbox) + self.change_address_table_entries(row=currentrow, description=description, address=address, + typeofaddress=typeofaddress_text, value=str(value)) + self.show() # In case of getting called from elsewhere + self.activateWindow() + + def on_address_table_double_click(self, index): + current_row = index.row() + current_column = index.column() + if current_column is VALUE_COL: + value = self.tableWidget_addresstable.item(current_row, VALUE_COL).text() + value_index = GuiUtils.text_to_index(self.tableWidget_addresstable.item(current_row, TYPE_COL).text()) + dialog = DialogWithButtonsForm(label_text="Enter the new value", hide_line_edit=False, + line_edit_text=value, parse_string=True, value_index=value_index) + if dialog.exec_(): + table_contents = [] + value_text = dialog.get_values() + selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows() + for item in selected_rows: + row = item.row() + address = self.tableWidget_addresstable.item(row, ADDR_COL).text() + value_type = self.tableWidget_addresstable.item(row, TYPE_COL).text() + value_index = GuiUtils.text_to_index(value_type) + if GuiUtils.text_to_length(value_type) is not -1: + unknown_type = SysUtils.parse_string(value_text, value_index) + if unknown_type is not None: + length = len(unknown_type) + self.tableWidget_addresstable.setItem(row, TYPE_COL, QTableWidgetItem( + GuiUtils.change_text_length(value_type, length))) + table_contents.append([address, value_index]) + GDB_Engine.set_multiple_addresses(table_contents, value_text) + self.update_address_table_manually() + + elif current_column is DESC_COL: + description = self.tableWidget_addresstable.item(current_row, DESC_COL).text() + dialog = DialogWithButtonsForm(label_text="Enter the new description", hide_line_edit=False, + line_edit_text=description) + if dialog.exec_(): + description_text = dialog.get_values() + selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows() + for item in selected_rows: + self.tableWidget_addresstable.setItem(item.row(), DESC_COL, QTableWidgetItem(description_text)) + elif current_column is ADDR_COL or current_column is TYPE_COL: + description, address, value_type = self.read_address_table_entries(row=current_row) + index, length, unicode, zero_terminate = GuiUtils.text_to_valuetype(value_type) + manual_address_dialog = ManualAddressDialogForm(description=description, address=address, index=index, + length=length, unicode=unicode, + zero_terminate=zero_terminate) + if manual_address_dialog.exec_(): + description, address, typeofaddress, length, unicode, zero_terminate = manual_address_dialog.get_values() + typeofaddress_text = GuiUtils.valuetype_to_text(value_index=typeofaddress, length=length, + is_unicode=unicode, + zero_terminate=zero_terminate) + address_text = GDB_Engine.convert_symbol_to_address(address) + if address_text: + address = address_text + value = GDB_Engine.read_single_address(address=address, value_index=typeofaddress, + length=length, is_unicode=unicode, + zero_terminate=zero_terminate) + self.change_address_table_entries(row=current_row, description=description, address=address, + typeofaddress=typeofaddress_text, value=str(value)) + + # Changes the column values of the given row + def change_address_table_entries(self, row, description="", address="", typeofaddress="", value=""): + self.tableWidget_addresstable.setItem(row, DESC_COL, QTableWidgetItem(description)) + self.tableWidget_addresstable.setItem(row, ADDR_COL, QTableWidgetItem(address)) + self.tableWidget_addresstable.setItem(row, TYPE_COL, QTableWidgetItem(typeofaddress)) + self.tableWidget_addresstable.setItem(row, VALUE_COL, QTableWidgetItem(value)) + + # Returns the column values of the given row + def read_address_table_entries(self, row): + description = self.tableWidget_addresstable.item(row, DESC_COL).text() + address = self.tableWidget_addresstable.item(row, ADDR_COL).text() + value_type = self.tableWidget_addresstable.item(row, TYPE_COL).text() + return description, address, value_type + + +# process select window +class ProcessForm(QMainWindow, ProcessWindow): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + GuiUtils.center_to_parent(self) + # self.loadingwidget = LoadingWidgetForm() + processlist = SysUtils.get_process_list() + self.refresh_process_table(self.processtable, processlist) + self.pushButton_Close.clicked.connect(self.pushbutton_close_onclick) + self.pushButton_Open.clicked.connect(self.pushbutton_open_onclick) + self.lineEdit_searchprocess.textChanged.connect(self.generate_new_list) + self.processtable.itemDoubleClicked.connect(self.pushbutton_open_onclick) + + # refreshes process list + def generate_new_list(self): + text = self.lineEdit_searchprocess.text() + processlist = SysUtils.search_in_processes_by_name(text) + self.refresh_process_table(self.processtable, processlist) + + # closes the window whenever ESC key is pressed + def keyPressEvent(self, e): + if e.key() == Qt.Key_Escape: + self.close() + + # lists currently working processes to table + def refresh_process_table(self, tablewidget, processlist): + tablewidget.setRowCount(0) + tablewidget.setRowCount(len(processlist)) + for i, row in enumerate(processlist): + tablewidget.setItem(i, 0, QTableWidgetItem(str(row.pid))) + tablewidget.setItem(i, 1, QTableWidgetItem(row.username())) + tablewidget.setItem(i, 2, QTableWidgetItem(row.name())) + + # self-explanatory + def pushbutton_close_onclick(self): + self.close() + + # gets the pid out of the selection to attach + def pushbutton_open_onclick(self): + currentitem = self.processtable.item(self.processtable.currentIndex().row(), 0) + if currentitem is None: + QMessageBox.information(self, "Error", "Please select a process first") + else: + pid = int(currentitem.text()) + if not SysUtils.is_process_valid(pid): + QMessageBox.information(self, "Error", "Selected process is not valid") + return + if pid == selfpid: + QMessageBox.information(self, "Error", "What the fuck are you trying to do?") # planned easter egg + return + if pid == GDB_Engine.currentpid: + QMessageBox.information(self, "Error", "You're debugging this process already") + return + tracedby = SysUtils.is_traced(pid) + if tracedby: + QMessageBox.information(self, "Error", + "That process is already being traced by " + tracedby + ", could not attach to the process") + return + self.setCursor(QCursor(Qt.WaitCursor)) + # self.setCentralWidget(self.loadingwidget) + # self.loadingwidget.show() + print("processing") # loading_widget start + result = GDB_Engine.can_attach(pid) + if not result: + print("done") # loading_widget finish + QMessageBox.information(self, "Error", "Permission denied, could not attach to the process") + return + if not GDB_Engine.currentpid == 0: + GDB_Engine.detach() + GDB_Engine.attach(pid) + p = SysUtils.get_process_information(GDB_Engine.currentpid) + self.parent().label_SelectedProcess.setText(str(p.pid) + " - " + p.name()) + self.parent().QWidget_Toolbox.setEnabled(True) + self.parent().pushButton_NextScan.setEnabled(False) + self.parent().pushButton_UndoScan.setEnabled(False) + readable_only, writeable, executable, readable = SysUtils.get_memory_regions_by_perms( + GDB_Engine.currentpid) # test + SysUtils.exclude_system_memory_regions(readable) + print(len(readable)) + print("done") # loading_widget finish + # self.loadingwidget.hide() + self.close() + + +# Add Address Manually Dialog +class ManualAddressDialogForm(QDialog, ManualAddressDialog): + def __init__(self, parent=None, description="No Description", address="0x", index=INDEX_4BYTES, length=10, + unicode=False, + zero_terminate=True): + super().__init__(parent=parent) + self.setupUi(self) + self.lineEdit_description.setText(description) + self.lineEdit_address.setText(address) + self.comboBox_ValueType.setCurrentIndex(index) + if self.comboBox_ValueType.currentIndex() is INDEX_STRING: + self.label_length.show() + self.lineEdit_length.show() + try: + length = str(length) + except: + length = "10" + self.lineEdit_length.setText(length) + self.checkBox_Unicode.show() + self.checkBox_Unicode.setChecked(unicode) + self.checkBox_zeroterminate.show() + self.checkBox_zeroterminate.setChecked(zero_terminate) + elif self.comboBox_ValueType.currentIndex() is INDEX_AOB: + self.label_length.show() + self.lineEdit_length.show() + try: + length = str(length) + except: + length = "10" + self.lineEdit_length.setText(length) + self.checkBox_Unicode.hide() + self.checkBox_zeroterminate.hide() + else: + self.label_length.hide() + self.lineEdit_length.hide() + self.checkBox_Unicode.hide() + self.checkBox_zeroterminate.hide() + self.comboBox_ValueType.currentIndexChanged.connect(self.valuetype_on_current_index_change) + self.lineEdit_length.textChanged.connect(self.length_text_on_change) + self.checkBox_Unicode.stateChanged.connect(self.unicode_box_on_check) + self.checkBox_zeroterminate.stateChanged.connect(self.zeroterminate_box_on_check) + self.update_needed = True + self.lineEdit_address.textChanged.connect(self.address_on_change) + self.update_thread = Thread(target=self.update_value_of_address) + self.update_thread.daemon = True + self.update_thread.start() + + # constantly updates the value of the address + def update_value_of_address(self): + while not self.update_thread._is_stopped: + sleep(0.01) + if self.update_needed: + self.update_needed = False + address = self.lineEdit_address.text() + address_type = self.comboBox_ValueType.currentIndex() + if address_type is INDEX_AOB: + length = self.lineEdit_length.text() + self.label_valueofaddress.setText( + GDB_Engine.read_single_address_by_expression(address, address_type, length)) + elif address_type is INDEX_STRING: + length = self.lineEdit_length.text() + is_unicode = self.checkBox_Unicode.isChecked() + is_zeroterminate = self.checkBox_zeroterminate.isChecked() + self.label_valueofaddress.setText( + GDB_Engine.read_single_address_by_expression(address, address_type, length, is_unicode, + is_zeroterminate)) + else: + self.label_valueofaddress.setText( + GDB_Engine.read_single_address_by_expression(address, address_type)) + + def address_on_change(self): + self.update_needed = True + + def length_text_on_change(self): + self.update_needed = True + + def unicode_box_on_check(self): + self.update_needed = True + + def zeroterminate_box_on_check(self): + self.update_needed = True + + def valuetype_on_current_index_change(self): + if self.comboBox_ValueType.currentIndex() is INDEX_STRING: + self.label_length.show() + self.lineEdit_length.show() + self.checkBox_Unicode.show() + self.checkBox_zeroterminate.show() + elif self.comboBox_ValueType.currentIndex() is INDEX_AOB: + self.label_length.show() + self.lineEdit_length.show() + self.checkBox_Unicode.hide() + self.checkBox_zeroterminate.hide() + else: + self.label_length.hide() + self.lineEdit_length.hide() + self.checkBox_Unicode.hide() + self.checkBox_zeroterminate.hide() + self.update_needed = True + + def reject(self): + self.update_thread._is_stopped = True + super(ManualAddressDialogForm, self).reject() + + def accept(self): + if self.label_length.isVisible(): + length = self.lineEdit_length.text() + try: + length = int(length) + except: + QMessageBox.information(self, "Error", "Length is not valid") + return + if length < 0: + QMessageBox.information(self, "Error", "Length cannot be smaller than 0") + return + self.update_thread._is_stopped = True + super(ManualAddressDialogForm, self).accept() + + def get_values(self): + description = self.lineEdit_description.text() + address = self.lineEdit_address.text() + length = self.lineEdit_length.text() + try: + length = int(length) + except: + length = 0 + unicode = False + zero_terminate = False + if self.checkBox_Unicode.isChecked(): + unicode = True + if self.checkBox_zeroterminate.isChecked(): + zero_terminate = True + typeofaddress = self.comboBox_ValueType.currentIndex() + return description, address, typeofaddress, length, unicode, zero_terminate + + +# FIXME: the gif in qlabel won't update itself, also the design of this class is generally shitty +# FIXME: this class is temporary and buggy, so all implementations of this shit should be fixed as soon as this class gets fixed +# I designed(sorry) this as a widget, but you can transform it to anything if it's going to fix the gif problem +class LoadingWidgetForm(QWidget, LoadingWidget): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint) + self.setAttribute(Qt.WA_TranslucentBackground) + pince_directory = SysUtils.get_current_script_directory() + self.movie = QMovie(pince_directory + "/media/loading_widget_gondola.gif", QByteArray()) + self.label_Animated.setMovie(self.movie) + self.movie.setScaledSize(QSize(50, 50)) + self.movie.setCacheMode(QMovie.CacheAll) + self.movie.setSpeed(100) + self.movie.start() + self.not_finished = True + # self.update_thread = Thread(target=self.update_widget) + # self.update_thread.daemon = True + # self.movie.frameChanged.connect(self.update_shit) + # self.loading_thread = LoadingWindowThread() + # self.loading_thread.update_needed.connect(QApplication.processEvents) + + def showEvent(self, QShowEvent): # from here + QApplication.processEvents() + # self.update_thread.start() + + def hideEvent(self, QHideEvent): + self.not_finished = False + + def update_widget(self): + while self.not_finished: + QApplication.processEvents() + + def change_text(self, text): + self.label_StatusText.setText(text) + QApplication.processEvents() + + +class LoadingWindowThread(QThread): + not_finished = True + update_needed = pyqtSignal() + + def run(self): + while self.not_finished: + sleep(0.001) + self.update_needed.emit() # to here should be reworked + + +class DialogWithButtonsForm(QDialog, DialogWithButtons): + def __init__(self, parent=None, label_text="", hide_line_edit=True, line_edit_text="", parse_string=False, + value_index=INDEX_4BYTES): + super().__init__(parent=parent) + self.setupUi(self) + self.parse_string = parse_string + self.value_index = value_index + label_text = str(label_text) + self.label.setText(label_text) + if hide_line_edit: + self.lineEdit.hide() + else: + line_edit_text = str(line_edit_text) + self.lineEdit.setText(line_edit_text) + + def get_values(self): + line_edit_text = self.lineEdit.text() + return line_edit_text + + def accept(self): + if self.parse_string: + string = self.lineEdit.text() + if SysUtils.parse_string(string, self.value_index) is None: + QMessageBox.information(self, "Error", "Can't parse the input") + return + super(DialogWithButtonsForm, self).accept() + + +class SettingsDialogForm(QDialog, SettingsDialog): + reset_settings = pyqtSignal() + + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + + # Yet another retarded hack, thanks to pyuic5 not supporting QKeySequenceEdit + self.keySequenceEdit = QKeySequenceEdit() + self.verticalLayout_Hotkey.addWidget(self.keySequenceEdit) + self.listWidget_Options.currentRowChanged.connect(self.change_display) + self.listWidget_Functions.currentRowChanged.connect(self.on_hotkey_index_change) + self.keySequenceEdit.keySequenceChanged.connect(self.on_key_sequence_change) + self.pushButton_ClearHotkey.clicked.connect(self.on_clear_button_pressed) + self.pushButton_ResetSettings.clicked.connect(self.on_reset_button_pressed) + self.checkBox_AutoUpdateAddressTable.stateChanged.connect(self.on_checkbox_auto_update_address_table_pressed) + self.config_gui() + + def accept(self): + try: + current_table_update_interval = float(self.lineEdit_UpdateInterval.text()) + except: + QMessageBox.information(self, "Error", "Update interval must be a float") + return + try: + current_insturctions_shown = int(self.lineEdit_InstructionsPerScroll.text()) + except: + QMessageBox.information(self, "Error", "Instruction count must be an integer") + return + if current_insturctions_shown < 1: + QMessageBox.information(self, "Error", "Instruction count cannot be lower than 1" + + "\nIt would be retarded anyways, wouldn't it?") + return + if current_table_update_interval < 0: + QMessageBox.information(self, "Error", "Update interval cannot be a negative number") + return + elif current_table_update_interval == 0: + + # Easter egg #2 + if not DialogWithButtonsForm(label_text="You are asking for it, aren't you?").exec_(): + return + elif current_table_update_interval < 0.1: + if not DialogWithButtonsForm(label_text="Update interval should be bigger than 0.1 seconds" + + "\nSetting update interval less than 0.1 seconds may cause slowness" + + "\n\tProceed?").exec_(): + return + self.settings.setValue("General/auto_update_address_table", self.checkBox_AutoUpdateAddressTable.isChecked()) + self.settings.setValue("General/address_table_update_interval", current_table_update_interval) + self.settings.setValue("Hotkeys/pause", self.pause_hotkey) + self.settings.setValue("Hotkeys/continue", self.continue_hotkey) + if self.radioButton_SimpleDLopenCall.isChecked(): + injection_method = SIMPLE_DLOPEN_CALL + elif self.radioButton_AdvancedInjection.isChecked(): + injection_method = ADVANCED_INJECTION + self.settings.setValue("CodeInjection/code_injection_method", injection_method) + self.settings.setValue("Disassemble/bring_disassemble_to_front", + self.checkBox_BringDisassembleToFront.isChecked()) + self.settings.setValue("Disassemble/instructions_per_scroll", current_insturctions_shown) + super(SettingsDialogForm, self).accept() + + def config_gui(self): + self.settings = QSettings() + self.checkBox_AutoUpdateAddressTable.setChecked( + self.settings.value("General/auto_update_address_table", type=bool)) + self.lineEdit_UpdateInterval.setText( + str(self.settings.value("General/address_table_update_interval", type=float))) + self.pause_hotkey = self.settings.value("Hotkeys/pause") + self.continue_hotkey = self.settings.value("Hotkeys/continue") + injection_method = self.settings.value("CodeInjection/code_injection_method", type=int) + if injection_method == SIMPLE_DLOPEN_CALL: + self.radioButton_SimpleDLopenCall.setChecked(True) + elif injection_method == ADVANCED_INJECTION: + self.radioButton_AdvancedInjection.setChecked(True) + self.checkBox_BringDisassembleToFront.setChecked( + self.settings.value("Disassemble/bring_disassemble_to_front", type=bool)) + self.lineEdit_InstructionsPerScroll.setText( + str(self.settings.value("Disassemble/instructions_per_scroll", type=int))) + + def change_display(self, index): + self.stackedWidget.setCurrentIndex(index) + + def on_hotkey_index_change(self, index): + if index is 0: + self.keySequenceEdit.setKeySequence(self.pause_hotkey) + elif index is 1: + self.keySequenceEdit.setKeySequence(self.continue_hotkey) + + def on_key_sequence_change(self): + current_index = self.listWidget_Functions.currentIndex().row() + if current_index is 0: + self.pause_hotkey = self.keySequenceEdit.keySequence().toString() + elif current_index is 1: + self.continue_hotkey = self.keySequenceEdit.keySequence().toString() + + def on_clear_button_pressed(self): + self.keySequenceEdit.clear() + + def on_reset_button_pressed(self): + confirm_dialog = DialogWithButtonsForm(label_text="This will reset to the default settings\n\tProceed?") + if confirm_dialog.exec_(): + self.reset_settings.emit() + else: + return + self.config_gui() - sys.exit(app.exec()) + def on_checkbox_auto_update_address_table_pressed(self): + if self.checkBox_AutoUpdateAddressTable.isChecked(): + self.QWidget_UpdateInterval.setEnabled(True) + else: + self.QWidget_UpdateInterval.setEnabled(False) + + +class ConsoleWidgetForm(QWidget, ConsoleWidget): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + GuiUtils.center(self) + self.await_async_output_thread = AwaitAsyncOutput() + self.await_async_output_thread.async_output_ready.connect(self.on_async_output) + self.await_async_output_thread.start() + self.pushButton_Send.clicked.connect(self.communicate) + self.pushButton_SendCtrl.clicked.connect(lambda: self.communicate(control=True)) + self.shortcut_send = QShortcut(QKeySequence("Return"), self) + self.shortcut_send.activated.connect(self.communicate) + self.shortcut_send_ctrl = QShortcut(QKeySequence("Ctrl+C"), self) + self.shortcut_send_ctrl.activated.connect(lambda: self.communicate(control=True)) + self.textBrowser.append("Hotkeys:") + self.textBrowser.append("--------------------") + self.textBrowser.append("Send=Enter |\nSend ctrl+c=Ctrl+C |") + self.textBrowser.append("--------------------") + self.textBrowser.append("Commands:") + self.textBrowser.append("---------------------------") + self.textBrowser.append("/clear: Clear the console |") + self.textBrowser.append("---------------------------") + self.textBrowser.append("You can change the output mode from bottom right") + self.textBrowser.append("Note: Changing output mode only affects commands sent. Any other " + + "output coming from external sources(e.g async output) will be shown in MI format") + + def communicate(self, control=False): + if control: + console_input = "/Ctrl+C" + else: + console_input = self.lineEdit.text() + if console_input.lower() == "/clear": + self.textBrowser.clear() + console_output = "Cleared" + elif console_input.strip().lower().startswith("-"): + console_output = "GDB/MI commands aren't supported yet" + elif console_input.strip().lower() == "q" or console_input.strip().lower() == "quit": + console_output = "pls don't" + else: + if not control: + if self.radioButton_CLI.isChecked(): + console_output = GDB_Engine.send_command(console_input, cli_output=True) + else: + console_output = GDB_Engine.send_command(console_input) + if not console_output: + console_output = "Inferior is running" + else: + GDB_Engine.interrupt_inferior() + if GDB_Engine.inferior_status == INFERIOR_STOPPED: + console_output = "Inferior is already stopped" + else: + console_output = "" + self.textBrowser.append("-->" + console_input) + self.textBrowser.append(console_output) + self.textBrowser.verticalScrollBar().setValue(self.textBrowser.verticalScrollBar().maximum()) + + def on_async_output(self): + self.textBrowser.append(GDB_Engine.gdb_async_output) + self.textBrowser.verticalScrollBar().setValue(self.textBrowser.verticalScrollBar().maximum()) + + +class AboutWidgetForm(QTabWidget, AboutWidget): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + GuiUtils.center(self) + license_text = open("COPYING").read() + authors_text = open("AUTHORS").read() + thanks_text = open("THANKS").read() + self.textBrowser_License.setPlainText(license_text) + self.textBrowser_Contributors.append( + "This is only a placeholder, this section may look different when the project finishes" + + "\nIn fact, something like a demo-scene for here would look absolutely fabulous <:") + self.textBrowser_Contributors.append("\n########") + self.textBrowser_Contributors.append("#AUTHORS#") + self.textBrowser_Contributors.append("########\n") + self.textBrowser_Contributors.append(authors_text) + self.textBrowser_Contributors.append("\n#######") + self.textBrowser_Contributors.append("#THANKS#") + self.textBrowser_Contributors.append("#######\n") + self.textBrowser_Contributors.append(thanks_text) + + +class MemoryViewWindowForm(QMainWindow, MemoryViewWindow): + process_stopped = pyqtSignal() + process_running = pyqtSignal() + + # TODO: Change this nonsense when the huge refactorization happens + address_added = pyqtSignal(object, object, object, object, object, object) + + def set_dynamic_debug_hotkeys(self): + self.shortcut_break.setKey(QKeySequence(pause_hotkey)) + self.shortcut_run.setKey(QKeySequence(continue_hotkey)) + self.actionBreak.setText("Break[" + pause_hotkey + "]") + self.actionRun.setText("Run[" + continue_hotkey + "]") + + def set_debug_menu_shortcuts(self): + self.shortcut_break = QShortcut(QKeySequence(pause_hotkey), self) + self.shortcut_break.activated.connect(GDB_Engine.interrupt_inferior) + self.shortcut_run = QShortcut(QKeySequence(continue_hotkey), self) + self.shortcut_run.activated.connect(GDB_Engine.continue_inferior) + self.shortcut_step = QShortcut(QKeySequence("F7"), self) + self.shortcut_step.activated.connect(GDB_Engine.step_instruction) + self.shortcut_step_over = QShortcut(QKeySequence("F8"), self) + self.shortcut_step_over.activated.connect(GDB_Engine.step_over_instruction) + self.shortcut_execute_till_return = QShortcut(QKeySequence("Shift+F8"), self) + self.shortcut_execute_till_return.activated.connect(GDB_Engine.execute_till_return) + self.shortcut_toggle_breakpoint = QShortcut(QKeySequence("F5"), self) + + def initialize_debug_context_menu(self): + self.actionBreak.triggered.connect(GDB_Engine.interrupt_inferior) + self.actionRun.triggered.connect(GDB_Engine.continue_inferior) + self.actionStep.triggered.connect(GDB_Engine.step_instruction) + self.actionStep_Over.triggered.connect(GDB_Engine.step_over_instruction) + self.actionExecute_Till_Return.triggered.connect(GDB_Engine.execute_till_return) + + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + GuiUtils.center(self) + self.process_stopped.connect(self.on_process_stop) + self.process_running.connect(self.on_process_running) + self.set_debug_menu_shortcuts() + self.set_dynamic_debug_hotkeys() + self.initialize_debug_context_menu() + self.initialize_disassemble_view() + self.initialize_register_view() + self.initialize_stack_view() + self.initialize_hex_view() + + self.actionBookmarks.triggered.connect(self.on_ViewBookmarks_triggered) + self.actionStackTrace_Info.triggered.connect(self.on_stacktrace_info_triggered) + self.actionInject_so_file.triggered.connect(self.on_inject_so_file_triggered) + + self.splitter_Disassemble_Registers.setStretchFactor(0, 1) + self.widget_StackView.resize(420, self.widget_StackView.height()) # blaze it + self.widget_Registers.resize(330, self.widget_Registers.height()) + + def initialize_register_view(self): + self.pushButton_ShowFloatRegisters.clicked.connect(self.on_show_float_registers_button_clicked) + + def initialize_stack_view(self): + self.tableWidget_StackTrace.setColumnWidth(STACKTRACE_RETURN_ADDRESS_COL, 350) + + self.tableWidget_Stack.contextMenuEvent = self.tableWidget_Stack_context_menu_event + self.tableWidget_StackTrace.contextMenuEvent = self.tableWidget_StackTrace_context_menu_event + self.tableWidget_StackTrace.itemDoubleClicked.connect(self.tableWidget_StackTrace_double_click) + + def initialize_disassemble_view(self): + self.disassemble_currently_displayed_address = "0x00400000" + self.widget_Disassemble.wheelEvent = self.widget_Disassemble_wheel_event + + self.tableWidget_Disassemble.wheelEvent = QEvent.ignore + self.verticalScrollBar_Disassemble.wheelEvent = QEvent.ignore + + GuiUtils.center_scroll_bar(self.verticalScrollBar_Disassemble) + self.verticalScrollBar_Disassemble.mouseReleaseEvent = self.verticalScrollBar_Disassemble_mouse_release_event + + self.disassemble_scroll_bar_timer = QTimer() + self.disassemble_scroll_bar_timer.setInterval(100) + self.disassemble_scroll_bar_timer.timeout.connect(self.check_disassemble_scrollbar) + self.disassemble_scroll_bar_timer.start() + + # Format: [address1, address2, ...] + self.tableWidget_Disassemble.travel_history = [] + + # Format: {address1:comment1,address2:comment2, ...} + self.tableWidget_Disassemble.bookmarks = {} + + self.tableWidget_Disassemble.keyPressEvent = self.tableWidget_Disassemble_key_press_event + self.tableWidget_Disassemble.contextMenuEvent = self.tableWidget_Disassemble_context_menu_event + + self.tableWidget_Disassemble.itemDoubleClicked.connect(self.on_disassemble_double_click) + + def initialize_hex_view(self): + self.hex_view_currently_displayed_address = 0x00400000 + self.widget_HexView.wheelEvent = self.widget_HexView_wheel_event + + self.widget_HexView.contextMenuEvent = self.widget_HexView_context_menu_event + + self.verticalScrollBar_HexView.wheelEvent = QEvent.ignore + self.listWidget_HexView_Address.wheelEvent = QEvent.ignore + self.scrollArea_Hex.keyPressEvent = QEvent.ignore + self.listWidget_HexView_Address.setAutoScroll(False) + self.listWidget_HexView_Address.setStyleSheet("QListWidget {background-color: transparent;}") + + self.hex_model = QHexModel(HEX_VIEW_ROW_COUNT, HEX_VIEW_COL_COUNT) + self.ascii_model = QAsciiModel(HEX_VIEW_ROW_COUNT, HEX_VIEW_COL_COUNT) + self.tableView_HexView_Hex.setModel(self.hex_model) + self.tableView_HexView_Ascii.setModel(self.ascii_model) + + self.tableView_HexView_Hex.selectionModel().currentChanged.connect(self.on_hex_view_current_changed) + self.tableView_HexView_Ascii.selectionModel().currentChanged.connect(self.on_ascii_view_current_changed) + + self.scrollArea_Hex.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.scrollArea_Hex.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.listWidget_HexView_Address.setVerticalScrollBarPolicy((Qt.ScrollBarAlwaysOff)) + self.listWidget_HexView_Address.setHorizontalScrollBarPolicy((Qt.ScrollBarAlwaysOff)) + + GuiUtils.center_scroll_bar(self.verticalScrollBar_HexView) + self.hex_view_scroll_bar_timer = QTimer() + self.hex_view_scroll_bar_timer.setInterval(100) + self.hex_view_scroll_bar_timer.timeout.connect(self.check_hex_view_scrollbar) + self.hex_view_scroll_bar_timer.start() + self.verticalScrollBar_HexView.mouseReleaseEvent = self.verticalScrollBar_HexView_mouse_release_event + + def widget_HexView_context_menu_event(self, event): + menu = QMenu() + go_to = menu.addAction("Go to expression") + menu.addSeparator() + add_address = menu.addAction("Add this address to address list") + menu.addSeparator() + refresh = menu.addAction("Refresh") + font_size = self.widget_HexView.font().pointSize() + menu.setStyleSheet("font-size: " + str(font_size) + "pt;") + current_address = hex(self.hex_view_currently_displayed_address) + action = menu.exec_(event.globalPos()) + if action == go_to: + go_to_dialog = DialogWithButtonsForm(label_text="Enter the expression", hide_line_edit=False, + line_edit_text=current_address) + if go_to_dialog.exec_(): + expression = go_to_dialog.get_values() + dest_address = GDB_Engine.convert_symbol_to_address(expression) + if dest_address is None: + QMessageBox.information(self, "Error", "Cannot access memory at expression " + expression) + return + self.hex_dump_address(int(dest_address, 16)) + elif action == add_address: + selected_address = self.hex_view_currently_displayed_address + self.tableView_HexView_Hex.get_current_offset() + manual_address_dialog = ManualAddressDialogForm(address=hex(selected_address), index=INDEX_AOB) + if manual_address_dialog.exec_(): + description, address, typeofaddress, length, unicode, zero_terminate = manual_address_dialog.get_values() + self.address_added.emit(description, address, typeofaddress, length, unicode, zero_terminate) + elif action == refresh: + self.hex_dump_address(self.hex_view_currently_displayed_address) + + def verticalScrollBar_HexView_mouse_release_event(self, event): + GuiUtils.center_scroll_bar(self.verticalScrollBar_HexView) + + def verticalScrollBar_Disassemble_mouse_release_event(self, event): + GuiUtils.center_scroll_bar(self.verticalScrollBar_Disassemble) + + def check_hex_view_scrollbar(self): + if GDB_Engine.inferior_status != INFERIOR_STOPPED: + return + maximum = self.verticalScrollBar_HexView.maximum() + minimum = self.verticalScrollBar_HexView.minimum() + midst = (maximum + minimum) / 2 + current_value = self.verticalScrollBar_HexView.value() + if midst - 10 < current_value < midst + 10: + return + current_address = self.hex_view_currently_displayed_address + if current_value < midst: + next_address = current_address - 0x40 + else: + next_address = current_address + 0x40 + self.hex_dump_address(next_address) + + def check_disassemble_scrollbar(self): + if GDB_Engine.inferior_status != INFERIOR_STOPPED: + return + maximum = self.verticalScrollBar_Disassemble.maximum() + minimum = self.verticalScrollBar_Disassemble.minimum() + midst = (maximum + minimum) / 2 + current_value = self.verticalScrollBar_Disassemble.value() + if midst - 10 < current_value < midst + 10: + return + current_address = self.disassemble_currently_displayed_address + if current_value < midst: + next_address = GDB_Engine.find_address_of_closest_instruction(current_address, instructions_per_scroll, + "previous") + else: + next_address = GDB_Engine.find_address_of_closest_instruction(current_address, instructions_per_scroll, + "next") + self.disassemble_expression(next_address) + + def on_hex_view_current_changed(self, QModelIndex_current): + self.tableView_HexView_Ascii.selectionModel().setCurrentIndex(QModelIndex_current, + QItemSelectionModel.ClearAndSelect) + self.listWidget_HexView_Address.setCurrentRow(QModelIndex_current.row()) + + def on_ascii_view_current_changed(self, QModelIndex_current): + self.tableView_HexView_Hex.selectionModel().setCurrentIndex(QModelIndex_current, + QItemSelectionModel.ClearAndSelect) + self.listWidget_HexView_Address.setCurrentRow(QModelIndex_current.row()) + + def hex_dump_address(self, int_address, offset=HEX_VIEW_ROW_COUNT * HEX_VIEW_COL_COUNT): + information = SysUtils.get_region_info(GDB_Engine.currentpid, int_address) + if information is not None: + self.label_HexView_Information.setText( + "Protection:" + information.region.perms + " | Base:" + information.start + "-" + information.end) + else: + self.label_HexView_Information.setText("This region is invalid") + self.listWidget_HexView_Address.clear() + for current_offset in range(HEX_VIEW_ROW_COUNT): + self.listWidget_HexView_Address.addItem(hex(int_address + current_offset * 16)) + listwidget_column_size = self.listWidget_HexView_Address.sizeHintForColumn(0) + 10 + self.listWidget_HexView_Address.setMaximumWidth(listwidget_column_size) + self.listWidget_HexView_Address.setMinimumWidth(listwidget_column_size) + hex_list = GDB_Engine.hex_dump(int_address, offset) + self.hex_model.refresh(hex_list) + self.ascii_model.refresh(hex_list) + self.hex_view_currently_displayed_address = int_address + + def refresh_hex_view(self): + if self.listWidget_HexView_Address.count() == 0: + # ELF header usually starts at address 0x00400000 + self.hex_dump_address(0x00400000) + self.tableView_HexView_Hex.resize_to_contents() + self.tableView_HexView_Ascii.resize_to_contents() + else: + self.hex_dump_address(self.hex_view_currently_displayed_address) + + # offset can also be an address as hex str + def disassemble_expression(self, expression, offset="+200", append_to_travel_history=False): + disas_data = GDB_Engine.disassemble(expression, offset) + if not disas_data: + QMessageBox.information(self, "Error", "Cannot access memory at expression " + expression) + return + program_counter = GDB_Engine.convert_symbol_to_address("$pc", check=False) + program_counter_int = int(program_counter, 16) + row_of_pc = False + rows_of_encountered_bookmarks_list = [] + + # TODO: Change this nonsense when the huge refactorization happens + current_first_address = SysUtils.extract_address(disas_data[0][0]) # address of first list entry + try: + previous_first_address = SysUtils.extract_address( + self.tableWidget_Disassemble.item(0, DISAS_ADDR_COL).text()) + except AttributeError: + previous_first_address = current_first_address + + self.tableWidget_Disassemble.setRowCount(0) + self.tableWidget_Disassemble.setRowCount(len(disas_data)) + for row, item in enumerate(disas_data): + comment = "" + current_address = int(SysUtils.extract_address(item[0]), 16) + if current_address == program_counter_int: + item[0] = ">>>" + item[0] + row_of_pc = row + for bookmark_item in self.tableWidget_Disassemble.bookmarks.keys(): + if current_address == bookmark_item: + rows_of_encountered_bookmarks_list.append(row) + item[0] = "(M)" + item[0] + comment = self.tableWidget_Disassemble.bookmarks[bookmark_item] + break + self.tableWidget_Disassemble.setItem(row, DISAS_ADDR_COL, QTableWidgetItem(item[0])) + self.tableWidget_Disassemble.setItem(row, DISAS_BYTES_COL, QTableWidgetItem(item[1])) + self.tableWidget_Disassemble.setItem(row, DISAS_OPCODES_COL, QTableWidgetItem(item[2])) + self.tableWidget_Disassemble.setItem(row, DISAS_COMMENT_COL, QTableWidgetItem(comment)) + self.handle_colours(row_of_pc, rows_of_encountered_bookmarks_list) + self.tableWidget_Disassemble.resizeColumnsToContents() + self.tableWidget_Disassemble.horizontalHeader().setStretchLastSection(True) + + # We append the old record to travel history as last action because we wouldn't like to see unnecessary + # addresses in travel history if any error occurs while displaying the next location + if append_to_travel_history: + self.tableWidget_Disassemble.travel_history.append(previous_first_address) + self.disassemble_currently_displayed_address = current_first_address + + # Set colour of a row if a specific address is encountered(e.g $pc, a bookmarked address etc.) + def handle_colours(self, row_of_pc, encountered_bookmark_list): + if row_of_pc: + self.set_row_colour(row_of_pc, PC_COLOUR) + if encountered_bookmark_list: + for encountered_row in encountered_bookmark_list: + self.set_row_colour(encountered_row, BOOKMARK_COLOUR) + + # color parameter should be Qt.colour + def set_row_colour(self, row, colour): + for item in range(self.tableWidget_Disassemble.columnCount()): + self.tableWidget_Disassemble.item(row, item).setData(Qt.BackgroundColorRole, QColor(colour)) + + def on_process_stop(self): + time0 = time() + thread_info = GDB_Engine.get_current_thread_information() + self.setWindowTitle("Memory Viewer - Currently Debugging Thread " + thread_info) + self.disassemble_expression("$pc") + self.update_registers() + if self.stackedWidget_StackScreens.currentWidget() == self.StackTrace: + self.update_stacktrace() + elif self.stackedWidget_StackScreens.currentWidget() == self.Stack: + self.update_stack() + self.refresh_hex_view() + self.showMaximized() + if bring_disassemble_to_front: + self.activateWindow() + try: + if self.stacktrace_info_widget.isVisible(): + self.stacktrace_info_widget.update_stacktrace() + except AttributeError: + pass + try: + if self.float_registers_widget.isVisible(): + self.float_registers_widget.update_registers() + except AttributeError: + pass + time1 = time() + print("UPDATED MEMORYVIEW IN:" + str(time1 - time0)) + + def on_process_running(self): + self.setWindowTitle("Memory Viewer - Running") + + def update_registers(self): + registers = GDB_Engine.read_registers() + if GDB_Engine.inferior_arch == ARCH_64: + self.stackedWidget.setCurrentWidget(self.registers_64) + self.RAX.set_value(registers["rax"]) + self.RBX.set_value(registers["rbx"]) + self.RCX.set_value(registers["rcx"]) + self.RDX.set_value(registers["rdx"]) + self.RSI.set_value(registers["rsi"]) + self.RDI.set_value(registers["rdi"]) + self.RBP.set_value(registers["rbp"]) + self.RSP.set_value(registers["rsp"]) + self.RIP.set_value(registers["rip"]) + self.R8.set_value(registers["r8"]) + self.R9.set_value(registers["r9"]) + self.R10.set_value(registers["r10"]) + self.R11.set_value(registers["r11"]) + self.R12.set_value(registers["r12"]) + self.R13.set_value(registers["r13"]) + self.R14.set_value(registers["r14"]) + self.R15.set_value(registers["r15"]) + elif GDB_Engine.inferior_arch == ARCH_32: + self.stackedWidget.setCurrentWidget(self.registers_32) + self.EAX.set_value(registers["eax"]) + self.EBX.set_value(registers["ebx"]) + self.ECX.set_value(registers["ecx"]) + self.EDX.set_value(registers["edx"]) + self.ESI.set_value(registers["esi"]) + self.EDI.set_value(registers["edi"]) + self.EBP.set_value(registers["ebp"]) + self.ESP.set_value(registers["esp"]) + self.EIP.set_value(registers["eip"]) + self.CF.set_value(registers["cf"]) + self.PF.set_value(registers["pf"]) + self.AF.set_value(registers["af"]) + self.ZF.set_value(registers["zf"]) + self.SF.set_value(registers["sf"]) + self.TF.set_value(registers["tf"]) + self.IF.set_value(registers["if"]) + self.DF.set_value(registers["df"]) + self.OF.set_value(registers["of"]) + self.CS.set_value(registers["cs"]) + self.SS.set_value(registers["ss"]) + self.DS.set_value(registers["ds"]) + self.ES.set_value(registers["es"]) + self.GS.set_value(registers["gs"]) + self.FS.set_value(registers["fs"]) + + def update_stacktrace(self): + stack_trace_info = GDB_Engine.get_stacktrace_info() + self.tableWidget_StackTrace.setRowCount(0) + self.tableWidget_StackTrace.setRowCount(len(stack_trace_info)) + for row, item in enumerate(stack_trace_info): + self.tableWidget_StackTrace.setItem(row, STACKTRACE_RETURN_ADDRESS_COL, QTableWidgetItem(item[0])) + self.tableWidget_StackTrace.setItem(row, STACKTRACE_FRAME_ADDRESS_COL, QTableWidgetItem(item[1])) + + def tableWidget_StackTrace_context_menu_event(self, event): + menu = QMenu() + switch_to_stack = menu.addAction("Full Stack") + font_size = self.tableWidget_StackTrace.font().pointSize() + menu.setStyleSheet("font-size: " + str(font_size) + "pt;") + action = menu.exec_(event.globalPos()) + if action == switch_to_stack: + self.stackedWidget_StackScreens.setCurrentWidget(self.Stack) + self.update_stack() + + def update_stack(self): + stack_info = GDB_Engine.get_stack_info() + self.tableWidget_Stack.setRowCount(0) + self.tableWidget_Stack.setRowCount(len(stack_info)) + for row, item in enumerate(stack_info): + self.tableWidget_Stack.setItem(row, STACK_POINTER_ADDRESS_COL, QTableWidgetItem(item[0])) + self.tableWidget_Stack.setItem(row, STACK_VALUE_COL, QTableWidgetItem(item[1])) + self.tableWidget_Stack.setItem(row, STACK_INT_REPRESENTATION_COL, QTableWidgetItem(item[2])) + self.tableWidget_Stack.setItem(row, STACK_FLOAT_REPRESENTATION_COL, QTableWidgetItem(item[3])) + self.tableWidget_Stack.resizeColumnsToContents() + + def tableWidget_Stack_context_menu_event(self, event): + menu = QMenu() + switch_to_stacktrace = menu.addAction("Stacktrace") + font_size = self.tableWidget_Stack.font().pointSize() + menu.setStyleSheet("font-size: " + str(font_size) + "pt;") + action = menu.exec_(event.globalPos()) + if action == switch_to_stacktrace: + self.stackedWidget_StackScreens.setCurrentWidget(self.StackTrace) + self.update_stacktrace() + + def tableWidget_StackTrace_double_click(self, index): + if index.column() == STACKTRACE_RETURN_ADDRESS_COL: + selected_row = self.tableWidget_StackTrace.selectionModel().selectedRows()[-1].row() + current_address_text = self.tableWidget_StackTrace.item(selected_row, DISAS_ADDR_COL).text() + current_address = SysUtils.extract_address(current_address_text) + self.disassemble_expression(current_address, append_to_travel_history=True) + + def widget_Disassemble_wheel_event(self, event): + steps = event.angleDelta() + current_address = self.disassemble_currently_displayed_address + if steps.y() > 0: + next_address = GDB_Engine.find_address_of_closest_instruction(current_address, instructions_per_scroll, + "previous") + else: + next_address = GDB_Engine.find_address_of_closest_instruction(current_address, instructions_per_scroll, + "next") + self.disassemble_expression(next_address) + + def widget_HexView_wheel_event(self, event): + steps = event.angleDelta() + current_address = self.hex_view_currently_displayed_address + if steps.y() > 0: + next_address = current_address - 0x40 + else: + next_address = current_address + 0x40 + self.hex_dump_address(next_address) + + def tableWidget_Disassemble_key_press_event(self, event): + selected_row = self.tableWidget_Disassemble.selectionModel().selectedRows()[-1].row() + current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() + current_address = SysUtils.extract_address(current_address_text) + if event.key() == Qt.Key_Space: + self.follow_instruction(selected_row) + elif event.key() == Qt.Key_B: + self.bookmark_address(int(current_address, 16)) + + def on_disassemble_double_click(self, index): + if index.column() == DISAS_COMMENT_COL: + selected_row = self.tableWidget_Disassemble.selectionModel().selectedRows()[-1].row() + current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() + current_address = int(SysUtils.extract_address(current_address_text), 16) + if current_address in self.tableWidget_Disassemble.bookmarks: + self.change_bookmark_comment(current_address) + else: + self.bookmark_address(current_address) + + # Search the item in given row for location changing instructions + # Go to the address pointed by that instruction if it contains any + def follow_instruction(self, selected_row): + address = SysUtils.extract_address( + self.tableWidget_Disassemble.item(selected_row, DISAS_OPCODES_COL).text(), + search_for_location_changing_instructions=True) + if address: + self.disassemble_expression(address, append_to_travel_history=True) + + def tableWidget_Disassemble_context_menu_event(self, event): + selected_row = self.tableWidget_Disassemble.selectionModel().selectedRows()[-1].row() + current_address_text = self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text() + current_address = SysUtils.extract_address(current_address_text) + current_address_int = int(current_address, 16) + first_address = self.disassemble_currently_displayed_address + + menu = QMenu() + go_to = menu.addAction("Go to expression") + back = menu.addAction("Back") + followable = SysUtils.extract_address( + self.tableWidget_Disassemble.item(selected_row, DISAS_OPCODES_COL).text(), + search_for_location_changing_instructions=True) + if followable: + follow = menu.addAction("Follow[Space]") + else: + follow = -1 + is_bookmarked = current_address_int in self.tableWidget_Disassemble.bookmarks + if not is_bookmarked: + bookmark = menu.addAction("Bookmark this address[B]") + delete_bookmark = -1 + else: + bookmark = -1 + delete_bookmark = menu.addAction("Delete this bookmark") + go_to_bookmark = menu.addMenu("Go to bookmarked address") + bookmark_action_list = [] + for item in self.tableWidget_Disassemble.bookmarks.keys(): + + # FIXME: Implement and use optimized version of convert_address_to_symbol if performance issues occur + current_text = GDB_Engine.convert_address_to_symbol(hex(item), include_address=True) + if current_text is None: + text_append = hex(item) + "(Unreachable)" + else: + text_append = current_text + bookmark_action_list.append(go_to_bookmark.addAction(text_append)) + menu.addSeparator() + refresh = menu.addAction("Refresh") + menu.addSeparator() + clipboard_menu = menu.addMenu("Copy to Clipboard") + copy_address = clipboard_menu.addAction("Copy Address") + copy_bytes = clipboard_menu.addAction("Copy Bytes") + copy_opcode = clipboard_menu.addAction("Copy Opcode") + copy_comment = clipboard_menu.addAction("Copy Comment") + font_size = self.tableWidget_Disassemble.font().pointSize() + menu.setStyleSheet("font-size: " + str(font_size) + "pt;") + action = menu.exec_(event.globalPos()) + if action == go_to: + go_to_dialog = DialogWithButtonsForm(label_text="Enter the expression", hide_line_edit=False, + line_edit_text=first_address) + if go_to_dialog.exec_(): + traveled_exp = go_to_dialog.get_values() + self.disassemble_expression(traveled_exp, append_to_travel_history=True) + elif action == back: + if self.tableWidget_Disassemble.travel_history: + last_location = self.tableWidget_Disassemble.travel_history[-1] + self.disassemble_expression(last_location) + self.tableWidget_Disassemble.travel_history.pop() + elif action == follow: + self.follow_instruction(selected_row) + elif action == bookmark: + self.bookmark_address(current_address_int) + elif action == delete_bookmark: + self.delete_bookmark(current_address_int) + elif action == refresh: + self.disassemble_expression(self.disassemble_currently_displayed_address) + elif action == copy_address: + QApplication.clipboard().setText(self.tableWidget_Disassemble.item(selected_row, DISAS_ADDR_COL).text()) + elif action == copy_bytes: + QApplication.clipboard().setText(self.tableWidget_Disassemble.item(selected_row, DISAS_BYTES_COL).text()) + elif action == copy_opcode: + QApplication.clipboard().setText(self.tableWidget_Disassemble.item(selected_row, DISAS_OPCODES_COL).text()) + elif action == copy_comment: + QApplication.clipboard().setText(self.tableWidget_Disassemble.item(selected_row, DISAS_COMMENT_COL).text()) + for item in bookmark_action_list: + if action == item: + self.disassemble_expression(SysUtils.extract_address(action.text()), append_to_travel_history=True) + + def bookmark_address(self, int_address): + if int_address in self.tableWidget_Disassemble.bookmarks: + QMessageBox.information(self, "Error", "This address has already been bookmarked") + return + comment_dialog = DialogWithButtonsForm(label_text="Enter the comment for bookmarked address", + hide_line_edit=False) + if comment_dialog.exec_(): + comment = comment_dialog.get_values() + else: + return + self.tableWidget_Disassemble.bookmarks[int_address] = comment + for row in range(self.tableWidget_Disassemble.rowCount()): + current_text = self.tableWidget_Disassemble.item(row, DISAS_ADDR_COL).text() + current_address = int(SysUtils.extract_address(current_text), 16) + if current_address == int_address: + self.tableWidget_Disassemble.setItem(row, DISAS_ADDR_COL, QTableWidgetItem("(M)" + current_text)) + self.tableWidget_Disassemble.setItem(row, DISAS_COMMENT_COL, QTableWidgetItem(comment)) + self.set_row_colour(row, BOOKMARK_COLOUR) + self.tableWidget_Disassemble.resizeColumnsToContents() + self.tableWidget_Disassemble.horizontalHeader().setStretchLastSection(True) + break + + def change_bookmark_comment(self, int_address): + current_comment = self.tableWidget_Disassemble.bookmarks[int_address] + comment_dialog = DialogWithButtonsForm(label_text="Enter the comment for bookmarked address", + hide_line_edit=False, line_edit_text=current_comment) + if comment_dialog.exec_(): + new_comment = comment_dialog.get_values() + else: + return + self.tableWidget_Disassemble.bookmarks[int_address] = new_comment + for row in range(self.tableWidget_Disassemble.rowCount()): + current_text = self.tableWidget_Disassemble.item(row, DISAS_ADDR_COL).text() + current_address = int(SysUtils.extract_address(current_text), 16) + if current_address == int_address: + self.tableWidget_Disassemble.setItem(row, DISAS_COMMENT_COL, QTableWidgetItem(new_comment)) + self.set_row_colour(row, BOOKMARK_COLOUR) + self.tableWidget_Disassemble.resizeColumnsToContents() + self.tableWidget_Disassemble.horizontalHeader().setStretchLastSection(True) + break + + def delete_bookmark(self, int_address): + if int_address in self.tableWidget_Disassemble.bookmarks: + del self.tableWidget_Disassemble.bookmarks[int_address] + for row in range(self.tableWidget_Disassemble.rowCount()): + current_text = self.tableWidget_Disassemble.item(row, DISAS_ADDR_COL).text() + current_address = int(SysUtils.extract_address(current_text), 16) + if current_address == int_address: + mark_removed_text = GuiUtils.remove_bookmark_mark(current_text) + self.tableWidget_Disassemble.setItem(row, DISAS_ADDR_COL, QTableWidgetItem(mark_removed_text)) + self.tableWidget_Disassemble.setItem(row, DISAS_COMMENT_COL, QTableWidgetItem("")) + self.set_row_colour(row, DEFAULT_COLOUR) + self.tableWidget_Disassemble.resizeColumnsToContents() + self.tableWidget_Disassemble.horizontalHeader().setStretchLastSection(True) + break + + def on_ViewBookmarks_triggered(self): + self.bookmark_widget = BookmarkWidgetForm(self) + self.bookmark_widget.show() + + def on_stacktrace_info_triggered(self): + self.stacktrace_info_widget = StackTraceInfoWidgetForm() + self.stacktrace_info_widget.show() + + def on_inject_so_file_triggered(self): + file_name = QFileDialog.getOpenFileName(self, "Select the .so file", "", "Shared object library (*.so)")[0] + if file_name: + if GDB_Engine.inject_with_dlopen_call(file_name): + QMessageBox.information(self, "Success!", "The file has been injected") + else: + QMessageBox.information(self, "Error", "Failed to inject the .so file") + + def on_show_float_registers_button_clicked(self): + self.float_registers_widget = FloatRegisterWidgetForm() + self.float_registers_widget.show() + GuiUtils.center_to_window(self.float_registers_widget, self.widget_Registers) + + +class BookmarkWidgetForm(QWidget, BookmarkWidget): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + GuiUtils.center(self) + self.setWindowFlags(Qt.Window) + self.listWidget.contextMenuEvent = self.listWidget_context_menu_event + self.listWidget.currentRowChanged.connect(self.change_display) + self.listWidget.itemDoubleClicked.connect(self.on_item_double_clicked) + self.shortcut_delete = QShortcut(QKeySequence("Del"), self) + self.shortcut_delete.activated.connect(self.delete_record) + self.refresh_table() + + def refresh_table(self): + self.listWidget.clear() + for item in self.parent().tableWidget_Disassemble.bookmarks.keys(): + + # FIXME: Implement and use optimized version of convert_address_to_symbol if performance issues occur + current_text = GDB_Engine.convert_address_to_symbol(hex(item), include_address=True) + if current_text is None: + text_append = hex(item) + "(Unreachable)" + else: + text_append = current_text + self.listWidget.addItem(text_append) + + def change_display(self): + try: + current_item = self.listWidget.currentItem().text() + except AttributeError: + return + current_address = SysUtils.extract_address(current_item) + self.lineEdit_Info.setText(GDB_Engine.get_info_about_address(current_address)) + self.lineEdit_Comment.setText(self.parent().tableWidget_Disassemble.bookmarks[int(current_address, 16)]) + + def on_item_double_clicked(self, item): + self.parent().disassemble_expression(SysUtils.extract_address(item.text()), append_to_travel_history=True) + + def listWidget_context_menu_event(self, event): + if self.listWidget.count() != 0: + current_item = self.listWidget.currentItem().text() + current_address = int(SysUtils.extract_address(current_item), 16) + else: + current_item = None + current_address = None + if current_item is not None: + if not current_address in self.parent().tableWidget_Disassemble.bookmarks: + QMessageBox.information(self, "Error", "Invalid entries detected, refreshing the page") + self.refresh_table() + return + menu = QMenu() + add_entry = menu.addAction("Add new entry") + if current_item is not None: + change_comment = menu.addAction("Change comment of this record") + delete_record = menu.addAction("Delete this record[Del]") + else: + change_comment = -1 + delete_record = -1 + menu.addSeparator() + refresh = menu.addAction("Refresh") + font_size = self.listWidget.font().pointSize() + menu.setStyleSheet("font-size: " + str(font_size) + "pt;") + action = menu.exec_(event.globalPos()) + if action == add_entry: + entry_dialog = DialogWithButtonsForm(label_text="Enter the expression", hide_line_edit=False) + if entry_dialog.exec_(): + text = entry_dialog.get_values() + address = GDB_Engine.convert_symbol_to_address(text) + if address is None: + QMessageBox.information(self, "Error", "Invalid expression or address") + return + self.parent().bookmark_address(int(address, 16)) + self.refresh_table() + elif action == change_comment: + self.parent().change_bookmark_comment(current_address) + self.refresh_table() + elif action == delete_record: + self.delete_record() + elif action == refresh: + self.refresh_table() + + def delete_record(self): + current_item = self.listWidget.currentItem().text() + current_address = int(SysUtils.extract_address(current_item), 16) + self.parent().delete_bookmark(current_address) + self.refresh_table() + + +class FloatRegisterWidgetForm(QTabWidget, FloatRegisterWidget): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + self.setWindowFlags(Qt.Window) + self.update_registers() + self.tableWidget_FPU.itemDoubleClicked.connect(self.set_register) + self.tableWidget_XMM.itemDoubleClicked.connect(self.set_register) + + def update_registers(self): + self.tableWidget_FPU.setRowCount(0) + self.tableWidget_FPU.setRowCount(8) + self.tableWidget_XMM.setRowCount(0) + self.tableWidget_XMM.setRowCount(8) + float_registers = GDB_Engine.read_float_registers() + + # st0-7, xmm0-7 + for row, index in enumerate(range(8)): + current_st_register = "st" + str(index) + current_xmm_register = "xmm" + str(index) + self.tableWidget_FPU.setItem(row, FLOAT_REGISTERS_NAME_COL, QTableWidgetItem(current_st_register)) + self.tableWidget_FPU.setItem(row, FLOAT_REGISTERS_VALUE_COL, + QTableWidgetItem(float_registers[current_st_register])) + self.tableWidget_XMM.setItem(row, FLOAT_REGISTERS_NAME_COL, QTableWidgetItem(current_xmm_register)) + self.tableWidget_XMM.setItem(row, FLOAT_REGISTERS_VALUE_COL, + QTableWidgetItem(float_registers[current_xmm_register])) + + def set_register(self, index): + current_row = index.row() + if self.currentWidget() == self.FPU: + current_table_widget = self.tableWidget_FPU + elif self.currentWidget() == self.XMM: + current_table_widget = self.tableWidget_XMM + current_register = current_table_widget.item(current_row, FLOAT_REGISTERS_NAME_COL).text() + current_value = current_table_widget.item(current_row, FLOAT_REGISTERS_VALUE_COL).text() + label_text = "Enter the new value of register " + current_register.upper() + register_dialog = DialogWithButtonsForm(label_text=label_text, hide_line_edit=False, + line_edit_text=current_value) + if register_dialog.exec_(): + if self.currentWidget() == self.XMM: + current_register = current_register + ".v4_float" + GDB_Engine.set_convenience_variable(current_register, register_dialog.get_values()) + self.update_registers() + + +class StackTraceInfoWidgetForm(QWidget, StackTraceInfoWidget): + def __init__(self, parent=None): + super().__init__(parent=parent) + self.setupUi(self) + GuiUtils.center(self) + self.setWindowFlags(Qt.Window) + self.listWidget_ReturnAddresses.currentRowChanged.connect(self.update_frame_info) + self.update_stacktrace() + + def update_stacktrace(self): + self.listWidget_ReturnAddresses.clear() + return_addresses = GDB_Engine.get_stack_frame_return_addresses() + self.listWidget_ReturnAddresses.addItems(return_addresses) + + def update_frame_info(self, index): + frame_info = GDB_Engine.get_stack_frame_info(index) + self.textBrowser_Info.setText(frame_info) + + +if __name__ == "__main__": + app = QApplication(sys.argv) + window = MainForm() + window.show() + sys.exit(app.exec_()) diff --git a/PINCE.sh b/PINCE.sh old mode 100755 new mode 100644 index e24d046f..d2a664a8 --- a/PINCE.sh +++ b/PINCE.sh @@ -1,6 +1,6 @@ -#!/bin/sh +#!/bin/bash : ' -Copyright (C) 2016-2017 Korcan Karaokçu +Copyright (C) 2016 Korcan Karaokçu This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -16,71 +16,10 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . ' -SCRIPTDIR=$(cd -- "$(dirname -- "$0")" && pwd -P) -if [ ! -d "${SCRIPTDIR}/.venv/bin" ]; then - echo "Please run \"sh install.sh\" first!" - exit 1 -fi -. "${SCRIPTDIR}/.venv/bin/activate" - -PYTHON="${SCRIPTDIR}/.venv/bin/python3" -PINCE_PY="${SCRIPTDIR}/PINCE.py" - -if [ -n "$1" ]; then - PCT_DIR=$(cd -P -- "$(dirname -- "$1")" && pwd -P) || exit 1 - PCT_FILE="$PCT_DIR/$(basename -- "$1")" -fi - -if [ "$(id -u)" = "0" ]; then - "$PYTHON" "$PINCE_PY" "$PCT_FILE" +# Change this bullcrap when polkit is implemented +OS=$(lsb_release -si) +if [ $OS = "Debian" ]; then + gksudo python3 PINCE.py else - if command -v pkexec > /dev/null 2>&1; then - # Preserve env vars to keep settings like theme preferences. - # Pkexec does not support passing all of env via a flag like "-E", - # so we need to rebuild the env and then pass it through. - set -- - while IFS= read -r line - do - case "$line" in - BASH_FUNC_*%%=*) continue ;; - *=*) ;; - *) continue ;; - esac - set -- "$@" "$line" - done <"$out" 2>"$err"' \ - sh "$pince_stdout" "$pince_stderr" "$PYTHON" "$PINCE_PY" "$PCT_FILE" \ - 2>&1 >/dev/null) - pkexec_status=$? - - case "$pkexec_err" in - *"No authentication agent found"*) ;; - *"Request dismissed"*) exit 126 ;; - *) - if [ -n "$pkexec_err" ]; then - printf '%s\n' "$pkexec_err" >&2 - fi - exit "$pkexec_status" - ;; - esac - fi - - if command -v sudo > /dev/null 2>&1; then - # Debian/Ubuntu does not preserve PATH through sudo even with -E for security reasons, - # so we need to force PATH preservation with venv activated user's PATH. - sudo -E --preserve-env=PATH "$PYTHON" "$PINCE_PY" "$PCT_FILE" - else - echo "No supported privilege escalation utility found. Please run this as root manually." - echo "Don't forget to preserve normal user environment variables for proper functionality." - exit 1 - fi -fi + sudo python3 PINCE.py +fi \ No newline at end of file diff --git a/README.md b/README.md index a527f087..ea532e70 100644 --- a/README.md +++ b/README.md @@ -1,116 +1,107 @@ -# PINCE - -PINCE is a front-end/reverse engineering tool for the GNU Project Debugger (GDB), focused on games. However, it can be used for any reverse-engineering related stuff. PINCE is an abbreviation for "PINCE is not Cheat Engine". - -Read [Features](#features) part of the project to see what is done and [Roadmap](CONTRIBUTING.md#roadmap) part to see what is currently planned. Also, please read [Wiki Page](https://github.com/korcankaraokcu/PINCE/wiki) of the project to understand how PINCE works. - -### [Feel free to join our discord server!](https://discord.gg/jVt3BzTSpz) - -### [Browse and download community cheat tables at the PCT-archive!](https://pince-org.github.io/PCT-archive/) - -*Disclaimer: Do not trust to any source other than this GitHub repo that claims to have the source code or package for PINCE and remember to report them **immediately*** - -*Disclaimer: **YOU** are responsible for your actions. PINCE does **NOT** take any responsibility for the damage caused by the users* - -![pince1](https://github.com/user-attachments/assets/7894b8da-160b-437f-9d02-a2ba6ebbcc02) -![pince2](https://github.com/user-attachments/assets/5184628d-084e-4e92-bae9-a2ff34bbeaef) -![pince3](https://github.com/user-attachments/assets/1fb6777b-2a07-40de-9bdd-89db6c7da822) -![pince4](https://github.com/user-attachments/assets/68b2ef52-9d64-4687-9c28-0573c1a3aa15) -![pince5](https://github.com/user-attachments/assets/cc09e467-d7de-4231-b181-7cc794ecaea5) - - -# Features -- **Memory and pointer scanning:** PINCE uses [libmemscan](https://github.com/brkzlr/libmemscan) to scan the memory efficiently -- **Speedhack:** Both Linux native and WINE/Proton compatible speedhack built-in. No **`LD_PRELOAD`** or other libraries necessary -- **Libpince Engine:** Powerful scripting engine built-in that allows you to perform advanced tasks such as code injection -- **Background Execution:** PINCE uses background execution by default, allowing users to run GDB commands while process is running -- **Variable Inspection & Modification** - * **CheatEngine-like value type support:** Currently supports all types of CE and memscan along with extended strings(utf-8, utf-16, utf-32) - * **BitField support:** Similarly to CE's `Binary`, read and edit 1–64 bit fields at any bit offset as signed, unsigned or hexadecimal values without altering surrounding bits - * **Symbol Recognition:** See [here](https://github.com/korcankaraokcu/PINCE/wiki/GDB-Expressions) - * **Automatic Variable Allocation:** See [here](https://github.com/korcankaraokcu/PINCE/wiki/GDB-Expressions#allocation-using-expressions) - * **Dynamic Address Table:** Supports drag&drop, recursive copy&pasting&inserting and many more - * **Smart casting:** PINCE lets you modify multiple different-type values together as long as the input is parsable. All parsing/memory errors are directed to the terminal - * **Variable Locking:** PINCE lets you freeze(constantly write a value to memory cell) variables -- **Sessions:** Save and restore your work as a session file (**`.pct`**), including the address table, bookmarks, free-form session notes and structures. You can browse and share these tables in the community [PCT-archive](https://github.com/PINCE-org/PCT-archive) -- **Memory View** - * **Assembler:** PINCE uses keystone engine to assemble code on the fly - * **Dissect Code:** You can dissect desired memory regions to find referenced calls, jumps and strings. Disassemble screen will automatically handle the referenced data and show you if there's a referenced address in the current disassemble view. It can be used from **`Tools -> Dissect Code`** in the MemoryView window. Using its hotkey instead in the MemoryView window automatically dissects the currently viewed region. You can separately view referenced calls and strings after the search from **`View -> Referenced Calls/Strings`**. *Note: If you decide to uncheck 'Discard invalid strings' before the search, PINCE will try to search for regular pointers as well* - * **Bookmarking:** Bookmark menu is dynamically created when right clicked in the disassemble screen. PINCE also lets you set an unlimited number of bookmarks. List of bookmarks can also be viewed from **`View -> Bookmarks`** in the MemoryView window. Commenting on an address automatically bookmarks it - * **Modify on the fly:** PINCE lets you modify registers on the fly. Check [GDB expressions in the Wiki page](https://github.com/korcankaraokcu/PINCE/wiki/GDB-Expressions) for additional information - * **Instructions Search:** You can search instructions with python regular expressions. To use this feature, click **`Tools -> Search Instructions`** in the MemoryView window - * **Search Functions:** Search the target's defined functions and symbols with python regular expressions and jump straight to their addresses. Click **`View -> Functions`** in the MemoryView window - * **Memory Regions:** View the target's memory map and jump to any of its regions. Click **`View -> Memory Regions`** in the MemoryView window - * **Restore Instructions:** Revert instructions you've assembled over back to their original bytes. Click **`View -> Restore Instructions`** in the MemoryView window - * **Call Function:** Call a function inside the target process with a GDB expression and inspect its return value. Click **`Tools -> Call Function`** in the MemoryView window -- **Mono/IL2CPP Dissection** - * Dissect the managed runtime of Mono and IL2CPP games. Browse classes along with their fields and methods, read static and instance field values, and drill into nested types. Accessible from **`Tools -> Dissect Mono/IL2CPP`** in the MemoryView window. Works for both Linux native and WINE/Proton processes - * **Find Instances:** Locate live instances of a class in the target process - * **Invoke Methods:** Call methods directly on a chosen instance and inspect the returned value - * **Export to Structures:** Turn a dissected class into a PINCE structure for reuse -- **Structures:** Define and view memory structures with named, typed members. Build them by hand or generate them automatically from a dissected Mono/IL2CPP class, then overlay them on any address to inspect memory through the structure -- **Debugging** - * Has basic debugging features such as stepping, stepping over, execute till return, break, continue. Also has breakpoints, watchpoints and breakpoint conditions. Has advanced debugging utilities such as Watchpoint/Breakpoint Tracking and Tracing - * **Chained Breakpoints:** Just like CE, PINCE allows you to set multiple, connected breakpoints at once. If an event(such as condition modification or deletion) happens in one of the breakpoints, other connected breakpoints will get affected as well - * **Watchpoint Tracking:** Allows you to see which instructions have been accessing to the specified address, just like "What accesses/writes to this address" feature in CE - * **Breakpoint Tracking:** Allows you to track down addresses calculated by the given register expressions at the specified instruction, just like "Find out what addresses this instruction accesses" feature in CE with a little addon, you can enter multiple register expressions, this allows you to check the value of "esi" even if the instruction is something irrelevant like "mov [eax],edx" - * **Tracing:** Almost the same with CE. But unlike CE, you can stop tracing whenever you want. Created from scratch with custom features instead of using gdb's built-in trace commands, this allows tracing to be done without the need of a gdbserver - * **Collision Detection:** GDB normally permits setting unlimited watchpoints next to each other. But this behaviour leads to unexpected outcomes such as causing GDB or the inferior become completely inoperable. GDB also doesn't care about the number(max 4) or the size(x86->max 4, x64->max 8) of hardware breakpoints. Fortunately, PINCE checks for these problems whenever you set a new breakpoint and detects them before they happen and then inhibits them in a smart way. Lets say you want to set a breakpoint in the size of 32 bytes. But the maximum size for a breakpoint is 8! So, PINCE creates 4 different breakpoints with the size of 8 bytes and then chains them for future actions - * **Stack Trace:** View the call stack of the stopped thread along with the return and frame addresses of each frame. Click **`View -> StackTrace Info`** in the MemoryView window - * **Signal Handling:** Configure how the inferior handles each signal, choosing whether GDB stops on it and whether it's passed on to the program, just like GDB's `handle` command. Accessible from PINCE's Settings -- **Code Injection** - * **Run-time injection:** Both native `.so` injection and WINE/Proton DLL injection are supported. In the MemoryView window, click **`Tools -> Inject .so file`** or **`Tools -> Inject DLL file`** to select the file -- **GDB Console:** You can use the GDB Console to interact with GDB, it's on the top right in main window -- **libpince library:** PINCE provides a reusable python library. You can either read the code or check the [Github Pages](https://korcankaraokcu.github.io/PINCE/) for documentation. Additionally, libpince can be used via console by following [these instructions](https://github.com/korcankaraokcu/PINCE/issues/232#issuecomment-1872906700). - -# Installing and running PINCE -### Users -No need to install anything. Just grab the latest AppImage over at [Releases](https://github.com/korcankaraokcu/PINCE/releases) and mark it as executable. You can then double click on the AppImage or run it through terminal, however you prefer. - -To mark as executable, either: -- Run the following command in terminal in the same folder as the downloaded AppImage: `chmod +x PINCE-x86_64.AppImage` -- Or you can right-click on the AppImage, click on Properties and tick "Allow this file to run as a program" under "Permissions" - - The last step might be different depending on your desktop environment, but most of them should have similar words so just make sure to edit permissions to allow running as executable. - -### Developers and Contributors -- If you want to have a local install of PINCE so you can modify code or contribute with PRs, you'll have to use our installer script in the repo to setup a venv dev environment or do it yourself. -- To install local dev environment, run the following commands in a terminal anywhere you'd like to have the PINCE folder: -```bash -git clone --recursive https://github.com/korcankaraokcu/PINCE -sh PINCE/install.sh +#PINCE +PINCE is a front-end/reverse engineering tool for the GNU Project Debugger (GDB), focused on games. But it can be used for any reverse-engineering related stuff. PINCE is an abbreviation for "PINCE is not Cheat Engine". PINCE's GUI is heavily "inspired(;D)" by Cheat Engine. PINCE is in development right now, read features part of the project to see what is planned and what is done for now. Also, please read [Wiki Page](https://github.com/korcankaraokcu/PINCE/wiki) of the project to understand how PINCE works. + +Pre-release screenshots: +![](screenshots/pince.png) +![](screenshots/pince1.png) +![](screenshots/pince2.png) +![](screenshots/pince3.png) +#Features +- **Memory searching** **[Planned]** (The plan is to use libscanmem by wrapping it with a gdb python script) +- **Variable Inspection&Modification** **[Done/Basic]** + * **CheatEngine-like value type support:** Byte to 8 Bytes, Float, Double, Strings(including utf-8 and zero-terminate strings), Array of Bytes **[Done]** + * **Symbol Recognition:** Try typing any widely used library function(such as malloc, open, printf, scanf etc) to AddAddressManually dialog **[Done]** + * **Automatic Variable Allocation:** In AddAddressManually dialog, if your input is in quotes it's treated as a string, if your input is in curly brackets, it's treated as an array of variables(for instance: "asdf"=string, {0x00ffba42}=integer(4byte), {0x00000023,0x00513245,..}=array of 2 integers. After pressing OK button PINCE will allocate memory for you to use that variable right away! **[Done]** + * **Dynamic Address Table:** Drag&drop rows, ctrl+c&ctrl+v between independent PINCE processes, clipboard text analysis(PINCE will try to analyze the contents of the current clipboard and try to pick data from it to convert for address table) **[Planned]** + * **Manual Address Table Update:** **[Done]** + * **Smart casting:** PINCE lets you modify multiple different-type values together as long as the input is parsable. All parsing/memory errors are directed to the terminal **[Done]** + * **Continuous Address Table Update:** You can adjust update timer or cancel updating by modifying settings. Non-stop version is Postponed\Quarterway Done **[Done\Only works when the inferior is stopped]** + * **Variable Locking:** PINCE lets you freeze(constantly write a value to memory cell) variables **[Postponed\Quarterway Done]** + * *Postpone reason:* These two features requires thread injection to the target or gdb and PINCE's injection methods are not perfect yet, I've already spent more(read:WAY MORE) time than I should on this, these features are not vital for now, also you have got the options to manually update the table and set the value manually already +- **Memory View** **[Done/Basic]** + * **Infinite Scrolling:** PINCE automatically disassembles the next available instruction(s) on mouse wheel/scrollbar move. Instruction count can be changed from settings. Hex View also supports this feature **[Done]** + * **Following:** If you press [space], PINCE automatically analyzes the selected instruction and if any location changing instruction is found, PINCE disassembles the address that's pointed by the instruction **[Done]** + * **Travel History:** PINCE records your previous location when you jump to an address explicitly(e.g by pressing [space] or using "Go to expression" etc.). Right click->Back to go back to your previous location(s) **[Done]** + * **Bookmarking:** Bookmark menu is dynamically created when right clicked in the disassemble screen. So unlike Cheat Engine, PINCE lets you set unlimited number of bookmarks. List of bookmarks can also be viewed from View->Bookmarks in the MemoryView window. Commenting on an address automatically bookmarks it. **[Done]** + * **Modify on the fly:** PINCE lets you modify registers on the fly. Unlike CE, you can also change XMM and FPU registers. **[Done]** +- **Debugging** **[Working on it]** + * Can interrupt and continue the inferior, Check wiki for instructions +- **Code Injection** **[Working on it]** + * **Run-time injection:** Only .so injection is supported for now. In Memory View window, click Tools->Inject .so file to select the .so file. An example for creating .so file can be found in "libPINCE/Injection/". PINCE will be able to inject single line instructions or code caves in near future **[Partially Done?]** +- **GDB Console** **[Done]** + * Is the power of PINCE not enough for you? Then you can use the gdb console provided by PINCE, it's on the top right in main window +- **Simplified/Optimized gdb command alternatives** **[Working on it]** + * Custom scripts instead of using gdb's x command for reading memory **[Done]** + * Custom scripts instead of using gdb's set command for modifying memory **[Done]** +- **libPINCE- A reusable python library** **[Current Status:*Reusable for FP* , *Refactoring for OOP*]** + * PINCE provides a reusable python library. I'll write a fully-documented guide about how to use it as soon as the project finishes at basic level. Until that moment, I'll keep developing libPINCE as modular as possible +- **Automatic Trainer Generation:** **[Planned]** + * PINCE provides a trainer auto-generated from current address table on demand by using libPINCE and PyQT5 together + +#Installing Automatically +Just run ```sudo sh install.sh``` in the PINCE directory. Install script currently supports Ubuntu and Debian. See below if the automatic installation fails. This install script is temporary. I'll make a PPA when this project finishes. +#Installing Manually +To run PINCE, run this command chain then compile gdb if necessary: + ``` -- Make sure to check our [Officially supported platforms](#officially-supported-platforms) section below. Our installer might not work on distros that are not listed there, but it will still try to install using some package managers, just follow the on-screen instructions. -- If installer fails trying to install on an unsupported distro, you're on your own on trying to get the local dev environment up and running. Check `install.sh` to get an idea about what you might need. -- If you'd like to uninstall PINCE, just delete this folder, almost everything is installed locally. Config and user files of PINCE can be found in "~/.config/PINCE", you can manually delete them as well if you want. - -### Notes -- Check https://github.com/korcankaraokcu/PINCE/issues/116 for a possible fix if you encounter `'GtkSettings' has no property named 'gtk-fallback-icon-theme'` - -# Officially supported platforms -### AppImage -Our AppImage should run on any distro that is as new or newer than Ubuntu 22.04. Anything older than this might not work and is not officially supported. - -### Local dev -Local dev installs of PINCE should technically run on any distro that comes with **Python 3.11+** and **PyQt 6.11+** installed or available in the package manager, but below is the list of distros that we officially support, as in we actively test on these and help with issues: -- Kubuntu 22.04+ -- Arch Linux (**Not AUR**) - -Additionally the distros below are "partially" supported as our installer will try to install on them but ***they're not actively tested***: -- Debian 12+ (or Testing) -- Fedora 35+ -- OpenSUSE - -### Notes -- If you encounter issues installing local dev and you're on one of these distros, feel free to open a PR fixing the installation process for your platform. -- If your distro has any of the above as its base, you can still try to use the installer anyway and pick the relevant package manager. If this still does not work then sorry, you're on your own. -- ***DO NOT open issues if you cannot repro using a local dev build on a supported distro from above or AppImage!*** - - **This includes AUR or NIXPKGS. We don't care about the issues present on these packaged versions unless you can repro them on AppImage (or also local dev if you're on Arch).** - -# Contributing -Want to help? Check out [CONTRIBUTING.md](CONTRIBUTING.md) - -# License -GPLv3+. See [COPYING](COPYING) file for details +sudo apt-get install python3-setuptools +sudo apt-get install python3-pip +sudo apt-get install python3-pyqt5 +sudo pip3 install psutil +sudo pip3 install pexpect +``` +###**Compiling the most recent gdb version with python support** +#####*You can skip this part if you already have gdb 7.11.1 with python3 support, but it's strongly recommended to compile from source instead of downloading from repos because python version of gdb may mismatch with default interpreter and it usually causes ImportError within gdb scripts* +Download the latest source from [here](http://ftp.gnu.org/gnu/gdb/gdb-7.11.1.tar.gz), then install packages required for gdb +``` +sudo apt-get install python3-dev +sudo apt-get install gcc +``` +Then ```cd``` to the source file you downloaded and run: +```CC=gcc ./configure --prefix=/usr --with-python=python3 && make && sudo make -C gdb install``` +Note: If gdb says something about missing python files, move the contents of gdb/data-directory to /usr/share/gdb: +```sudo cp -R gdb/data-directory/* /usr/share/gdb/``` +#####Relocating PINCE files +Create the file ```.gdbinit``` in your home directory and add the line ```set auto-load safe-path /``` to it +#Running PINCE +Just run ```sh PINCE.sh``` in the PINCE directory + +###For developers: +``` +sudo apt-get install qttools5-dev-tools (qt5 form designer) +sudo apt-get install pyqt5-dev-tools (pyuic5) +``` + +#History +- A few weeks till 17/01/2016 : Learned GDB, process of analysis +- 17/01/2016-22/01/2016 : Basic design, grasping of Python3 and Pyqt5, proof-testing +- 22/01/2016 : First commit +- 19/02/2016 : Moved to Github from Bitbucket +- 25/02/2016 : First successful implementation of thread injection[Update-08/05/2016 : PINCE now uses ```linux-inject``` as a secondary injection method] +- 18/06/2016 : PINCE now supports all-stop mode instead of non-stop mode +- 21/06/2016 : Variable Inspection&Modification is finished +- 21/08/2016 : Memory View is finished +- 24/08/2016 : PINCE no more uses linux-inject because of licensing and stability issues + +#License +GPLv3+. See COPYING file for details + +#Contact Information +Korcan Karaokçu +Çağrı Ulaş + +#Supported platforms +- **Platforms tested so far:** + * Kubuntu 14.04 & 16.04(Also tested on x86 variants) + * Debian 8.5 + * Archlinux(contact with [Çağrı Ulaş](https://github.com/cagriulas)) +- **Games&Applications tested so far:** + * KMines + * Torchlight 2 + * Skullgirls + * Steam + * Firefox + * WINE Games + * FTL + * Undertale + * Hearthstone(It interrupts itself with SIGUSR1 whenever continued, implementing signal passing on PINCE might be very useful in future) diff --git a/THANKS b/THANKS index 0ace4688..de8df276 100644 --- a/THANKS +++ b/THANKS @@ -1,7 +1,6 @@ Sebastian Parschauer -Andrea Stacchiotti -XutaxKamay +Andrea Stacchiotti Salih Marangoz Hjalte Skjold Hørsdal Juuso Lapinlampi -Özcan Esen +Özcan Esen \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100644 index 00000000..8d1c8b69 --- /dev/null +++ b/__init__.py @@ -0,0 +1 @@ + diff --git a/ci/package.sh b/ci/package.sh deleted file mode 100755 index 0b30b0c5..00000000 --- a/ci/package.sh +++ /dev/null @@ -1,211 +0,0 @@ -#!/bin/sh -: ' -Copyright (C) 2024 brkzlr - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -' - -# Check if the file is in the correct directory and cd there -# This script should be only in PINCE/ci folder -PACKAGEDIR="$(dirname "$(readlink -f "$0")")" -cd "$PACKAGEDIR" || exit -[ -f ../install.sh ] && [ -f ../PINCE.py ] || { echo "package.sh is not in PINCE/ci folder!"; exit 1; } - -# Create cleanup function to remove remaining deps/files -cleanup () { - cd "$PACKAGEDIR" || return - # Remove everything outside of package.sh and AppImage output - find ! -iname "package.sh" ! -iname "PINCE*.AppImage" ! -iname "PINCE*.zsync" -delete -} -trap cleanup EXIT - -# Error checking function -exit_on_failure() { - echo - echo "Error occurred while creating AppImage! Check the log above!" - exit 1 -} -cleanup || exit_on_failure - -# Reuse install.sh's functions -PINCE_LIB_ONLY=1 -. ../install.sh - -if [ -r /etc/os-release ]; then - . /etc/os-release - OS_NAME="$ID $ID_LIKE" -fi -set_install_vars "$OS_NAME" || LRELEASE_CMD="$(command -v lrelease6)" # fallback for unsupported distros -case $OS_NAME in *arch*) export NO_STRIP=1 ;; esac # skip strip on Arch for linuxdeploy -export ARCH=x86_64 - -# Download necessary tools -DEPLOYTOOL=./linuxdeploy-x86_64.AppImage -curl -fLO https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage || exit_on_failure -curl -fLO https://raw.githubusercontent.com/TheAssassin/linuxdeploy-plugin-conda/master/linuxdeploy-plugin-conda.sh || exit_on_failure -chmod +x "$DEPLOYTOOL" linuxdeploy-plugin-conda.sh || exit_on_failure - -# Create AppImage's AppDir with a Conda environment pre-baked containing Python, GDB and our pip packages. -# Need xcb-util-cursor for Debian family and a CA bundle for Python HTTPS requests inside the AppImage. -# Qt intentionally stays on the PyQt6 wheels instead of conda because the wheels bundle no glib/pango/cairo, -# so the entire GTK stack comes from the host and stays self-consistent. -# Conda ships its own copies of those and wins some SONAMEs while the host wins others, breaking the GTK platform theme when the versions differ. -printf '%s\n' 'channels: [conda-forge]' 'default_channels: []' > conda-appimage.yml || exit_on_failure -CONDARC="$PWD/conda-appimage.yml" PIP_REQUIREMENTS="--only-binary=:all: -r ../requirements.txt" \ - CONDA_PACKAGES="python=3.14.6;gdb=17.2;xcb-util-cursor;ca-certificates" "$DEPLOYTOOL" --appdir AppDir -pconda || exit_on_failure - -# The wheels ship the whole of Qt, so walk the ELF dependencies of the modules a widgets app actually loads and delete everything unreachable, -# dropping Quick, QML, 3D, Multimedia/ffmpeg and Designer. -AppDir/usr/conda/bin/python3 - AppDir/usr/conda/lib/python3.14/site-packages/PyQt6/Qt6 <<'PRUNE_EOF' || exit_on_failure -import glob, os, shutil, subprocess, sys -qt_dir, lib = sys.argv[1], sys.argv[1] + "/lib" -keep = ["platforms", "platformthemes", "platforminputcontexts", "iconengines", "imageformats", "printsupport", - "xcbglintegrations", "tls", "networkinformation", "generic", "wayland-decoration-client", - "wayland-graphics-integration-client", "wayland-shell-integration"] -todo = [f"{lib}/libQt6{m}.so.6" for m in ("Core", "Gui", "Widgets", "DBus", "Svg", "PrintSupport", "Network")] -todo += [p for name in keep for p in glob.glob(f"{qt_dir}/plugins/{name}/*.so")] -alive = set() -while todo: - path = os.path.realpath(todo.pop()) - if path in alive or not os.path.isfile(path): - continue - alive.add(path) - needed = subprocess.run(["patchelf", "--print-needed", path], capture_output=True, text=True).stdout - todo += [f"{lib}/{so}" for so in needed.split()] -for path in glob.glob(f"{lib}/*.so*"): - if os.path.isfile(path) and os.path.realpath(path) not in alive: - os.remove(path) -for name in os.listdir(f"{qt_dir}/plugins"): - if name not in keep: - shutil.rmtree(f"{qt_dir}/plugins/{name}") -shutil.rmtree(f"{qt_dir}/qml", ignore_errors=True) -PRUNE_EOF - -# Keep AppImage paths out of programs launched by GDB -rm AppDir/usr/bin/gdb || exit_on_failure -cat > AppDir/usr/bin/gdb <<'GDB_WRAPPER_EOF' || exit_on_failure -#!/bin/sh -exec "$(dirname "$0")/../conda/bin/gdb" -iex 'unset environment PYTHONHOME' -iex 'unset environment APPDIR' "$@" -GDB_WRAPPER_EOF -chmod +x AppDir/usr/bin/gdb || exit_on_failure - -# Create PINCE directory -mkdir -p AppDir/opt/PINCE || exit_on_failure - -# Set LIBMEMSCAN_CPU so libmemscan builds with SSE4.2 and not AVX512 (which is the default on our GitHub runner). -# This way users with CPUs older than 2016 (but not older than 2009) can use our AppImage. -# Also target glibc 2.35 so the build does not inherit a newer runner host's ABI. -cd .. -SCRIPTDIR="$PWD" -LIBMEMSCAN_CPU="-Dtarget=x86_64-linux-gnu.2.35 -Dcpu=x86_64_v2" -build_libmemscan || exit_on_failure -build_mono_collector || exit_on_failure -compile_translations || exit_on_failure - -# Copy necessary PINCE folders/files to inside AppDir -cp -r GUI i18n libpince media tr AUTHORS COPYING COPYING.CC-BY PINCE.py THANKS ci/AppDir/opt/PINCE/ || exit_on_failure -cd ci || exit_on_failure - -cat > AppDir/opt/PINCE/update-check.json <<\EOF || exit_on_failure -{ - "type": "zsync", - "url": "https://github.com/korcankaraokcu/PINCE/releases/latest/download/PINCE-x86_64.AppImage.zsync" -} -EOF - -# Create a desktop file for AppImage -cat > AppDir/usr/share/applications/PINCE.desktop <<\EOF || exit_on_failure -[Desktop Entry] -Name=PINCE -Exec=PINCE -Icon=PINCE -Type=Application -Categories=Development; -EOF - -# Copy icon for the above desktop file -cp ../media/logo/ozgurozbek/pince_appimage.png PINCE.png || exit_on_failure - -# Create main running script -cat > AppRun.sh <<\APPRUN_EOF || exit_on_failure -#!/bin/sh - -if [ -n "$1" ]; then - PCT_DIR=$(cd -P -- "$(dirname -- "$1")" && pwd -P) || exit 1 - PCT_FILE="$PCT_DIR/$(basename -- "$1")" -fi - -if [ "$(id -u)" != "0" ]; then - if command -v pkexec > /dev/null 2>&1; then - # Preserve env vars to keep settings like theme preferences. - # Pkexec does not support passing all of env via a flag like "-E", - # so we need to rebuild the env and then pass it through. - set -- - while IFS= read -r line - do - case "$line" in - BASH_FUNC_*%%=*) continue ;; - *=*) ;; - *) continue ;; - esac - set -- "$@" "$line" - done <"$out" 2>"$err"' \ - sh "$pince_stdout" "$pince_stderr" "$APPIMAGE" "$PCT_FILE" \ - 2>&1 >/dev/null) - pkexec_status=$? - - case "$pkexec_err" in - *"No authentication agent found"*) ;; - *"Request dismissed"*) exit 126 ;; - *) - [ -z "$pkexec_err" ] || printf '%s\n' "$pkexec_err" >&2 - exit "$pkexec_status" - ;; - esac - fi - - if command -v sudo > /dev/null 2>&1; then - # Debian/Ubuntu does not preserve PATH through sudo even with -E for security reasons, - # so we need to force PATH preservation with venv activated user's PATH. - sudo -E --preserve-env=PATH "$APPIMAGE" "$PCT_FILE" - else - echo "No supported privilege escalation utility found. Please run this as root manually." - exit 1 - fi - - exit -fi -APPDIR="$(dirname "$0")" -export APPDIR -export PYTHONHOME="$APPDIR/usr/conda" -exec "$APPDIR/usr/conda/bin/python3" "$APPDIR/opt/PINCE/PINCE.py" "$PCT_FILE" -APPRUN_EOF -chmod +x AppRun.sh || exit_on_failure - -# Patch libqxcb's runpath (not rpath) to point to our packaged libxcb-cursor to fix X11 issues -patchelf --add-rpath "\$ORIGIN/../../../../../../" AppDir/usr/conda/lib/python3.14/site-packages/PyQt6/Qt6/plugins/platforms/libqxcb.so || exit_on_failure - -# Package AppDir into AppImage -export LDAI_UPDATE_INFORMATION="gh-releases-zsync|korcankaraokcu|PINCE|latest|PINCE-x86_64.AppImage.zsync" -"$DEPLOYTOOL" --icon-file PINCE.png --appdir AppDir/ --output appimage --custom-apprun AppRun.sh || exit_on_failure diff --git a/compile_ts.sh b/compile_ts.sh deleted file mode 100755 index 589c1956..00000000 --- a/compile_ts.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/sh -SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" -cd "$SCRIPT_DIR" || exit - -venv_activator=".venv/bin/activate" -if [ -f "$venv_activator" ]; then - . "$venv_activator" -else - echo "ERROR: Virtual environment not found, please use install.sh to install PINCE first" - exit -fi - -supported_locale_list=$(python3 -c " -import locale -print('\n'.join(value.split('.')[0] for value in locale.locale_alias.values())) -") -list_ts=$(find i18n/ts -maxdepth 1 -type f -name '*.ts') - -# If there's a user parameter, create a new locale based on it -if [ -n "$1" ]; then - list_ts="$list_ts i18n/ts/$1.ts" -fi - -for ts in $list_ts; do - # Check if the locale is valid - if echo "$supported_locale_list" | grep -q "$(basename "$ts" .ts)"; then - pylupdate6 GUI/Widgets/*/Form/*.ui tr/tr.py --no-obsolete --ts "$ts" - python3 fix_ts.py "$ts" - else - list_invalidts="$list_invalidts $ts" - fi -done - -if [ -n "$list_invalidts" ]; then - echo - echo "ERROR: The following locales are invalid, please check:" - echo "$list_invalidts" - exit 1 -fi diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index d0c3cbf1..00000000 --- a/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = source -BUILDDIR = build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/build_html.sh b/docs/build_html.sh deleted file mode 100755 index 601bbf82..00000000 --- a/docs/build_html.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" -cd "$SCRIPT_DIR" || exit - -venv_activator="../.venv/bin/activate" -if [ -f "$venv_activator" ]; then - . "$venv_activator" -else - echo "ERROR: Virtual environment not found, please use install.sh to install PINCE first" - exit -fi - -make clean -make html diff --git a/docs/install_sphinx.sh b/docs/install_sphinx.sh deleted file mode 100755 index 0ec1e2b5..00000000 --- a/docs/install_sphinx.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" -cd "$SCRIPT_DIR" || exit - -venv_activator="../.venv/bin/activate" -if [ -f "$venv_activator" ]; then - . "$venv_activator" -else - echo "ERROR: Virtual environment not found, please use install.sh to install PINCE first" - exit -fi - -pip install sphinx -pip install sphinx-autodoc-typehints diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 46bdf9c8..00000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,37 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# For the full list of built-in configuration values, see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Project information ----------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information - -import os -import sys - -sys.path.insert(0, os.path.abspath(os.path.join("..", ".."))) - -project = "PINCE" -copyright = "2024, PINCE Contributors" -author = "PINCE Contributors" - -# -- General configuration --------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration - -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "sphinx.ext.intersphinx", - "sphinx_autodoc_typehints", -] - -templates_path = ["_templates"] -exclude_patterns = [] - -# -- Options for HTML output ------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output - -html_theme = "alabaster" -html_static_path = ["_static"] diff --git a/docs/source/gui_utils.rst b/docs/source/gui_utils.rst deleted file mode 100644 index 7f073e39..00000000 --- a/docs/source/gui_utils.rst +++ /dev/null @@ -1,29 +0,0 @@ -GUI.Utils package -================= - -Submodules ----------- - -GUI.Utils.guiutils module -------------------------- - -.. automodule:: GUI.Utils.guiutils - :members: - :undoc-members: - :show-inheritance: - -GUI.Utils.guitypedefs module ----------------------------- - -.. automodule:: GUI.Utils.guitypedefs - :members: - :undoc-members: - :show-inheritance: - -GUI.Utils.utilwidgets module ----------------------------- - -.. automodule:: GUI.Utils.utilwidgets - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index 37ff02b7..00000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,19 +0,0 @@ -.. PINCE documentation master file, created by sphinx-quickstart - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -Welcome to PINCE's documentation! -================================= - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - - modules - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/source/libpince.rst b/docs/source/libpince.rst deleted file mode 100644 index 74b57ad6..00000000 --- a/docs/source/libpince.rst +++ /dev/null @@ -1,45 +0,0 @@ -libpince package -================ - -Submodules ----------- - -libpince.debugcore module -------------------------- - -.. automodule:: libpince.debugcore - :members: - :undoc-members: - :show-inheritance: - -libpince.regexes module ------------------------ - -.. automodule:: libpince.regexes - :members: - :undoc-members: - :show-inheritance: - -libpince.typedefs module ------------------------- - -.. automodule:: libpince.typedefs - :members: - :undoc-members: - :show-inheritance: - -libpince.utils module ---------------------- - -.. automodule:: libpince.utils - :members: - :undoc-members: - :show-inheritance: - -Module contents ---------------- - -.. automodule:: libpince - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/modules.rst b/docs/source/modules.rst deleted file mode 100644 index 6e7eea6e..00000000 --- a/docs/source/modules.rst +++ /dev/null @@ -1,15 +0,0 @@ -libpince -======== - -.. toctree:: - :maxdepth: 4 - - libpince - -GUI.Utils -========= - -.. toctree:: - :maxdepth: 4 - - gui_utils diff --git a/fix_ts.py b/fix_ts.py deleted file mode 100644 index 8c619bf9..00000000 --- a/fix_ts.py +++ /dev/null @@ -1,28 +0,0 @@ -import xml.etree.ElementTree as ET -import sys -import os - -file = sys.argv[1] -tree = ET.parse(file, parser=ET.XMLParser(encoding="utf-8")) -root = tree.getroot() - -# pylupdate6 doesn't set locale on creation, make sure it's there -locale = os.path.splitext(os.path.basename(file))[0] -root.set("language", locale) - -# Removing line info so updating tr.py affects git history much less -for location in root.findall(".//location"): - location.set("line", "0") - -modified_xml = ET.tostring(root, encoding="utf-8", xml_declaration=False).decode() -with open(file, "r", encoding="utf-8") as f: - original_xml = f.read() - -# These declarations are hardcoded in pylupdate6, make sure everything is correct -declarations = original_xml.split("\n", 2)[:2] -assert declarations[0] == '', "xml format has changed" -assert declarations[1] == "", "doctype format has changed" -final_xml = "\n".join(declarations) + "\n" + modified_xml + "\n" - -with open(file, "w", encoding="utf-8") as f: - f.write(final_xml) diff --git a/i18n/ts/it_IT.ts b/i18n/ts/it_IT.ts deleted file mode 100644 index 78b89c9d..00000000 --- a/i18n/ts/it_IT.ts +++ /dev/null @@ -1,3522 +0,0 @@ - - - - - Dialog - - - Dissect Code - - - - - Regions - - - - - Path - - - - - Selected regions will be scanned - - - - - Currently scanning range: - - - - - String references found: - - - - - Jumps found: - - - - - Calls found: - - - - - Entries that can't be decoded as utf-8 won't be included in referenced strings -Unchecking it makes ReferencedStringsWidget load slower but allows you to examine non-string pointers on it - - - - - Discard invalid strings - - - - - Edit Instruction - - - - - - - Address: - Indirizzo: - - - - Instruction: - - - - - Multiple entries are separated with ; - - - - - - - - - Type - - - - - - Endianness - - - - - - Hex - - - - - - Signed - - - - - - Length - Lunghezza - - - - - Zero-Terminated - - - - - - Start bit - - - - - - Handle Signals - - - - - Signal - - - - - Stop & Print - - - - - Pass to Program - - - - - Hex Edit - - - - - - Length: - - - - - Refresh - - - - - Processing - - - - - Cancel - Annulla - - - - Manage Scan Regions - - - - - Selected regions will be deleted from the current scan - - - - - Invert Selection - - - - - Reset Regions - - - - - ID - - - - - Start Address - - - - - Size(bytes) - - - - - Load Address - - - - - Perms - - - - - File - - - - - Add Address Manually - - - - - Type: - - - - - - Endianness: - - - - - Start bit: - - - - - Base Address: - - - - - Add Offset - - - - - Remove Offset - - - - - Description: - - - - - - Pointer - - - - - Dissect Mono/IL2CPP - - - - - Search - - - - - Show inherited members - - - - - - - - - - Name - - - - - - - Value - Valore - - - - Find Instances - - - - - Invoke - - - - - Call - - - - - Compare & Filter Pointers - - - - - Previous Map: - - - - - - - - Browse - - - - - Current Map: - - - - - New Output Map: - - - - - Scan for Pointers - - - - - Target Address: - - - - - Pointer Map File Path: - - - - - Advanced Options - - - - - Scan Scope: - - - - - Pointer Size: - - - - - Max Depth: - - - - - Max Positive Offset: - - - - - - - 0x - - - - - Max Negative Offset: - - - - - Last Offset - - - - - Max Results - - - - - Module Bases Only - - - - - Settings - Impostazioni - - - - General - - - - - Hotkeys - - - - - Memory View - - - - - Debug - - - - - Java - - - - - Auto-update address table - - - - - Check for AppImage updates on startup - - - - - Update Interval - - - - - Freeze Interval - - - - - GDB output: - - - - - Async - - - - - Command - - - - - Command info - - - - - On start, automatically attach to processes with name matching one of the entries -Patterns at former positions have higher priority if regex is off - - - - - Auto-attach to processes named - - - - - Regex - - - - - Language - - - - - Logo - - - - - Theme - - - - - Save session when exiting PINCE - - - - - Remember last file save/open across restarts - - - - - Functions - - - - - Hotkey - - - - - Press shortcut - - - - - Clear - - - - - Bring Memory View to front when the inferior is stopped - - - - - Instructions shown per scroll in Disassembly View - - - - - Bytes shown per scroll in Hex View - - - - - GDB Path - - - - - GDB Logging - - - - - Interruption signal - - - - - Ignore SIGSEGV for Java processes (overrides signal settings if enabled) - - - - - Reset Settings - - - - - Member - - - - - Offset (hex) - - - - - Kind - - - - - Value type - - - - - Repr - - - - - Structure - - - - - Edit structure - - - - - - Offset - - - - - Add - - - - - Edit - - - - - Remove - - - - - Up - - - - - Down - - - - - Structure view - - - - - Base address - - - - - Add to address table - - - - - Dialog - - - - - Hit Esc to cancel and Ctrl+Enter to accept - - - - - Parameters for tracing - - - - - Number of the instructions that'll be traced - - - - - Max trace count(1 or greater): - - - - - Tracing will start if this condition is met - - - - - Trigger condition(Optional, gdb expression): - - - - - Tracing will stop whenever this condition is met - - - - - Stop condition(Optional, gdb expression): - - - - - Step over instead of single step - - - - - Stop when tracing ends - - - - - Collect registers - - - - - Select an address to track - - - - - Pointed Address - - - - Form - - - Bookmarks - - - - - Bookmarked Addresses - - - - - - Info - - - - - Comment - - - - - GDB Console - - - - - Send - - - - - CLI - - - - - MI - - - - - Examine Referrers - - - - - - - - - Enter a string or a python regex - - - - - - - - - Ignore case if checked - - - - - - - - - Case sensitive - - - - - - - - Your string will be treated as a regex if checked - - - - - - - - Regex - - - - - - - - - Search(Enter) - - - - - Functions - - - - - - - - - - - Address - Indirizzo - - - - Symbol - - - - - Enter the regex. Leave blank to see all functions - - - - - - - Form - - - - - - TextLabel - - - - - Memory Regions - - - - - Search path - - - - - Regions - - - - - Perms - - - - - Offset - - - - - Path - - - - - Referenced Calls - - - - - - Refcount - - - - - Referenced Strings and Values - - - - - - Value - Valore - - - - Restore Instructions - - - - - Original Opcodes - - - - - Original Instruction - - - - - Search for Instructions - - - - - Search: - - - - - Start - Inizio - - - - End - Fine - - - - Instruction - - - - - StackTrace Information - - - - - Return Address - - - - - Structures - - - - - Name - - - - - New - - - - - Edit - - - - - Delete - - - - - View at address… - - - - - Add to address table - - - - - Tracer Status - - - - - Cancel - Annulla - - - - - Count - - - - - Source - - - - - - Stop - - - - - Refresh - - - - MainWindow - - - Libpince Engine - - - - - (untitled) - - - - - + - - - - - Script output - - - - - - File - - - - - Templates - - - - - Help - - - - - Run - - - - - Code injection - - - - - - - Open - - - - - Ctrl+O - - - - - - Save - - - - - Ctrl+S - - - - - Libpince - - - - - Run [ENABLE] - - - - - Ctrl+Shift+E - - - - - Run [DISABLE] - - - - - Ctrl+Shift+D - - - - - Run selection - - - - - Ctrl+R - - - - - Clear output - - - - - Send to cheat table - - - - - Ctrl+Shift+T - - - - - AOB scan + NOP - - - - - AOB scan + patch - - - - - Read/write address - - - - - Memory View - - - - - Copy selected items to the address table - - - - - Erase all the table contents - - - - - Refresh the address table[R] - - - - - Add Address Manually - - - - - Freeze - - - - - Freeze the value. Click just to the right of checkbox to cycle between freeze types: -- No arrow: Frozen at current value -- ▲: Allow increments only -- ▼: Allow decrements only - - - - - Description - - - - - - Address - Indirizzo - - - - Type - - - - - - Value - Valore - - - - Match count: 0 - - - - - Previous - Precedente - - - - First Scan - Prima Ricerca - - - - Next Scan - - - - - Cancel Scan - - - - - Undo Scan - - - - - Hex - - - - - Scan Type: - - - - - Value Type: - - - - - Scan Scope: - - - - - Endianness: - - - - - Alignment: - - - - - Manage Scan Regions - - - - - Enable Speedhack - - - - - Open session notes - - - - - Notes - - - - - Create or attach to a process - - - - - Open a cheat table - - - - - Save current table to a file - - - - - Wiki - - - - - About - - - - - No Process Selected - Nessun Processo Selezionato - - - - Open a gdb console - - - - - Check for updates - - - - - Configure options - - - - - Pointer Scanner - - - - - Fi&le - - - - - Actio&ns - - - - - &Open - - - - - &Save As... - - - - - &Scan - - - - - &Filter - - - - - Please select a Process - - - - - Name or PID of the Process: - Nome o PID del processo: - - - - PID - - - - - Username - Nome Utente - - - - Process Name - Nome Processo - - - - Attach to the selected process - - - - - Cancel - Annulla - - - - Open an executable - - - - - Create Process[F1] - - - - - Tracer - - - - - Save as a text file - - - - MainWindow_MemoryView - - - Memory Viewer - - - - - - - Address - Indirizzo - - - - Opcodes - - - - - Instruction - - - - - Comment - - - - - Registers - - - - - Flags - - - - - Segment Registers - - - - - Show Float Registers - - - - - Return Address - - - - - Frame Address - - - - - Value - Valore - - - - Points to - - - - - V&iew - - - - - &Debug - - - - - &Tools - - - - - Fi&le - - - - - Help - - - - - &Bookmarks - - - - - &StackTrace Info - - - - - &Inject .so file - - - - - Inject D&LL file - - - - - &Break - - - - - &Run - - - - - &Step[F7] - - - - - Step &Over[F8] - - - - - &Execute Till Return[Shift+F8] - - - - - &Toggle Breakpoint[F5] - - - - - B&reakpoints - - - - - &Functions - - - - - Set Address[Shift+F4] - - - - - &Call Function - - - - - &Load Trace - - - - - &Libpince - - - - - &GDB Log File - - - - - &Search Instructions - - - - - &Memory Regions - - - - - &Dissect Code - - - - - Dissect &Mono/IL2CPP - - - - - R&eferenced Strings - - - - - Referenced &Calls - - - - - To&ggle Attach - - - - - Restore Instructions - - - - - Libpince Engine - - - - - Structures - - - - SessionNotes - - - Notes - - - - - Session Notes - - - - TabWidget - - - About PINCE - - - - - Contributors - - - - - License - - - - - Breakpoints - - - - - Interactive - - - - - No - - - - - Type - - - - - Disp - - - - - Enabled - - - - - Address - Indirizzo - - - - Size - - - - - On Hit - - - - - Hit Count - - - - - Condition - - - - - Raw - - - - - Floating Point Registers - - - - - - Register - - - - - - Value - Valore - - - TranslationConstants - - - Pause the process - - - - - Break the process - - - - - Continue the process - - - - - Cancel ongoing GDB command - - - - - Toggle attach/detach - - - - - Toggle speedhack - - - - - Speedhack - Increase speed - - - - - Speedhack - Decrease speed - - - - - Next Scan - Exact - - - - - Next Scan - Not - - - - - Next Scan - Increased - - - - - Next Scan - Increased By - - - - - Next Scan - Decreased - - - - - Next Scan - Decreased By - - - - - Next Scan - Less Than - - - - - Next Scan - More Than - - - - - Next Scan - Between - - - - - Next Scan - Changed - - - - - Next Scan - Unchanged - - - - - Error - - - - - Success - - - - - Information - - - - - Could not check for updates. - - - - - A newer PINCE AppImage is available. - -You can grab it from PINCE's GitHub releases or update this AppImage with AppImageUpdate/appimageupdatetool. - - - - - PINCE can check for AppImage updates on startup. This contacts the configured release host to download update metadata. - - - - - Allow startup update checks - - - - - This PINCE AppImage is up to date. - - - - - This feature is not available while attached to a WINE/Proton process! - - - - - Speedhack couldn't be enabled for this process. - - - - - GDB isn't initialized yet - - - - - Unable to initialize GDB -You might want to reinstall GDB or use the system GDB -To change the current GDB path, check Settings->Debug - - - - - Edit - - - - - Show as hexadecimal - - - - - Show as decimal - - - - - Show as unsigned - - - - - Show as signed - - - - - Toggle - - - - - Toggle including children - - - - - Auto - - - - - Browse this memory region - - - - - Disassemble this address - - - - - Delete - - - - - Delete selection - - - - - Cut - - - - - Copy - - - - - Paste - - - - - Stop - - - - - Stopping - - - - - Paste inside - - - - - Pointer scan for this address - - - - - Open pointer scanner - - - - - Pointer scan finished. Found {} valid pointer paths. - - - - - Pointer filtering finished. Found {} stable pointer paths. - - - - - Scanning for pointers - - - - - Resolving pointer paths - - - - - Base Address - - - - - Offset - - - - - Pointer paths count: {} - - - - - Find out what writes to this address - - - - - Find out what reads this address - - - - - Find out what accesses this address - - - - - Add to a new group - - - - - Create a new group - - - - - Group - - - - - Invalid clipboard content - - - - - New Scan - - - - - Match count: {} ({} shown) - - - - - Match count: {} - - - - - No Description - - - - - Open PCT file(s) - - - - - Open script file - - - - - Save script file - - - - - (untitled) - - - - - Script execution failed - - - - - Unsaved script - - - - - Save changes to {}? - - - - - --- Running {} --- - - - - - --- Finished --- - - - - - This script has no [DISABLE] section - - - - - Send to cheat table - - - - - Sent to the cheat table - - - - - Script - - - - - Edit script - - - - - Running the script failed, see the details below. - -{} - - - - - Remember my decision for all sessions - - - - - Always ask - - - - - Always save - - - - - Always discard - - - - - PINCE Cheat Table (*.pct) - - - - - Python Scripts (*.py) - - - - - Shared object library (*.so) - - - - - Dynamic-link library (*.dll) - - - - - Trace File (*.trace) - - - - - Pointer Scan Map (*.lmptr) - - - - - Add to address table - - - - - File {} is inaccessible or contains invalid content - - - - - Save PCT file - - - - - Cannot save to file - - - - - Nice try, smartass - - - - - Selected process is not valid - - - - - You're debugging this process already - - - - - That process is already being traced by {}, could not attach to the process - - - - - Permission denied, could not attach to the process - - - - - An error occurred while trying to create process - - - - - Scan for - - - - - First Scan - Prima Ricerca - - - - No Process Selected - Nessun Processo Selezionato - - - - [detached] - - - - - [stopped] - - - - - This requires the process to be stopped - - - - - Enter the new value - - - - - Enter the new description - - - - - Enter the new address - - - - - Edit Address - - - - - Please select a process first - - - - - Select the target binary - - - - - Enter the optional arguments - - - - - LD_PRELOAD .so path (optional) - - - - - Refresh - - - - - Length is not valid - - - - - Length must be greater than 0 - - - - - Can't parse the input - - - - - {} isn't a valid regex - - - - - Language settings will take effect upon the next restart - - - - - You have changed the GDB path, reset GDB now? - - - - - This will reset to the default settings -Proceed? - - - - - Mouse over on this text for examples - - - - - asdf|qwer --> search for asdf or qwer -[as]df --> search for both adf and sdf -Use the char \ to escape special chars such as [ - - - - - - Separate processes with {} - - - - - This setting is unused in AppImage builds - - - - - Select the gdb binary - - - - - Quitting current session will crash PINCE - - - - - Use global hotkeys or the commands 'interrupt' and 'c&' to stop/run the inferior - - - - - Hotkeys: ------------------------------ -Send: Enter | -Multi-line mode: Ctrl+Enter | -Complete command: Tab | ------------------------------ -Commands: ----------------------------------------------------------- -/clear: Clear the console | -phase-out: Detach from the current process | -phase-in: Attach back to the previously detached process | ---------------------------------------------------------------------------------------------------- -You can change the output mode from bottom right -Changing output mode only affects commands sent. Any other output coming from external sources(e.g async output) will be shown in MI format - - - - - Break[{}] - - - - - Run[{}] - - - - - Toggle Attach[{}] - - - - - Failed to set breakpoint at address {} - - - - - Failed to set watchpoint at address {} - - - - - Copy to Clipboard - - - - - Go to expression - - - - - Add this address to address list - - - - - Set Watchpoint - - - - - Write Only - - - - - Read Only - - - - - Both - - - - - Add/Change condition for breakpoint - - - - - Set Breakpoint - - - - - Toggle Breakpoint - - - - - Delete Breakpoint - - - - - Enter the expression - - - - - {} is invalid - - - - - Protection:{} | Base:{}-{} | Module:{} - - - - - Invalid Region - - - - - Cannot access memory at expression {} - - - - - Referenced by: - - - - - Press 'Ctrl+E' to see a detailed list of referrers - - - - - Memory Viewer - Paused - - - - - Memory Viewer - Currently debugging {} - - - - - Memory Viewer - Running - - - - - Enter the expression for condition, for instance: - -$eax==0x523 -$rax>0 && ($rbp<0 || $rsp==0) -printf($r10)==3 - - - - - Failed to set condition for address {} -Check terminal for details - - - - - Full Stack - - - - - Copy Return Address - - - - - Copy Frame Address - - - - - Stacktrace - - - - - Toggle stack from BP/SP register - - - - - Copy Address - - - - - Copy Value - - - - - Copy Points to - - - - - Disassemble 'value' pointer address - - - - - Show 'value' pointer in HexView - - - - - Back - - - - - Show this address in HexView - - - - - Follow - - - - - Examine Referrers - - - - - Bookmark this address - - - - - Delete this bookmark - - - - - Change comment - - - - - Go to bookmarked address - - - - - Edit instruction - - - - - Replace instruction with NOPs - - - - - Find out which addresses this instruction accesses - - - - - Break and trace instructions - - - - - Dissect this region - - - - - Copy Bytes - - - - - Copy Instruction - - - - - Copy Comment - - - - - Copy All - - - - - Enter the register expression(s) you want to track -Register names must start with $ -Each expression must be separated with a comma - -For instance: -Let's say the instruction is mov [rax+rbx],30 -Then you should enter $rax+$rbx -So PINCE can track address [rax+rbx] - -Another example: -If you enter $rax,$rbx*$rcx+4,$rbp -PINCE will track down addresses [rax],[rbx*rcx+4] and [rbp] - - - - - This address has already been bookmarked - - - - - Enter the comment for bookmarked address - - - - - Select the shared object (.so) file - - - - - The shared object (.so) file has been injected - - - - - Failed to inject the shared object (.so) file - - - - - Select the DLL file - - - - - DLL injection thread started. The DLL may still fail to load due to bitness mismatch or missing dependencies. - - - - - Failed to inject the DLL - - - - - DLL injection is only supported for WINE/Proton processes - - - - - Enter the expression for the function that'll be called from the inferior -You can view functions list from View->Functions - -For instance: -Calling printf("1234") will yield something like this -↓ -$28 = 4 - -$28 is the assigned convenience variable -4 is the result -You can use the assigned variable from the GDB Console - - - - - Failed to call the expression {} - - - - - Invalid expression or address - - - - - Invalid entries detected, refreshing the page - - - - - Add new entry - - - - - Enter the new value of register {} - - - - - Enter the new value of flag {} - - - - - Restore this instruction - - - - - Enter the hit count({} or higher) - - - - - Hit count must be an integer - - - - - Hit count can't be lower than {} - - - - - Change condition - - - - - Enable - - - - - Disable - - - - - Disable after hit - - - - - Disable after X hits - - - - - Delete after hit - - - - - Instructions writing to the address {} - - - - - Instructions reading from the address {} - - - - - Instructions accessing to the address {} - - - - - Unable to track watchpoint at expression {} - - - - - Unable to delete watchpoint at expression {} - - - - - Close - - - - - Addresses accessed by instruction {} - - - - - Unable to track breakpoint at expression {} - - - - - Accessed by {} - - - - - Unable to delete breakpoint at expression {} - - - - - Max trace count must be greater than or equal to {} - - - - - Save trace file - - - - - Open trace file - - - - - Expand All - - - - - Collapse All - - - - - Select a pointer map file - - - - - Scan - - - - - Scanning - - - - - Filter - - - - - Filtering - - - - - DEFINED - - - - - This symbol is defined. You can use its body as a gdb expression. For instance: - -void func(param) can be used as 'func' as a gdb expression - - - - - Copy Symbol - - - - - Here's some useful regex tips: -^quaso --> search for everything that starts with quaso -[ab]cd --> search for both acd and bcd - - How to interpret symbols: -A symbol that looks like 'func(param)@plt' consists of 3 pieces -func, func(param), func(param)@plt -These 3 functions will have different addresses -@plt means this function is a subroutine for the original one -There can be more than one of the same function -It means that the function is overloaded - - - - - New instruction is {} bytes long but old instruction is only {} bytes long -This will cause an overflow, proceed? - - - - - {} isn't a valid expression - - - - - Log File of PID {} - - - - - Contents of {} (only last {} bytes are shown) - - - - - ON - - - - - OFF - - - - - LOGGING: {} - - - - - Unable to read log file at {} - - - - - Go to Settings->Debug to enable logging - - - - - Invalid Regex - - - - - Here's some useful regex examples: -call|rax --> search for instructions that contain call or rax -[re]cx --> search for both rcx and ecx -Use the char \ to escape special chars such as [ -\[rsp\] --> search for instructions that contain [rsp] - - - - - Copy Addresses - - - - - Copy Offset - - - - - Copy Path - - - - - Start - Inizio - - - - Currently scanning region: - - - - - Cancel - Annulla - - - - Scan finished - - - - - Scan was canceled - - - - - Select at least one region - - - - - You need to dissect code first -Proceed? - - - - - Waiting for breakpoint to trigger - - - - - Tracing has been completed - - - - - Not - - - - - Exact - - - - - Increased - - - - - Increased by - - - - - Decreased - - - - - Decreased by - - - - - Less Than - - - - - More Than - - - - - Between - - - - - Changed - - - - - Unchanged - - - - - Unknown Value - - - - - Basic - - - - - Normal - - - - - Read+Write - - - - - Full - - - - - Host - - - - - Little - - - - - Big - - - - - Show in HexView - - - - - Show in Disassembler - - - - - Dark - - - - - Light - - - - - System Default - - - - - Wong (Colorblind Friendly) - - - - - Session - Unsaved changes - - - - - You have unsaved changes. -Do you want to save the current session? - - - - - The session reset was cancelled because the current session was not saved. - - - - - Session - Process changed - - - - - The process name has changed. -Do you want to keep the current session with the new process? - - - - - Mono collector is not connected - - - - - No supported managed runtime found in this process - - - - - Invoke... - - - - - Instance (this) - - - - - Result: {} - - - - - Returned (void) - - - - - Exception thrown (object @ {}) - - - - - Could not parse the argument values - - - - - Invalid instance pointer - - - - - This method has a parameter type that can't be marshalled yet - - - - - {} raw bytes (hex) - - - - - Find instance... - - - - - Select a live instance: - - - - - Static field address is unavailable for this runtime - - - - - (type could not be resolved) - - - - - (maximum drill depth reached) - - - - - Find Instances - - - - - Find Instances - {} - - - - - {} instance(s) found - - - - - (showing first {}) - - - - - No live instances found - - - - - Could not resolve an instance marker for this class - - - - - Fields - - - - - Methods - - - - - Disassemble - - - - - View at address… - - - - - Delete structure - - - - - Delete structure '{}'? - - - - - View as structure - - - - - Enter base address - - - - - Value - Valore - - - - Pointer - - - - - Inline - - - - - A structure with this name already exists - - - - - Structure name cannot be empty - - - - - Unsigned - - - - - Signed - - - - - Hex - - - - - Export as structure - - - - - Dissect as structure - - - diff --git a/i18n/ts/zh_CN.ts b/i18n/ts/zh_CN.ts deleted file mode 100644 index 997fbec9..00000000 --- a/i18n/ts/zh_CN.ts +++ /dev/null @@ -1,3594 +0,0 @@ - - - - - Dialog - - - Dissect Code - 分析代码 - - - - Regions - 区域 - - - - Path - 路径 - - - - Selected regions will be scanned - 选中区域将会被扫描 - - - - Currently scanning range: - 当前扫描范围: - - - - String references found: - 找到的字符串引用: - - - - Jumps found: - 找到的跳转: - - - - Calls found: - 找到的调用: - - - - Entries that can't be decoded as utf-8 won't be included in referenced strings -Unchecking it makes ReferencedStringsWidget load slower but allows you to examine non-string pointers on it - 无法解码为 UTF-8 的条目将不会包含在引用的字符串中 -取消勾选此选项会导致引用的字符串窗口(ReferencedStringsWidget)加载变慢,但允许你检查其中的非字符串指针 - - - - Discard invalid strings - 丢弃无效的字符串 - - - - Edit Instruction - 编辑指令 - - - - - - Address: - 地址: - - - - Instruction: - 指令: - - - - Multiple entries are separated with ; - 多个条目用分号(;)分隔 - - - - - - - - Type - 类型 - - - - - Endianness - 字节序 - - - - - Hex - 十六进制 - - - - - Signed - 有符号 - - - - - Length - 长度 - - - - - Zero-Terminated - 以零终止 - - - - - Start bit - - - - - - Handle Signals - 处理信号 - - - - Signal - 信号 - - - - Stop & Print - 停止并打印 - - - - Pass to Program - 传递到程序 - - - - Hex Edit - 十六进制编辑 - - - - - Length: - 长度: - - - - Refresh - 刷新 - - - - Processing - 处理中 - - - - Cancel - 取消 - - - - Manage Scan Regions - 管理扫描区域 - - - - Selected regions will be deleted from the current scan - 选中的区域将会从当前的扫描中删除 - - - - Invert Selection - 反选 - - - - Reset Regions - - - - - ID - ID - - - - Start Address - 起始地址 - - - - Size(bytes) - 大小(字节) - - - - Load Address - 加载地址 - - - - Perms - 权限 - - - - File - 文件 - - - - Add Address Manually - 手动添加地址 - - - - Type: - 类型: - - - - - Endianness: - 字节序: - - - - Start bit: - - - - - Base Address: - 基址: - - - - Add Offset - 添加偏移量 - - - - Remove Offset - 移除偏移量 - - - - Description: - 备注: - - - - - Pointer - 指针 - - - - Dissect Mono/IL2CPP - 分析 Mono/IL2CPP - - - - Search - 搜索 - - - - Show inherited members - 显示继承的成员 - - - - - - - - - Name - 名称 - - - - - - Value - 值 - - - - Find Instances - 查找实例 - - - - Invoke - 调用 - - - - Call - 执行 - - - - Compare & Filter Pointers - 对比和过滤指针 - - - - Previous Map: - 先前的图: - - - - - - - Browse - 浏览 - - - - Current Map: - 现在的图: - - - - New Output Map: - 新输出图: - - - - Scan for Pointers - 指针扫描 - - - - Target Address: - 目标地址: - - - - Pointer Map File Path: - 指针图文件路径: - - - - Advanced Options - 高级选项 - - - - Scan Scope: - 扫描范围: - - - - Pointer Size: - 指针大小: - - - - Max Depth: - 最大深度: - - - - Max Positive Offset: - 最大正偏移: - - - - - - 0x - 0x - - - - Max Negative Offset: - 最大负偏移: - - - - Last Offset - - - - - Max Results - 最大结果 - - - - Module Bases Only - 仅模块基址 - - - - Settings - 设置 - - - - General - 通用 - - - - Hotkeys - 快捷键 - - - - Memory View - 内存查看器 - - - - Debug - 调试 - - - - Java - Java - - - - Auto-update address table - 自动更新地址表 - - - - Check for AppImage updates on startup - - - - - Update Interval - 更新间隔 - - - - Freeze Interval - 冻结间隔 - - - - GDB output: - GDB 输出: - - - - Async - 异步 - - - - Command - 命令 - - - - Command info - 命令信息 - - - - On start, automatically attach to processes with name matching one of the entries -Patterns at former positions have higher priority if regex is off - 启动时,自动附加到名称与其中一个条目匹配的进程 -如果正则表达式关闭,靠前的条目有更高的优先级 - - - - Auto-attach to processes named - 自动附加到的进程名为 - - - - Regex - 正则表达式 - - - - Language - 语言 - - - - Logo - 图标 - - - - Theme - 主题 - - - - Save session when exiting PINCE - - - - - Remember last file save/open across restarts - - - - - Functions - 功能 - - - - Hotkey - 快捷键 - - - - Press shortcut - 按下快捷键 - - - - Clear - 清除 - - - - Bring Memory View to front when the inferior is stopped - 当被调试程序停止时将内存查看器置于前台 - - - - Instructions shown per scroll in Disassembly View - 反汇编视图中每次滚动显示的指令数 - - - - Bytes shown per scroll in Hex View - 十六进制视图中每次滚动显示的字节数 - - - - GDB Path - GDB 路径 - - - - GDB Logging - GDB 日志记录 - - - - Interruption signal - 中断信号 - - - - Ignore SIGSEGV for Java processes (overrides signal settings if enabled) - 忽略 Java 进程的分段错误(SIGSEGV)(如果启用,将会覆盖信号设置) - - - - Reset Settings - 重置设置 - - - - Member - 成员 - - - - Offset (hex) - 偏移量(十六进制) - - - - Kind - 种类 - - - - Value type - 值类型 - - - - Repr - 表现形式 - - - - Structure - 结构体 - - - - Edit structure - 编辑结构体 - - - - - Offset - 偏移量 - - - - Add - 添加 - - - - Edit - 编辑 - - - - Remove - 删除 - - - - Up - 上 - - - - Down - 下 - - - - Structure view - 结构体查看器 - - - - Base address - 基址 - - - - Add to address table - 添加到地址表 - - - - Dialog - 对话框 - - - - Hit Esc to cancel and Ctrl+Enter to accept - 按 Esc 取消,按 Ctrl+Enter 接受 - - - - Parameters for tracing - 用于追踪的参数 - - - - Number of the instructions that'll be traced - 将被追踪的指令数量 - - - - Max trace count(1 or greater): - 最大追踪次数(1 或更多): - - - - Tracing will start if this condition is met - 如果满足此条件,将开始追踪 - - - - Trigger condition(Optional, gdb expression): - 触发条件(可选,gdb表达式): - - - - Tracing will stop whenever this condition is met - 每当满足此条件时,追踪将停止 - - - - Stop condition(Optional, gdb expression): - 停止条件(可选,gdb表达式): - - - - Step over instead of single step - 步过(Step over)而不是单步 - - - - Stop when tracing ends - 当追踪结束时停止 - - - - Collect registers - 收集寄存器 - - - - Select an address to track - 选择要跟踪的地址 - - - - Pointed Address - 指向的地址 - - - Form - - - Bookmarks - 书签 - - - - Bookmarked Addresses - 书签地址 - - - - - Info - 信息 - - - - Comment - 注解 - - - - GDB Console - GDB 控制台 - - - - Send - 发送 - - - - CLI - CLI - - - - MI - MI - - - - Examine Referrers - 检查引用来源 - - - - - - - - Enter a string or a python regex - 输入字符串或 Python 正则表达式 - - - - - - - - Ignore case if checked - 如果选中则忽略大小写 - - - - - - - - Case sensitive - 大小写敏感 - - - - - - - Your string will be treated as a regex if checked - 如果选中,你的字符串将被视为正则表达式 - - - - - - - Regex - 正则 - - - - - - - - Search(Enter) - 搜索(Enter) - - - - Functions - 函数 - - - - - - - - - - Address - 地址 - - - - Symbol - 符号 - - - - Enter the regex. Leave blank to see all functions - 请输入正则表达式。如果不输入任何内容,则会显示所有函数 - - - - - - Form - 表格 - - - - - TextLabel - 文本标签 - - - - Memory Regions - 内存区域 - - - - Search path - 搜索路径 - - - - Regions - 区域 - - - - Perms - 权限 - - - - Offset - 偏移量 - - - - Path - 路径 - - - - Referenced Calls - 引用的调用 - - - - - Refcount - 引用计数 - - - - Referenced Strings and Values - 引用的字符串和值 - - - - - Value - 值 - - - - Restore Instructions - 还原指令 - - - - Original Opcodes - 原始操作码 - - - - Original Instruction - 原始指令 - - - - Search for Instructions - 指令搜索 - - - - Search: - 搜索: - - - - Start - 开始 - - - - End - 结束 - - - - Instruction - 指令 - - - - StackTrace Information - 堆栈跟踪信息 - - - - Return Address - 返回地址 - - - - Structures - 结构体 - - - - Name - 名称 - - - - New - 新建 - - - - Edit - 编辑 - - - - Delete - 删除 - - - - View at address… - 查看此地址... - - - - Add to address table - 添加到地址表 - - - - Tracer Status - 追踪器状态 - - - - Cancel - 取消 - - - - - Count - 计数 - - - - Source - 源 - - - - - Stop - 停止 - - - - Refresh - 刷新 - - - MainWindow - - - Libpince Engine - Libpince 引擎 - - - - (untitled) - (无标题) - - - - + - + - - - - Script output - 脚本输出 - - - - - File - 文件 - - - - Templates - 模板 - - - - Help - 帮助 - - - - Run - 运行 - - - - Code injection - 代码注入 - - - - - - Open - 打开 - - - - Ctrl+O - Ctrl+O - - - - - Save - 保存 - - - - Ctrl+S - Ctrl+S - - - - Libpince - Libpince - - - - Run [ENABLE] - 运行 [启用] - - - - Ctrl+Shift+E - Ctrl+Shift+E - - - - Run [DISABLE] - 运行 [禁用] - - - - Ctrl+Shift+D - Ctrl+Shift+D - - - - Run selection - 运行选定 - - - - Ctrl+R - Ctrl+R - - - - Clear output - 清除输出 - - - - Send to cheat table - 发送到作弊表 - - - - Ctrl+Shift+T - Ctrl+Shift+T - - - - AOB scan + NOP - AOB 扫描 + NOP - - - - AOB scan + patch - AOB 扫描 + patch - - - - Read/write address - 读/写 地址 - - - - Memory View - 内存查看器 - - - - Copy selected items to the address table - 将所选项目复制到地址表 - - - - Erase all the table contents - 删除地址表中所有内容 - - - - Refresh the address table[R] - 刷新地址表[R] - - - - Add Address Manually - 手动添加地址 - - - - Freeze - 冻结 - - - - Freeze the value. Click just to the right of checkbox to cycle between freeze types: -- No arrow: Frozen at current value -- ▲: Allow increments only -- ▼: Allow decrements only - 冻结该值。点击复选框右侧区域可在不同冻结模式之间切换: -无箭头:冻结为当前值 -▲:只允许值增加 -▼:只允许值减少 - - - - Description - 备注 - - - - - Address - 地址 - - - - Type - 类型 - - - - - Value - 值 - - - - Match count: 0 - 匹配次数:0 - - - - Previous - 先前的值 - - - - First Scan - 首次扫描 - - - - Next Scan - 再次扫描 - - - - Cancel Scan - 终止扫描 - - - - Undo Scan - 撤销扫描 - - - - Hex - 十六进制 - - - - Scan Type: - 扫描类型: - - - - Value Type: - 值类型: - - - - Scan Scope: - 扫描范围: - - - - Endianness: - 字节序: - - - - Alignment: - 对齐: - - - - Manage Scan Regions - 管理扫描区域 - - - - Enable Speedhack - 启用速度修改 - - - - Open session notes - 打开会话笔记 - - - - Notes - 笔记 - - - - Create or attach to a process - 创建或附加到进程 - - - - Open a cheat table - 打开一个作弊表 - - - - Save current table to a file - 将当前表保存到文件 - - - - Wiki - 文档 - - - - About - 关于 - - - - No Process Selected - 未附加到任何进程 - - - - Open a gdb console - 打开一个 GDB 控制台 - - - - Check for updates - - - - - Configure options - 配置选项 - - - - Pointer Scanner - 指针扫描器 - - - - Fi&le - 文件[&l] - - - - Actio&ns - 行动[&n] - - - - &Open - 打开[&O] - - - - &Save As... - 另存为[&S]... - - - - &Scan - 扫描[&S] - - - - &Filter - 过滤[&F] - - - - Please select a Process - 请选择一个进程 - - - - Name or PID of the Process: - 进程名称或PID: - - - - PID - PID - - - - Username - 用户名 - - - - Process Name - 进程名称 - - - - Attach to the selected process - 附加到选中进程 - - - - Cancel - 取消 - - - - Open an executable - 打开一个可执行程序 - - - - Create Process[F1] - 创建进程[F1] - - - - Tracer - 追踪器 - - - - Save as a text file - 保存为文本文件 - - - MainWindow_MemoryView - - - Memory Viewer - 内存查看器 - - - - - - Address - 地址 - - - - Opcodes - 操作码 - - - - Instruction - 指令 - - - - Comment - 注解 - - - - Registers - 寄存器(Registers) - - - - Flags - 状态标志(Flags) - - - - Segment Registers - 段(Segment)寄存器 - - - - Show Float Registers - 显示浮点(Float)寄存器 - - - - Return Address - 返回地址 - - - - Frame Address - 帧地址 - - - - Value - 值 - - - - Points to - 指向 - - - - V&iew - 视图[&i] - - - - &Debug - 调试[&D] - - - - &Tools - 工具[&T] - - - - Fi&le - 文件[&l] - - - - Help - 帮助 - - - - &Bookmarks - 书签[&B] - - - - &StackTrace Info - 堆栈跟踪信息[&S] - - - - &Inject .so file - 注入 .so 文件[&I] - - - - Inject D&LL file - 注入 DLL 文件[&L] - - - - &Break - 中断[&B] - - - - &Run - 运行[&R] - - - - &Step[F7] - 步进[&S][F7] - - - - Step &Over[F8] - 步过[&O][F8] - - - - &Execute Till Return[Shift+F8] - 执行直到返回[&E][Shift+F8] - - - - &Toggle Breakpoint[F5] - 切换断点[&T][F5] - - - - B&reakpoints - 断点[&r] - - - - &Functions - 函数[&F] - - - - Set Address[Shift+F4] - 设置地址[Shift+F4] - - - - &Call Function - 调用函数[&C] - - - - &Load Trace - 加载追踪[&L] - - - - &Libpince - &Libpince - - - - &GDB Log File - &GDB 日志文件 - - - - &Search Instructions - 搜索指令[&S] - - - - &Memory Regions - 内存区域[&M] - - - - &Dissect Code - 分析代码[&D] - - - - Dissect &Mono/IL2CPP - 分析 Mono/IL2CPP[&M] - - - - R&eferenced Strings - 引用的字符串[&e] - - - - Referenced &Calls - 引用的调用[&C] - - - - To&ggle Attach - 切换附加​​[&g] - - - - Restore Instructions - 还原指令 - - - - Libpince Engine - Libpince 引擎 - - - - Structures - 结构体 - - - SessionNotes - - - Notes - 笔记 - - - - Session Notes - 会话笔记 - - - TabWidget - - - About PINCE - 关于 PINCE - - - - Contributors - 贡献者 - - - - License - 许可 - - - - Breakpoints - 断点 - - - - Interactive - 交互 - - - - No - No - - - - Type - 类型 - - - - Disp - 显示 - - - - Enabled - 启用 - - - - Address - 地址 - - - - Size - 大小 - - - - On Hit - 命中时 - - - - Hit Count - 命中计数 - - - - Condition - 条件 - - - - Raw - 原始 - - - - Floating Point Registers - 浮点寄存器 - - - - - Register - 寄存器 - - - - - Value - 值 - - - TranslationConstants - - - Pause the process - 暂停进程 - - - - Break the process - 中断进程 - - - - Continue the process - 继续进程 - - - - Cancel ongoing GDB command - 取消正在运行的 GDB 命令 - - - - Toggle attach/detach - 切换附加 / 分离 - - - - Toggle speedhack - 切换速度修改 - - - - Speedhack - Increase speed - 速度修改 - 增加速度 - - - - Speedhack - Decrease speed - 速度修改 - 减少速度 - - - - Next Scan - Exact - 再次扫描 - 精确 - - - - Next Scan - Not - 再次扫描 - 不等 - - - - Next Scan - Increased - 再次扫描 - 增加 - - - - Next Scan - Increased By - 再次扫描 - 增加自 - - - - Next Scan - Decreased - 再次扫描 - 减少 - - - - Next Scan - Decreased By - 再次扫描 - 减少自 - - - - Next Scan - Less Than - 再次扫描 - 少于 - - - - Next Scan - More Than - 再次扫描 - 多于 - - - - Next Scan - Between - 再次扫描 - 介于 - - - - Next Scan - Changed - 再次扫描 - 改变 - - - - Next Scan - Unchanged - 再次扫描 - 未变 - - - - Error - 错误 - - - - Success - 成功 - - - - Information - 信息 - - - - Could not check for updates. - - - - - A newer PINCE AppImage is available. - -You can grab it from PINCE's GitHub releases or update this AppImage with AppImageUpdate/appimageupdatetool. - - - - - PINCE can check for AppImage updates on startup. This contacts the configured release host to download update metadata. - - - - - Allow startup update checks - - - - - This PINCE AppImage is up to date. - - - - - This feature is not available while attached to a WINE/Proton process! - 此功能在附加到 WINE/Proton 进程时无效! - - - - Speedhack couldn't be enabled for this process. - 速度修改无法在此进程中启用。 - - - - GDB isn't initialized yet - GDB 尚未初始化 - - - - Unable to initialize GDB -You might want to reinstall GDB or use the system GDB -To change the current GDB path, check Settings->Debug - 无法初始化 GDB -你可能想重新安装 GDB 或者使用系统 GDB -要更改当前 GDB 路径,请检查 “设置” -> “调试” - - - - Edit - 编辑 - - - - Show as hexadecimal - 显示为十六进制 - - - - Show as decimal - 显示为十进制 - - - - Show as unsigned - 显示为无符号数 - - - - Show as signed - 显示为有符号数 - - - - Toggle - 切换 - - - - Toggle including children - 切换包括子项 - - - - Auto - 自动 - - - - Browse this memory region - 浏览此内存区域 - - - - Disassemble this address - 反汇编这个地址 - - - - Delete - 删除 - - - - Delete selection - 删除选定 - - - - Cut - 剪切 - - - - Copy - 复制 - - - - Paste - 粘贴 - - - - Stop - 停止 - - - - Stopping - 停止中 - - - - Paste inside - 粘贴到其内 - - - - Pointer scan for this address - 此地址的指针扫描 - - - - Open pointer scanner - 打开指针扫描器 - - - - Pointer scan finished. Found {} valid pointer paths. - 指针扫描完成。发现 {} 个有效指针路径。 - - - - Pointer filtering finished. Found {} stable pointer paths. - 指针过滤完成。发现 {} 个稳定指针路径。 - - - - Scanning for pointers - 指针扫描中 - - - - Resolving pointer paths - 解析指针路径中 - - - - Base Address - 基址 - - - - Offset - 偏移量 - - - - Pointer paths count: {} - 指针路径数量:{} - - - - Find out what writes to this address - 找出是什么写入了这个地址 - - - - Find out what reads this address - 找出是什么读取了这个地址 - - - - Find out what accesses this address - 找出是什么访问了这个地址 - - - - Add to a new group - 加入一个新组 - - - - Create a new group - 创建一个新组 - - - - Group - 组 - - - - Invalid clipboard content - 剪贴板内容无效 - - - - New Scan - 新的扫描 - - - - Match count: {} ({} shown) - 匹配次数:{}(显示了{}个) - - - - Match count: {} - 匹配次数:{} - - - - No Description - 无备注 - - - - Open PCT file(s) - 打开 PCT 文件 - - - - Open script file - 打开脚本文件 - - - - Save script file - 保存脚本文件 - - - - (untitled) - (无标题) - - - - Script execution failed - 脚本执行失败 - - - - Unsaved script - 未保存的脚本 - - - - Save changes to {}? - 保存修改到 {}? - - - - --- Running {} --- - --- 运行 {} --- - - - - --- Finished --- - --- 完成 --- - - - - This script has no [DISABLE] section - 此脚本无 [禁用] 段 - - - - Send to cheat table - 发送到作弊表 - - - - Sent to the cheat table - 发送到作弊表 - - - - Script - 脚本 - - - - Edit script - 编辑脚本 - - - - Running the script failed, see the details below. - -{} - 脚本运行失败,详情如下。 - -{} - - - - Remember my decision for all sessions - - - - - Always ask - - - - - Always save - - - - - Always discard - - - - - PINCE Cheat Table (*.pct) - PINCE 作弊表 (*.pct) - - - - Python Scripts (*.py) - Python 脚本 (*.py) - - - - Shared object library (*.so) - 共享对象库 (*.so) - - - - Dynamic-link library (*.dll) - 动态链接库 (*.dll) - - - - Trace File (*.trace) - 追踪文件 (*.trace) - - - - Pointer Scan Map (*.lmptr) - 指针扫描图 (*.lmptr) - - - - Add to address table - 添加到地址表 - - - - File {} is inaccessible or contains invalid content - 文件 {} 无法访问或包含无效的内容 - - - - Save PCT file - 保存 PCT 文件 - - - - Cannot save to file - 无法保存为文件 - - - - Nice try, smartass - 好会试,聪明屁股 - - - - Selected process is not valid - 所选进程无效 - - - - You're debugging this process already - 你已经在调试这个进程了 - - - - That process is already being traced by {}, could not attach to the process - 此进程已被 {} 追踪,无法附加到此进程 - - - - Permission denied, could not attach to the process - 请求被拒,无法附加到此进程 - - - - An error occurred while trying to create process - 尝试创建进程时发生错误 - - - - Scan for - 在这里输入扫描内容 - - - - First Scan - 首次扫描 - - - - No Process Selected - 未附加到任何进程 - - - - [detached] - [已分离] - - - - [stopped] - [已停止] - - - - This requires the process to be stopped - 这需要进程停止 - - - - Enter the new value - 输入新值 - - - - Enter the new description - 输入新备注 - - - - Enter the new address - 输入新地址 - - - - Edit Address - 编辑地址 - - - - Please select a process first - 请先选择一个进程 - - - - Select the target binary - 选择目标二进制文件 - - - - Enter the optional arguments - 输入可选参数 - - - - LD_PRELOAD .so path (optional) - LD_PRELOAD .so 路径(可选) - - - - Refresh - 刷新 - - - - Length is not valid - 长度无效 - - - - Length must be greater than 0 - 长度必须大于0 - - - - Can't parse the input - 无法解析输入 - - - - {} isn't a valid regex - {} 非有效正则表达式 - - - - Language settings will take effect upon the next restart - 语言设置会在下次重启时生效 - - - - You have changed the GDB path, reset GDB now? - 你已经更改了 GDB 路径,现在重置 GDB 吗? - - - - This will reset to the default settings -Proceed? - 这将会重置设置为默认 -继续? - - - - Mouse over on this text for examples - 将鼠标悬停在此文本上查看示例 - - - - asdf|qwer --> search for asdf or qwer -[as]df --> search for both adf and sdf -Use the char \ to escape special chars such as [ - - asdf|qwer --> 搜索 asdf 或 qwer -[as]df --> 搜索 adf 和 sdf -用字符 \ 转义特殊字符,比如 [ - - - - - Separate processes with {} - 使用 {} 分隔进程 - - - - This setting is unused in AppImage builds - 此设置在 AppImage 构建中未使用 - - - - Select the gdb binary - 选择 GDB 的可执行文件 - - - - Quitting current session will crash PINCE - 退出当前会话会导致 PINCE 崩溃 - - - - Use global hotkeys or the commands 'interrupt' and 'c&' to stop/run the inferior - 使用全局快捷键或者命令 'interrupt' 和 'c&' 停止/运行被调试程序 - - - - Hotkeys: ------------------------------ -Send: Enter | -Multi-line mode: Ctrl+Enter | -Complete command: Tab | ------------------------------ -Commands: ----------------------------------------------------------- -/clear: Clear the console | -phase-out: Detach from the current process | -phase-in: Attach back to the previously detached process | ---------------------------------------------------------------------------------------------------- -You can change the output mode from bottom right -Changing output mode only affects commands sent. Any other output coming from external sources(e.g async output) will be shown in MI format - 快捷键: --------------------- -发送: Enter | -多行模式:Ctrl+Enter | -命令补全:Tab | --------------------- -命令: --------------------------------- -/clear:清空控制台 | -phase-out: 分离当前进程 | -phase-in: 重新附加上一个分离的进程 | ------------------------------------------------------------------------------------------ -你可以在右下角切换输出模式 -更改输出模式仅影响命令的发送。来自外部源的任何其他输出(例如异步输出)将以 MI 格式显示 - - - - Break[{}] - 中断[{}] - - - - Run[{}] - 运行[{}] - - - - Toggle Attach[{}] - 切换附加[{}] - - - - Failed to set breakpoint at address {} - 在地址 {} 处设置断点失败 - - - - Failed to set watchpoint at address {} - 无法在地址 {} 设置监视点 - - - - Copy to Clipboard - 复制到剪切板 - - - - Go to expression - 跳转到表达式 - - - - Add this address to address list - 添加此地址到地址列表 - - - - Set Watchpoint - 设置监视点 - - - - Write Only - 仅写入 - - - - Read Only - 仅读取 - - - - Both - 两者都 - - - - Add/Change condition for breakpoint - 添加/更改断点条件 - - - - Set Breakpoint - 设置断点 - - - - Toggle Breakpoint - 切换断点 - - - - Delete Breakpoint - 删除断点 - - - - Enter the expression - 输入表达式 - - - - {} is invalid - {} 无效 - - - - Protection:{} | Base:{}-{} | Module:{} - 保护:{} | 基础:{}-{} | 模块:{} - - - - Invalid Region - 无效的区域 - - - - Cannot access memory at expression {} - 无法访问表达式 {} 处的内存 - - - - Referenced by: - 引用自: - - - - Press 'Ctrl+E' to see a detailed list of referrers - 按下 'Ctrl+E' 可以查看引用来源的详细列表 - - - - Memory Viewer - Paused - 内存查看器 - 已暂停 - - - - Memory Viewer - Currently debugging {} - 内存查看器 - 正调试 {} - - - - Memory Viewer - Running - 内存查看器 - 运行中 - - - - Enter the expression for condition, for instance: - -$eax==0x523 -$rax>0 && ($rbp<0 || $rsp==0) -printf($r10)==3 - 输入条件表达式,例如: - -$eax==0x523 -$rax>0 && ($rbp<0 || $rsp==0) -printf($r10)==3 - - - - Failed to set condition for address {} -Check terminal for details - 无法设置地址 {} 的条件 -检查终端了解详情 - - - - Full Stack - 全栈 - - - - Copy Return Address - 复制返回地址 - - - - Copy Frame Address - 复制帧地址 - - - - Stacktrace - 堆栈跟踪 - - - - Toggle stack from BP/SP register - 从 BP/SP 寄存器中切换堆栈 - - - - Copy Address - 复制地址 - - - - Copy Value - 复制值 - - - - Copy Points to - 复制指向 - - - - Disassemble 'value' pointer address - 反汇编 '值' 指针地址 - - - - Show 'value' pointer in HexView - 在十六进制视图中显示 '值' 指针 - - - - Back - 后退 - - - - Show this address in HexView - 在十六进制视图中显示这个地址 - - - - Follow - 跟踪 - - - - Examine Referrers - 检查引用来源 - - - - Bookmark this address - 添加此地址到书签 - - - - Delete this bookmark - 删除此书签 - - - - Change comment - 更改注解 - - - - Go to bookmarked address - 跳转到已添加书签的地址 - - - - Edit instruction - 编辑指令 - - - - Replace instruction with NOPs - 用 NOPs 替换指令 - - - - Find out which addresses this instruction accesses - 找出此指令访问的地址 - - - - Break and trace instructions - 中断并跟踪指令 - - - - Dissect this region - 分析此区域 - - - - Copy Bytes - 复制字节 - - - - Copy Instruction - 复制指令 - - - - Copy Comment - 复制注解 - - - - Copy All - 复制全部 - - - - Enter the register expression(s) you want to track -Register names must start with $ -Each expression must be separated with a comma - -For instance: -Let's say the instruction is mov [rax+rbx],30 -Then you should enter $rax+$rbx -So PINCE can track address [rax+rbx] - -Another example: -If you enter $rax,$rbx*$rcx+4,$rbp -PINCE will track down addresses [rax],[rbx*rcx+4] and [rbp] - 请输入你想要追踪的寄存器表达式 -寄存器名称必须以$开头 -每个表达式必须用逗号分隔 - -例如: -假设指令是 mov [rax+rbx],30 -那么你应该输入 $rax+$rbx -这样 PINCE 就可以追踪地址 [rax+rbx] - -另一个例子: -如果你输入 $rax,$rbx*$rcx+4,$rbp -PINCE 将追踪地址 [rax],[rbx*rcx+4] 和 [rbp] - - - - This address has already been bookmarked - 这个地址已经被添加到书签了 - - - - Enter the comment for bookmarked address - 输入已书签地址的注解 - - - - Select the shared object (.so) file - 选择共享对象库 (*.so) 文件 - - - - The shared object (.so) file has been injected - 共享对象库 (*.so) 文件已注入 - - - - Failed to inject the shared object (.so) file - 共享对象库 (*.so) 文件注入失败 - - - - Select the DLL file - 选择 DLL 文件 - - - - DLL injection thread started. The DLL may still fail to load due to bitness mismatch or missing dependencies. - DLL 注入线程已启动。DLL 仍可能因位数不匹配或缺少依赖项而加载失败。 - - - - Failed to inject the DLL - DLL 注入失败 - - - - DLL injection is only supported for WINE/Proton processes - DLL 注入只支持 WINE/Proton 进程 - - - - Enter the expression for the function that'll be called from the inferior -You can view functions list from View->Functions - -For instance: -Calling printf("1234") will yield something like this -↓ -$28 = 4 - -$28 is the assigned convenience variable -4 is the result -You can use the assigned variable from the GDB Console - 输入要从被调试程序中调用的函数表达式 -你可以从 视图 -> 函数 查看函数列表 - -例如: -调用 printf("1234") 会产生类似如下的结果 -↓ -$28 = 4 - -$28 是分配的便利变量 -4 是函数调用的结果 -你可以在 GDB 控制台中使用该已赋值的变量 - - - - Failed to call the expression {} - 调用表达式 {} 失败 - - - - Invalid expression or address - 无效的表达式或地址 - - - - Invalid entries detected, refreshing the page - 检测到无效条目,正在刷新页面 - - - - Add new entry - 添加新条目 - - - - Enter the new value of register {} - 输入寄存器{}的新值 - - - - Enter the new value of flag {} - 输入标志(flag){}的新值 - - - - Restore this instruction - 还原此指令 - - - - Enter the hit count({} or higher) - 输入命中计数({}或更高) - - - - Hit count must be an integer - 命中计数必须是整数 - - - - Hit count can't be lower than {} - 命中计数不能少于 {} - - - - Change condition - 更改条件 - - - - Enable - 开启 - - - - Disable - 关闭 - - - - Disable after hit - 命中后关闭 - - - - Disable after X hits - 命中 X 次后关闭 - - - - Delete after hit - 命中后删除 - - - - Instructions writing to the address {} - 从地址 {} 写入指令中 - - - - Instructions reading from the address {} - 从地址 {} 读取指令中 - - - - Instructions accessing to the address {} - 从地址 {} 访问指令中 - - - - Unable to track watchpoint at expression {} - 无法追踪表达式 {} 处的监视点 - - - - Unable to delete watchpoint at expression {} - 无法删除表达式 {} 处的监视点 - - - - Close - 关闭 - - - - Addresses accessed by instruction {} - 指令 {} 访问的地址 - - - - Unable to track breakpoint at expression {} - 无法跟踪表达式 {} 处的断点 - - - - Accessed by {} - 访问自 {} - - - - Unable to delete breakpoint at expression {} - 无法删除表达式 {} 处的断点 - - - - Max trace count must be greater than or equal to {} - 最大追踪次数必须大或等于 {} - - - - Save trace file - 保存追踪文件 - - - - Open trace file - 打开追踪文件 - - - - Expand All - 展开全部 - - - - Collapse All - 收起全部 - - - - Select a pointer map file - 选择一个指针图文件 - - - - Scan - 扫描 - - - - Scanning - 扫描中 - - - - Filter - 过滤 - - - - Filtering - 过滤中 - - - - DEFINED - 定义 - - - - This symbol is defined. You can use its body as a gdb expression. For instance: - -void func(param) can be used as 'func' as a gdb expression - 该符号已定义。你可以直接将其主体作为 GDB 表达式使用。例如: - -void func(param) 可用 'func' 作为 GDB 表达式使用 - - - - Copy Symbol - 复制符号 - - - - Here's some useful regex tips: -^quaso --> search for everything that starts with quaso -[ab]cd --> search for both acd and bcd - - How to interpret symbols: -A symbol that looks like 'func(param)@plt' consists of 3 pieces -func, func(param), func(param)@plt -These 3 functions will have different addresses -@plt means this function is a subroutine for the original one -There can be more than one of the same function -It means that the function is overloaded - 这里有一些实用的正则表达式小技巧: -^quaso --> 匹配所有以 quaso 开头的内容 -[ab]cd --> 同时匹配 acd 和 bcd - - 如何解读符号: -一个形如 func(param)@plt 的符号由 3 个部分组成,分别是: -func, func(param), func(param)@plt -这 3 个函数(地址)各不相同 -其中,@plt 表示该函数是原始函数的一个子程序 -此外,如果出现多个同名函数, -这表示该函数发生了重载(Overload) - - - - New instruction is {} bytes long but old instruction is only {} bytes long -This will cause an overflow, proceed? - 新指令的长度为 {} 字节,但旧指令的长度仅为 {} 字节 -这会导致溢出,是否继续? - - - - {} isn't a valid expression - {} 不是有效的表达式 - - - - Log File of PID {} - PID {} 的日志文件 - - - - Contents of {} (only last {} bytes are shown) - {} 的内容(仅显示最后 {} 字节) - - - - ON - 开 - - - - OFF - 关 - - - - LOGGING: {} - 日志: {} - - - - Unable to read log file at {} - 无法读取位于 {} 的日志文件 - - - - Go to Settings->Debug to enable logging - 请转到“设置”->“调试”以启用日志记录 - - - - Invalid Regex - 无效的正则表达式 - - - - Here's some useful regex examples: -call|rax --> search for instructions that contain call or rax -[re]cx --> search for both rcx and ecx -Use the char \ to escape special chars such as [ -\[rsp\] --> search for instructions that contain [rsp] - 这里有一些有用的正则表达式示例: -call|rax --> 搜索包含 call 或 rax 的指令 -[re]cx --> 搜索 rcx 和 ecx -用字符 \ 转义特殊字符,比如 [ -\[rsp\] --> 搜索包含 [rsp] 的指令 - - - - Copy Addresses - 复制地址 - - - - Copy Offset - 复制偏移量 - - - - Copy Path - 复制路径 - - - - Start - 开始 - - - - Currently scanning region: - 当前扫描区域: - - - - Cancel - 取消 - - - - Scan finished - 扫描完成 - - - - Scan was canceled - 扫描被取消了 - - - - Select at least one region - 选中至少一个区域 - - - - You need to dissect code first -Proceed? - 你需要先分析代码 -是否继续? - - - - Waiting for breakpoint to trigger - 等待断点被触发 - - - - Tracing has been completed - 追踪已完成 - - - - Not - 不等 - - - - Exact - 精确 - - - - Increased - 增加 - - - - Increased by - 增加自 - - - - Decreased - 减少 - - - - Decreased by - 减少自 - - - - Less Than - 少于 - - - - More Than - 多于 - - - - Between - 介于 - - - - Changed - 改变 - - - - Unchanged - 未变 - - - - Unknown Value - 未知 - - - - Basic - 基础 - - - - Normal - 正常 - - - - Read+Write - 读+写 - - - - Full - 全部 - - - - Host - 主机 - - - - Little - 小 - - - - Big - 大 - - - - Show in HexView - 在十六进制视图中显示 - - - - Show in Disassembler - 在反汇编器中显示 - - - - Dark - 暗 - - - - Light - 亮 - - - - System Default - 系统默认 - - - - Wong (Colorblind Friendly) - 错(色盲友好) - - - - Session - Unsaved changes - 会话 - 未保存的修改 - - - - You have unsaved changes. -Do you want to save the current session? - 你有未保存的修改。 -你是否想保存当前会话? - - - - The session reset was cancelled because the current session was not saved. - - - - - Session - Process changed - 会话 - 进程变动 - - - - The process name has changed. -Do you want to keep the current session with the new process? - 进程名已变化。 -你是否想保留当前会话到新进程? - - - - Mono collector is not connected - Mono 收集器未连接 - - - - No supported managed runtime found in this process - 在此进程中未找到受支持的托管运行时环境 - - - - Invoke... - 调用... - - - - Instance (this) - 实例 (this) - - - - Result: {} - 结果:{} - - - - Returned (void) - 返回了 (void) - - - - Exception thrown (object @ {}) - 抛出异常 (object @ {}) - - - - Could not parse the argument values - 无法解析参数值 - - - - Invalid instance pointer - 无效的实例指针 - - - - This method has a parameter type that can't be marshalled yet - 此方法的某个参数类型尚无法进行封送处理 - - - - {} raw bytes (hex) - {} 原始字节(十六进制) - - - - Find instance... - 查找实例... - - - - Select a live instance: - 选择一个活动实例: - - - - Static field address is unavailable for this runtime - 此运行时无法获取静态字段地址 - - - - (type could not be resolved) - (类型无法解析) - - - - (maximum drill depth reached) - (达到最大钻洞深度) - - - - Find Instances - 查找实例 - - - - Find Instances - {} - 查找实例 - {} - - - - {} instance(s) found - 发现 {} 个实例 - - - - (showing first {}) - (展示第一个 {}) - - - - No live instances found - 未找到活动实例 - - - - Could not resolve an instance marker for this class - 无法解析此类别的实例标记 - - - - Fields - 字段 - - - - Methods - 方法 - - - - Disassemble - 反汇编 - - - - View at address… - 查看此地址... - - - - Delete structure - 删除结构体 - - - - Delete structure '{}'? - 删除结构体 '{}'? - - - - View as structure - 以结构体形式查看 - - - - Enter base address - 输入基址 - - - - Value - 值 - - - - Pointer - 指针 - - - - Inline - 内联 - - - - A structure with this name already exists - 以此为命名的结构体已存在 - - - - Structure name cannot be empty - 结构体名称不能为空 - - - - Unsigned - 无符号 - - - - Signed - 有符号 - - - - Hex - 十六进制 - - - - Export as structure - 导出为结构体 - - - - Dissect as structure - 以结构体形式分析 - - diff --git a/install.sh b/install.sh old mode 100755 new mode 100644 index 644b2be0..6db8dbbe --- a/install.sh +++ b/install.sh @@ -1,6 +1,6 @@ -#!/bin/sh +#!/bin/bash : ' -Copyright (C) 2016-2017 Korcan Karaokçu +Copyright (C) 2016 Korcan Karaokçu This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -16,200 +16,39 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . ' -exit_on_error() { - echo - echo "Error occurred while installing PINCE, check the output above for more information" - echo "Installation failed." - exit 1 -} - -build_libmemscan() { - git submodule init libmemscan || return 1 - if [ ! -e "libmemscan/.git" ]; then - git submodule update --init --recursive libmemscan || return 1 - fi - mkdir -p libpince/libmemscan - if [ -f "libpince/libmemscan/libmemscan.so" ] && [ -z "$PINCE_LIB_ONLY" ]; then - echo "Recompile libmemscan? [y/n]" - read -r answer - if ! echo "$answer" | grep -iq "^[Yy]"; then - return 0 - fi - fi - ( - echo "Building libmemscan..." - cd libmemscan || return 1 - if [ ! -f "./zig" ]; then - echo "Downloading Zig v0.16.0" - curl -L -o zig.tar.xz https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz - tar xf zig.tar.xz --strip-components 1 --wildcards "*/lib" "*/zig" - rm zig.tar.xz - fi - ./zig build -Doptimize=ReleaseFast ${LIBMEMSCAN_CPU} || return 1 - cp --preserve zig-out/lib/libmemscan.so ../libpince/libmemscan/ || return 1 - cp --preserve memscan.py ../libpince/libmemscan/ || return 1 - ) || return 1 - return 0 -} - -build_mono_collector() { - ZIG="$SCRIPTDIR/libmemscan/zig" - mkdir -p libpince/libmono_collector - if [ -f "libpince/libmono_collector/mono_collector_x64.so" ] && [ -f "libpince/libmono_collector/mono_collector_x86.so" ] && [ -f "libpince/libmono_collector/mono_collector_wine_x64.dll" ] && [ -f "libpince/libmono_collector/mono_collector_wine_x86.dll" ] && [ -z "$PINCE_LIB_ONLY" ]; then - echo "Recompile Mono collector? [y/n]" - read -r answer - if ! echo "$answer" | grep -iq "^[Yy]"; then - return 0 - fi - fi - ( - echo "Building Mono collector..." - cd mono_collector || return 1 - "$ZIG" build -Doptimize=ReleaseFast -Dtarget=x86_64-linux-gnu || return 1 - cp --preserve zig-out/lib/libmono_collector.so ../libpince/libmono_collector/mono_collector_x64.so || return 1 - "$ZIG" build -Doptimize=ReleaseFast -Dtarget=x86-linux-gnu || return 1 - cp --preserve zig-out/lib/libmono_collector.so ../libpince/libmono_collector/mono_collector_x86.so || return 1 - "$ZIG" build -Doptimize=ReleaseFast -Dtarget=x86_64-windows-gnu || return 1 - cp --preserve zig-out/bin/mono_collector.dll ../libpince/libmono_collector/mono_collector_wine_x64.dll || return 1 - "$ZIG" build -Doptimize=ReleaseFast -Dtarget=x86-windows-gnu || return 1 - cp --preserve zig-out/bin/mono_collector.dll ../libpince/libmono_collector/mono_collector_wine_x86.dll || return 1 - ) || return 1 - return 0 -} - -ask_pkg_mgr() { - echo - echo "Your distro is not officially supported! Trying to install anyway." - echo "Please choose your package manager." - echo "1) APT" - echo "2) Pacman" - echo "3) DNF" - echo "4) Zypper" - echo "5) None of the above" - - printf "%s" "Choose: "; read -r OPTION - OPTION=$(echo "$OPTION" | tr '[:lower:]' '[:upper:]') - - case $OPTION in - 1|*APT*) - OS_NAME="debian" - ;; - 2|*PACMAN*) - OS_NAME="arch" - ;; - 3|*DNF*) - OS_NAME="fedora" - ;; - 4|*ZYPPER*) - OS_NAME="suse" - ;; - *) - return 1 - ;; - esac - - return 0 -} - -# About xcb packages -> https://github.com/cdgriffith/FastFlix/wiki/Common-questions-and-problems -PKG_NAMES_ALL="python3-pip gdb" -PKG_NAMES_DEBIAN="$PKG_NAMES_ALL python3-dev python3-venv qt6-l10n-tools libxcb-randr0 libxcb-shape0 libxcb-xkb1 libxcb-cursor0" -PKG_NAMES_SUSE="$PKG_NAMES_ALL python3-devel qt6-tools-linguist" -PKG_NAMES_FEDORA="$PKG_NAMES_ALL python3-devel qt6-linguist" -PKG_NAMES_ARCH="python-pip qt6-tools gdb" # arch defaults to py3 nowadays - -INSTALL_COMMAND="install" - -set_install_vars() { - case $1 in - *suse*) - PKG_MGR="zypper" - PKG_NAMES="$PKG_NAMES_SUSE" - LRELEASE_CMD="lrelease6" - ;; - *arch*) - PKG_MGR="pacman" - PKG_NAMES="$PKG_NAMES_ARCH" - INSTALL_COMMAND="-S --needed" - LRELEASE_CMD="/usr/lib/qt6/bin/lrelease" - ;; - *fedora*) - PKG_MGR="dnf -y" - PKG_NAMES="$PKG_NAMES_FEDORA" - LRELEASE_CMD="lrelease-qt6" - ;; - *debian*|*ubuntu*) - PKG_MGR="apt -y" - PKG_NAMES="$PKG_NAMES_DEBIAN" - LRELEASE_CMD="/usr/lib/qt6/bin/lrelease" - ;; - *) - return 1 - ;; - esac - - return 0 -} - -compile_translations() { - ${LRELEASE_CMD} i18n/ts/* || return 1 - mkdir -p i18n/qm - mv i18n/ts/*.qm i18n/qm/ - return 0 -} - -main() { - if [ "$(id -u)" = "0" ]; then - echo "Please do not run this script as root!" - exit 1 - fi - - SCRIPTDIR=$(cd -- "$(dirname -- "$0")" && pwd -P) - cd "$SCRIPTDIR" || exit - - if [ ! -d ".git" ]; then - echo "Error! Could not find \".git\" folder!" - echo "This can happen if you downloaded the ZIP file instead of cloning through git." - echo "Please clone the PINCE repository using the \"--recursive\" flag and try again!" - echo "For more information, please follow the installation instructions on GitHub." - exit 1 - fi - - if [ -r /etc/os-release ]; then - . /etc/os-release - OS_NAME="$ID $ID_LIKE" - fi - - if ! set_install_vars "$OS_NAME"; then - if ! ask_pkg_mgr; then - echo - echo "Sorry, your distro is not supported!" - exit 1 - fi - - set_install_vars "$OS_NAME" - fi - - sudo ${PKG_MGR} ${INSTALL_COMMAND} ${PKG_NAMES} || exit_on_error - - # Prepare Python virtual environment - if [ ! -d ".venv/bin" ]; then - python3 -m venv .venv - fi - . .venv/bin/activate - - pip3 install --upgrade pip || exit_on_error - pip3 install -r requirements.txt || exit_on_error - - build_libmemscan || exit_on_error - build_mono_collector || exit_on_error - compile_translations || exit_on_error - - echo - echo "PINCE has been installed successfully!" - echo "Now, just run 'sh PINCE.sh' from terminal" -} - -if [ -z "$PINCE_LIB_ONLY" ]; then - main +sudo apt-get install python3-setuptools +sudo apt-get install python3-pip +sudo apt-get install python3-pyqt5 +sudo pip3 install psutil +sudo pip3 install pexpect +mkdir -p gdb_pince +cd gdb_pince + +# clean the directory if another install happened +rm -rf gdb-7.11.1 + +wget "http://ftp.gnu.org/gnu/gdb/gdb-7.11.1.tar.gz" +tar -zxvf gdb-7.11.1.tar.gz +cd gdb-7.11.1 + +# Dependencies required for compiling gdb +sudo apt-get install python3-dev +sudo apt-get install gcc + +# FIXME: Is setting prefix as "/usr" bad? +CC=gcc ./configure --prefix=/usr --with-python=python3 && make && sudo make -C gdb install + +# Relocating PINCE files +cd +auto_load_command="set auto-load safe-path /" +if [ ! -e .gdbinit ] ; then + touch .gdbinit +fi +if grep "$auto_load_command" .gdbinit +then + echo "auto_load already satisfied" +else + echo "\n"$auto_load_command >> .gdbinit fi +echo "PINCE has been installed successfully!" +echo "Now, just run 'sh PINCE.sh' from terminal" \ No newline at end of file diff --git a/libPINCE/.gdbinit b/libPINCE/.gdbinit new file mode 100644 index 00000000..100ccdb7 --- /dev/null +++ b/libPINCE/.gdbinit @@ -0,0 +1 @@ +set disassembly-flavor intel \ No newline at end of file diff --git a/libpince/.gitignore b/libPINCE/.gitignore similarity index 79% rename from libpince/.gitignore rename to libPINCE/.gitignore index dfa456c9..6addce1c 100644 --- a/libpince/.gitignore +++ b/libPINCE/.gitignore @@ -1,5 +1,5 @@ __pycache__/ .idea/* +.directory *.py[cod] *$py.class -gdb_pince/* \ No newline at end of file diff --git a/libPINCE/GDB_Engine.py b/libPINCE/GDB_Engine.py new file mode 100644 index 00000000..e6f17d41 --- /dev/null +++ b/libPINCE/GDB_Engine.py @@ -0,0 +1,835 @@ +# -*- coding: utf-8 -*- +""" +Copyright (C) 2016 Korcan Karaokçu + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" +from re import search, split, findall, escape +from threading import Lock, Thread, Condition +from time import sleep, time +import pexpect +import os +import ctypes +import pickle +from . import SysUtils +from . import type_defs + +INDEX_BYTE = type_defs.VALUE_INDEX.INDEX_BYTE +INDEX_2BYTES = type_defs.VALUE_INDEX.INDEX_2BYTES +INDEX_4BYTES = type_defs.VALUE_INDEX.INDEX_4BYTES +INDEX_8BYTES = type_defs.VALUE_INDEX.INDEX_8BYTES +INDEX_FLOAT = type_defs.VALUE_INDEX.INDEX_FLOAT +INDEX_DOUBLE = type_defs.VALUE_INDEX.INDEX_DOUBLE +INDEX_STRING = type_defs.VALUE_INDEX.INDEX_STRING +INDEX_AOB = type_defs.VALUE_INDEX.INDEX_AOB + +INITIAL_INJECTION_PATH = type_defs.PATHS.INITIAL_INJECTION_PATH + +INFERIOR_RUNNING = type_defs.INFERIOR_STATUS.INFERIOR_RUNNING +INFERIOR_STOPPED = type_defs.INFERIOR_STATUS.INFERIOR_STOPPED + +SIMPLE_DLOPEN_CALL = type_defs.INJECTION_METHOD.SIMPLE_DLOPEN_CALL +ADVANCED_INJECTION = type_defs.INJECTION_METHOD.ADVANCED_INJECTION + +ARCH_32 = type_defs.INFERIOR_ARCH.ARCH_32 +ARCH_64 = type_defs.INFERIOR_ARCH.ARCH_64 + +libc = ctypes.CDLL('libc.so.6') +inferior_arch = int + +currentpid = 0 +child = object # this object will be used with pexpect operations +lock_send_command = Lock() +gdb_async_condition = Condition() +status_changed_condition = Condition() +inferior_status = -1 +gdb_output = "" +gdb_async_output = "" + +index_to_gdbcommand_dict = type_defs.index_to_gdbcommand_dict + + +# The comments next to the regular expressions shows the expected gdb output, hope it helps to the future developers + +def send_command(command, control=False, cli_output=False, send_with_file=False, file_contents_send=None, + recv_with_file=False): + """Issues the command sent + + Args: + command (str): The command that'll be sent + control (bool): This param should be True if the command sent is ctrl+key instead of the regular command + cli_output (bool): If True, returns the readable parsed cli output instead of gdb/mi garbage + send_with_file (bool): Custom commands declared in GDBCommandExtensions.py requires file communication. If + called command has any parameters, pass this as True + file_contents_send (any type that pickle.dump supports): Arguments for the called custom gdb command + recv_with_file (bool): Pass this as True if the called custom gdb command returns something + + Examples: + send_command(c,control=True)--> Sends ctrl+c instead of the str "c" + send_command("pince-read-multiple-addresses", file_contents_send=nested_list, recv_file=True)--> This line calls + the custom gdb command "pince-read-multiple-addresses" with parameter nested_list and since that gdb command + returns the addresses read as a list, we also pass the parameter recv_file as True + + Returns: + str: Result of the command sent, commands in the form of "ctrl+key" always returns a null string + None: If the inferior is running or no inferior has been selected + + Todo: + Support GDB/MI commands. In fact, this is something gdb itself should fix. Because gdb python API doesn't + support gdb/mi commands and since PINCE uses gdb python API, it can't support gdb/mi commands as well + + Note: + File communication system is used to avoid BEL emitting bug of pexpect. If you send more than a certain amount + of characters to gdb, the input will be sheared at somewhere and gdb won't be receiving all of the input + Visit this page for more information-->http://pexpect.readthedocs.io/en/stable/commonissues.html + """ + global child + global gdb_output + with lock_send_command: + time0 = time() + if currentpid == 0: + print("no process has been selected") + return + if inferior_status is INFERIOR_RUNNING and not control: + print("inferior is running") + return + gdb_output = "" + if send_with_file: + send_file = SysUtils.get_ipc_from_PINCE_file(currentpid) + pickle.dump(file_contents_send, open(send_file, "wb")) + if recv_with_file or cli_output: + recv_file = SysUtils.get_ipc_to_PINCE_file(currentpid) + + # Truncating the recv_file because we wouldn't like to see output of previous command in case of errors + open(recv_file, "w").close() + command = str(command) + print("Last command: " + (command if not control else "Ctrl+" + command)) + if control: + child.sendcontrol(command) + else: + command_file = SysUtils.get_gdb_command_file(currentpid) + command_fd = open(command_file, "w") + command_fd.write(command) + command_fd.close() + if not cli_output: + child.sendline("source " + command_file) + else: + child.sendline("cli-output source " + command_file) + if not control: + while gdb_output is "": + sleep(0.00001) + if not control: + if recv_with_file or cli_output: + output = pickle.load(open(recv_file, "rb")) + else: + output = gdb_output + else: + output = "" + if type(output) == str: + output = output.strip() + time1 = time() + print(time1 - time0) + return output + + +def can_attach(pid): + """Check if we can attach to the target + + Args: + pid (int,str): PID of the process that'll be attached + + Returns: + bool: True if attaching is successful, False otherwise + """ + result = libc.ptrace(16, int(pid), 0, 0) # 16 is PTRACE_ATTACH, check ptrace.h for details + if result is -1: + return False + os.waitpid(int(pid), 0) + libc.ptrace(17, int(pid), 0, 17) # 17 is PTRACE_DETACH, check ptrace.h for details + sleep(0.01) + return True + + +def state_observe_thread(): + """ + Observes the state of gdb, uses conditions to inform other functions and threads about gdb's state + Also generates output for send_command function + Should be called by creating a thread. Usually called in initialization process by attach function + """ + global inferior_status + global child + global gdb_output + global gdb_async_output + while True: + child.expect_exact("(gdb)") + print(child.before) # debug mode on! + matches = findall(r"stopped\-threads=\"all\"|\*running,thread\-id=\"all\"", + child.before) # stopped-threads="all" # *running,thread-id="all" + if len(matches) > 0: + if search(r"stopped", matches[-1]): + inferior_status = INFERIOR_STOPPED + else: + inferior_status = INFERIOR_RUNNING + with status_changed_condition: + status_changed_condition.notify_all() + try: + # The command will always start with the word "source", check send_command function for the cause + command_file = escape(SysUtils.get_gdb_command_file(currentpid)) + gdb_output = split(r"&\".*source\s" + command_file + r"\\n\"", child.before, 1)[1] # &"command\n" + except: + with gdb_async_condition: + gdb_async_output = child.before + gdb_async_condition.notify_all() + + +def interrupt_inferior(): + """Interrupt the inferior""" + send_command("c", control=True) + + +def continue_inferior(): + """Continue the inferior""" + send_command("c") + + +def step_instruction(): + """Step one assembly instruction""" + send_command("stepi") + + +def step_over_instruction(): + """Step over one assembly instruction""" + send_command("nexti") + + +def execute_till_return(): + """Continues inferior till current stack frame returns""" + send_command("finish") + + +def attach(pid): + """Attaches gdb to the target and initializes some of the global variables + + Args: + pid (int,str): PID of the process that'll be attached to + """ + global currentpid + global child + global inferior_arch + currentpid = int(pid) + SysUtils.create_PINCE_IPC_PATH(pid) + currentdir = SysUtils.get_current_script_directory() + child = pexpect.spawn('sudo LC_NUMERIC=C gdb --interpreter=mi', cwd=currentdir + "/libPINCE", encoding="utf-8") + child.setecho(False) + child.delaybeforesend = 0 + child.timeout = None + child.expect_exact("(gdb)") + status_thread = Thread(target=state_observe_thread) + status_thread.daemon = True + status_thread.start() + send_command("set logging file " + SysUtils.get_gdb_async_file(pid)) + send_command("set logging on") + send_command("attach " + str(pid)) + + # gdb scripts needs to know PINCE directory, unfortunately they don't start from the place where script exists + send_command('set $PINCE_PATH=' + '"' + currentdir + '"') + send_command("source gdb_python_scripts/GDBCommandExtensions.py") + inferior_arch = get_inferior_arch() + continue_inferior() + + +def detach(): + """See you, space cowboy""" + global child + global currentpid + global inferior_status + child.sendcontrol("d") + child.close() + currentpid = 0 + inferior_status = -1 + + +def inject_with_advanced_injection(library_path): + """Injects the given .so file to current process + + Args: + library_path (str): Path to the .so file that'll be injected + + Returns: + bool: Result of the injection + + Notes: + This function was reserved for linux-inject and since linux-inject is no more(F to pay respects), I'll leave + this function as a template for now + """ + raise NotImplementedError + + +def inject_with_dlopen_call(library_path): + """Injects the given .so file to current process + This is a variant of the function inject_with_advanced_injection + This function won't break the target process unlike other complex injection methods + The downside is it fails if the target doesn't support dlopen calls or simply doesn't have the library + + Args: + library_path (str): Path to the .so file that'll be injected + + Returns: + bool: Result of the injection + """ + injectionpath = '"' + library_path + '"' + result = send_command("call dlopen(" + injectionpath + ", 1)") + filtered_result = search(r"\$\d+\s*=\s*\-*\d+", result) # $1 = -1633996800 + if filtered_result: + dlopen_return_value = split(" ", filtered_result.group(0))[-1] + if dlopen_return_value is "0": + result = send_command("call __libc_dlopen_mode(" + injectionpath + ", 1)") + filtered_result = search(r"\$\d+\s*=\s*\-*\d+", result) # $1 = -1633996800 + if filtered_result: + dlopen_return_value = split(" ", filtered_result.group(0))[-1] + if dlopen_return_value is "0": + return False + return True + return False + return True + result = send_command("call __libc_dlopen_mode(" + injectionpath + ", 1)") + filtered_result = search(r"\$\d+\s*=\s*\-*\d+", result) # $1 = -1633996800 + if filtered_result: + dlopen_return_value = split(" ", filtered_result.group(0))[-1] + if dlopen_return_value is "0": + return False + return True + return False + + +def value_index_to_gdbcommand(index=int): + """Converts the given value_index to a parameter that'll be used in "x" command of gdb + + Args: + index (int): Can be a member of type_defs.VALUE_INDEX + + Returns: + str: The str corresponding to the index in type_defs.index_to_gdbcommand_dict + """ + return index_to_gdbcommand_dict.get(index, "out of bounds") + + +def check_for_restricted_gdb_symbols(string): + """Checks for characters that cause unexpected behaviour + "$" makes gdb show it's value history(e.g $4=4th value) and it's convenience variables(such as $pc, $g_thread) + Also whitespaces(or simply inputting nothing) makes gdb show the last shown value + If you don't like the user to see these, use this function to check the input + + Args: + string (str): The str that'll be checked for specific characters + + Returns: + bool: True if one of the characters are encountered, False otherwise + """ + string = str(string) + string = string.strip() + if string is "": + return True + if search(r"\".*\"", string) or search(r"\{.*\}", string): # For string and array expressions + return False + if search(r'\$', string): # These characters make gdb show it's value history, so they should be avoided + return True + return False + + +def read_single_address_by_expression(expression, value_index, length=None, is_unicode=False, zero_terminate=True, + check=True): + """Reads value from the given address or expression by using "x" command of gdb then converts it to the given + value type + + The expression can also be a function name such as "_start", "malloc", "printf" and "scanf" + + Args: + expression (str): Can be a hex string or an expression. By default, expressions using the character "$" are not + permitted. The character "$" is useful when displaying convenience variables, but it's also confusing because it + makes gdb show it's value history. To include "$" in the permitted characters, pass the parameter check as True + value_index (int): Determines the type of data read. Can be a member of type_defs.VALUE_INDEX + length (int): Length of the data that'll be read. Only used when the value_index is INDEX_STRING or INDEX_AOB. + Ignored otherwise. + is_unicode (bool): If True, data will be considered as utf-8, ascii otherwise. Only used when value_index is + INDEX_STRING. Ignored otherwise. + zero_terminate (bool): If True, data will be split when a null character has been read. Only used when + value_index is INDEX_STRING. Ignored otherwise. + check (bool): If True, the parameter expression will be checked by check_for_restricted_gdb_symbols function. If + any specific character is found, this function will return "??" + + Returns: + str: The value of address read as str. If the expression/address is not valid, returns the string "??" + """ + if check: + if check_for_restricted_gdb_symbols(expression): + return "??" + if length is "": + return "??" + if value_index is INDEX_AOB: + typeofaddress = value_index_to_gdbcommand(value_index) + try: + expectedlength = str(int(length)) # length must be a legit number, so had to do this trick + except: + return "??" + result = send_command("x/" + expectedlength + typeofaddress + " " + expression) + filteredresult = findall(r"\\t0x[0-9a-fA-F]+", result) # 0x40c431:\t0x31\t0xed\t0x49\t... + if filteredresult: + returned_string = ''.join(filteredresult) # combine all the matched results + return returned_string.replace(r"\t0x", " ") + return "??" + elif value_index is INDEX_STRING: + typeofaddress = value_index_to_gdbcommand(value_index) + if not is_unicode: + try: + expectedlength = str(int(length)) + except: + return "??" + result = send_command("x/" + expectedlength + typeofaddress + " " + expression) + else: + try: + expectedlength = str(int(length) * 2) + except: + return "??" + result = send_command("x/" + expectedlength + typeofaddress + " " + expression) + filteredresult = findall(r"\\t0x[0-9a-fA-F]+", result) # 0x40c431:\t0x31\t0xed\t0x49\t... + if filteredresult: + filteredresult = ''.join(filteredresult) + returned_string = filteredresult.replace(r"\t0x", "") + if not is_unicode: + returned_string = bytes.fromhex(returned_string).decode("ascii", "replace") + else: + returned_string = bytes.fromhex(returned_string).decode("utf-8", "replace") + if zero_terminate: + if returned_string.startswith('\x00'): + returned_string = '\x00' + else: + returned_string = returned_string.split('\x00')[0] + return returned_string[0:int(length)] + return "??" + else: + typeofaddress = value_index_to_gdbcommand(value_index) + result = send_command("x/" + typeofaddress + " " + expression) + filteredresult = search(r":\\t[0-9a-fA-F-,]+", result) # 0x400000:\t1,3961517377359369e-309 + if filteredresult: + return split("t", filteredresult.group(0))[-1] + return "??" + + +def read_single_address(address, value_index, length=None, is_unicode=False, zero_terminate=True): + """Reads value from the given address by using an optimized gdb python script + + A variant of the function read_single_address_by_expression. This function is slightly faster and it only accepts + addresses instead of expressions. Use this function if you like to read only addresses, use the other variant if you + also would like to input expressions. This function also calculates float and double variables more precisely, for + instance, if you calculate the address 0x40c495(_start+100) on KMines with value_index=INDEX_DOUBLE with the + function read_single_address_by_expression(which uses gdb's "x" command), you'll get the result "6". But if you use + this function instead(custom script), you'll get the result "6.968143721100816e+38" instead + + Args: + address (str): Can be a hex string. + value_index (int): Determines the type of data read. Can be a member of type_defs.VALUE_INDEX + length (int): Length of the data that'll be read. Only used when the value_index is INDEX_STRING or INDEX_AOB. + Ignored otherwise. + is_unicode (bool): If True, data will be considered as utf-8, ascii otherwise. Only used when value_index is + INDEX_STRING. Ignored otherwise. + zero_terminate (bool): If True, data will be split when a null character has been read. Only used when + value_index is INDEX_STRING. Ignored otherwise. + + Returns: + str: If the value_index is INDEX_STRING or INDEX_AOB. If an error occurs when reading, returns a null string + float: If the value_index is INDEX_FLOAT or INDEX_DOUBLE + int: If the value_index is anything else + """ + return send_command("pince-read-single-address", send_with_file=True, + file_contents_send=(address, value_index, length, is_unicode, zero_terminate), + recv_with_file=True) + + +def read_multiple_addresses(nested_list): + """Reads multiple values from the given addresses by using an optimized gdb python script + + Optimized version of the function read_single_address. This function is significantly faster after 100 addresses + compared to using read_single_address in a for loop. + + Args: + nested_list (list): List of *args of the function read_single_address. You don't have to pass all of the + parameters for each list in the nested_list, only parameters address and value_index are obligatory. Defaults + of the other parameters are the same with the function read_single_address. + + Examples: + All parameters are passed-->[[address1, value_index1, length1, unicode1, zero_terminate1],[address2, ...], ...] + Parameters are partially passed--▼ + [[address1, value_index1],[address2, value_index2, length2],[address3, value_index3, zero_terminate], ...] + + Returns: + list: A list of the values read. + If any errors occurs while reading addresses, it's ignored and the belonging address is returned as null string + For instance; If 4 addresses has been read and 3rd one is problematic, the returned list will be + [returned_value1,returned_value2,"",returned_value4] + """ + contents_recv = send_command("pince-read-multiple-addresses", send_with_file=True, file_contents_send=nested_list, + recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading addresses") + contents_recv = [] + return contents_recv + + +def set_multiple_addresses(nested_list, value): + """Sets the given value to the given addresses by using an optimized gdb python script + + There's no single version of this function yet. Use this even for single addresses + If any errors occurs while setting values to the according addresses, it'll be ignored but the information about + error will be printed to the terminal. + + Args: + nested_list (list): List of the address and value_index parameters of the function read_single_address + Both parameters address and value_index are necessary. + value (str): The value that'll be written to the given addresses + + Examples: + nested_list-->[[address1, value_index1],[address2, value_index2], ...] + """ + nested_list.append(value) + send_command("pince-set-multiple-addresses", send_with_file=True, file_contents_send=nested_list) + + +def disassemble(expression, offset_or_address): + """Disassembles the address evaluated by the given expression + + Args: + expression (str): Any gdb expression + offset_or_address (str): If you pass this parameter as an offset, you should add "+" in front of it + (e.g "+42" or "+0x42"). If you pass this parameter as an hex address, the address range between the expression + and the secondary address is disassembled. + If the second parameter is an address. it always should be bigger than the first address. + + Returns: + list: A list of str values in this format-->[[address1,bytes1,opcodes1],[address2, ...], ...] + """ + returned_list = [] + output = send_command("disas /r " + expression + "," + offset_or_address) + filtered_output = findall(r"0x[0-9a-fA-F]+.*\\t.+\\t.+\\n", + output) # 0x00007fd81d4c7400 <__printf+0>:\t48 81 ec d8 00 00 00\tsub rsp,0xd8\n + for item in filtered_output: + returned_list.append(list(filter(None, split(r"\\t|\\n", item)))) + return returned_list + + +def convert_address_to_symbol(expression, include_address=False, check=True): + """Converts the address evaluated by the given expression to symbol if any symbol exists for it + + Args: + expression (str): Any gdb expression + include_address (bool): If true, returned string includes address + check (bool): If your string contains one of the restricted characters($ etc.) pass the check parameter as False + + Returns: + str: Symbol of corresponding address(such as printf, scanf, _start etc.). If no symbols are found, address as + str returned instead. If include_address is passed as True, returned str looks like this-->0x40c435 <_start+4> + If the parameter "check" is True, returns the expression itself untouched if any restricted characters are found + None: If the address is unreachable + """ + if check: + if check_for_restricted_gdb_symbols(expression): + return expression + result = send_command("x/b " + expression) + if search(r"Cannot\s*access\s*memory\s*at\s*address", result): + return + filteredresult = search(r"0x[0-9a-fA-F]+\s+<.+>:\\t", result) # 0x40c435 <_start+4>:\t0x89485ed1\n + if filteredresult: + if include_address: + return split(":", filteredresult.group(0))[0] + return split(">:", filteredresult.group(0))[0].split("<")[1] + else: + filteredresult = search(r"0x[0-9a-fA-F]+:\\t", result) # 0x1f58010:\t0x00647361\n + if filteredresult: + return split(":", filteredresult.group(0))[0] + + +def convert_symbol_to_address(expression, check=True): + """Converts the symbol evaluated by the given expression to address + + Args: + expression (str): Any gdb expression + check (bool): If your string contains one of the restricted symbols(such as $) pass the check parameter as False + + Returns: + str: Address of corresponding symbol + If the parameter "check" is True, returns the expression itself untouched if any restricted characters are found + None: If the address is unreachable + """ + if check: + if check_for_restricted_gdb_symbols(expression): + return expression + result = send_command("x/b " + expression) + if search(r"Cannot\s*access\s*memory\s*at\s*address", result): + return + filteredresult = search(r"0x[0-9a-fA-F]+\s+<.+>:\\t", result) # 0x40c435 <_start+4>:\t0x89485ed1\n + if filteredresult: + return split(" ", filteredresult.group(0))[0] + else: + filteredresult = search(r"0x[0-9a-fA-F]+:\\t", result) # 0x1f58010:\t0x00647361\n + if filteredresult: + return split(":", filteredresult.group(0))[0] + + +def parse_convenience_variables(variable_list): + """Converts the convenience variables to their str equivalents + + Args: + variable_list (list of str): List of convenience variables as strings. + + Examples: + variable_list-->["$pc","$_gthread","$_inferior","$_exitcode","$_siginfo"] + + Returns: + list: List of str values of the corresponding convenience variables + """ + contents_recv = send_command("pince-parse-convenience-variables", send_with_file=True, + file_contents_send=variable_list, + recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading variables") + contents_recv = [] + return contents_recv + + +# Returns address and the LWP of the current thread +def get_current_thread_information(): + """Gather information about the current thread + + Returns: + str: "Thread "+thread_address+" (LWP "+LWP_ID+")" + + Examples: + returned_str-->"Thread 0x7f34730d77c0 (LWP 6189)" + """ + thread_info = send_command("info threads") + parsed_info = search(r"\*\s+\d+\s+Thread\s+0x[0-9a-fA-F]+\s+\(LWP\s+\d+\)", + thread_info).group(0) # * 1 Thread 0x7f34730d77c0 (LWP 6189) + return split(r"Thread\s+", parsed_info)[-1] + + +def find_address_of_closest_instruction(address, how_many_instructions_to_look_for=1, instruction_location="next"): + """Finds address of the closest instruction next to the given address, assuming that the given address is valid + + Args: + address (str): Hex address + how_many_instructions_to_look_for (int): Number of the instructions that'll be lo- OH COME ON NOW! That one is + obvious! + instruction_location (str): If it's "next", instructions coming after the address is searched. If it's anything + else, the instructions coming before the address is searched instead. + + Returns: + str: The address found as hex string. If starting/ending of a valid memory range is reached, starting/ending + address is returned instead as hex string. + """ + if instruction_location == "next": + offset = "+" + str(how_many_instructions_to_look_for * 30) + disas_data = disassemble(address, address + offset) + else: + offset = "-" + str(how_many_instructions_to_look_for * 30) + disas_data = disassemble(address + offset, address) + if not disas_data: + if instruction_location != "next": + start_address = SysUtils.get_region_info(currentpid, address).start + disas_data = disassemble(start_address, address) + if instruction_location == "next": + try: + return SysUtils.extract_address(disas_data[how_many_instructions_to_look_for][0]) + except IndexError: + return SysUtils.get_region_info(currentpid, address).end + else: + try: + return SysUtils.extract_address(disas_data[-how_many_instructions_to_look_for][0]) + except IndexError: + try: + return start_address + except UnboundLocalError: + return SysUtils.get_region_info(currentpid, address).start + + +def get_info_about_address(expression): + """Runs the gdb command "info symbol" for given expression and returns the result of it + + Args: + expression (str): Any gdb expression + + Returns: + str: The result of the command "info symbol" for given expression + """ + return send_command("info symbol " + expression, cli_output=True) + + +def get_inferior_arch(): + """Returns the architecture of the current inferior + + Returns: + int: A member of type_defs.INFERIOR_ARCH + """ + if parse_convenience_variables(["$rax"])[0] == "void": + return ARCH_32 + return ARCH_64 + + +def read_registers(): + """Returns the current registers + + Returns: + dict: A dict that holds general registers, flags and segment registers + """ + contents_recv = send_command("pince-read-registers", recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading registers") + contents_recv = {} + return contents_recv + + +def read_float_registers(): + """Returns the current floating point registers + + Returns: + dict: A dict that holds float registers(st0-7, xmm0-7) + """ + contents_recv = send_command("pince-read-float-registers", recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading float registers") + contents_recv = {} + return contents_recv + + +def set_convenience_variable(variable, value): + """Sets given convenience variable to given value + + Args: + variable (str): Any gdb convenience variable(with "$" character removed) + value (str): Anything + """ + send_command("set $" + variable + "=" + value) + + +def set_register_flag(flag, value): + """Sets given register flag to given value + + Args: + flag (str): "cf", "pf", "af", "zf", "sf", "tf", "if", "df" or "of" + value (str): "0" or "1" + Theoretically, you can pass anything as value. But, it may fuck other flag registers... VERY BADLY! + """ + registers = read_registers() + registers[flag] = value + eflags_hex_value = hex(int( + registers["of"] + registers["df"] + registers["if"] + registers["tf"] + registers["sf"] + registers[ + "zf"] + "0" + registers["af"] + "0" + registers["pf"] + "0" + registers["cf"], 2)) + set_convenience_variable("eflags", eflags_hex_value) + + +def get_stacktrace_info(): + """Returns information about current stacktrace + + Returns: + list: A list of str values in this format-->[[return_address_info1,frame_address_info1],[info2, ...], ...] + + return_address_info looks like this-->Return address of frame+symbol-->0x40c431 <_start> + frame_address_info looks like this-->Beginning of frame+distance from stack pointer-->0x7ffe1e989a40(rsp+0x100) + """ + contents_recv = send_command("pince-get-stack-trace-info", recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading stacktrace") + contents_recv = [] + return contents_recv + + +def get_stack_info(): + """Returns information about current stack + + Returns: + list: A list of str values in this format--▼ + [[stack_pointer_info1,hex_value1,int_representation1,float_representation1],[stack_pointer_info2, ...], ...] + + stack_pointer_info looks like this-->Hex address+distance from stack pointer-->0x7ffd0d232f88(rsp+0xff8) + hex_value looks like this-->Value holden by corresponding address-->0x00302e322d63726b + int_representation looks like this-->integer representation of the hex_value-->13561591926846059 + float_representation looks like this-->float representation of the hex_value--->9.000675827832922e-308 + """ + contents_recv = send_command("pince-get-stack-info", recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading stack") + contents_recv = [] + return contents_recv + + +def get_stack_frame_return_addresses(): + """Returns return addresses of stack frames + + Returns: + list: A list of str values in this format-->[return_address_info1,return_address_info2, ...] + + return_address_info looks like this-->Return address of frame+symbol-->0x40c431 <_start> + """ + contents_recv = send_command("pince-get-frame-return-addresses", recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading return addresses of stack frames") + contents_recv = [] + return contents_recv + + +def get_stack_frame_info(index): + """Returns information about stack by the given index + + Args: + index (int,str): Index of the frame + + Returns: + str: Information that looks like this--▼ + Stack level 0, frame at 0x7ffc5f87f6a0: + rip = 0x7fd1d639412d in poll (../sysdeps/unix/syscall-template.S:81); saved rip = 0x7fd1d27fcfe4 + called by frame at 0x7ffc5f87f700 + source language asm. + Arglist at 0x7ffc5f87f688, args: + Locals at 0x7ffc5f87f688, Previous frame's sp is 0x7ffc5f87f6a0 + Saved registers: + rip at 0x7ffc5f87f698 + """ + contents_recv = send_command("pince-get-frame-info", send_with_file=True, file_contents_send=str(index), + recv_with_file=True) + if contents_recv is None: + print("an error occurred while reading stack frame " + str(index)) + return contents_recv + + +def hex_dump(address, offset): + """Returns hex dump of range (address to address+offset) + + Args: + address (int,str): Hex address or an int + offset (int,str): The range that'll be read + + Returns: + list: List of strings read as str. If an error occurs while reading a memory cell, that cell is returned as "??" + + Examples: + returned list-->["??","??","??","7f","43","67","40","??","??, ...] + """ + if type(address) != int: + address = int(address, 16) + if type(offset) != int: + offset = int(offset) + contents_recv = send_command("pince-hex-dump", send_with_file=True, file_contents_send=(address, offset), + recv_with_file=True) + if contents_recv is None: + print("an error occurred while hex dumping address " + hex(address) + " with offset " + str(offset)) + return contents_recv diff --git a/libPINCE/GuiUtils.py b/libPINCE/GuiUtils.py new file mode 100644 index 00000000..a604283a --- /dev/null +++ b/libPINCE/GuiUtils.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +""" +Copyright (C) 2016 Korcan Karaokçu + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" +from PyQt5.QtWidgets import QDesktopWidget +from re import search, sub +from . import type_defs + +INDEX_BYTE = type_defs.VALUE_INDEX.INDEX_BYTE +INDEX_2BYTES = type_defs.VALUE_INDEX.INDEX_2BYTES +INDEX_4BYTES = type_defs.VALUE_INDEX.INDEX_4BYTES +INDEX_8BYTES = type_defs.VALUE_INDEX.INDEX_8BYTES +INDEX_FLOAT = type_defs.VALUE_INDEX.INDEX_FLOAT +INDEX_DOUBLE = type_defs.VALUE_INDEX.INDEX_DOUBLE +INDEX_STRING = type_defs.VALUE_INDEX.INDEX_STRING +INDEX_AOB = type_defs.VALUE_INDEX.INDEX_AOB + +index_to_text_dict = type_defs.index_to_text_dict +text_to_index_dict = type_defs.text_to_index_dict + + +def center(window): + """Center the given window to desktop + + Args: + window (QMainWindow, QWidget etc.): The window that'll be centered to desktop + """ + window.move(QDesktopWidget().availableGeometry().center() - window.frameGeometry().center()) + + +def center_to_parent(window): + """Center the given window to it's parent + + Args: + window (QMainWindow, QWidget etc.): The window that'll be centered to it's parent + """ + window.move(window.parent().frameGeometry().center() - window.frameGeometry().center()) + + +def center_to_window(window_secondary, window_main): + """Center the given window_secondary to window_main + + Args: + window_secondary (QMainWindow, QWidget etc.): The window that'll be centered to window_main + window_main (QMainWindow, QWidget etc.): The window that window_secondary will centered to + """ + window_secondary.move(window_main.frameGeometry().center() - window_secondary.frameGeometry().center()) + + +def center_scroll_bar(QScrollBar): + """Center the given scrollbar + + Args: + QScrollBar (QScrollbar): The scrollbar that'll be centered + """ + maximum = QScrollBar.maximum() + minimum = QScrollBar.minimum() + QScrollBar.setValue((maximum + minimum) / 2) + + +def valuetype_to_text(value_index=int, length=0, is_unicode=False, zero_terminate=True): + """Returns a str according to given parameters + + Args: + value_index (int): Determines the type of data. Can be a member of type_defs.VALUE_INDEX + length (int): Length of the data. Only used when the value_index is INDEX_STRING or INDEX_AOB. Ignored otherwise + is_unicode (bool): If True, ",U" will be appended to str. Only used when value_index is INDEX_STRING. + Ignored otherwise. "U" stands for "Unicode" + zero_terminate (bool): If False, ",NZT" will be appended to str. Only used when value_index is INDEX_STRING. + Ignored otherwise. "NZT" stands for "Not Zero Terminate" + + Returns: + str: A str generated by given parameters + str "out of bounds" is returned if the value_index doesn't match the dictionary + + Examples: + value_index=INDEX_STRING, length=15, is_unicode=True, zero_terminate=False-->returned str="String[15],U,NZT" + value_index=INDEX_AOB, length=42-->returned str="AoB[42]" + """ + returned_string = index_to_text_dict.get(value_index, "out of bounds") + if value_index is INDEX_STRING: + returned_string = returned_string + "[" + str(length) + "]" + if is_unicode: + returned_string = returned_string + ",U" + if not zero_terminate: + returned_string = returned_string + ",NZT" + elif value_index is INDEX_AOB: + returned_string = returned_string + "[" + str(length) + "]" + return returned_string + + +def text_to_valuetype(string): + """Returns a tuple of parameters of the function valuetype_to_text evaluated according to given str + + Args: + string (str): String must be generated from the function valuetype_to_text + + Returns: + tuple: A tuple consisting of parameters of the function valuetype_to_text--▼ + value_index, length, unicode, zero_terminate + + Examples: + string="String[15],U,NZT"-->value_index=INDEX_STRING, length=15, is_unicode=True, zero_terminate=False + string="AoB[42]"-->value_index=INDEX_AOB, length=42, None, None + """ + length = unicode = zero_terminate = None + index = text_to_index_dict.get(string, -1) + if index is -1: + if search(r"String\[\d*\]", string): # String[10],U,NZT + index = INDEX_STRING + length = sub("[^0-9]", "", string) + length = int(length) + if search(r",U", string): # check if Unicode, literal string + unicode = True + else: + unicode = False + if search(r",NZT", string): # check if not zero terminate, literal string + zero_terminate = False + else: + zero_terminate = True + elif search(r"AoB\[\d*\]", string): # AoB[10] + index = INDEX_AOB + length = sub("[^0-9]", "", string) + length = int(length) + return index, length, unicode, zero_terminate + + +def text_to_index(string): + """Converts given str to type_defs.VALUE_INDEX + + Simplified version of the function text_to_valuetype for only extracting value_index + + Args: + string (str): String must be generated from the function valuetype_to_text + + Returns: + int: A member of type_defs.VALUE_INDEX + """ + index = text_to_index_dict.get(string, -1) + if index is -1: + if search(r"String", string): # String[10],U,NZT + index = INDEX_STRING + elif search(r"AoB", string): # AoB[10] + index = INDEX_AOB + return index + + +def text_to_length(string): + """Converts given str to length + + Simplified version of the function text_to_valuetype for only extracting length + + Args: + string (str): String must be generated from the function valuetype_to_text + + Returns: + int: Length + -1 is returned if the value_index of the given string isn't INDEX_STRING or INDEX_AOB + """ + index = text_to_index_dict.get(string, -1) + if index is -1: + search(r"\[\d*\]", string) + length = sub("[^0-9]", "", string) + return int(length) + return -1 + + +def change_text_length(string, length): + """Changes the length of the given str to the given length + + Args: + string (str): String must be generated from the function valuetype_to_text + length (int,str): New length + + Returns: + str: The changed str + int: -1 is returned if the value_index of the given string isn't INDEX_STRING or INDEX_AOB + """ + index = text_to_index_dict.get(string, -1) + if index is -1: + return sub(r"\[\d*\]", "[" + str(length) + "]", string) + return -1 + + +def remove_bookmark_mark(string): + """Removes the bookmark mark from the given string + + Args: + string (str): String that'll be cleansed from the bookmark mark + + Returns: + str: Remaining str after the cleansing + """ + return sub(r"\(M\)", "", string, count=1) diff --git a/libPINCE/Injection/.gitignore b/libPINCE/Injection/.gitignore new file mode 100644 index 00000000..fe7e4638 --- /dev/null +++ b/libPINCE/Injection/.gitignore @@ -0,0 +1,2 @@ +example.so +.directory \ No newline at end of file diff --git a/libPINCE/Injection/Notes.txt b/libPINCE/Injection/Notes.txt new file mode 100644 index 00000000..4c06d8c2 --- /dev/null +++ b/libPINCE/Injection/Notes.txt @@ -0,0 +1,5 @@ +Compile C files with -g option for gdb to read their symbols. + +For example: + +"gcc -pthread -shared -g -O2 -o example.so -fPIC example.c" diff --git a/libPINCE/Injection/example.c b/libPINCE/Injection/example.c new file mode 100644 index 00000000..0c542d53 --- /dev/null +++ b/libPINCE/Injection/example.c @@ -0,0 +1,20 @@ +#include + +void *infinite_thread(void *a); + +//Injects a thread that runs forever at the background +__attribute__((constructor)) +void inject_infinite_thread() +{ + int *a=1; + pthread_t* threadinf=(pthread_t*) malloc(sizeof(pthread_t)); + pthread_create(threadinf, NULL, infinite_thread, (void*) a); +} + +void *infinite_thread(void *a) +{ + while(1) + { + sleep(1); + } +} \ No newline at end of file diff --git a/libPINCE/SysUtils.py b/libPINCE/SysUtils.py new file mode 100644 index 00000000..3c606f6a --- /dev/null +++ b/libPINCE/SysUtils.py @@ -0,0 +1,443 @@ +# -*- coding: utf-8 -*- +""" +Copyright (C) 2016 Korcan Karaokçu + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" +import psutil +import os +import shutil +import sys +import collections +from . import type_defs +from re import match, search, IGNORECASE, split + +PINCE_IPC_PATH = type_defs.PATHS.PINCE_IPC_PATH +IPC_FROM_PINCE_PATH = type_defs.PATHS.IPC_FROM_PINCE_PATH +IPC_TO_PINCE_PATH = type_defs.PATHS.IPC_TO_PINCE_PATH + +INDEX_BYTE = type_defs.VALUE_INDEX.INDEX_BYTE +INDEX_2BYTES = type_defs.VALUE_INDEX.INDEX_2BYTES +INDEX_4BYTES = type_defs.VALUE_INDEX.INDEX_4BYTES +INDEX_8BYTES = type_defs.VALUE_INDEX.INDEX_8BYTES +INDEX_FLOAT = type_defs.VALUE_INDEX.INDEX_FLOAT +INDEX_DOUBLE = type_defs.VALUE_INDEX.INDEX_DOUBLE +INDEX_STRING = type_defs.VALUE_INDEX.INDEX_STRING +INDEX_AOB = type_defs.VALUE_INDEX.INDEX_AOB + + +def get_process_list(): + """Returns a list of psutil.Process objects corresponding to currently running processes + + Returns: + list: List of psutil.Process objects + """ + processlist = [] + for p in psutil.process_iter(): + processlist.append(p) + return processlist + + +def get_process_information(pid): + """Returns a psutil.Process object corresponding to given pid + + Args: + pid (int): PID of the process + + Returns: + psutil.Process: psutil.Process object corresponding to the given pid + """ + p = psutil.Process(pid) + return p + + +def search_in_processes_by_name(process_name): + """Searches currently running processes and returns a list of psutil.Process objects corresponding to processes that + has the str process_name in them + + Args: + process_name (str): Name of the process that'll be searched for + + Returns: + list: List of psutil.Process objects corresponding to the filtered processes + """ + processlist = [] + for p in psutil.process_iter(): + if search(process_name, p.name(), IGNORECASE): + processlist.append(p) + return processlist + + +def get_memory_regions(pid): + """Returns memory regions as a list of pmmap_ext objects + + Args: + pid (int): PID of the process + + Returns: + list: List of pmmap_ext objects corresponding to the given pid + """ + maplist = [] + p = psutil.Process(pid) + for m in p.memory_maps(grouped=False): + maplist.append(m) + return maplist + + +def get_region_info(pid, address): + """Finds the closest valid starting/ending address and region to given address, assuming given address is in the + valid address range + + Args: + pid (int): PID of the process + address (int,str): Can be an int or a hex str + + Returns: + collections.namedtuple("get_region_info","start end region"): Starting address as hex str, ending address as hex + str and region corresponding to the given address as pmmap_ext object + """ + if type(pid) != int: + pid = int(pid) + if type(address) != int: + address = int(address, 16) + region_list = get_memory_regions(pid) + for item in region_list: + splitted_address = item.addr.split("-") + start = int(splitted_address[0], 16) + end = int(splitted_address[1], 16) + if start <= address <= end: + returned_tuple = collections.namedtuple("get_region_info", "start end region") + return returned_tuple(hex(start), hex(end), item) + + +def get_memory_regions_by_perms(pid): + """Returns a tuple of four lists based on the permissions given to them + + Args: + pid (int): PID of the process + + Returns: + tuple: A tuple of four different lists formed of pmmap_ext objects + First list holds readable only regions + Second list holds writeable regions + Third list holds executable regions + Fourth list holds readable regions + """ + readable_only, writeable, executable, readable = [], [], [], [] + p = psutil.Process(pid) + for m in p.memory_maps(grouped=False): + if search("r--", m.perms): + readable_only.append(m) + if search("w", m.perms): + writeable.append(m) + if search("x", m.perms): + executable.append(m) + if search("r", m.perms): + readable.append(m) + return readable_only, writeable, executable, readable + + +def exclude_shared_memory_regions(generated_list): + """Excludes the shared memory regions from the list + + Args: + generated_list (list): The list must be generated from the function get_memory_regions_by_perms or + get_memory_regions. + + Returns: + list: List of the remaining pmmap_ext objects after exclusion + """ + for m in generated_list[:]: + if search("s", m.perms): + generated_list.remove(m) + return generated_list + + +def exclude_system_memory_regions(generated_list): + """Excludes the system-related memory regions from the list + + Args: + generated_list (list): The list must be generated from the function get_memory_regions_by_perms or + get_memory_regions. + + Returns: + list: List of the remaining pmmap_ext objects after exclusion + """ + for m in generated_list[:]: + if match("[7-f]", m.addr): + generated_list.remove(m) + return generated_list + + +def is_traced(pid): + """Check if the process corresponding to given pid traced by any other process + + Args: + pid (int): PID of the process + + Returns: + str: Name of the tracer if the specified process is being traced + bool: False, if the specified process is not being traced + """ + for line in open("/proc/%d/status" % pid).readlines(): + if line.startswith("TracerPid:"): + tracerpid = line.split(":", 1)[1].strip() + if tracerpid == "0": + return False + else: + return psutil.Process(int(tracerpid)).name() + + +def is_process_valid(pid): + """Check if the process corresponding to given pid is valid + + Args: + pid (int): PID of the process + + Returns: + bool: True if the process is still running, False if not + """ + return is_path_valid("/proc/%d" % pid) + + +def get_home_directory(): + """Get home directory of the current user + + Returns: + str: A string pointing to the home directory + """ + return os.path.expanduser("~") + + +def get_current_script_directory(): + """Get current working directory + + Returns: + str: A string pointing to the current working directory + """ + return sys.path[0] + + +def is_path_valid(dest_path, issue_path=""): + """Check if the given path is valid + + Args: + dest_path (str): Path + issue_path (str): If this parameter is passed as "delete", given path will be deleted if it's valid. + If this parameter is passed as "create", given path path will be created if it's not valid. + + Returns: + bool: True if path is valid, False if not + """ + if os.path.exists(dest_path): + if issue_path is "delete": + shutil.rmtree(dest_path) + return True + else: + if issue_path is "create": + os.makedirs(dest_path) + return False + + +def do_cleanups(pid): + """Deletes the IPC directory of given pid + + Args: + pid (int,str): PID of the process + """ + is_path_valid(get_PINCE_IPC_directory(pid), "delete") + + +def create_PINCE_IPC_PATH(pid): + """Creates the IPC directory of given pid + + Args: + pid (int,str): PID of the process + """ + do_cleanups(pid) + is_path_valid(get_PINCE_IPC_directory(pid), "create") + + +def get_PINCE_IPC_directory(pid): + """Get the IPC directory of given pid + + Args: + pid (int): PID of the process + + Returns: + str: Path of IPC directory + """ + return PINCE_IPC_PATH + str(pid) + + +def get_gdb_async_file(pid): + """Get the path of gdb logfile of given pid + + Args: + pid (int,str): PID of the process + + Returns: + str: Path of gdb logfile + """ + return get_PINCE_IPC_directory(pid) + "/gdb_async_output.txt" + + +def get_gdb_command_file(pid): + """Get the path of gdb command file of given pid + + Args: + pid (int,str): PID of the process + + Returns: + str: Path of gdb command file + """ + return get_PINCE_IPC_directory(pid) + "/gdb_command.txt" + + +def get_ipc_from_PINCE_file(pid): + """Get the path of IPC file sent to custom gdb commands from PINCE for given pid + + Args: + pid (int,str): PID of the process + + Returns: + str: Path of IPC file + """ + return get_PINCE_IPC_directory(pid) + IPC_FROM_PINCE_PATH + + +def get_ipc_to_PINCE_file(pid): + """Get the path of IPC file sent to PINCE from custom gdb commands for given pid + + Args: + pid (int,str): PID of the process + + Returns: + str: Path of IPC file + """ + return get_PINCE_IPC_directory(pid) + IPC_TO_PINCE_PATH + + +def parse_string(string, value_index): + """Parses the string according to the given value_index + + Args: + string (str): String that'll be parsed + value_index (int): Determines the type of data. Can be a member of type_defs.VALUE_INDEX + + Returns: + str: If the value_index is INDEX_STRING + list: If the value_index is INDEX_AOB. A list of ints is returned + float: If the value_index is INDEX_FLOAT or INDEX_DOUBLE + int: If the value_index is anything else + None: If the string is not parseable by using the parameter value_index + + Examples: + string="42 DE AD BE EF 24",value_index=INDEX_AOB-->returned_list=[66, 222, 173, 190, 239, 36] + """ + string = str(string) + if not string: + print("please enter a string first") + return + try: + value_index = int(value_index) + except: + print(str(value_index) + " can't be converted to int") + return + if value_index is INDEX_STRING: + return string + string = string.strip() + if value_index is INDEX_AOB: + try: + string = str(string) + stripped_string = string.strip() + string_list = split(r"\s+", stripped_string) + for item in string_list: + if len(item) > 2: + print(string + " can't be parsed as array of bytes") + return + hex_list = [int(x, 16) for x in string_list] + return hex_list + except: + print(string + " can't be parsed as array of bytes") + return + elif value_index is INDEX_FLOAT or value_index is INDEX_DOUBLE: + try: + string = float(string) + except: + try: + string = float(int(string, 16)) + except: + print(string + " can't be parsed as floating point variable") + return + return string + else: + try: + string = int(string) + except: + try: + string = int(string, 16) + except: + try: + string = int(float(string)) + except: + print(string + " can't be parsed as integer or hexadecimal") + return + if value_index is INDEX_BYTE: + string = string % 256 + elif value_index is INDEX_2BYTES: + string = string % 65536 + elif value_index is INDEX_4BYTES: + string = string % 4294967296 + elif value_index is INDEX_8BYTES: + string = string % 18446744073709551616 + return string + + +def extract_address(string, search_for_location_changing_instructions=False): + """Extracts hex address from the given string + + Args: + string (str): The string that the hex address will be extracted from + search_for_location_changing_instructions (bool): Searches for the location changing instructions such as Jcc, + CALL and LOOPcc in the given string + + Returns: + str: The hex address found + None: If no hex address is found or no location changing instructions found(applies only if the parameter + search_for_location_changing_instructions is passed as True) + """ + if search_for_location_changing_instructions: + result = search(r"(j|call|loop).*\s+0x[0-9a-fA-F]+", string) + if result: + result = result.group(0).split()[-1] + return result + else: + result = search(r"0x[0-9a-fA-F]+", string) + if result: + return result.group(0) + + +def aob_to_ascii(list_of_bytes): + """Converts given array of hex strings to ascii str + + Args: + list_of_bytes (list): Must be returned from GDB_Engine.hex_dump() + + Returns: + str: Ascii equivalent of array + """ + + # 3f is ascii hex representation of char "?" + return bytes.fromhex("".join(list_of_bytes).replace("??", "3f")).decode("ascii", "replace") diff --git a/libPINCE/__init__.py b/libPINCE/__init__.py new file mode 100644 index 00000000..8d1c8b69 --- /dev/null +++ b/libPINCE/__init__.py @@ -0,0 +1 @@ + diff --git a/libPINCE/gdb_python_scripts/GDBCommandExtensions.py b/libPINCE/gdb_python_scripts/GDBCommandExtensions.py new file mode 100644 index 00000000..477b61ba --- /dev/null +++ b/libPINCE/gdb_python_scripts/GDBCommandExtensions.py @@ -0,0 +1,399 @@ +# -*- coding: utf-8 -*- +""" +Copyright (C) 2016 Korcan Karaokçu + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" +import gdb +import pickle +import sys +import re +import struct +import io + +# This is some retarded hack +gdbvalue = gdb.parse_and_eval("$PINCE_PATH") +PINCE_PATH = gdbvalue.string() +sys.path.append(PINCE_PATH) # Adds the PINCE directory to PYTHONPATH to import libraries from PINCE + +from libPINCE.gdb_python_scripts import ScriptUtils +from libPINCE import SysUtils +from libPINCE import type_defs + +REGISTERS_32 = ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp", "eip"] +REGISTERS_64 = ["rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "rip", "r8", "r9", "r10", "r11", "r12", + "r13", "r14", "r15"] +REGISTERS_SEGMENT = ["cs", "ss", "ds", "es", "fs", "gs"] + +INDEX_BYTE = type_defs.VALUE_INDEX.INDEX_BYTE +INDEX_2BYTES = type_defs.VALUE_INDEX.INDEX_2BYTES +INDEX_4BYTES = type_defs.VALUE_INDEX.INDEX_4BYTES +INDEX_8BYTES = type_defs.VALUE_INDEX.INDEX_8BYTES +INDEX_FLOAT = type_defs.VALUE_INDEX.INDEX_FLOAT +INDEX_DOUBLE = type_defs.VALUE_INDEX.INDEX_DOUBLE +INDEX_STRING = type_defs.VALUE_INDEX.INDEX_STRING +INDEX_AOB = type_defs.VALUE_INDEX.INDEX_AOB + +ARCH_32 = type_defs.INFERIOR_ARCH.ARCH_32 +ARCH_64 = type_defs.INFERIOR_ARCH.ARCH_64 + +inferior = gdb.selected_inferior() +pid = inferior.pid +recv_file = SysUtils.get_ipc_from_PINCE_file(pid) +send_file = SysUtils.get_ipc_to_PINCE_file(pid) +if str(gdb.parse_and_eval("$rax")) == "void": + current_arch = ARCH_32 +else: + current_arch = ARCH_64 + + +def receive_from_pince(): + return pickle.load(open(recv_file, "rb")) + + +def send_to_pince(contents_send): + pickle.dump(contents_send, open(send_file, "wb")) + + +class ReadMultipleAddresses(gdb.Command): + def __init__(self): + super(ReadMultipleAddresses, self).__init__("pince-read-multiple-addresses", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = [] + contents_recv = receive_from_pince() + + # contents_recv format: [[address1, index1, length1, unicode1, zero_terminate1],[address2, ...], ...] + for item in contents_recv: + address = item[0] + index = item[1] + try: + length = item[2] + except IndexError: + length = 0 + try: + unicode = item[3] + except IndexError: + unicode = False + try: + zero_terminate = item[4] + except IndexError: + zero_terminate = True + data_read = ScriptUtils.read_single_address(address, index, length, unicode, zero_terminate) + contents_send.append(data_read) + send_to_pince(contents_send) + + +class SetMultipleAddresses(gdb.Command): + def __init__(self): + super(SetMultipleAddresses, self).__init__("pince-set-multiple-addresses", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_recv = receive_from_pince() + + # last item of contents_recv is always value, so we pop it from the list first + value = contents_recv.pop() + + # contents_recv format after popping the value: [[address1, index1],[address2, index2], ...] + for item in contents_recv: + address = item[0] + index = item[1] + + ''' + The reason we do the check here instead of inside of the function set_single_address() is because try/except + block doesn't work in function set_single_address() when writing something to file in /proc/$pid/mem. Python + is normally capable of catching IOError exception, but I have no idea about why it doesn't work in function + set_single_address() + ''' + try: + ScriptUtils.set_single_address(address, index, value) + except IOError: + print("Can't access the address " + address if type(address) == str else hex(address)) + pass + + +class ReadSingleAddress(gdb.Command): + def __init__(self): + super(ReadSingleAddress, self).__init__("pince-read-single-address", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_recv = receive_from_pince() + address = contents_recv[0] + value_index = contents_recv[1] + length = contents_recv[2] + is_unicode = contents_recv[3] + zero_terminate = contents_recv[4] + contents_send = ScriptUtils.read_single_address(address, value_index, length, is_unicode, zero_terminate) + send_to_pince(contents_send) + + +class IgnoreErrors(gdb.Command): + def __init__(self): + super(IgnoreErrors, self).__init__("ignore-errors", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + try: + gdb.execute(arg, from_tty) + except: + pass + + +class CLIOutput(gdb.Command): + def __init__(self): + super(CLIOutput, self).__init__("cli-output", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + try: + contents_send = gdb.execute(arg, from_tty, to_string=True) + except Exception as e: + contents_send = str(e) + print(contents_send) + send_to_pince(contents_send) + + +class ParseConvenienceVariables(gdb.Command): + def __init__(self): + super(ParseConvenienceVariables, self).__init__("pince-parse-convenience-variables", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = [] + contents_recv = receive_from_pince() + for item in contents_recv: + try: + value = gdb.parse_and_eval(item) + parsed_value = str(value) + except: + parsed_value = None + contents_send.append(parsed_value) + send_to_pince(contents_send) + + +class ReadRegisters(gdb.Command): + def __init__(self): + super(ReadRegisters, self).__init__("pince-read-registers", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = {"cf": "0", "pf": "0", "af": "0", "zf": "0", "sf": "0", "tf": "0", "if": "0", "df": "0", + "of": "0"} + if current_arch == ARCH_64: + general_register_list = REGISTERS_64 + else: + general_register_list = REGISTERS_32 + regex_hex = re.compile(r"0x[0-9a-fA-F]+") # $6 = 0x7f0bc0b6bb40 + for item in general_register_list: + result = gdb.execute("p/x $" + item, from_tty, to_string=True) + parsed_result = regex_hex.search(result).group(0) + contents_send[item] = parsed_result + result = gdb.execute("p/t $eflags", from_tty, to_string=True) + parsed_result = re.search(r"=\s+\d+", result).group(0).split()[-1] # $8 = 1010010011 + reversed_parsed_result = "".join(reversed(parsed_result)) + try: + contents_send["cf"] = reversed_parsed_result[0] + contents_send["pf"] = reversed_parsed_result[2] + contents_send["af"] = reversed_parsed_result[4] + contents_send["zf"] = reversed_parsed_result[6] + contents_send["sf"] = reversed_parsed_result[7] + contents_send["tf"] = reversed_parsed_result[8] + contents_send["if"] = reversed_parsed_result[9] + contents_send["df"] = reversed_parsed_result[10] + contents_send["of"] = reversed_parsed_result[11] + except IndexError: + pass + for item in REGISTERS_SEGMENT: + result = gdb.execute("p/x $" + item, from_tty, to_string=True) + parsed_result = regex_hex.search(result).group(0) + contents_send[item] = parsed_result + send_to_pince(contents_send) + + +class ReadFloatRegisters(gdb.Command): + def __init__(self): + super(ReadFloatRegisters, self).__init__("pince-read-float-registers", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = {} + + # st0-7 + for index in range(8): + current_register = "st" + str(index) + value = gdb.parse_and_eval("$" + current_register) + contents_send[current_register] = str(value) + + # xmm0-7 + for index in range(8): + current_register = "xmm" + str(index) + value = gdb.parse_and_eval("$" + current_register + ".v4_float") + contents_send[current_register] = str(value) + send_to_pince(contents_send) + + +class GetStackTraceInfo(gdb.Command): + def __init__(self): + super(GetStackTraceInfo, self).__init__("pince-get-stack-trace-info", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = [] + if current_arch == ARCH_64: + sp_register = "rsp" + result = gdb.execute("p/x $rsp", from_tty, to_string=True) + else: + sp_register = "esp" + result = gdb.execute("p/x $esp", from_tty, to_string=True) + stack_pointer_int = int(re.search(r"0x[0-9a-fA-F]+", result).group(0), 16) # $6 = 0x7f0bc0b6bb40 + result = gdb.execute("bt", from_tty, to_string=True) + + # Example: #10 0x000000000040c45a in--->#10--->10 + max_frame = re.findall(r"#\d+\s+0x[0-9a-fA-F]+\s+in", result)[-1].split()[0].replace("#", "") + + # +1 because frame numbers start from 0 + for item in range(int(max_frame) + 1): + result = gdb.execute("info frame " + str(item), from_tty, to_string=True) + + # frame at 0x7ffe1e989950--->0x7ffe1e989950 + frame_address = re.search(r"frame\s+at\s+0x[0-9a-fA-F]+", result).group(0).split()[-1] + difference = hex(int(frame_address, 16) - stack_pointer_int) + frame_address_with_difference = frame_address + "(" + sp_register + "+" + difference + ")" + + # saved rip = 0x7f633a853fe4 + return_address = re.search(r"saved.*=\s+0x[0-9a-fA-F]+", result) + if return_address: + return_address = return_address.group(0).split()[-1] + result = gdb.execute("x/b " + return_address, from_tty, to_string=True) + + # 0x40c431 <_start>:--->0x40c431 <_start> + return_address_with_info = re.search(r"0x[0-9a-fA-F]+.*:", result).group(0).split(":")[0] + else: + return_address_with_info = "" + contents_send.append([return_address_with_info, frame_address_with_difference]) + send_to_pince(contents_send) + + +class GetStackInfo(gdb.Command): + def __init__(self): + super(GetStackInfo, self).__init__("pince-get-stack-info", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = [] + if current_arch == ARCH_64: + chunk_size = 8 + float_format = "d" + stack_register = "rsp" + result = gdb.execute("p/x $rsp", from_tty, to_string=True) + else: + chunk_size = 4 + float_format = "f" + stack_register = "esp" + result = gdb.execute("p/x $esp", from_tty, to_string=True) + stack_address = int(re.search(r"0x[0-9a-fA-F]+", result).group(0), 16) # $6 = 0x7f0bc0b6bb40 + mem_file = "/proc/" + str(pid) + "/mem" + with open(mem_file, "rb") as FILE: + FILE.seek(stack_address) + for index in range(int(4096 / chunk_size)): + current_offset = chunk_size * index + stack_indicator = hex(stack_address + current_offset) + "(" + stack_register + "+" + hex( + current_offset) + ")" + try: + read = FILE.read(chunk_size) + except: + print("Can't access the stack after address " + stack_indicator) + break + hex_data = "0x" + "".join(format(n, '02x') for n in reversed(read)) + int_data = str(int(hex_data, 16)) + float_data = str(struct.unpack_from(float_format, read)[0]) + contents_send.append([stack_indicator, hex_data, int_data, float_data]) + send_to_pince(contents_send) + + +class GetFrameReturnAddresses(gdb.Command): + def __init__(self): + super(GetFrameReturnAddresses, self).__init__("pince-get-frame-return-addresses", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_send = [] + result = gdb.execute("bt", from_tty, to_string=True) + + # Example: #10 0x000000000040c45a in--->#10--->10 + max_frame = re.findall(r"#\d+\s+0x[0-9a-fA-F]+\s+in", result)[-1].split()[0].replace("#", "") + + # +1 because frame numbers start from 0 + for item in range(int(max_frame) + 1): + result = gdb.execute("info frame " + str(item), from_tty, to_string=True) + + # saved rip = 0x7f633a853fe4 + return_address = re.search(r"saved.*=\s+0x[0-9a-fA-F]+", result) + if return_address: + return_address = return_address.group(0).split()[-1] + result = gdb.execute("x/b " + return_address, from_tty, to_string=True) + + # 0x40c431 <_start>:--->0x40c431 <_start> + return_address_with_info = re.search(r"0x[0-9a-fA-F]+.*:", result).group(0).split(":")[0] + else: + return_address_with_info = "" + contents_send.append(return_address_with_info) + send_to_pince(contents_send) + + +class GetFrameInfo(gdb.Command): + def __init__(self): + super(GetFrameInfo, self).__init__("pince-get-frame-info", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_recv = receive_from_pince() + result = gdb.execute("bt", from_tty, to_string=True) + + # Example: #10 0x000000000040c45a in--->#10--->10 + max_frame = re.findall(r"#\d+\s+0x[0-9a-fA-F]+\s+in", result)[-1].split()[0].replace("#", "") + if 0 <= int(contents_recv) <= int(max_frame): + contents_send = gdb.execute("info frame " + contents_recv, from_tty, to_string=True) + else: + print("Frame " + contents_recv + " doesn't exist") + contents_send = None + send_to_pince(contents_send) + + +class HexDump(gdb.Command): + def __init__(self): + super(HexDump, self).__init__("pince-hex-dump", gdb.COMMAND_USER) + + def invoke(self, arg, from_tty): + contents_recv = receive_from_pince() + contents_send = [] + address = contents_recv[0] + offset = contents_recv[1] + mem_file = "/proc/" + str(pid) + "/mem" + with open(mem_file, "rb") as FILE: + FILE.seek(address) + for item in range(offset): + try: + current_item = " ".join(format(n, '02x') for n in FILE.read(1)) + except IOError: + current_item = "??" + FILE.seek(1, io.SEEK_CUR) # Necessary since read() failed to execute + contents_send.append(current_item) + send_to_pince(contents_send) + + +IgnoreErrors() +CLIOutput() +ReadMultipleAddresses() +SetMultipleAddresses() +ReadSingleAddress() +ParseConvenienceVariables() +ReadRegisters() +ReadFloatRegisters() +GetStackTraceInfo() +GetStackInfo() +GetFrameReturnAddresses() +GetFrameInfo() +HexDump() diff --git a/libPINCE/gdb_python_scripts/ScriptUtils.py b/libPINCE/gdb_python_scripts/ScriptUtils.py new file mode 100644 index 00000000..087d32aa --- /dev/null +++ b/libPINCE/gdb_python_scripts/ScriptUtils.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +""" +Copyright (C) 2016 Korcan Karaokçu + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" +import gdb +import struct +import sys + +# This is some retarded hack +gdbvalue = gdb.parse_and_eval("$PINCE_PATH") +PINCE_PATH = gdbvalue.string() +sys.path.append(PINCE_PATH) # Adds the PINCE directory to PYTHONPATH to import libraries from PINCE + +from libPINCE import SysUtils +from libPINCE import type_defs + +INDEX_BYTE = type_defs.VALUE_INDEX.INDEX_BYTE +INDEX_2BYTES = type_defs.VALUE_INDEX.INDEX_2BYTES +INDEX_4BYTES = type_defs.VALUE_INDEX.INDEX_4BYTES +INDEX_8BYTES = type_defs.VALUE_INDEX.INDEX_8BYTES +INDEX_FLOAT = type_defs.VALUE_INDEX.INDEX_FLOAT +INDEX_DOUBLE = type_defs.VALUE_INDEX.INDEX_DOUBLE +INDEX_STRING = type_defs.VALUE_INDEX.INDEX_STRING +INDEX_AOB = type_defs.VALUE_INDEX.INDEX_AOB + +index_to_valuetype_dict = type_defs.index_to_valuetype_dict +index_to_struct_pack_dict = type_defs.index_to_struct_pack_dict + +inferior = gdb.selected_inferior() +pid = inferior.pid +mem_file = "/proc/" + str(pid) + "/mem" + + +# This function is used to avoid errors in gdb scripts, because gdb scripts stop working when encountered an error +def issue_command(command, error_message=""): + try: + gdb.execute(command) + except: + if error_message: + error_message = str(error_message) + gdb.execute('echo ' + error_message + '\n') + + +def read_single_address(address, value_type, length=0, unicode=False, zero_terminate=True): + try: + value_type = int(value_type) + except: + print(str(value_type) + " is not a valid value index") + return "" + try: + address = int(address, 16) + except: + print(str(address) + " is not a valid address") + return "" + packed_data = index_to_valuetype_dict.get(value_type, -1) + if value_type is INDEX_STRING: + try: + expected_length = int(length) + except: + print(str(length) + " is not a valid length") + return "" + if unicode: + expected_length = length * 2 + elif value_type is INDEX_AOB: + try: + expected_length = int(length) + except: + print(str(length) + " is not a valid length") + return "" + else: + expected_length = packed_data[0] + data_type = packed_data[1] + FILE = open(mem_file, "rb") + try: + FILE.seek(address) + data_read = FILE.read(expected_length) + except IOError: + FILE.close() + print("Can't access the memory at address " + hex(address) + " or offset " + hex(address + expected_length)) + return "" + FILE.close() + if value_type is INDEX_STRING: + if unicode: + returned_string = data_read.decode("utf-8", "replace") + else: + returned_string = data_read.decode("ascii", "replace") + if zero_terminate: + if returned_string.startswith('\x00'): + returned_string = '\x00' + else: + returned_string = returned_string.split('\x00')[0] + return returned_string[0:length] + elif value_type is INDEX_AOB: + return " ".join(format(n, '02x') for n in data_read) + else: + return struct.unpack_from(data_type, data_read)[0] + + +def set_single_address(address, value_index, value): + try: + address = int(address, 16) + except: + print(str(address) + " is not a valid address") + return + write_data = SysUtils.parse_string(value, value_index) + if write_data is None: + return + if value_index is INDEX_STRING: + write_data = bytearray(write_data, "utf-8", "replace") + elif value_index is INDEX_AOB: + write_data = bytearray(write_data) + else: + data_type = index_to_struct_pack_dict.get(value_index, -1) + write_data = struct.pack(data_type, write_data) + FILE = open(mem_file, "rb+") + + # Check SetMultipleAddresses class in GDBCommandExtensions.py to see why we moved away the try/except block + FILE.seek(address) + FILE.write(write_data) + FILE.close() diff --git a/libPINCE/gdb_python_scripts/__init__.py b/libPINCE/gdb_python_scripts/__init__.py new file mode 100644 index 00000000..8d1c8b69 --- /dev/null +++ b/libPINCE/gdb_python_scripts/__init__.py @@ -0,0 +1 @@ + diff --git a/libPINCE/type_defs.py b/libPINCE/type_defs.py new file mode 100644 index 00000000..ba9fbef5 --- /dev/null +++ b/libPINCE/type_defs.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +""" +Copyright (C) 2016 Korcan Karaokçu + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + + +# IMPORTANT: Any constant involving only PINCE.py should be declared in PINCE.py + +class PATHS: + PINCE_IPC_PATH = "/tmp/PINCE-connection/" + INITIAL_INJECTION_PATH = "/Injection/InitialCodeInjections.so" + IPC_FROM_PINCE_PATH = "/from_PINCE_file" + IPC_TO_PINCE_PATH = "/to_PINCE_file" + + +class INFERIOR_STATUS: + INFERIOR_RUNNING = 0 + INFERIOR_STOPPED = 1 + + +class INFERIOR_ARCH: + ARCH_32 = 0 + ARCH_64 = 1 + + +class INJECTION_METHOD: + SIMPLE_DLOPEN_CALL = 1 + ADVANCED_INJECTION = 2 + + +# represents the indexes of value types +# Also used in PINCE's value comboboxes +class VALUE_INDEX: + INDEX_BYTE = 0 + INDEX_2BYTES = 1 + INDEX_4BYTES = 2 + INDEX_8BYTES = 3 + INDEX_FLOAT = 4 + INDEX_DOUBLE = 5 + INDEX_STRING = 6 + INDEX_AOB = 7 # Array of Bytes + + +# Represents the texts at indexes in combobox +index_to_text_dict = { + VALUE_INDEX.INDEX_BYTE: "Byte", + VALUE_INDEX.INDEX_2BYTES: "2 Bytes", + VALUE_INDEX.INDEX_4BYTES: "4 Bytes", + VALUE_INDEX.INDEX_8BYTES: "8 Bytes", + VALUE_INDEX.INDEX_FLOAT: "Float", + VALUE_INDEX.INDEX_DOUBLE: "Double", + VALUE_INDEX.INDEX_STRING: "String", + VALUE_INDEX.INDEX_AOB: "AoB" +} + +text_to_index_dict = { + "Byte": VALUE_INDEX.INDEX_BYTE, + "2 Bytes": VALUE_INDEX.INDEX_2BYTES, + "4 Bytes": VALUE_INDEX.INDEX_4BYTES, + "8 Bytes": VALUE_INDEX.INDEX_8BYTES, + "Float": VALUE_INDEX.INDEX_FLOAT, + "Double": VALUE_INDEX.INDEX_DOUBLE +} + +# A dictionary used to convert value_combobox index to gdb/mi x command +# Check GDB_Engine for an exemplary usage +index_to_gdbcommand_dict = { + VALUE_INDEX.INDEX_BYTE: "db", + VALUE_INDEX.INDEX_2BYTES: "dh", + VALUE_INDEX.INDEX_4BYTES: "dw", + VALUE_INDEX.INDEX_8BYTES: "dg", + VALUE_INDEX.INDEX_FLOAT: "fw", + VALUE_INDEX.INDEX_DOUBLE: "fg", + VALUE_INDEX.INDEX_STRING: "xb", + VALUE_INDEX.INDEX_AOB: "xb" +} + +# first value is the length and the second one is the type +# Check ScriptUtils for an exemplary usage +index_to_valuetype_dict = { + VALUE_INDEX.INDEX_BYTE: [1, "b"], + VALUE_INDEX.INDEX_2BYTES: [2, "h"], + VALUE_INDEX.INDEX_4BYTES: [4, "i"], + VALUE_INDEX.INDEX_8BYTES: [8, "q"], + VALUE_INDEX.INDEX_FLOAT: [4, "f"], + VALUE_INDEX.INDEX_DOUBLE: [8, "d"], + VALUE_INDEX.INDEX_STRING: [None, None], + VALUE_INDEX.INDEX_AOB: [None, None] +} + +# Check ScriptUtils for an exemplary usage +index_to_struct_pack_dict = { + VALUE_INDEX.INDEX_BYTE: "B", + VALUE_INDEX.INDEX_2BYTES: "H", + VALUE_INDEX.INDEX_4BYTES: "I", + VALUE_INDEX.INDEX_8BYTES: "Q", + VALUE_INDEX.INDEX_FLOAT: "f", + VALUE_INDEX.INDEX_DOUBLE: "d" +} diff --git a/libmemscan b/libmemscan deleted file mode 160000 index a0381945..00000000 --- a/libmemscan +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a038194566187f5df282c5fd551bf60ed745b9d6 diff --git a/libpince/debugcore.py b/libpince/debugcore.py deleted file mode 100644 index 3d3707bb..00000000 --- a/libpince/debugcore.py +++ /dev/null @@ -1,3436 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from threading import Lock, Thread, Condition -from time import sleep, time -from collections import OrderedDict, defaultdict -import pexpect, os, ctypes, pickle, shelve, re, struct, io, traceback -from capstone import Cs, CsError, CS_ARCH_X86, CS_MODE_32, CS_MODE_64 -from . import utils, typedefs, regexes -from .utils import safe_str_to_int, safe_int_cast, logger -from typing import Any, Callable - -utils.clear_log() -utils.init_logging() -self_pid = os.getpid() -libc = ctypes.CDLL("libc.so.6") - -# A boolean value. True if gdb is initialized, False if not -gdb_initialized = False - -# An integer. Can be a member of typedefs.INFERIOR_ARCH -inferior_arch = -1 - -# An integer. Can be a member of typedefs.INFERIOR_ARCH -# The arch of the code the debugged program actually executes, see utils.get_effective_arch -# Prefer this over inferior_arch when pointer size or struct layout of the debugged program matters -effective_arch = -1 - -# An integer. Can be a member of typedefs.INFERIOR_STATUS -inferior_status = -1 - -# An integer. PID of the current attached/created process -currentpid = -1 - -# An integer. Can be a member of typedefs.STOP_REASON -stop_reason = -1 - -# A dictionary. Holds breakpoint numbers and what to do on hit -# Format: {bp_num1:on_hit1, bp_num2:on_hit2, ...} -breakpoint_on_hit_dict = {} - -# A dictionary. Holds address and aob of instructions that were nop'ed out -# Format: {identity: {address1:orig_instruction1_aob, address2:orig_instruction2_aob, ...}, ...} -# where identity = (pid, start_time) tuple -modified_instructions_dict = {} - -# Identity (pid, start_time) of the current process, or None when detached -current_process_identity: tuple[int, int | None] | None = None - -# If an action such as deletion or condition modification happens in one of the breakpoints in a list, others in the -# same list will get affected as well -# Format: [[bp_num1, bp_num2, ...], [bp_num1, ...], ...] -chained_breakpoints = [] - -breakpoints_changed = typedefs.Signal() -instructions_changed = typedefs.Signal() - -child = object # this object will be used with pexpect operations - -# This Lock is used by the function send_command to ensure synchronous execution -lock_send_command = Lock() - -# This condition is notified whenever status of the inferior changes -# Use the variable inferior_status to get information about inferior's status -# See CheckInferiorStatus class for an example -status_changed_condition = Condition() - -# This condition is notified if the current inferior gets terminated -# See AwaitProcessExit class for an example -process_exited_condition = Condition() - -# This condition is notified if gdb starts to wait for the prompt output -# See function send_command for an example -gdb_waiting_for_prompt_condition = Condition() - -# A string. Stores the output of the last command. None means no output has been received yet. -gdb_output = None - -# An instance of typedefs.RegisterQueue. Updated whenever GDB receives an async event such as breakpoint modification -# See AwaitAsyncOutput class for an example of usage -gdb_async_output = typedefs.RegisterQueue() - -# A boolean value. Used to cancel the last gdb command sent -# Use the function cancel_ongoing_command to make use of this variable -# Return value of the current send_command call will be an empty string -cancel_send_command = False - -# True while an internal routine (the tracer or inject_dll) is driving the inferior's execution. -# state_observe_thread checks it to skip UI stop/run notifications and PINCE blocks user run controls -# (pause/continue/step) while it's set so nothing interferes with the operation. -driving_inferior = False - -# A boolean value. Used by dissect_code() to mark an ongoing code dissection. -dissect_code_active = False - -# A boolean value. Set by cancel_dissect_code() to stop the ongoing code dissection early -dissect_code_cancelled = False - -# Current state of the ongoing code dissection, see get_dissect_code_status for its format -dissect_code_status = "", "", "", 0, 0, 0 - -# Emitted whenever dissect_code() advances, read the new state with get_dissect_code_status() -dissect_code_status_changed = typedefs.Signal() - -# A boolean value. Set to True when a tracking breakpoint (on_hit != BREAK) was the last stop -# This prevents the subsequent *running event from notifying the UI -last_stop_was_tracking = False - -# A string. Holds the last command sent to gdb -last_gdb_command = "" - -# A list of booleans. Used to adjust gdb output -# Use the function set_gdb_output_mode to make use of this variable -gdb_output_mode = typedefs.gdb_output_mode(True, True, True) - -# A string. Memory file of the currently attached/created process -mem_file = "/proc/" + str(currentpid) + "/mem" - -# A string. Determines which signal to use to interrupt the process -interrupt_signal = "SIGINT" - -# Dictionary that maps an id or name to allocated memory. -# If an user allocates memory without a name, it will be given a random ID set as string. -allocated_memory_chunks: dict[str, typedefs.AllocatedMemory] = {} - -# ID generator used for the above. -allocated_memory_gen_id = 0 - -# Dictionary that maps an id or name to an allocated code cave (mmap-backed, executable) through allocate_cave. -# Kept separate from allocated_memory_chunks so free_cave and free_memory can never be applied to each other's allocations. -allocated_cave_chunks: dict[str, typedefs.AllocatedMemory] = {} - -# ID generator used for the above. -allocated_cave_gen_id = 0 - -# Dictionary cache for manually resolved libc symbols. Cleared whenever the inferior changes. -_libc_symbol_cache: dict[str, int] = {} - -# Reusable new-WoW64 injection buffer. Cleared whenever the inferior changes. -_wow64_inject_buffer: tuple[int, int] = (0, 0) - -# A bool. Used by is_address_static() and _refresh_main_module_info() to mark if the main executable is PIE enabled or not. -_main_module_is_static: bool = False - -# Cached (start, end) range of the main module's mappings, filled by _refresh_main_module_info() when the module is static. -_main_module_ranges: list[tuple[int, int]] = [] - -""" -When PINCE was first launched, it used gdb 7.7.1, which is a very outdated version of gdb -interpreter-exec mi command of gdb showed some buggy behaviour at that time -Because of that, PINCE couldn't support gdb/mi commands for a while -But PINCE is now updated with the new versions of gdb as much as possible and the interpreter-exec works much better -So, old parts of codebase still get their required information by parsing gdb console output -New parts can try to rely on gdb/mi output -""" - -""" -Functions that require breakpoint commands, such as track_watchpoint and track_breakpoint, requires process to be -stopped beforehand. If the process is running before we give the breakpoint its commands, there's a chance that the -breakpoint will be triggered before we give it commands. The process must be stopped to avoid this race condition -It's also necessary to stop the process to run commands like "watch" -""" - - -def set_gdb_output_mode(output_mode_tuple: typedefs.gdb_output_mode) -> None: - """Adjusts gdb output - - Args: - output_mode_tuple (typedefs.gdb_output_mode): Setting any field True will enable the output that's associated - with that field. Setting it False will disable the associated output - """ - global gdb_output_mode - gdb_output_mode = output_mode_tuple - - -def cancel_ongoing_command() -> bool: - """Cancels the last gdb command sent if it's still present - - Returns: - bool: True if cancel was successful, False if nothing to cancel - """ - if lock_send_command.locked(): - global cancel_send_command - cancel_send_command = True - return True - return False - - -def send_command( - command: str, - control: bool = False, - cli_output: bool = False, - send_with_file: bool = False, - file_contents_send: Any = None, - recv_with_file: bool = False, -) -> Any: - """Issues the command sent, raises an exception if gdb isn't initiated - - Args: - command (str): The command that'll be sent - control (bool): This param should be True if the command sent is ctrl+key instead of the regular command - cli_output (bool): If True, returns a readable cli output instead of gdb/mi output - send_with_file (bool): Custom commands declared in gdbextensions.py requires file communication. If - called command has any parameters, pass this as True - file_contents_send (any): Arguments for the custom gdb command called - recv_with_file (bool): Pass this as True if the called custom gdb command returns something - - Examples: - send_command(c,control=True)--> Sends ctrl+c instead of the str "c" - send_command("pince-read-addresses", file_contents_send=nested_list, recv_file=True)--> This line calls the - custom gdb command "pince-read-addresses" with parameter nested_list and since that gdb command returns the - addresses read as a list, we also pass the parameter recv_file as True - - Returns: - str: Result of the command sent, commands in the form of "ctrl+key" always returns a null string - ???: If recv_with_file is True. Content of the returned thing depends on the command sent - - Note: - TODO:This bug doesn't seem like to exist anymore. Remove the unnecessary file communication layer of IPC - File communication system is used to avoid BEL emitting bug of pexpect. If you send more than a certain amount - of characters to gdb, the input will be sheared at somewhere and gdb won't be receiving all of the input - Visit this page for more information-->http://pexpect.readthedocs.io/en/stable/commonissues.html - - You don't have to write interpreter-exec while sending a gdb/mi command. Just pass the gdb/mi command as itself. - This function will convert it automatically. - """ - global child - global gdb_output - global cancel_send_command - global last_gdb_command - with lock_send_command: - if gdb_output_mode.command_info: - time0 = time() - if not gdb_initialized: - raise typedefs.GDBInitializeException - gdb_output = None - if send_with_file: - send_file = utils.get_from_pince_file(currentpid) - with open(send_file, "wb") as send_file_handle: - pickle.dump(file_contents_send, send_file_handle) - if recv_with_file or cli_output: - recv_file = utils.get_to_pince_file(currentpid) - - # Truncating the recv_file because we wouldn't like to see output of previous command in case of errors - with open(recv_file, "w"): - pass - - command = str(command) - command = 'interpreter-exec mi "' + command + '"' if command.startswith("-") else command - last_gdb_command = command if not control else "Ctrl+" + command - if gdb_output_mode.command_info: - logger.debug(f"Last gdb command: {last_gdb_command}") - if control: - child.sendcontrol(command) - else: - command_file = utils.get_gdb_command_file(currentpid) - with open(command_file, "r+") as command_fd: - command_fd.truncate() - command_fd.write(command) - if not cli_output: - child.sendline("source " + command_file) - else: - child.sendline("cli-output source " + command_file) - if not control: - with gdb_waiting_for_prompt_condition: - while gdb_output is None: - gdb_waiting_for_prompt_condition.wait(timeout=0.01) - if cancel_send_command or not gdb_initialized: - break - if not gdb_initialized: - output = "" - elif not cancel_send_command: - if recv_with_file or cli_output: - try: - with open(recv_file, "rb") as recv_file_handle: - output = pickle.load(recv_file_handle) - except (EOFError, pickle.UnpicklingError, OSError): - output = "" - else: - output = gdb_output - else: - output = "" - child.sendcontrol("c") - with gdb_waiting_for_prompt_condition: - while gdb_output is None: - gdb_waiting_for_prompt_condition.wait(timeout=0.01) - if not gdb_initialized: - break - else: - output = "" - if gdb_output_mode.command_info: - time1 = time() - try: - logger.debug(f"Processed gdb command in: {str(time1 - time0)}") - except NameError: - pass - cancel_send_command = False - return output - - -def state_observe_thread() -> None: - """ - Observes the state of gdb, uses conditions to inform other functions and threads about gdb's state - Also generates output for send_command function - Should be called by creating a thread. Usually called in initialization process by attach function - """ - - def check_inferior_status() -> None: - matches = regexes.gdb_state_observe.findall(child.before) - if len(matches) > 0: - global stop_reason - global inferior_status - global last_stop_was_tracking - old_status = inferior_status - for match in matches: - if match[0].startswith('stopped,reason="exited'): - with process_exited_condition: - terminated_pid = currentpid - detach() - logger.info(f"Process terminated (PID: {terminated_pid})") - process_exited_condition.notify_all() - return - - # For multiline outputs, only the last async event is important - # Get the last match only to optimize parsing - stop_info = matches[-1][0] - if stop_info: - stop_reason = typedefs.STOP_REASON.DEBUG - inferior_status = typedefs.INFERIOR_STATUS.STOPPED - else: - inferior_status = typedefs.INFERIOR_STATUS.RUNNING - - # Check if the FINAL stopped event in this batch is a tracking breakpoint - # We need to check the last *stopped event, not just any tracking bp in the batch - # Because there might be multiple events arriving in same buffer - if inferior_status == typedefs.INFERIOR_STATUS.STOPPED: - # Find the LAST stopped event in matches (working backwards) - last_stop_was_tracking = False - for match in reversed(matches): - if match[0]: # This is a *stopped event - bp_match = regexes.breakpoint_number.search(match[0]) - if bp_match: - bp_num_str = bp_match.group(1) - # We'll use a default of BREAK as users might use the gdb console to place break conditions - # such as catchpoints, where they won't be added to breakpoint_on_hit_dict. - # Our own tracer which we must ignore will correctly use this dictionary so no worries there. - bp_on_hit = breakpoint_on_hit_dict.get(bp_num_str, typedefs.BREAKPOINT_ON_HIT.BREAK) - last_stop_was_tracking = bp_on_hit != typedefs.BREAKPOINT_ON_HIT.BREAK - # Found the last stopped event, stop searching - break - # If we ended in RUNNING state, last_stop_was_tracking persists from previous STOPPED event - - # Don't notify UI if: - # 1. Status hasn't changed - # 2. Last stop was a tracking breakpoint - # 3. A trace is active - should_not_notify = old_status == inferior_status or last_stop_was_tracking or driving_inferior - - if not should_not_notify: - with status_changed_condition: - status_changed_condition.notify_all() - - global child - global gdb_output - try: - while True: - child.expect_exact("\r\n") # A new line for TTY devices - child.before = child.before.strip() - if not child.before: - continue - check_inferior_status() - command_file = re.escape(utils.get_gdb_command_file(currentpid)) - if regexes.gdb_command_source(command_file).search(child.before): - child.expect_exact("(gdb)") - child.before = child.before.strip() - check_inferior_status() - gdb_output = child.before - with gdb_waiting_for_prompt_condition: - gdb_waiting_for_prompt_condition.notify_all() - if gdb_output_mode.command_output: - logger.debug(child.before) - else: - if gdb_output_mode.async_output: - logger.debug(child.before) - gdb_async_output.broadcast_message(child.before) - except (OSError, ValueError, pexpect.EOF) as e: - global gdb_initialized - gdb_initialized = False - with gdb_waiting_for_prompt_condition: - gdb_waiting_for_prompt_condition.notify_all() - with process_exited_condition: - if currentpid != -1: - process_exited_condition.notify_all() - if isinstance(e, pexpect.EOF): - logger.exception(f"EOF exception caught within pexpect, here's the contents of child.before:\n{child.before}") - logger.info("Exiting state_observe_thread") - - -def execute_func_temporary_interruption(func: Callable, *args: Any, **kwargs: Any) -> Any: - """Interrupts the inferior before executing the given function, continues inferior's execution after calling the - given function - - !!!WARNING!!! This function is NOT thread-safe. Use it with caution! - - Args: - func (function): The function that'll be called between interrupt&continue routine - *args (args): Arguments for the function that'll be called - **kwargs (kwargs): Keyword arguments for the function that'll be called - - Returns: - ???: Result of the given function. Return type depends on the given function - """ - old_status = inferior_status - if old_status == typedefs.INFERIOR_STATUS.RUNNING: - interrupt_inferior(typedefs.STOP_REASON.PAUSE) - try: - return func(*args, **kwargs) - finally: - if old_status == typedefs.INFERIOR_STATUS.RUNNING: - continue_inferior() - - -def execute_with_temporary_interruption(func: Callable) -> Callable: - """Decorator version of execute_func_temporary_interruption""" - - def wrapper(*args: Any, **kwargs: Any) -> Any: - return execute_func_temporary_interruption(func, *args, **kwargs) - - return wrapper - - -def can_attach(pid: int | str) -> bool: - """Check if we can attach to the target - - Args: - pid (int,str): PID of the process that'll be attached - - Returns: - bool: True if attaching is successful, False otherwise - """ - pid_int = safe_int_cast(pid) - if pid_int == 0: - return False - result = libc.ptrace(16, pid_int, 0, 0) # 16 is PTRACE_ATTACH, check ptrace.h for details - if result == -1: - return False - try: - os.waitpid(pid_int, 0) - finally: - libc.ptrace(17, pid_int, 0, 0) # 17 is PTRACE_DETACH - sleep(0.01) - return True - - -def wait_for_stop(timeout: float = 0) -> bool: - """Block execution till the inferior stops - - Args: - timeout (float): Timeout time in seconds, passing 0 will wait for stop indefinitely - - Returns: - bool: True if the inferior is stopped when this function exits, False otherwise - """ - remaining_time = timeout - while inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - sleep(0.0001) - if timeout == 0: - continue - remaining_time -= 0.0001 - if remaining_time < 0: - break - return inferior_status == typedefs.INFERIOR_STATUS.STOPPED - - -def interrupt_inferior(interrupt_reason: int = typedefs.STOP_REASON.DEBUG) -> bool: - """Interrupt the inferior - - Args: - interrupt_reason (int): Just changes the global variable stop_reason. Can be a member of typedefs.STOP_REASON - - Returns: - bool: True if the inferior is stopped after the interrupt attempt, False otherwise - """ - if currentpid == -1: - return False - global stop_reason - if interrupt_signal == "SIGINT": - send_command("interrupt") - elif inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - sig_num = interrupt_signal[3:] - if sig_num.isnumeric(): - os.system(f"kill -{sig_num} {currentpid}") - else: - os.system(f"kill -s {interrupt_signal} {currentpid}") - stopped = wait_for_stop(1) - stop_reason = interrupt_reason - return stopped - - -def continue_inferior() -> None: - """Continue the inferior""" - if currentpid == -1: - return - send_command("c&") - - -def step_instruction() -> None: - """Step one assembly instruction""" - send_command("stepi&") - - -def step_over_instruction() -> None: - """Step over one assembly instruction""" - send_command("nexti&") - - -def execute_till_return() -> None: - """Continues inferior till current stack frame returns""" - send_command("finish&") - - -def set_interrupt_signal(signal_name: str) -> None: - """Decides on what signal to use to stop the process - - Args: - signal_name (str): Name of the signal - """ - global interrupt_signal - handle_signal(signal_name, True, False) - interrupt_signal = signal_name - - -def handle_signal(signal_name: str, stop: bool, pass_to_program: bool) -> None: - """Decides on what will GDB do when the process receives a signal - - Args: - signal_name (str): Name of the signal - stop (bool): Stop the program and print to the console - pass_to_program (bool): Pass signal to program - """ - params = [[signal_name, stop, pass_to_program]] - send_command("pince-handle-signals", send_with_file=True, file_contents_send=params) - - -def handle_signals(signal_list: list) -> None: - """Optimized version of handle_signal for multiple signals - - Args: - signal_list (list): A list of the parameters of handle_signal - """ - send_command("pince-handle-signals", send_with_file=True, file_contents_send=signal_list) - - -def init_gdb(gdb_path: str = utils.get_default_gdb_path()) -> bool: - """Spawns gdb and initializes/resets some of the global variables - - Args: - gdb_path (str): Path of the gdb binary - - Returns: - bool: True if initialization is successful, False otherwise - - Note: - Calling init_gdb() will reset the current session - """ - global child - global gdb_initialized - global breakpoint_on_hit_dict - global chained_breakpoints - global gdb_output - global cancel_send_command - global last_gdb_command - global last_stop_was_tracking - utils.init_user_files() - detach() - - # Temporary IPC_PATH, this little hack is needed because send_command requires a valid IPC_PATH - utils.create_ipc_path(currentpid) - utils.create_tmp_path(currentpid) - - breakpoint_on_hit_dict.clear() - chained_breakpoints.clear() - gdb_output = None - cancel_send_command = False - last_gdb_command = "" - last_stop_was_tracking = False - - libpince_dir = utils.get_libpince_directory() - new_child = None - try: - new_child = pexpect.spawn( - gdb_path, - ["--nx", "--interpreter=mi"], - cwd=libpince_dir, - env=os.environ | {"LC_NUMERIC": "C"}, - encoding="utf-8", - codec_errors="replace", - ) - new_child.setecho(False) - new_child.delaybeforesend = 0 - new_child.expect_exact("(gdb)") - except (pexpect.ExceptionPexpect, OSError): - logger.exception(f"Failed to start GDB: {gdb_path}") - if new_child is not None: - new_child.close() - return False - child = new_child - child.timeout = None - status_thread = Thread(target=state_observe_thread) - status_thread.daemon = True - status_thread.start() - gdb_initialized = True - set_logging(False) - if not os.environ.get("APPDIR"): - send_command("source ./gdbinit_venv") - set_pince_paths() - send_command("source " + utils.get_user_path(typedefs.USER_PATHS.GDBINIT)) - utils.execute_script(utils.get_user_path(typedefs.USER_PATHS.PINCEINIT)) - return True - - -def set_logging(state: bool) -> None: - """Sets logging on or off - - Args: - state (bool): Sets logging on if True, off if False - """ - send_command("set logging enabled off") - send_command("set logging file " + utils.get_logging_file(currentpid)) - if state: - send_command("set logging enabled on") - - -def set_pince_paths() -> None: - """Initializes $PINCE_PATH and $GDBINIT_AA_PATH convenience variables to make commands in gdbextensions.py - and gdbutils.py work. GDB scripts need to know libpince and .config directories, unfortunately they don't start - from the place where script exists - """ - libpince_dir = utils.get_libpince_directory() - pince_dir = os.path.dirname(libpince_dir) - gdbinit_aa_dir = utils.get_user_path(typedefs.USER_PATHS.GDBINIT_AA) - # Force C while defining these vars and sourcing the scripts to avoid some languages (like debug Rust) - # causing issues where strings are being inferred as types that do not have gdb python's ".string()" support. - send_command("set language c") - send_command("set $GDBINIT_AA_PATH=" + '"' + gdbinit_aa_dir + '"') - send_command("set $PINCE_PATH=" + '"' + pince_dir + '"') - send_command("source gdb_python_scripts/gdbextensions.py") - send_command("set language auto") - - -def init_referenced_dicts(pid: int | str) -> None: - """Initializes referenced dict shelve databases - - Args: - pid (int,str): PID of the attached process - """ - with shelve.open(utils.get_referenced_strings_file(pid), "c"): - pass - with shelve.open(utils.get_referenced_jumps_file(pid), "c"): - pass - with shelve.open(utils.get_referenced_calls_file(pid), "c"): - pass - - -def attach(pid: int | str, gdb_path: str = utils.get_default_gdb_path()) -> int | None: - """Attaches gdb to the target and initializes some of the global variables - - Args: - pid (int,str): PID of the process that'll be attached to - gdb_path (str): Path of the gdb binary - - Returns: - int | None: A member of typedefs.ATTACH_RESULT or None if GDB initialization fails - - Note: - If gdb is already initialized, gdb_path will be ignored - """ - global currentpid - pid = int(pid) - traced_by = utils.is_traced(pid) - pid_control_list = [ - # Attaching PINCE to itself makes PINCE freeze immediately because gdb freezes the target on attach - (lambda: pid == self_pid, typedefs.ATTACH_RESULT.ATTACH_SELF), - (lambda: not utils.is_process_valid(pid), typedefs.ATTACH_RESULT.PROCESS_NOT_VALID), - (lambda: pid == currentpid, typedefs.ATTACH_RESULT.ALREADY_DEBUGGING), - (lambda: traced_by is not None, typedefs.ATTACH_RESULT.ALREADY_TRACED), - (lambda: not can_attach(pid), typedefs.ATTACH_RESULT.PERM_DENIED), - ] - for control_func, attach_result in pid_control_list: - if control_func(): - return attach_result - if currentpid != -1 or not gdb_initialized: - if not init_gdb(gdb_path): - return - global inferior_arch - global effective_arch - global mem_file - global current_process_identity - global _wow64_inject_buffer - currentpid = pid - current_process_identity = (currentpid, utils.get_process_start_time(currentpid)) - _libc_symbol_cache.clear() - _wow64_inject_buffer = (0, 0) - mem_file = "/proc/" + str(currentpid) + "/mem" - utils.create_ipc_path(pid) - utils.create_tmp_path(pid) - send_command("attach " + str(pid)) - set_pince_paths() - init_referenced_dicts(pid) - inferior_arch = get_inferior_arch() - effective_arch = utils.get_effective_arch(currentpid) - if effective_arch == -1: - effective_arch = inferior_arch - utils.execute_script(utils.get_user_path(typedefs.USER_PATHS.PINCEINIT_AA)) - _refresh_main_module_info() - return typedefs.ATTACH_RESULT.SUCCESSFUL - - -def create_process(process_path: str, args: str = "", ld_preload_path: str = "", gdb_path: str = utils.get_default_gdb_path()) -> bool: - """Creates a new process for debugging and initializes some of the global variables - Current process will be detached even if the create_process call fails - Make sure to save your data before calling this monstrosity - - Args: - process_path (str): Absolute path of the target binary - args (str): Arguments of the inferior, optional - ld_preload_path (str): Path of the preloaded .so file, optional - gdb_path (str): Path of the gdb binary - - Returns: - bool: True if the process has been created successfully, False otherwise - - Note: - If gdb is already initialized, gdb_path will be ignored - """ - global currentpid - global inferior_arch - global effective_arch - global mem_file - global current_process_identity - global _wow64_inject_buffer - if currentpid != -1 or not gdb_initialized: - if not init_gdb(gdb_path): - return False - output = send_command(f'file "{process_path}"') - if regexes.gdb_error.search(output): - logger.error(f"An error occurred while trying to create process from the file at {process_path}") - detach() - return False - send_command("starti") - wait_for_stop() - entry_point = find_entry_point() - if entry_point: - send_command("tbreak *" + entry_point) - else: - send_command("tbreak _start") - send_command("set args " + args) - if ld_preload_path: - send_command("set exec-wrapper env 'LD_PRELOAD=" + ld_preload_path + "'") - send_command("run") - - # We have to wait till breakpoint hits - wait_for_stop() - pid = get_inferior_pid() - if pid is None: - logger.error("Failed to get inferior pid while creating process!") - detach() - return False - currentpid = int(pid) - current_process_identity = (currentpid, utils.get_process_start_time(currentpid)) - _libc_symbol_cache.clear() - _wow64_inject_buffer = (0, 0) - mem_file = "/proc/" + str(currentpid) + "/mem" - utils.create_ipc_path(pid) - utils.create_tmp_path(pid) - set_pince_paths() - init_referenced_dicts(pid) - inferior_arch = get_inferior_arch() - effective_arch = utils.get_effective_arch(currentpid) - if effective_arch == -1: - effective_arch = inferior_arch - utils.execute_script(utils.get_user_path(typedefs.USER_PATHS.PINCEINIT_AA)) - _refresh_main_module_info() - return True - - -def detach() -> None: - """See you, space cowboy""" - global gdb_initialized - global currentpid - global current_process_identity - global _wow64_inject_buffer - old_pid = currentpid - current_process_identity = None - _libc_symbol_cache.clear() - _wow64_inject_buffer = (0, 0) - if gdb_initialized: - global child - global inferior_status - currentpid = -1 - inferior_status = -1 - gdb_initialized = False - child.close() - if old_pid != -1: - utils.delete_ipc_path(old_pid) - logger.info(f"Detached from the process with PID: {str(old_pid)}") - - -def toggle_attach() -> int | None: - """Detaches from the current process without ending the season if currently attached. Attaches back if detached - - Returns: - int: The new state of the process as a member of typedefs.TOGGLE_ATTACH - None: If detaching or attaching fails - """ - if currentpid == -1: - return - if is_attached(): - if regexes.gdb_error.search(send_command("phase-out")): - return - return typedefs.TOGGLE_ATTACH.DETACHED - if regexes.gdb_error.search(send_command("phase-in")): - return - return typedefs.TOGGLE_ATTACH.ATTACHED - - -def is_attached() -> bool: - """Checks if gdb is attached to the current process - - Returns: - bool: True if attached, False if not - """ - if regexes.gdb_error.search(send_command("info proc")): - return False - return True - - -def resolve_libc_symbol(name: str) -> int: - if address := _libc_symbol_cache.get(name, 0): - return address - for lib_regex in (r"^libc\.so", r"^libc-[\d.]+\.so", r"libc\.musl", r"ld-musl"): - module = utils.get_module_load_bias(currentpid, lib_regex) - if module is None: - continue - load_bias, path = module - path = utils.resolve_mapped_path(currentpid, path) - if offset := utils.get_defined_dynamic_symbols(path, [name]).get(name, 0): - _libc_symbol_cache[name] = load_bias + offset - return _libc_symbol_cache[name] - return 0 - - -def inject_so(library_path: str) -> bool: - """Injects the given .so file to the current process using dlopen. - This function will first try to ask gdb to resolve "dlopen"/"__libc_dlopen_mode" by symbol name. - If that fails (stripped binary or no libc symbol loaded yet), it will fallback to resolving - the address manually by using /proc//maps + the on-disk .dynsym and then calling the function. - - Args: - library_path (str): Path to the .so file that'll be injected - - Returns: - bool: True if the injection is successful, False if no dlopen found. - """ - if currentpid == -1: - return False - quoted = '"' + library_path + '"' - # Try using GDB to resolve the symbols. - for func in ("dlopen", "__libc_dlopen_mode"): - result = call_function_from_inferior(f"{func}({quoted}, 2)")[1] - address = regexes.hex_number.search(result) if result else None - if address and int(address.group(), 16): - return True - # Fallback to manual address resolution if GDB failed. - _lib_regexes = [ - r"^libc\.so", - r"^libc-[\d.]+\.so", - r"libc\.musl", - r"ld-musl", - r"^libdl\.so", - r"^libdl-[\d.]+\.so", - ] - _sym_names = ["dlopen", "__libc_dlopen_mode"] - path_bytes = os.fsencode(library_path) + b"\x00" - malloc = resolve_libc_symbol("malloc") - if not malloc: - return False - free = resolve_libc_symbol("free") - - global driving_inferior - driving_inferior = True - was_running = inferior_status == typedefs.INFERIOR_STATUS.RUNNING - - try: - if was_running: - interrupt_inferior() - - for regex in _lib_regexes: - module = utils.get_module_load_bias(currentpid, regex) - if module is None: - continue - - load_bias, path = module - path = utils.resolve_mapped_path(currentpid, path) # resolve sandboxed (Flatpak/pressure-vessel) paths - symbols = utils.get_defined_dynamic_symbols(path, _sym_names) - - for sym in _sym_names: - if sym not in symbols: - continue - - addr = load_bias + symbols[sym] - out = send_command(f"call ((void *(*)(unsigned long)) {hex(malloc)})({len(path_bytes)})") - m = regexes.convenience_variable.search(out) - hex_m = regexes.hex_number.search(m.group(2)) if m else None - if hex_m is None: - continue - - buf = safe_str_to_int(hex_m[0], 16) - if not buf: - continue - try: - write_memory(buf, typedefs.ByteArrayValueType(len(path_bytes)), path_bytes) - out = send_command(f"call ((void *(*)(char *, int)) {hex(addr)})((char *){hex(buf)}, 2)") - m = regexes.convenience_variable.search(out) - hex_m = regexes.hex_number_grouped.search(m.group(2)) if m else None - if hex_m and int(hex_m.group(1), 16) != 0: - return True - finally: - if free and currentpid != -1: - try: - send_command(f"call ((void (*)(void *)) {hex(free)})((void *){hex(buf)})") - except typedefs.GDBInitializeException: - pass - finally: - try: - if was_running: - continue_inferior() - finally: - driving_inferior = False - - return False - - -def _inject_dll_wow64(dll_path: str, llw: int, traps: list, nt_alloc: int, get_cpu_area: int) -> bool: - """Inject a 32 bits DLL into a new-WoW64 target by patching the live guest eip.""" - global _wow64_inject_buffer - if not (llw and traps and nt_alloc and get_cpu_area): - return False - wide = ("Z:" + dll_path.replace("/", "\\")).encode("utf-16le") + b"\x00\x00" - - # Find a clean native wait point before touching the guest context. - bps = [(t, regexes.breakpoint_number.search(send_command(f"tbreak *{hex(t)}"))) for t in traps] - if not any(b for _, b in bps): - return False - continue_inferior() - wait_for_stop(10) - if inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - for _, b in bps: - if b: - send_command(f"delete {b.group(1)}") - return False - pc = parse_and_eval("$pc", int) - brk = pc if pc in traps else 0 - for t, b in bps: - if b and t != brk: - send_command(f"delete {b.group(1)}") - if not brk: - return False - - # Save the native thread state so it can be restored after our helper calls. - tid = parse_and_eval("$_thread", int) - thread_scope = f" thread {tid}" if tid else "" - saved = {r: parse_and_eval(f"${r}", int) for r in ("rax", "rcx", "rdx", "r8", "r9", "r10", "r11", "rip", "rsp")} - sp0 = saved["rsp"] - if sp0 is None or saved["rip"] is None: - return False - - def write_bytes(addr, data): - try: - with memory_handle("rb+") as mem: - mem.seek(addr) - return mem.write(data) == len(data) - except (OSError, ValueError): - return False - - def read_int(addr, size): - try: - with memory_handle() as mem: - mem.seek(addr) - return int.from_bytes(mem.read(size), "little") - except (OSError, ValueError): - return None - - # Call a native 64 bits function from the parked wait point. - def win64(func, args): - stack_args = args[4:] - frame = ((sp0 - 0x300 - len(stack_args) * 8) & ~0xF) - 8 - blob = brk.to_bytes(8, "little") + b"\x00" * 32 - blob += b"".join((a & 0xFFFFFFFFFFFFFFFF).to_bytes(8, "little") for a in stack_args) - if not write_bytes(frame, blob): - return None - tb = regexes.breakpoint_number.search(send_command(f"tbreak *{hex(brk)}{thread_scope} if $rsp == {hex(frame + 8)}")) - if not tb: - return None - for reg, value in zip(("rcx", "rdx", "r8", "r9"), list(args[:4]) + [0] * 4): - set_convenience_variable(reg, hex(value & 0xFFFFFFFFFFFFFFFF)) - set_convenience_variable("rsp", hex(frame)) - set_convenience_variable("rip", hex(func)) - continue_inferior() - wait_for_stop(10) - if inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - interrupt_inferior() - send_command(f"delete {tb.group(1)}") - return None - if parse_and_eval("$pc", int) != brk: - send_command(f"delete {tb.group(1)}") - return None - return parse_and_eval("$rax", int) - - try: - pbase, psize, pmach, pctx, pctxex = (sp0 - off for off in (0x80, 0x78, 0x70, 0x68, 0x60)) - size = (0x800 + len(wide) + 0xFFF) & ~0xFFF - - # Allocate or reuse memory that 32 bits guest code can reach. - cached_buf, cached_size = _wow64_inject_buffer - buf = cached_buf if cached_buf and cached_size >= size else 0 - if not buf: - for hint in (0x50000000, 0): - if not (write_bytes(pbase, hint.to_bytes(8, "little")) and write_bytes(psize, size.to_bytes(8, "little"))): - break - status = win64(nt_alloc, [0xFFFFFFFFFFFFFFFF, pbase, 0, psize, 0x3000, 0x40]) - if status is None: - break - if status: - continue - buf = read_int(pbase, 8) or 0 - if 0 < buf <= 0xFFFFFFFF: - _wow64_inject_buffer = (buf, size) - break - buf = 0 - if not buf or not all(write_bytes(slot, b"\x00" * 8) for slot in (pmach, pctx, pctxex)): - return False - - # Ask Wine for the current 32 bit guest CPU context. - if win64(get_cpu_area, [pmach, pctx, pctxex]) != 0: - return False - machine = read_int(pmach, 2) - ctxptr = read_int(pctx, 8) or 0 - orig_eip = read_int(ctxptr + 0xB8, 4) if ctxptr else None - if machine != 0x14C or not ctxptr or orig_eip is None: - return False - - path_ptr = buf + 0x800 - # Run LoadLibraryW through the guest eip then return to the original code. - asm = f""" - pushfd - pushad - push {hex(path_ptr & 0xFFFFFFFF)} - mov eax, {hex(llw & 0xFFFFFFFF)} - call eax - popad - popfd - push {hex(orig_eip & 0xFFFFFFFF)} - ret - """ - assembled = utils.assemble(asm, buf, typedefs.INFERIOR_ARCH.ARCH_32) - code = bytes(assembled[0]) if assembled else b"" - return ( - bool(code) - and len(code) <= 0x800 - and write_bytes(path_ptr, wide) - and write_bytes(buf, code) - and write_bytes(ctxptr + 0xB8, (buf & 0xFFFFFFFF).to_bytes(4, "little")) - ) - finally: - # Restore the native thread state. - if tid: - send_command(f"thread {tid}") - for reg, value in saved.items(): - if value is not None: - set_convenience_variable(reg, hex(value & 0xFFFFFFFFFFFFFFFF)) - - -def inject_dll(dll_path: str) -> bool: - """Injects a Windows DLL into the current WINE/Proton inferior via "kernel32!LoadLibraryW". - - PE exports are resolved from the target memory. Helper calls run from an ntdll wait/sleep wrapper. - LoadLibraryW runs from a bootstrap thread or from a patched guest thread on new-WoW64. - - Args: - dll_path (str): Path to the Windows .dll on the Linux filesystem. - - Returns: - bool: True if the DLL injection was started - """ - if currentpid == -1: - return False - - global driving_inferior - driving_inferior = True - was_running = inferior_status == typedefs.INFERIOR_STATUS.RUNNING - try: - # Stop the process while resolving exports and setting up the call frame. - if was_running: - interrupt_inferior() - - # Walk the export tables and find the PE-side functions we need. - with memory_handle() as mem: - - def u(addr, n): - mem.seek(addr) - return int.from_bytes(mem.read(n), "little") - - def pe_magic(base): - try: - if u(base, 2) != 0x5A4D: # "MZ" DOS magic - return 0 - pe = base + u(base + 0x3C, 4) - return u(pe + 0x18, 2) if u(pe, 4) == 0x4550 else 0 # "PE\0\0" - except (OSError, ValueError): - return 0 - - # Cache relevant PE image bases by bitness. - pe_bases = {} - process_name = utils.get_process_name(currentpid).lower() - main_pe_magic = 0 - fallback_exe_magic = 0 - for start, _, _, offset, _, _, path in utils.get_regions(currentpid): - name = os.path.basename(path).lower() if path and int(offset, 16) == 0 else "" - if name.endswith(".exe"): - magic = pe_magic(int(start, 16)) - if magic in (0x10B, 0x20B): - if name == process_name: - main_pe_magic = magic - elif not fallback_exe_magic: - fallback_exe_magic = magic - if name in ("kernel32.dll", "ntdll.dll", "kernelbase.dll"): - base = int(start, 16) - magic = pe_magic(base) - if magic in (0x10B, 0x20B): - pe_bases.setdefault((name, magic), base) - - # New-WoW64 can map both 32 and 64 bits PE images. The launched exe decides the Windows bitness. - main_pe_magic = main_pe_magic or fallback_exe_magic - wow64 = inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 and main_pe_magic == 0x10B - want_magic = 0x10B if wow64 or inferior_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 0x20B - k32 = pe_bases.get(("kernel32.dll", want_magic), 0) - nt = pe_bases.get(("ntdll.dll", want_magic), 0) - kb = pe_bases.get(("kernelbase.dll", want_magic), 0) - if not (k32 and nt): - return False - - # Resolve a PE export by name and ignore forwarded exports. - def export(base, name): - magic = pe_magic(base) - if not magic: - return 0 - opt = base + u(base + 0x3C, 4) + 0x18 # optional header - dd = opt + (0x70 if magic == 0x20B else 0x60) # export data directory - ed_rva, ed_size = u(dd, 4), u(dd + 4, 4) - if ed_rva == 0: - return 0 - ed = base + ed_rva # IMAGE_EXPORT_DIRECTORY - funcs, names, ords = (base + u(ed + off, 4) for off in (0x1C, 0x20, 0x24)) - want = name.encode() + b"\x00" - for i in range(u(ed + 0x18, 4)): # NumberOfNames - mem.seek(base + u(names + i * 4, 4)) - if mem.read(len(want)) == want: - frva = u(funcs + u(ords + i * 2, 2) * 4, 4) - return 0 if ed_rva <= frva < ed_rva + ed_size else base + frva - return 0 - - # Grab the addresses of all of the functions we need. - llw = export(k32, "LoadLibraryW") or (export(kb, "LoadLibraryW") if kb else 0) - traps = [t for t in (export(nt, "NtWaitForSingleObject"), export(nt, "NtDelayExecution")) if t] - valloc = export(k32, "VirtualAlloc") or (export(kb, "VirtualAlloc") if kb else 0) - vfree = export(k32, "VirtualFree") or (export(kb, "VirtualFree") if kb else 0) - create_thread = export(k32, "CreateThread") or (export(kb, "CreateThread") if kb else 0) - close_handle = export(k32, "CloseHandle") or (export(kb, "CloseHandle") if kb else 0) - - # Extra stuff for New-WoW64. - if wow64: - nt64 = pe_bases.get(("ntdll.dll", 0x20B), 0) - traps64 = [t for t in (export(nt64, "NtWaitForSingleObject"), export(nt64, "NtDelayExecution")) if t] - nt_alloc = export(nt64, "NtAllocateVirtualMemory") - get_cpu_area = export(nt64, "RtlWow64GetCurrentCpuArea") - - # The entire logic of New-WoW64 injection will be handled by this separate function. - # This was the most problematic piece to implement so having it separate makes it easier to debug in the future, - # as the pure 32/64 bits path uses very stable Wine/Windows ABI/API but wow64 relies more on unstable stuff. - if wow64: - return _inject_dll_wow64(dll_path, llw, traps64, nt_alloc, get_cpu_area) - - # If pure 32/64bits WINE process, check that we have the necessary exports then proceed. - if not (llw and traps and valloc and vfree and create_thread and close_handle): - return False - - # Park in a PE entry before issuing helper calls. - bps = [(t, regexes.breakpoint_number.search(send_command(f"tbreak *{hex(t)}"))) for t in traps] - if not any(b for _, b in bps): - return False - continue_inferior() - wait_for_stop(10) - if inferior_status == typedefs.INFERIOR_STATUS.RUNNING: - for _, b in bps: - if b: - send_command(f"delete {b.group(1)}") - return False - pc = examine_expression("$pc").address - brk = int(pc, 16) if pc and int(pc, 16) in traps else 0 - for t, b in bps: # the fired tbreak auto-deletes itself, so drop the ones that didn't fire - if b and t != brk: - send_command(f"delete {b.group(1)}") - - # The breakpoint address also becomes the return trap for helper calls. - injected = False - if brk: - # Default Wine maps Z: to /. - # TODO BRK: Maybe change this later to query user's mappings. - wide = ("Z:" + dll_path.replace("/", "\\")).encode("utf-16le") + b"\x00\x00" - - # Pick registers and calling convention for the Windows side we are in. - pe32 = inferior_arch == typedefs.INFERIOR_ARCH.ARCH_32 - stack_reg = "esp" if pe32 else "rsp" - pc_reg = "eip" if pe32 else "rip" - ret_reg = "eax" if pe32 else "rax" - sp0 = parse_and_eval(f"${stack_reg}", int) - tid = parse_and_eval("$_thread", int) - - if sp0 is None: - return False - else: - thread_scope = f" thread {tid}" if tid else "" - saved_regs = {reg: parse_and_eval(f"${reg}", int) for reg in ("rcx", "rdx", "r8", "r9")} if not pe32 else {} - - def write_bytes(addr, data): - try: - with memory_handle("rb+") as mem: - mem.seek(addr) - return mem.write(data) == len(data) - except (OSError, ValueError): - return False - - # Run one PE function and wait until it returns to the trap. - def run_call(func, frame, return_condition, regs): - tb = regexes.breakpoint_number.search(send_command(f"tbreak *{hex(brk)}{thread_scope} if {return_condition}")) - if not tb: - return 0 - for reg, value in regs.items(): - set_convenience_variable(reg, hex(value)) - set_convenience_variable(stack_reg, hex(frame)) - set_convenience_variable(pc_reg, hex(func)) - continue_inferior() - wait_for_stop(10) - timed_out = inferior_status == typedefs.INFERIOR_STATUS.RUNNING - if timed_out: - interrupt_inferior() - pc = examine_expression("$pc").address - if timed_out: - send_command(f"delete {tb.group(1)}") - return 0 - if not pc or int(pc, 16) != brk: - send_command(f"delete {tb.group(1)}") - return 0 - return parse_and_eval(f"${ret_reg}", int) or 0 - - # Build a 32 bits stdcall frame. - def stdcall(func, args): - if brk > 0xFFFFFFFF: - return 0 - blob = brk.to_bytes(4, "little") + b"".join((a & 0xFFFFFFFF).to_bytes(4, "little") for a in args) - frame = (sp0 - len(blob) - 0x20) & 0xFFFFFFF0 - if not write_bytes(frame, blob): - return 0 - expected = frame + 4 + 4 * len(args) - cond = f"$esp == {hex(expected)}" - return run_call(func, frame, cond, {}) & 0xFFFFFFFF - - # Build a 64 bits Windows call frame. - def win64_call(func, args): - args = list(args) - stack_args = args[4:] - frame = ((sp0 - 0x100 - len(stack_args) * 8) & ~0xF) - 8 # Win64 entry rsp must be 16n+8. - blob = brk.to_bytes(8, "little") + b"\x00" * 32 # return address + shadow space - blob += b"".join((a & 0xFFFFFFFFFFFFFFFF).to_bytes(8, "little") for a in stack_args) - if not write_bytes(frame, blob): - return 0 - reg_args = args[:4] + [0] * (4 - len(args[:4])) - regs = dict(zip(("rcx", "rdx", "r8", "r9"), reg_args)) - return run_call(func, frame, f"$rsp == {hex(frame + 8)}", regs) - - pe_call = stdcall if pe32 else win64_call - try: - # Keep the path, thread handle slot and bootstrap in one allocation. - ptr_size = 4 if pe32 else 8 - handle_addr = (len(wide) + ptr_size - 1) & ~(ptr_size - 1) - code_addr = (handle_addr + ptr_size + 0xF) & ~0xF - alloc_size = code_addr + 0x400 - buf = pe_call(valloc, [0, alloc_size, 0x3000, 0x40]) # COMMIT|RESERVE, PAGE_EXECUTE_READWRITE - handle_ptr = buf + handle_addr - code_ptr = buf + code_addr - - # The bootstrap calls LoadLibraryW then frees its own allocation. - if pe32: - asm = f""" - push {hex(buf & 0xFFFFFFFF)} - mov eax, {hex(llw & 0xFFFFFFFF)} - call eax - mov ecx, 0x10000000 - wait_loop: - mov eax, dword ptr [{hex(handle_ptr & 0xFFFFFFFF)}] - test eax, eax - jne close_self - pause - dec ecx - jne wait_loop - jmp free_self - close_self: - push eax - mov eax, {hex(close_handle & 0xFFFFFFFF)} - call eax - free_self: - mov eax, dword ptr [esp] - mov dword ptr [esp - 8], eax - mov dword ptr [esp - 4], {hex(buf & 0xFFFFFFFF)} - mov dword ptr [esp], 0 - mov dword ptr [esp + 4], 0x8000 - sub esp, 8 - mov eax, {hex(vfree & 0xFFFFFFFF)} - jmp eax - """ - remote_arch = typedefs.INFERIOR_ARCH.ARCH_32 - else: - asm = f""" - sub rsp, 0x28 - mov rcx, {hex(buf)} - mov rax, {hex(llw)} - call rax - mov r11, {hex(handle_ptr)} - mov r10d, 0x10000000 - wait_loop: - mov rcx, qword ptr [r11] - test rcx, rcx - jne close_self - pause - dec r10d - jne wait_loop - jmp free_self - close_self: - mov rax, {hex(close_handle)} - call rax - free_self: - add rsp, 0x28 - mov rcx, {hex(buf)} - xor edx, edx - mov r8d, 0x8000 - mov rax, {hex(vfree)} - jmp rax - """ - remote_arch = typedefs.INFERIOR_ARCH.ARCH_64 - - # Write the path and bootstrap, then start it in a Windows thread. - assembled = utils.assemble(asm, code_ptr, remote_arch) - code = bytes(assembled[0]) if assembled else b"" - if ( - buf - and code - and len(code) <= alloc_size - code_addr - and write_bytes(buf, wide) - and write_bytes(handle_ptr, b"\x00" * ptr_size) - and write_bytes(code_ptr, code) - ): - thread_handle = pe_call(create_thread, [0, 0, code_ptr, 0, 0, 0]) - if thread_handle: - injected = True - write_bytes(handle_ptr, thread_handle.to_bytes(ptr_size, "little")) - finally: - # Restore the parked thread after the helper calls. - if tid: - send_command(f"thread {tid}") - for reg, value in saved_regs.items(): - if value is not None: - set_convenience_variable(reg, hex(value)) - set_convenience_variable(pc_reg, hex(brk)) - set_convenience_variable(stack_reg, hex(sp0)) - - return injected - finally: - try: - if was_running and inferior_status != typedefs.INFERIOR_STATUS.RUNNING: - continue_inferior() - finally: - driving_inferior = False - - -def read_pointer_chain(pointer_request: typedefs.PointerChainRequest) -> typedefs.PointerChainResult | None: - """Reads the addresses pointed by this pointer chain - - Args: - pointer_request (typedefs.PointerChainRequest): class containing a base_address and an offsets list - - Returns: - typedefs.PointerChainResult: Class containing every pointer dereference result while walking the chain - None: If an error occurs while reading the given pointer chain - """ - if not isinstance(pointer_request, typedefs.PointerChainRequest): - raise TypeError("Passed non-PointerChainRequest type to read_pointer_chain!") - - pointer_type = typedefs.IntegerValueType(32 if effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 64) - - # Simple addresses first, examine_expression takes much longer time, especially for larger tables - try: - start_address = int(pointer_request.base_address, 0) - except (ValueError, TypeError): - start_address = examine_expression(pointer_request.base_address).address - - pointer_results: typedefs.PointerChainResult = typedefs.PointerChainResult() - try: - with memory_handle() as mem_handle: - # Dereference the first address which is the base or (base + offset) - deref_address = read_memory(start_address, pointer_type, mem_handle=mem_handle) - if deref_address is None: - # Simply return None because no point reading further if base is not valid - return None - pointer_results.pointer_chain.append(deref_address) - - for index, offset in enumerate(pointer_request.offsets_list): - # If deref_address is 0, we found an invalid read in the chain - # so we can just keep adding 0 until the end of offsets list - if deref_address == 0: - pointer_results.pointer_chain.append(0) - continue - offset_address = deref_address + offset - if index != len(pointer_request.offsets_list) - 1: # CE derefs every offset except for the last one - deref_address = read_memory(offset_address, pointer_type, mem_handle=mem_handle) - if deref_address is None: - deref_address = 0 - else: - deref_address = offset_address - pointer_results.pointer_chain.append(deref_address) - except OSError: - return None - return pointer_results - - -def memory_handle(mode: str = "rb") -> io.BufferedReader: - """ - Acquire the handle of the currently attached process - - Args: - mode (str): string detailing the open mode, default "rb" - - Returns: - BinaryIO: A file handle that points to the memory file of the current process - """ - return open(mem_file, mode) - - -def mprotect_memory(address: int, length: int, prot: int = 7) -> bool: # PROT_READ | PROT_WRITE | PROT_EXEC = 7 - """Changes the memory protection of the pages overlapping [address, address + length). - - mprotect requires a page-aligned address and acts on whole pages, so we calculate the page boundary given address + length. - Tries a direct inferior call and falls back to the resolved libc symbol. - - Args: - address (int): Start address of the range to reprotect. - length (int): Size of the range in bytes. - prot (int): Bitmask of PROT_* flags, default 7 (PROT_READ | PROT_WRITE | PROT_EXEC). - - Returns: - bool: True if the inferior's mprotect call returned 0, False otherwise. - """ - if address <= 0 or length <= 0: - return False - page_size = os.sysconf("SC_PAGE_SIZE") - start = address & ~(page_size - 1) - length = address + length - start # grow to cover the pages the original range touched - output = send_command(f"p (int)mprotect({start}, {length}, {prot})") - match = regexes.convenience_variable.search(output) - if match is None and (mprotect := resolve_libc_symbol("mprotect")): - output = send_command(f"p ((int(*)(void*, unsigned long, int)) {hex(mprotect)})((void*){start}, {length}, {prot})") - match = regexes.convenience_variable.search(output) - if match is None: - logger.error(f"Failed to change protection for memory at {hex(address)}") - return False - result = match.group(2) - value = regexes.hex_number.search(result) or re.search(r"-?\d+", result) - success = value is not None and safe_str_to_int(value.group(0), 0) == 0 - if not success: - logger.error(f"Failed to change protection for memory at {hex(address)}") - return success - - -@execute_with_temporary_interruption -def allocate_memory(size: int, name: str | None) -> int: - """Allocates writable (non-executable) memory in the inferior via malloc. - - This hands back ordinary heap memory, so for executable code (e.g. code caves) just simply use allocate_cave. - A caller that needs this region executable can mprotect_memory it afterwards, - but be aware that flips protection on the whole page(s) and so affects any heap neighbours sharing them. - - Args: - size (int): Number of bytes to allocate. Allocating 0 bytes does nothing and returns 0. - name (str | None): Key to track the allocation under so free_memory can release it later. - If None, an auto-incrementing id is used instead. - - Returns: - int: Address of the allocated memory or 0 on failure. - """ - global allocated_memory_gen_id - if size == 0: - return 0 - if name is None: - allocated_memory_gen_id += 1 - name = str(allocated_memory_gen_id) - output = send_command(f"p (void*)malloc({size})") - match = regexes.convenience_variable.search(output) - hex_match = regexes.hex_number.search(match.group(2)) if match else None - if hex_match is None and (malloc := resolve_libc_symbol("malloc")): - output = send_command(f"p ((void*(*)(unsigned long)) {hex(malloc)})({size})") - match = regexes.convenience_variable.search(output) - hex_match = regexes.hex_number.search(match.group(2)) if match else None - if hex_match is None: - logger.error("Memory allocation failed!") - return 0 - allocated_address = safe_str_to_int(hex_match[0], 16) - if allocated_address == 0: - logger.error("Couldn't find allocation address!") - return 0 - allocated_memory_chunks[name] = typedefs.AllocatedMemory(allocated_address, size, current_process_identity) - return allocated_address - - -@execute_with_temporary_interruption -def free_memory(name: str) -> bool: - """Frees memory previously allocated with allocate_memory. - - Args: - name (str): Key the allocation was tracked under when allocate_memory was called. - - Returns: - bool: True if the memory was freed, False otherwise (unknown name, wrong type or the allocation belongs to a different process). - """ - global allocated_memory_chunks - if not isinstance(name, str): - logger.error(f"Passed wrong type '{type(name)}' instead of str") - return False - if name == "": - logger.error(f"Passed empty str!") - return False - allocated_memory = allocated_memory_chunks.get(name) - if allocated_memory is None: - logger.error(f"Couldn't find allocated memory with name `{name}`!") - return False - if allocated_memory.identity != current_process_identity: - logger.error(f"Refusing to free memory '{name}' belonging to a different process") - return False - # This shit will crash the process if you call it on invalid or already freed memory. - output = send_command(f"p (void)free({allocated_memory.address})") - match = regexes.convenience_variable.search(output) - if match is None and (free := resolve_libc_symbol("free")): - output = send_command(f"p ((void(*)(void*)) {hex(free)})((void*){allocated_memory.address})") - match = regexes.convenience_variable.search(output) - if match is None: - logger.error(f"Failed to free memory '{name}' at {hex(allocated_memory.address)}") - return False - del allocated_memory_chunks[name] - return True - - -@execute_with_temporary_interruption -def allocate_cave(size: int, name: str | None, near: int | None = None) -> int: - """Allocates executable memory in the inferior via mmap. - - Args: - size (int): Number of bytes to allocate. Allocating 0 bytes does nothing and returns 0. - name (str | None): Key to track the allocation under so free_cave can release it later. - If None, an auto-incrementing id is used instead. - near (int | None): Preferred mmap address hint. If None, the kernel chooses the address. - - Returns: - int: Address of the allocated code cave or 0 on failure. - """ - global allocated_cave_gen_id - if size == 0: - return 0 - if name is None: - allocated_cave_gen_id += 1 - name = str(allocated_cave_gen_id) - - def mmap_cave(address: int, flags: int) -> int: - output = send_command(f"p (void*)mmap((void*){hex(address)}, {size}, 7, {hex(flags)}, -1, 0)") - match = regexes.convenience_variable.search(output) - hex_match = regexes.hex_number.search(match.group(2)) if match else None - if hex_match is None and (mmap := resolve_libc_symbol("mmap")): - cast = "(void*(*)(void*, unsigned long, int, int, int, long))" - output = send_command(f"p ({cast} {hex(mmap)})((void*){hex(address)}, {size}, 7, {hex(flags)}, -1, 0)") - match = regexes.convenience_variable.search(output) - hex_match = regexes.hex_number.search(match.group(2)) if match else None - if hex_match is None: - return 0 - allocated = safe_str_to_int(hex_match[0], 16) - # mmap returns MAP_FAILED ((void*)-1) on failure: 0xff..ff in the inferior's pointer width - return 0 if allocated in (0, 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF) else allocated - - # Just ask kernel for whatever address - if near is None: - # MAP_PRIVATE | MAP_ANONYMOUS (0x22), PROT_READ | PROT_WRITE | PROT_EXEC (7), fd -1, offset 0. - allocated_address = mmap_cave(0, 0x22) - else: - # We'll try to manually find free gaps near this address and tell the kernel to map the new memory there. - # This is because if we ask the kernel to give a memory address near target address with the hint, - # sometimes it will give a nearby address but other times (almost every time if main exe region from my tests) will not. - # Giving it an address that's guaranteed to not be mapped already with MAP_FIXED_NOREPLACE, - # will make mmap either land exactly there or fail without replacing an existing mapping. - near_address = safe_int_cast(near) - page_size = os.sysconf("SC_PAGE_SIZE") - page_mask = ~(page_size - 1) - near_page = near_address & page_mask - alloc_size = (size + page_size - 1) & page_mask - # Keep x86_64 caves well inside rel32 range so hooks can jump into them and back out with E9 rel32. - window_start, window_end = ( - (0, 0x100000000) if inferior_arch == typedefs.INFERIOR_ARCH.ARCH_32 else (max(0, near_address - 0x70000000), near_address + 0x70000000) - ) - # Fast path: exact requested page, if it is free. - allocated_address = mmap_cave(near_page, 0x100022) - if allocated_address and allocated_address != near_page: - # Old kernels may ignore unknown flags and treat this as a hint so we unmap to never keep a wrong address cave. - send_command(f"p (int)munmap((void*){hex(allocated_address)}, {size})") - allocated_address = 0 - - # Slower path: build one candidate from each free gap and sort them from closest to farthest. - # We'll then try to mmap each in order until we land a free page that is not mapped already. - if not allocated_address: - candidates = [] - previous_end = 0 - regions = ((safe_str_to_int(start, 16), safe_str_to_int(end, 16)) for start, end, *_ in utils.get_regions(currentpid)) - for start, end in sorted(regions) + [(window_end, window_end)]: - gap_start = (max(previous_end, window_start) + page_size - 1) & page_mask - gap_end = min(start, window_end) & page_mask - previous_end = max(previous_end, end) - if gap_end - gap_start >= alloc_size: - candidates.append(min(max(near_page, gap_start), gap_end - alloc_size)) - # MAP_FIXED_NOREPLACE (0x100000) makes the address exact without clobbering an existing mapping. - for candidate in sorted(candidates, key=lambda address: abs(address - near_address)): - allocated_address = mmap_cave(candidate, 0x100022) - if allocated_address == candidate: - break - if allocated_address: - send_command(f"p (int)munmap((void*){hex(allocated_address)}, {size})") - allocated_address = 0 - - if not allocated_address: - logger.error("Cave allocation failed!") - return 0 - allocated_cave_chunks[name] = typedefs.AllocatedMemory(allocated_address, size, current_process_identity) - return allocated_address - - -@execute_with_temporary_interruption -def free_cave(name: str) -> bool: - """Frees a code cave previously allocated with allocate_cave. - - Args: - name (str): Key the allocation was tracked under when allocate_cave was called. - - Returns: - bool: True if the cave was freed, False otherwise (unknown name, wrong type or the allocation belongs to a different process). - """ - global allocated_cave_chunks - if not isinstance(name, str): - logger.error(f"Passed wrong type '{type(name)}' instead of str") - return False - if name == "": - logger.error(f"Passed empty str!") - return False - allocated_cave = allocated_cave_chunks.get(name) - if allocated_cave is None: - logger.error(f"Couldn't find allocated cave with name `{name}`!") - return False - if allocated_cave.identity != current_process_identity: - logger.error(f"Refusing to free cave '{name}' belonging to a different process") - return False - addr = allocated_cave.address - output = send_command(f"p (int)munmap({addr}, {allocated_cave.size})") - match = regexes.convenience_variable.search(output) - if match is None and (munmap := resolve_libc_symbol("munmap")): - output = send_command(f"p ((int(*)(void*, unsigned long)) {hex(munmap)})((void*){addr}, {allocated_cave.size})") - match = regexes.convenience_variable.search(output) - if match is None: - logger.error(f"Failed to free cave '{name}' at {hex(addr)}") - return False - # munmap returns 0 on success, -1 on error. - # Drop our record either way: a non-zero result means our (address, size) no longer maps what we expect, so keeping it tracked is pointless. - result = match.group(2) - value = regexes.hex_number.search(result) or re.search(r"-?\d+", result) - succeeded = value is not None and safe_str_to_int(value.group(0), 0) == 0 - del allocated_cave_chunks[name] - if not succeeded: - logger.error(f"munmap failed for cave '{name}' at {hex(addr)}") - return succeeded - - -def read_memory( - address: str | int, - value_type: typedefs.ValueType, - mem_handle: io.BufferedReader | None = None, -) -> str | float | int | None: - """Reads value from the given address - - Args: - address (str, int): Can be a hex string or an integer. - value_type (typedefs.ValueType): Determines how many bytes to read and how to decode them. - mem_handle (io.BufferedReader, None): A file handle that points to the memory file of the current process - This parameter is used for optimization, See memory_handle - Don't forget to close the handle after you're done if you use this parameter manually - - Returns: - str: For string and byte-array types, also for hexadecimal integers - float: For float types - int: For integer and BitField types - None: If an error occurs while reading the given address - """ - if not isinstance(value_type, typedefs.ValueType): - return - if not type(address) == int: - try: - address = int(address, 0) - except Exception: - return - expected_length = value_type.read_size - if expected_length is None: - return - own_mem_handle = mem_handle is None - try: - if own_mem_handle: - mem_handle = memory_handle() - mem_handle.seek(address) - data_read = mem_handle.read(expected_length) - except (OSError, ValueError): - # TODO (read/write error output) - # Disabled read error printing. If needed, find a way to implement error logging with this function - # print("Can't access the memory at address " + hex(address) + " or offset " + hex(address + expected_length)) - return - finally: - if own_mem_handle and mem_handle is not None: - mem_handle.close() - if len(data_read) < expected_length: - return - return value_type.decode(data_read) - - -def write_memory( - address: str | int, - value_type: typedefs.ValueType, - value: str | int | float | bytes | bytearray | memoryview | list[int], -) -> None: - """Sets the given value to the given address - - If any errors occurs while setting value to the according address, it'll be ignored but the information about - error will be printed to the terminal. - - Args: - address (str, int): Can be a hex string or an integer - value_type (typedefs.ValueType): Determines how the value is encoded - value (str, int, float, bytes, bytearray, memoryview, list): The value that'll be written to the given address - - Notes: - TODO: Implement a mem_handle parameter for optimization, check read_memory for an example - If a file handle fails to write to an address, it becomes unusable - You have to reopen the file to continue writing - """ - if not isinstance(value_type, typedefs.ValueType): - return - if not type(address) == int: - try: - address = int(address, 0) - except Exception: - return - if isinstance(value_type, typedefs.BitFieldValueType): - value = value_type.parse(str(value)) - if value is None: - return - try: - with memory_handle("rb+") as mem_handle: - mem_handle.seek(address) - write_data = value_type.encode_into(mem_handle.read(value_type.read_size), value) - mem_handle.seek(address) - mem_handle.write(write_data) - except (OSError, ValueError): - return - return - try: - write_data = value_type.encode(value) - except (struct.error, OverflowError, TypeError, ValueError): - logger.error(f"Failed to encode value {value!r} as {value_type.text()}") - return - if write_data is None: - return - try: - with memory_handle("rb+") as mem_handle: - mem_handle.seek(address) - mem_handle.write(write_data) - except (OSError, ValueError): - # Refer to TODO (read/write error output) - # print("Can't access the memory at address " + hex(address) + " or offset " + hex(address + len(write_data))) - return - - -def aob_scan( - pattern: str, - writable: bool | None = None, - executable: bool | None = None, - limit: int | None = 1000, -) -> list[int]: - """Scan readable memory regions of the attached process for a byte pattern. - - Args: - pattern: Whitespace-separated hex tokens. Use '?' or '??' for a whole-byte wildcard, - e.g. '48 8b 05 ?? ?? ?? ??'. - writable: If True/False, restrict to writable/non-writable regions. None = either. - executable: If True/False, restrict to executable/non-executable regions. None = either. - limit: Stop after this many matches. None = unlimited. - - Returns: - List of match addresses in ascending order, including overlapping matches. - Empty list if no process is attached or the pattern is invalid. - """ - if limit is not None and limit <= 0: - return [] - if currentpid == -1: - return [] - try: - parts = [b"." if t in ("?", "??") else re.escape(bytes([int(t, 16)])) for t in pattern.split()] - except ValueError: - logger.error(f"Invalid hex token in AOB pattern: {pattern!r}") - return [] - if not parts: - return [] - matcher = re.compile(b"(?=(" + b"".join(parts) + b"))", re.DOTALL) - overlap = len(parts) - 1 - results = [] - with memory_handle() as mem: - for start, end, perms, *_ in utils.get_regions(currentpid): - if "r" not in perms: - continue - if writable is not None and ("w" in perms) != writable: - continue - if executable is not None and ("x" in perms) != executable: - continue - position = int(start, 16) - end_addr = int(end, 16) - tail = b"" - while position < end_addr: - read_size = min(1 << 20, end_addr - position) - try: - mem.seek(position) - chunk = mem.read(read_size) - except (OSError, ValueError): - position += read_size - tail = b"" - continue - if not chunk: - break - data = tail + chunk - base = position - len(tail) - for match in matcher.finditer(data): - results.append(base + match.start()) - if limit is not None and len(results) >= limit: - return results - tail = data[-overlap:] if overlap else b"" - position += len(chunk) - return results - - -def disassemble(expression: str, offset_or_address: str) -> list[tuple[str, str, str]]: - """Disassembles the address evaluated by the given expression - - Args: - expression (str): Any gdb expression - offset_or_address (str): If you pass this parameter as an offset, you should add "+" in front of it - (e.g "+42" or "+0x42"). If you pass this parameter as an hex address, the address range between the expression - and the secondary address is disassembled - If the second parameter is an address, it always should be bigger than the first address - - Returns: - list: A list of str values in this format-->[(address1, bytes1, instr1), (address2, ...), ...] - """ - output = send_command("disas /r " + expression + "," + offset_or_address) - disas_data = [] - for line in output.splitlines(): - result = regexes.disassemble_output.search(line) - if result: - disas_data.append(result.groups()) - return disas_data - - -def convert_to_hex(expression: str) -> str: - """Converts numeric values in the expression into their hex equivalents - Respects edge cases like indexed maps and keeps indices as decimals - - Args: - expression (str): Any gdb expression - - Returns: - str: Converted str - """ - # TODO (lldb): We'll most likely write our own expression parser once we switch to lldb - # Merge this function with examine_expression and gdbutils.examine_expression once that happens - return regexes.expression_with_hex.sub( - lambda m: "0x" + m.group(1) if m.group(1) and not examine_expression(m.group(1)).symbol else m.group(0), - expression, - ) - - -def examine_expression(expression: str) -> typedefs.tuple_examine_expression: - """Evaluates the given expression and returns evaluated value, address and symbol - - Args: - expression (str): Any gdb expression - - Returns: - typedefs.tuple_examine_expression: Evaluated value, address and symbol in a tuple - Any erroneous field will be returned as None instead of str - """ - if currentpid == -1: - return typedefs.tuple_examine_expression(None, None, None) - result = send_command("pince-examine-expressions", send_with_file=True, file_contents_send=[expression], recv_with_file=True) - if not result: - return typedefs.tuple_examine_expression(None, None, None) - return result[0] - - -def examine_expressions(expression_list: list[str]) -> list[typedefs.tuple_examine_expression]: - """Optimized version of examine_expression for multiple inputs - - Args: - expression_list (list): List of gdb expressions as str - - Returns: - list: List of typedefs.tuple_examine_expression - """ - if not expression_list: - return [] - if currentpid == -1: - return [typedefs.tuple_examine_expression(None, None, None) for _ in range(len(expression_list))] - result = send_command("pince-examine-expressions", send_with_file=True, file_contents_send=expression_list, recv_with_file=True) - if not result: - return [typedefs.tuple_examine_expression(None, None, None) for _ in range(len(expression_list))] - return result - - -def parse_and_eval(expression: str, cast: type = str) -> Any: - """Calls gdb.parse_and_eval with the given expression and returns the value after casting with the given type - Use examine_expression if your data can be expressed as an address or a symbol, use this function otherwise - Unlike examine_expression, this function can read data that has void type or multiple type representations - For instance: - - - $eflags has both str and int reprs - - $_siginfo is a struct with many fields - - x64 register convenience vars such as $rax are void if the process is x86 - - Args: - expression (str): Any gdb expression - cast (type): Evaluated value will be cast to this type in gdb - - Returns: - cast: Self-explanatory - None: If casting fails - """ - return send_command("pince-parse-and-eval", send_with_file=True, file_contents_send=(expression, cast), recv_with_file=True) - - -def _refresh_main_module_info() -> None: - """Caches main module info for static address checking. Called by attach() and create_process(). - - Identifies the main module and whether its address is static (no ASLR or PIE) or not: - - Native Linux: main module is /proc/PID/exe. Static if ET_EXEC (non-PIE). - - Windows PE under WINE: main module is the first .exe with executable permissions in /proc/PID/maps. - Static if DllCharacteristics has the IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE bit cleared. - """ - global _main_module_is_static, _main_module_ranges - _main_module_is_static = False - _main_module_ranges = [] - if currentpid == -1: - return - try: - exe_link = os.readlink(f"/proc/{currentpid}/exe") - except OSError: - return - - if "wine" in os.path.basename(exe_link).lower(): - # Running under WINE, find the launched .exe in maps. - # Note: WINE/Proton maps PE files as r--p (no x bit), so we don't filter on permissions. - module_path = next( - (path for _, _, _, _, _, _, path in utils.get_regions(currentpid) if path.lower().endswith(".exe")), - None, - ) - if module_path is None: - return - else: - module_path = exe_link - - try: - with open(module_path, "rb") as f: - magic = f.read(4) - if magic.startswith(b"\x7fELF"): - f.seek(0x05) # EI_DATA - byteorder = {b"\x01": "little", b"\x02": "big"}.get(f.read(1)) - if byteorder is None: - return # Invalid ELF data encoding - f.seek(0x10) - is_static = int.from_bytes(f.read(2), byteorder) == 2 # ET_EXEC - elif magic[:2] == b"MZ": - f.seek(0x3C) - pe_offset = int.from_bytes(f.read(4), "little") # PE mandates little endian, regardless of sys arch. - f.seek(pe_offset) - if f.read(4) != b"PE\x00\x00": - return - f.seek(pe_offset + 4 + 20 + 0x46) # COFF header + DllCharacteristics offset - is_static = (int.from_bytes(f.read(2), "little") & 0x40) == 0 # IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE - else: - return - _main_module_is_static = is_static - except (OSError, ValueError): - return - - if _main_module_is_static: - # Cache the module's ranges now so is_address_static() is a plain memory check, not a maps read per address. - _main_module_ranges = [ - (int(start, 16), int(end, 16)) for start, end, _, _, _, _, path in utils.get_regions(currentpid) if path == module_path - ] - - -def is_address_static(address: str | int) -> bool: - """Checks if the given address is a static address - - Returns True only for addresses inside the main module when that module is loaded at a fixed base: - - Native Linux: non-PIE ELF (ET_EXEC) - - WINE/Proton Windows: PE without IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE - Everything else is subject to ASLR. - - Args: - address (str | int): Address to check, in either hex str or int format - - Returns: - bool: True if the absolute address is static across restarts, False otherwise - """ - if currentpid == -1 or not _main_module_is_static: - return False - if isinstance(address, str): - address_str = utils.extract_hex_address(address) - if not address_str: - logger.error(f"Invalid hex address string '{address}'") - return False - address = int(address_str, 16) - elif not isinstance(address, int): - logger.error(f"Passed wrong type '{type(address)}' instead of str or int") - return False - return any(start <= address < end for start, end in _main_module_ranges) - - -def get_thread_info() -> str | None: - """Invokes "info threads" command and returns the line corresponding to the current thread - - Returns: - str: Current thread information - None: If the output doesn't fit the regex - """ - thread_info = send_command("info threads") - current_thread = regexes.thread_info.search(thread_info) - if not current_thread: - return - return re.sub(r'\\"', r'"', current_thread.group(1)) - - -def find_closest_instruction_address(address: str, instruction_location: str = "next", instruction_count: int = 1) -> str | None: - """Finds address of the closest instruction next to the given address, assuming that the given address is valid - - Args: - address (str): Hex address or any gdb expression that can be used in disas command - instruction_location (str): If it's "next", instructions coming after the address is searched - If it's "previous", the instructions coming before the address is searched instead - instruction_count (int): Number of the instructions that'll be looked for - - Returns: - str: The address found as hex string. If starting/ending of a valid memory range is reached, starting/ending - address is returned instead as hex string. - None: If the given address is not in a valid memory region. - - Note: - From gdb version 7.12 and onwards, inputting negative numbers in x command are supported(x/-3i for instance) - So, modifying this function according to the changes in 7.12 may speed up things a little bit but also breaks - the backwards compatibility. The speed gain is not much of a big deal compared to backwards compatibility, so - I'm not changing this function for now - """ - if instruction_location not in ("next", "previous"): - raise ValueError(f"invalid instruction_location: {instruction_location!r}") - region_info = utils.get_region_info(currentpid, address) - if region_info is None: - return - if instruction_location == "next": - offset = "+" + str(instruction_count * 30) - disas_data = disassemble(address, address + offset) - else: - offset = "-" + str(instruction_count * 30) - disas_data = disassemble(address + offset, address) - if not disas_data: - if instruction_location != "next": - start_address = hex(region_info.start) - disas_data = disassemble(start_address, address) - if instruction_location == "next": - try: - return utils.extract_hex_address(disas_data[instruction_count][0]) - except IndexError: - return hex(region_info.end) - else: - try: - return utils.extract_hex_address(disas_data[-instruction_count][0]) - except IndexError: - try: - return start_address - except UnboundLocalError: - return hex(region_info.start) - - -def get_address_info(expression: str) -> str: - """Runs the gdb command "info symbol" for given expression and returns the result of it - - Args: - expression (str): Any gdb expression - - Returns: - str: The result of the command "info symbol" for given expression - """ - return send_command("info symbol " + expression, cli_output=True) - - -def get_symbol_info(expression: str) -> str: - """Runs the gdb command "info address" for given expression and returns the result of it - - Args: - expression (str): Any gdb expression - - Returns: - str: The result of the command "info address" for given expression - """ - return send_command("info address " + expression, cli_output=True) - - -def search_functions(expression: str, case_sensitive: bool = False) -> list: - """Runs the gdb command "info functions" for given expression and returns the result of it - - Args: - expression (str): Any gdb expression - case_sensitive (bool): If True, search will be case sensitive - - Returns: - list: A list of str-->[(address1, symbol1), (address2, symbol2), ...] - address will be None if the corresponding symbol is in defined category - - Todo: - GDB-MI wiki points out to the command -symbol-list-functions but apparently it isn't implemented yet - If the feature below gets implemented, use it instead - https://sourceware.org/bugzilla/show_bug.cgi?id=23796 - - Add ability to show addresses of defined symbols when it gets implemented by gdb - Please don't try to write a symbol parser for every single language out there, it's an overkill - https://sourceware.org/bugzilla/show_bug.cgi?id=23899 - """ - return send_command( - "pince-search-functions", - send_with_file=True, - file_contents_send=(expression, case_sensitive), - recv_with_file=True, - ) - - -def get_inferior_pid() -> str | None: - """Get pid of the current inferior - - Returns: - str: pid - None: If the output doesn't fit the regex - """ - output = send_command("info inferior") - inferior_pid = regexes.inferior_pid.search(output) - if not inferior_pid: - return - return inferior_pid.group(1) - - -def get_inferior_arch() -> int: - """Returns the architecture of the current inferior - - Returns: - int: A member of typedefs.INFERIOR_ARCH - """ - if parse_and_eval("$rax") == "void": - return typedefs.INFERIOR_ARCH.ARCH_32 - return typedefs.INFERIOR_ARCH.ARCH_64 - - -def read_registers() -> dict[str, str | None]: - """Returns the current registers - - Returns: - dict[str, str | None]: A dict that holds general, flag and segment registers. Check typedefs.REGISTERS for the - full list. Segment register values may be None when the register can't be resolved - """ - return send_command("pince-read-registers", recv_with_file=True) or {} - - -def read_float_registers() -> OrderedDict[str, str]: - """Returns the current floating point registers - - Returns: - OrderedDict[str, str]: A dict that holds floating point registers. Check typedefs.REGISTERS.FLOAT for the full list - - Note: - Returned xmm values are based on xmm.v4_float - """ - return send_command("pince-read-float-registers", recv_with_file=True) or OrderedDict() - - -def set_convenience_variable(variable: str, value: str) -> None: - """Sets given convenience variable to given value - Can be also used for modifying registers directly - - Args: - variable (str): Any gdb convenience variable(with "$" character removed) - value (str): Anything - """ - send_command("set $" + variable + "=" + value) - - -def set_register_flag(flag: str, value: int | str) -> None: - """Sets given register flag to given value - - Args: - flag (str): A member of typedefs.REGISTERS.FLAG - value (Union[int,str]): 0 or 1 - """ - value = str(value) - if value != "0" and value != "1": - raise Exception(value + " isn't valid value. It can be only 0 or 1") - if flag not in typedefs.REGISTERS.FLAG: - raise Exception(flag + " isn't a valid flag, must be a member of typedefs.REGISTERS.FLAG") - flag_index = typedefs.REGISTERS.FLAG.index(flag) - # EFLAGS has reserved gaps at bits 1, 3 and 5, which typedefs.REGISTERS.FLAG omits. - flag_bit = flag_index + min(flag_index, 3) - flag_mask = 1 << flag_bit - eflags = parse_and_eval("$eflags", int) - if eflags is None: - raise Exception("Couldn't read $eflags") - if value == "1": - eflags |= flag_mask - else: - eflags &= ~flag_mask - set_convenience_variable("eflags", hex(eflags)) - - -def get_stacktrace_info() -> list: - """Returns information about current stacktrace - - Returns: - list: A list of str values in this format-->[[return_address_info1,frame_address_info1],[info2, ...], ...] - - return_address_info looks like this-->Return address of frame+symbol-->0x40c431 <_start> - frame_address_info looks like this-->Beginning of frame+distance from stack pointer-->0x7ffe1e989a40(rsp+0x100) - """ - return send_command("pince-get-stack-trace-info", recv_with_file=True) - - -def get_stack_info(from_base_pointer: bool = False) -> list[str]: - """Returns information about current stack - Also can view stack from EBP or RBP register - - Returns: - list: A list of str values in this format--▼ - [[stack_pointer_info1,hex_value1,pointer_info1],[stack_pointer_info2, ...], ...] - - stack_pointer_info looks like this-->Hex address+distance from stack pointer-->0x7ffd0d232f88(rsp+0xff8) - hex_value looks like this-->Value hold by corresponding address-->0x1bfda20 - pointer_info shows the value hold by hex_value address. It looks like this--▼ - if points to a string-->(str)Some String - if points to a symbol-->(ptr) - pointer_info becomes a null string if pointer isn't valid - """ - if from_base_pointer: - return send_command("pince-get-stack-info from-base-pointer", recv_with_file=True) - else: - return send_command("pince-get-stack-info", recv_with_file=True) - - -def get_stack_frame_return_addresses() -> list: - """Returns return addresses of stack frames - - Returns: - list: A list of str values in this format-->[return_address_info1,return_address_info2, ...] - - return_address_info looks like this-->Return address of frame+symbol-->0x40c431 <_start> - """ - return send_command("pince-get-frame-return-addresses", recv_with_file=True) - - -def get_stack_frame_info(index: int | str) -> str: - """Returns information about stack by the given index - - Args: - index (int,str): Index of the frame - - Returns: - str: Information that looks like this:: - - Stack level 0, frame at 0x7ffc5f87f6a0: - rip = 0x7fd1d639412d in poll (../sysdeps/unix/syscall-template.S:81); saved rip = 0x7fd1d27fcfe4 - called by frame at 0x7ffc5f87f700 - source language asm. - Arglist at 0x7ffc5f87f688, args: - Locals at 0x7ffc5f87f688, Previous frame's sp is 0x7ffc5f87f6a0 - Saved registers: - rip at 0x7ffc5f87f698 - """ - return send_command("pince-get-frame-info", send_with_file=True, file_contents_send=str(index), recv_with_file=True) - - -def hex_dump(address: int, offset: int) -> list[str]: - """Returns hex dump of range (address to address+offset) - - Args: - address (int): Self-explanatory - offset (int): The range that'll be read - - Returns: - list: List of byte values read as uppercase hex strings. Unreadable bytes are returned as "??". - - Examples: - returned list-->["??","??","??","7f","43","67","40","??","??, ...] - """ - hex_byte_list = [] - with memory_handle() as mem_handle: - for i in range(offset): - try: - mem_handle.seek(address + i) - byte = mem_handle.read(1) - current_item = format(byte[0], "02X") if byte else "??" - except (OSError, ValueError, IndexError): - current_item = "??" - hex_byte_list.append(current_item) - return hex_byte_list - - -def get_modified_instructions() -> dict: - """Returns currently modified instructions - - Returns: - dict: A dictionary where the key is the start address of instruction and value is the aob before modifying - - """ - return modified_instructions_dict.get(current_process_identity, {}) - - -def nop_instruction(start_address: int, length: int) -> None: - """Writes length NOPs beginning at start_address - - Args: - start_address (int): Self-explanatory - length (int): how many NOPs - - Returns: - None - """ - old_aob = " ".join(hex_dump(start_address, length)) - if "??" in old_aob: - logger.warning(f"Cannot NOP instruction at {hex(start_address)}: unreadable bytes in original opcodes") - return - table = modified_instructions_dict.setdefault(current_process_identity, {}) - if start_address not in table: - table[start_address] = old_aob - - nop_aob = " ".join(["90"] * length) - write_memory(start_address, typedefs.ByteArrayValueType(length), nop_aob) - instructions_changed.emit() - - -def modify_instruction(start_address: int, array_of_bytes: str) -> None: - """Replaces an instruction's opcodes with new bytes - - Args: - start_address (int): Self-explanatory - array_of_bytes (str): String that contains the replacement bytes of the instruction - - Returns: - None - """ - length = len(array_of_bytes.split()) - old_aob = " ".join(hex_dump(start_address, length)) - if "??" in old_aob: - logger.warning(f"Cannot modify instruction at {hex(start_address)}: unreadable bytes in original opcodes") - return - - table = modified_instructions_dict.setdefault(current_process_identity, {}) - if start_address not in table: - table[start_address] = old_aob - write_memory(start_address, typedefs.ByteArrayValueType(length), array_of_bytes) - instructions_changed.emit() - - -def restore_instruction(start_address: int) -> None: - """Restores a modified instruction to its original opcodes - - Args: - start_address (int): Self-explanatory - - Returns: - None - """ - table = modified_instructions_dict.get(current_process_identity) - if not table or start_address not in table: - return - array_of_bytes = table.pop(start_address) - write_memory(start_address, typedefs.ByteArrayValueType(len(array_of_bytes.split())), array_of_bytes) - instructions_changed.emit() - - -def get_breakpoint_info() -> list[typedefs.tuple_breakpoint_info]: - """Returns current breakpoint/watchpoint list - - Returns: - list: A list of typedefs.tuple_breakpoint_info where; - number is the gdb breakpoint number - breakpoint_type is the breakpoint type - disp shows what will be done after breakpoint hits - enabled shows if the breakpoint enabled or disabled - address is the address of breakpoint - size is the size of breakpoint - on_hit is the action that'll happen when the breakpoint is reached - hit_count shows how many times the breakpoint has been hit - enable_count shows how many times the breakpoint will get hit before it gets disabled - condition is the condition of breakpoint - - size-->int - everything else-->str - - Note: - GDB's python API can't detect hardware breakpoints, that's why we are using parser for this job - """ - returned_list = [] - multiple_break_data = OrderedDict() - raw_info = send_command("-break-list") - if not raw_info: - return returned_list - # Temporary fix for https://sourceware.org/bugzilla/show_bug.cgi?id=9659 - # TODO:Delete this line when gdb or pygdbmi fixes the problem - raw_info = re.sub(r"script={(.*?)}", r"script=[\g<1>]", raw_info) # Please refer to issue #53 - for item in utils.parse_response(raw_info)["payload"]["BreakpointTable"]["body"]: - item = defaultdict(lambda: "", item) - number, breakpoint_type, disp, enabled, address, what, condition, hit_count, enable_count = ( - item["number"], - item["type"], - item["disp"], - item["enabled"], - item["addr"], - item["what"], - item["cond"], - item["times"], - item["enable"], - ) - if address == "": - multiple_break_data[number] = (breakpoint_type, disp, condition, hit_count) - continue - if not breakpoint_type: - number = number.split(".")[0] - if number not in multiple_break_data: - continue - breakpoint_type, disp, condition, hit_count = multiple_break_data[number] - if what: - address = utils.extract_hex_address(what) - if not address: - address = examine_expression(what).address - on_hit_dict_value = breakpoint_on_hit_dict.get(number, typedefs.BREAKPOINT_ON_HIT.BREAK) - on_hit = typedefs.on_hit_to_text_dict.get(on_hit_dict_value, "Unknown") - if breakpoint_type.find("breakpoint") >= 0: - size = 1 - else: - possible_size = regexes.breakpoint_size.search(what) - if possible_size: - size = int(possible_size.group(1)) - else: - size = 1 - returned_list.append( - typedefs.tuple_breakpoint_info(number, breakpoint_type, disp, enabled, address, size, on_hit, hit_count, enable_count, condition) - ) - return returned_list - - -def get_breakpoints_in_range(address: str | int, length: int = 1) -> list[typedefs.tuple_breakpoint_info]: - """Checks if given address exists in breakpoint list - - Args: - address (str,int): Start address of the range, hex address or an int - length (int): If this parameter is bigger than 1, the range between address and address+length-1 will be - checked instead of just the address itself - - Returns: - list: A list of typedefs.tuple_breakpoint_info, info of the existing breakpoints for given address range - """ - breakpoint_list = [] - if type(address) != int: - address = safe_str_to_int(address, 0) - if address == 0: - return breakpoint_list - max_address = max(address, address + length - 1) - min_address = min(address, address + length - 1) - breakpoint_info = get_breakpoint_info() - for item in breakpoint_info: - breakpoint_address = safe_str_to_int(item.address, 16) - if not (max_address < breakpoint_address or min_address > breakpoint_address + item.size - 1): - breakpoint_list.append(item) - return breakpoint_list - - -def _get_watchpoint_ranges(address: int, length: int, max_length: int) -> list[tuple[int, int]]: - ranges = [] - while length > 0: - slot_length = min(max_length, 1 << (length.bit_length() - 1)) - while address % slot_length: - slot_length //= 2 - ranges.append((address, slot_length)) - address += slot_length - length -= slot_length - return ranges - - -def hardware_breakpoint_available(required_slots: int = 1) -> bool: - """Checks if enough hardware breakpoint slots are available - - Args: - required_slots (int): Number of slots required - - Returns: - bool: True if enough slots are available, False if not - - Todo: - Check debug registers to determine hardware breakpoint state rather than relying on gdb output because inferior - might modify its own debug registers - """ - hw_bp_total = 0 - max_length = 8 if inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 else 4 - for item in get_breakpoint_info(): - if regexes.hw_breakpoint_count.search(item.breakpoint_type): - if "breakpoint" in item.breakpoint_type: - hw_bp_total += 1 - else: - hw_bp_total += len(_get_watchpoint_ranges(safe_str_to_int(item.address, 16), item.size, max_length)) - - # Maximum number of hardware breakpoints is limited to 4 in x86 architecture - return hw_bp_total + required_slots <= 4 - - -def add_breakpoint( - expression: str, - breakpoint_type: int = typedefs.BREAKPOINT_TYPE.HARDWARE, - on_hit: int = typedefs.BREAKPOINT_ON_HIT.BREAK, -) -> int | None: - """Adds a breakpoint at the address evaluated by the given expression. Uses a software breakpoint if all hardware - breakpoint slots are being used - - Args: - expression (str): Any gdb expression - breakpoint_type (int): Can be a member of typedefs.BREAKPOINT_TYPE - on_hit (int): Can be a member of typedefs.BREAKPOINT_ON_HIT - - Returns: - int: Number of the breakpoint set - None: If setting breakpoint fails - """ - output = "" - str_address = examine_expression(expression).address - if not str_address: - logger.error(f"Failed to add breakpoint. Expression {expression} is not valid") - return - if get_breakpoints_in_range(str_address): - logger.error(f"Breakpoint/Watchpoint for address {str_address} is already set") - return - if breakpoint_type == typedefs.BREAKPOINT_TYPE.HARDWARE: - if hardware_breakpoint_available(): - output = send_command("hbreak *" + str_address) - else: - logger.warning("All hardware breakpoint slots are being used, using a software breakpoint instead") - output = send_command("break *" + str_address) - elif breakpoint_type == typedefs.BREAKPOINT_TYPE.SOFTWARE: - output = send_command("break *" + str_address) - if regexes.breakpoint_created.search(output): - global breakpoint_on_hit_dict - breakpoint_number = regexes.breakpoint_number.search(output) - if not breakpoint_number: - logger.error(f"Failed to extract breakpoint number from GDB output: {output}") - return - number = breakpoint_number.group(1) - breakpoint_on_hit_dict[number] = on_hit - breakpoints_changed.emit() - return int(number) - else: - return - - -@execute_with_temporary_interruption -def add_watchpoint( - expression: str, - length: int = 4, - watchpoint_type: int = typedefs.WATCHPOINT_TYPE.BOTH, - on_hit: int = typedefs.BREAKPOINT_ON_HIT.BREAK, -) -> list[str] | None: - """Adds a watchpoint at the address evaluated by the given expression - - Args: - expression (str): Any gdb expression - length (int): Length of the watchpoint - watchpoint_type (int): Can be a member of typedefs.WATCHPOINT_TYPE - on_hit (int): Can be a member of typedefs.BREAKPOINT_ON_HIT - - Returns: - list: Numbers of the successfully set breakpoints as strings - None: If setting watchpoint fails - """ - str_address = examine_expression(expression).address - if not str_address: - logger.error(f"Expression '{expression}' for watchpoint is not valid") - return - if watchpoint_type == typedefs.WATCHPOINT_TYPE.WRITE_ONLY: - watch_command = "watch" - elif watchpoint_type == typedefs.WATCHPOINT_TYPE.READ_ONLY: - watch_command = "rwatch" - elif watchpoint_type == typedefs.WATCHPOINT_TYPE.BOTH: - watch_command = "awatch" - str_address_int = int(str_address, 16) - watchpoints = _get_watchpoint_ranges(str_address_int, length, 8 if get_inferior_arch() == typedefs.INFERIOR_ARCH.ARCH_64 else 4) - if not watchpoints: - return [] - if get_breakpoints_in_range(str_address_int, length): - logger.error(f"Breakpoint/Watchpoint for address {hex(str_address_int)} is already set. Bailing out...") - return - if not hardware_breakpoint_available(len(watchpoints)): - logger.error("All hardware breakpoint slots are being used, unable to set a new watchpoint. Bailing out...") - return - breakpoints_set = [] - for str_address_int, breakpoint_length in watchpoints: - cmd = f"{watch_command} * (char[{breakpoint_length}] *) {hex(str_address_int)}" - output = execute_func_temporary_interruption(send_command, cmd) - if not regexes.breakpoint_created.search(output): - logger.error(f"Failed to create a watchpoint at address {hex(str_address_int)}. Bailing out...") - break - breakpoint_number_match = regexes.breakpoint_number.search(output) - if not breakpoint_number_match: - logger.error(f"Failed to extract watchpoint number from GDB output: {output}") - break - breakpoints_set.append(breakpoint_number_match.group(1)) - else: - breakpoint_on_hit_dict.update(dict.fromkeys(breakpoints_set, on_hit)) - chained_breakpoints.append([safe_int_cast(breakpoint) for breakpoint in breakpoints_set]) - breakpoints_changed.emit() - return breakpoints_set - for breakpoint_number in breakpoints_set: - send_command(f"delete {breakpoint_number}") - - -def modify_breakpoint(breakpoint_number: int, modify_what: int, condition: str | None = None, count: int | None = None) -> bool: - """Adds a condition to an existing breakpoint - - Args: - breakpoint_number (int): Breakpoint number in gdb - modify_what (typedefs.BREAKPOINT_MODIFY): This param controls how the function modifies the breakpoint: - - Modifies condition of the breakpoint if CONDITION - - Enables the breakpoint if ENABLE - - Disables the breakpoint if DISABLE - - Enables once then disables after hit if ENABLE_ONCE - - Enables for specified count then disables after the count is reached if ENABLE_COUNT - - Enables once then deletes the breakpoint if ENABLE_DELETE - condition (str | None): Any gdb condition expression. This parameter is only used if modify_what passed as CONDITION - count (int | None): Only used if modify_what passed as ENABLE_COUNT - - Returns: - bool: True if the condition has been set successfully, False otherwise - - Examples: - modify_what-->typedefs.BREAKPOINT_MODIFY.CONDITION - condition-->$eax==0x523 - condition-->$rax>0 && ($rbp<0 || $rsp==0) - condition-->printf($r10)==3 - - modify_what-->typedefs.BREAKPOINT_MODIFY.ENABLE_COUNT - count-->10 - """ - modification_list = [breakpoint_number] - global chained_breakpoints - for _, item in enumerate(chained_breakpoints): - if breakpoint_number in item: - modification_list = item - break - for breakpoint in modification_list: - if modify_what == typedefs.BREAKPOINT_MODIFY.CONDITION: - if condition is None: - logger.error("Missing condition for breakpoint modification") - return False - command = f"condition {breakpoint} {condition}" - elif modify_what == typedefs.BREAKPOINT_MODIFY.ENABLE: - command = f"enable {breakpoint}" - elif modify_what == typedefs.BREAKPOINT_MODIFY.DISABLE: - command = f"disable {breakpoint}" - elif modify_what == typedefs.BREAKPOINT_MODIFY.ENABLE_ONCE: - command = f"enable once {breakpoint}" - elif modify_what == typedefs.BREAKPOINT_MODIFY.ENABLE_COUNT: - if count is None: - logger.error("Missing count parameter for ENABLE_COUNT breakpoint modification") - return False - elif count < 1: - logger.error(f"Count parameter can't be less than 1 for ENABLE_COUNT breakpoint modification") - return False - command = f"enable count {count} {breakpoint}" - elif modify_what == typedefs.BREAKPOINT_MODIFY.ENABLE_DELETE: - command = f"enable delete {breakpoint}" - else: - logger.error("Parameter modify_what is not valid") - return False - if regexes.gdb_error.search(send_command(command)): - return False - breakpoints_changed.emit() - return True - - -def delete_breakpoint(breakpoint_number: int) -> bool: - """Deletes a breakpoint by given number - - Args: - breakpoint_number (int) - - Returns: - bool: True if the breakpoint has been deleted successfully, False otherwise - """ - deletion_list = [breakpoint_number] - chained_index = None - global chained_breakpoints - for n, item in enumerate(chained_breakpoints): - if breakpoint_number in item: - deletion_list = item - chained_index = n - break - for breakpoint in deletion_list: - if regexes.gdb_error.search(send_command(f"delete {breakpoint}")): - return False - global breakpoint_on_hit_dict - for breakpoint in deletion_list: - breakpoint_on_hit_dict.pop(str(breakpoint), None) - if chained_index is not None: - del chained_breakpoints[chained_index] - breakpoints_changed.emit() - return True - - -@execute_with_temporary_interruption -def track_watchpoint(expression: str, length: int, watchpoint_type: int) -> list[str] | None: - """Starts tracking a value by setting a watchpoint at the address holding it - Use get_track_watchpoint_info() to get info about the watchpoint you set - - Args: - expression (str): Any gdb expression - length (int): Length of the watchpoint - watchpoint_type (int): Can be a member of typedefs.WATCHPOINT_TYPE - - Returns: - list: Numbers of the successfully set breakpoints as strings - None: If fails to set any watchpoint - """ - breakpoints = add_watchpoint(expression, length, watchpoint_type, typedefs.BREAKPOINT_ON_HIT.FIND_CODE) - if not breakpoints: - return - for breakpoint in breakpoints: - send_command("commands " + breakpoint + "\npince-get-track-watchpoint-info " + str(breakpoints) + "\nc&" + "\nend") - return breakpoints - - -def get_track_watchpoint_info(watchpoint_list: list) -> dict | str: - """Gathers the information for the tracked watchpoint(s) - - Args: - watchpoint_list (list): A list that holds the watchpoint numbers, must be returned from track_watchpoint() - - Returns: - dict: Holds the program counter addresses at the moment watchpoint hits as keys - Format of dict--> {address1:info_list1, address2:info_list2, ...} - Format of info_list--> [count, previous_pc_address, register_info, float_info, disas_info] - count-->(int) Count of the hits for the same pc address - previous_pc_address-->(str) The address of the instruction that comes before the instruction pc address - holds. If there's no previous address available(end of region etc.), previous_pc_address=pc_address - register_info-->(dict) Same dict returned from read_registers() - float_info-->(dict) Same dict returned from read_float_registers() - disas_info-->(str) A small section that's disassembled just after previous_pc_counter - """ - track_watchpoint_file = utils.get_track_watchpoint_file(currentpid, watchpoint_list) - try: - with open(track_watchpoint_file, "rb") as track_watchpoint_handle: - output = pickle.load(track_watchpoint_handle) - except Exception: - output = "" - return output - - -@execute_with_temporary_interruption -def track_breakpoint(expression: str, register_expressions: str) -> int | None: - """Starts tracking a value by setting a breakpoint at the address holding it - Use get_track_breakpoint_info() to get info about the breakpoint you set - - Args: - expression (str): Any gdb expression - register_expressions (str): Register expressions, separated by a comma. Registers should start with "$" - PINCE will gather info about values presented by register expressions every time the breakpoint is reached - For instance, passing "$rax,$rcx+5,$rbp+$r12" will make PINCE track values rax, rcx+5 and rbp+r12 - - Returns: - int: Number of the breakpoint set - None: If fails to set any breakpoint - """ - breakpoint = add_breakpoint(expression, on_hit=typedefs.BREAKPOINT_ON_HIT.FIND_ADDR) - if not breakpoint: - return - # TODO (lldb): When we switch to LLDB, remove c& and only continue if there isn't an active trace - # Apply the same for track_watchpoint - send_command(f"commands {breakpoint}\npince-get-track-breakpoint-info {register_expressions.replace(' ', '')},{breakpoint}\nc&\nend") - return breakpoint - - -def get_track_breakpoint_info(breakpoint_number: int) -> dict | str: - """Gathers the information for the tracked breakpoint - - Args: - breakpoint_number (int): breakpoint number, must be returned from track_breakpoint() - - Returns: - dict: Holds the register expressions as keys and their info as values - Format of dict--> {expression1:expression_info_dict1, expression2:expression_info_dict2, ...} - expression-->(str) The register expression - Format of expression_info_dict--> {value1:count1, value2:count2, ...} - value-->(str) Value calculated by given register expression as hex str - count-->(int) How many times this expression has been reached - """ - track_breakpoint_file = utils.get_track_breakpoint_file(currentpid, breakpoint_number) - try: - with open(track_breakpoint_file, "rb") as track_breakpoint_handle: - output = pickle.load(track_breakpoint_handle) - except Exception: - output = "" - return output - - -class Tracer: - def __init__(self) -> None: - """Use set_breakpoint after init and if it succeeds, use tracer_loop within a thread - There can be only one trace session at a time. Don't create new trace sessions before finishing the last one""" - self.bp_num = -1 - self.max_trace_count = 1000 - self.stop_condition = "" - self.step_mode = typedefs.STEP_MODE.SINGLE_STEP - self.stop_after_trace = False - self.collect_registers = True - self.trace_status = typedefs.TRACE_STATUS.IDLE - self.current_trace_count = 0 - self.trace_data = ([], None) - self.cancel = False - utils.change_trace_status(currentpid, self.trace_status) - - @execute_with_temporary_interruption - def set_breakpoint( - self, - expression: str, - max_trace_count: int = 1000, - trigger_condition: str = "", - stop_condition: str = "", - step_mode: typedefs.STEP_MODE = typedefs.STEP_MODE.SINGLE_STEP, - stop_after_trace: bool = False, - collect_registers: bool = True, - ) -> int | None: - """Sets the breakpoint for tracing instructions at the address evaluated by the given expression - - Args: - expression (str): Any gdb expression - max_trace_count (int): Maximum number of steps taken while tracing. Must be greater than or equal to 1 - trigger_condition (str): Optional, any gdb expression. Tracing will start if the condition is met - stop_condition (str): Optional, any gdb expression. Tracing will stop whenever the condition is met - step_mode (int): Can be a member of typedefs.STEP_MODE - stop_after_trace (bool): Inferior won't be continuing after the tracing process - collect_registers (bool): Collect registers while stepping - - Returns: - int: Number of the breakpoint set - None: If fails to set any breakpoint or if max_trace_count is not valid - """ - if type(max_trace_count) != int: - logger.error(f"max_trace_count must be an integer. Was given type '{type(max_trace_count)}'") - return - if max_trace_count < 1: - logger.error("max_trace_count must be greater than or equal to 1") - return - breakpoint = add_breakpoint(expression, on_hit=typedefs.BREAKPOINT_ON_HIT.TRACE) - if not breakpoint: - return - modify_breakpoint(breakpoint, typedefs.BREAKPOINT_MODIFY.CONDITION, condition=trigger_condition) - ( - self.bp_num, - self.max_trace_count, - self.stop_condition, - self.step_mode, - self.stop_after_trace, - self.collect_registers, - ) = (breakpoint, max_trace_count, stop_condition, step_mode, stop_after_trace, collect_registers) - send_command(f"commands {breakpoint}\npince-trace-instructions\nend") - return breakpoint - - def tracer_loop(self) -> None: - """The main tracer loop, call within a thread""" - self.current_trace_count = 0 - trace_status_file = utils.get_trace_status_file(currentpid) - while not (self.trace_status != typedefs.TRACE_STATUS.IDLE or self.cancel or currentpid == -1): - try: - with open(trace_status_file, "r") as trace_file: - self.trace_status = int(trace_file.read()) - except (ValueError, FileNotFoundError): - pass - sleep(0.1) - if self.cancel or currentpid == -1: - delete_breakpoint(self.bp_num) - self.trace_status = typedefs.TRACE_STATUS.FINISHED - return - global driving_inferior - driving_inferior = True - delete_breakpoint(self.bp_num) - self.trace_status = typedefs.TRACE_STATUS.TRACING - - # The reason we don't use a tree class is to make the tree json-compatible - # tree format-->[node1, node2, node3, ...] - # node-->[(line_info, register_dict), parent_index, child_index_list] - tree = [] - current_index = 0 # Avoid calling len() - current_root_index = 0 - root_index = 0 - - # Root always be an empty node, it's up to you to use or delete it - tree.append([("", None), None, []]) - try: # In case process exits during the trace session - for x in range(self.max_trace_count): - if self.cancel or currentpid == -1: - break - output_lines = send_command("x/i $pc", cli_output=True).splitlines() - if not output_lines: - logger.warning("empty GDB output, stopping trace") - break - line_parts = output_lines[0].split(maxsplit=1) - if len(line_parts) < 2: - logger.warning("unexpected GDB output format, stopping trace") - break - line_info = line_parts[1] - collect_dict = OrderedDict() - if self.collect_registers: - collect_dict.update(read_registers()) - collect_dict.update(read_float_registers()) - current_index += 1 - tree.append([(line_info, collect_dict), current_root_index, []]) - tree[current_root_index][2].append(current_index) # Add a child - self.current_trace_count = x + 1 - if regexes.trace_instructions_ret.search(line_info): - if tree[current_root_index][1] is None: # If no parents exist - current_index += 1 - tree.append([("", None), None, [current_root_index]]) - tree[current_root_index][1] = current_index # Set new parent - current_root_index = current_index # current_node=current_node.parent - root_index = current_root_index # set new root - else: - current_root_index = tree[current_root_index][1] # current_node=current_node.parent - elif self.step_mode == typedefs.STEP_MODE.SINGLE_STEP: - if regexes.trace_instructions_call.search(line_info): - current_root_index = current_index - if self.stop_condition: - try: - if str(parse_and_eval(self.stop_condition)) == "1": - break - except Exception: - pass - if self.step_mode == typedefs.STEP_MODE.SINGLE_STEP: - step_instruction() - elif self.step_mode == typedefs.STEP_MODE.STEP_OVER: - step_over_instruction() - while inferior_status == typedefs.INFERIOR_STATUS.RUNNING and not (self.cancel or currentpid == -1): - wait_for_stop(0.1) - except Exception: - traceback.print_exc() - self.trace_data = (tree, root_index) - self.trace_status = typedefs.TRACE_STATUS.FINISHED - driving_inferior = False - if not self.stop_after_trace: - continue_inferior() - - def cancel_trace(self) -> None: - """Prematurely ends the trace session, trace data will still be collected""" - self.cancel = True - - -def call_function_from_inferior(expression: str) -> tuple[str, str] | tuple[bool, bool]: - """Calls the given function expression from the inferior - - Args: - expression (str): Any gdb expression - - Returns: - tuple: A tuple containing assigned value and result, both as str - Returns a tuple of (False, False) if the call fails - - Examples: - call_function_from_inferior("printf('123')") returns ("$26","3") - """ - result = execute_func_temporary_interruption(send_command, f"call (void*(*)(char*, int)) {expression}") - filtered_result = regexes.convenience_variable.search(result) - if filtered_result: - return filtered_result.group(1), filtered_result.group(2) - return False, False - - -def find_entry_point() -> str | None: - """Finds entry point of the inferior - - Returns: - str: Entry point as hex str - None: If fails to find an entry point - """ - result = send_command("info file") - filtered_result = regexes.entry_point.search(result) - if filtered_result: - return filtered_result.group(1) - - -def search_instr( - searched_str: str, - starting_address: str, - ending_address_or_offset: str, - case_sensitive: bool = False, - enable_regex: bool = False, -) -> list | None: - """Searches for the given str in the disassembled output - - Args: - searched_str (str): String that will be searched - starting_address (str): Any gdb expression - ending_address_or_offset (str): If you pass this parameter as an offset, you should add "+" in front of it - (e.g "+42" or "+0x42"). If you pass this parameter as an hex address, the address range between the expression - and the secondary address is disassembled. - If the second parameter is an address. it always should be bigger than the first address. - case_sensitive (bool): If True, search will be case sensitive - enable_regex (bool): If True, searched_str will be treated as a regex expression - - Returns: - list: A list of str values in this format-->[[address1, instr1],[address2, ...], ...] - None: If enable_regex is True and given regex isn't valid - """ - if enable_regex: - try: - if case_sensitive: - regex = re.compile(searched_str) - else: - regex = re.compile(searched_str, re.IGNORECASE) - except Exception: - logger.exception(f"An exception occurred while trying to compile the given regex '{searched_str}'") - return - else: - searched_str = regexes.whitespaces.sub(" ", searched_str).strip() - returned_list = [] - disas_output = disassemble(starting_address, ending_address_or_offset) - for item in disas_output: - address = item[0] - instr = item[2] - corrected_instruction = regexes.whitespaces.sub(" ", instr).strip() - if enable_regex: - if not regex.search(corrected_instruction): - continue - else: - if case_sensitive: - if corrected_instruction.find(searched_str) == -1: - continue - else: - if corrected_instruction.lower().find(searched_str.lower()) == -1: - continue - returned_list.append([address, instr]) - return returned_list - - -def _is_dissect_address_valid(memory: io.BufferedReader, int_address: int, discard_invalid_strings: bool = False) -> bool: - """Checks if the address referenced by a dissected instruction points to readable memory - - Args: - memory (BufferedReader): Memory handle of the currently attached process - int_address (int): Address that'll be checked - discard_invalid_strings (bool): If True, the address also has to hold a string that can be decoded as utf-8 - - Returns: - bool: True if the address is valid, False otherwise - """ - try: - memory.seek(int_address) - except (OSError, ValueError): - return False # vsyscall is ignored if vDSO is present, so we can safely ignore vsyscall - try: - if discard_invalid_strings: - data_read = memory.read(32) - if data_read.startswith(b"\0"): - return False - data_read = data_read.split(b"\0", maxsplit=1)[0] - data_read.decode("utf-8") - else: - memory.read(1) - except Exception: - return False - return True - - -def dissect_code(region_list: list, discard_invalid_strings: bool = True) -> None: - """Searches given regions for jumps, calls and string references - Use function get_dissect_code_data() to gather the results - Use function cancel_dissect_code() to stop the search early - - Args: - region_list (list): A list of (start_address, end_address) -> (str, str) - Can be returned from functions like utils.filter_regions - discard_invalid_strings (bool): Entries that can't be decoded as utf-8 won't be included in referenced strings - """ - global dissect_code_active - global dissect_code_cancelled - global dissect_code_status - # Dissection has its own disassembler instead of the shared ones in utils because it runs in its own thread - if inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64: - disassembler = Cs(CS_ARCH_X86, CS_MODE_64) - else: - disassembler = Cs(CS_ARCH_X86, CS_MODE_32) - disassembler.skipdata = True - dissect_code_active = True - dissect_code_cancelled = False - referenced_strings_dict = None - referenced_jumps_dict = None - referenced_calls_dict = None - try: - referenced_strings_dict = shelve.open(utils.get_referenced_strings_file(currentpid), writeback=True) - referenced_jumps_dict = shelve.open(utils.get_referenced_jumps_file(currentpid), writeback=True) - referenced_calls_dict = shelve.open(utils.get_referenced_calls_file(currentpid), writeback=True) - region_count = len(region_list) - with memory_handle() as memory: - ref_str_count = len(referenced_strings_dict) - ref_jmp_count = len(referenced_jumps_dict) - ref_call_count = len(referenced_calls_dict) - # Refresh the status every time we advance this many bytes through a region so the GUI - # can report live progress and reference counts instead of freezing until the region is done - status_update_range = 0x100000 - for region_index, (start_addr, end_addr) in enumerate(region_list): - if dissect_code_cancelled: - break - region_info = start_addr + "-" + end_addr, str(region_index + 1) + " / " + str(region_count) - start_addr = int(start_addr, 16) - end_addr = int(end_addr, 16) - try: - memory.seek(start_addr) - except (OSError, ValueError): - continue - buffer_size = end_addr - start_addr - code = memory.read(buffer_size) - next_status_addr = start_addr - try: - for instruction_addr, instruction_size, mnemonic, operands in disassembler.disasm_lite(code, start_addr): - if dissect_code_cancelled: - break - if instruction_addr >= next_status_addr: - dissect_code_status = region_info + ( - hex(instruction_addr)[2:] + "-" + hex(end_addr)[2:], - ref_str_count, - ref_jmp_count, - ref_call_count, - ) - next_status_addr = instruction_addr + status_update_range - dissect_code_status_changed.emit() - instruction = f"{mnemonic} {operands}" if operands != "" else mnemonic - if ":[rip" in operands: - continue - if "[rip" in operands and not instruction.startswith(("j", "loop", "call")): - offset = operands.partition("[rip")[2].partition("]")[0].replace(" ", "") - referenced_address_int = instruction_addr + instruction_size + int(offset or "0", 0) - referenced_address_str = hex(referenced_address_int) - else: - found = regexes.dissect_code_valid_address.search(instruction) - if not found: - continue - referenced_address_str = regexes.hex_number.search(found.group(0)).group(0).lower() - referenced_address_int = int(referenced_address_str, 16) - if instruction.startswith("j") or instruction.startswith("loop"): - if _is_dissect_address_valid(memory, referenced_address_int): - instruction_only = regexes.alphanumerics.search(instruction).group(0).casefold() - try: - referenced_jumps_dict[referenced_address_str][instruction_addr] = instruction_only - except KeyError: - referenced_jumps_dict[referenced_address_str] = {} - referenced_jumps_dict[referenced_address_str][instruction_addr] = instruction_only - ref_jmp_count += 1 - elif instruction.startswith("call"): - if _is_dissect_address_valid(memory, referenced_address_int): - try: - referenced_calls_dict[referenced_address_str].add(instruction_addr) - except KeyError: - referenced_calls_dict[referenced_address_str] = set() - referenced_calls_dict[referenced_address_str].add(instruction_addr) - ref_call_count += 1 - else: - if _is_dissect_address_valid(memory, referenced_address_int, discard_invalid_strings): - try: - referenced_strings_dict[referenced_address_str].add(instruction_addr) - except KeyError: - referenced_strings_dict[referenced_address_str] = set() - referenced_strings_dict[referenced_address_str].add(instruction_addr) - ref_str_count += 1 - except CsError: - logger.exception("An exception occurred while trying to dissect code") - continue - except Exception: - logger.exception("An exception occurred while trying to dissect code") - finally: - for db in (referenced_strings_dict, referenced_jumps_dict, referenced_calls_dict): - if db is not None: - db.close() - dissect_code_active = False - - -def get_dissect_code_status() -> tuple: - """Returns the current state of dissect code process - - Returns: - tuple:(current_region, current_region_count, current_range, referenced_strings_count, - referenced_jumps_count, referenced_calls_count) - - current_region-->(str) Currently scanned memory region - current_region_count-->(str) "Region x of y" - current_range-->(str) Currently scanned memory range(current buffer) - referenced_strings_count-->(int) Count of referenced strings - referenced_jumps_count-->(int) Count of referenced jumps - referenced_calls_count-->(int) Count of referenced calls - - Returns a tuple of ("", "", "", 0, 0, 0) if dissect_code() hasn't advanced far enough to report any progress - """ - return dissect_code_status - - -def cancel_dissect_code() -> None: - """Finishes the current dissect code process early on""" - global dissect_code_cancelled - if dissect_code_active: - dissect_code_cancelled = True - - -def get_dissect_code_data(referenced_strings: bool = True, referenced_jumps: bool = True, referenced_calls: bool = True) -> list[shelve.Shelf]: - """Returns shelve.DbfilenameShelf objects of referenced dicts - - Args: - referenced_strings (bool): If True, include referenced strings in the returned list - referenced_jumps (bool): If True, include referenced jumps in the returned list - referenced_calls (bool): If True, include referenced calls in the returned list - - Returns: - list: A list of shelve.DbfilenameShelf objects. Can be used as dicts, they are backwards compatible - - For instance, if you call this function with default params, you'll get this--▼ - [referenced_strings_dict,referenced_jumps_dict,referenced_calls_dict] - - And if you, let's say, pass referenced_jumps as False, you'll get this instead--▼ - [referenced_strings_dict,referenced_calls_dict] - - referenced_strings_dict-->(shelve.DbfilenameShelf object) Holds referenced string addresses - Format: {referenced_address1:referrer_address_set1, referenced_address2:referrer_address_set2, ...} - - referenced_jumps_dict-->(shelve.DbfilenameShelf object) Holds referenced jump addresses - Format: {referenced_address1:referenced_by_dict1, referenced_address2:referenced_by_dict2, ...} - Format of referenced_by_dict: {address1:instr1, address2:instr2, ...} - - referenced_calls_dict-->(shelve.DbfilenameShelf object) Holds referenced call addresses - Format: {referenced_address1:referrer_address_set1, referenced_address2:referrer_address_set2, ...} - """ - dict_list = [] - try: - if referenced_strings: - dict_list.append(shelve.open(utils.get_referenced_strings_file(currentpid), "r")) - if referenced_jumps: - dict_list.append(shelve.open(utils.get_referenced_jumps_file(currentpid), "r")) - if referenced_calls: - dict_list.append(shelve.open(utils.get_referenced_calls_file(currentpid), "r")) - except Exception: - for opened_dict in dict_list: - opened_dict.close() - raise - return dict_list - - -def search_referenced_strings( - searched_str: str, - value_type: typedefs.ValueType | None = None, - case_sensitive: bool = False, - enable_regex: bool = False, -) -> list | None: - """Searches for given str in the referenced strings - - Args: - searched_str (str): String that will be searched - value_type (typedefs.ValueType, None): Type used to read candidate values. Defaults to UTF-8. - case_sensitive (bool): If True, search will be case sensitive - enable_regex (bool): If True, searched_str will be treated as a regex expression - - Returns: - list: [[referenced_address1, reference_count1, found_value1], ...] - None: If enable_regex is True and searched_str isn't a valid regex expression - """ - if enable_regex: - try: - if case_sensitive: - regex = re.compile(searched_str) - else: - regex = re.compile(searched_str, re.IGNORECASE) - except Exception: - logger.exception(f"An exception occurred while trying to compile the given regex '{searched_str}'") - return - if value_type is None: - value_type = typedefs.StringValueType("utf-8", length=100) - elif not isinstance(value_type, typedefs.ValueType): - return [] - str_dict = get_dissect_code_data(True, False, False)[0] - try: - returned_list = [] - with memory_handle() as mem_handle: - for address, refs in str_dict.items(): - value = read_memory(int(address, 16), value_type, mem_handle=mem_handle) - value_str = "" if value is None else str(value) - if not value_str: - continue - if enable_regex: - if not regex.search(value_str): - continue - else: - if case_sensitive: - if value_str.find(searched_str) == -1: - continue - else: - if value_str.lower().find(searched_str.lower()) == -1: - continue - returned_list.append((address, len(refs), value)) - finally: - str_dict.close() - return returned_list - - -def search_referenced_calls(searched_str: str, case_sensitive: bool = True, enable_regex: bool = False) -> list | None: - """Searches for given str in the referenced calls - - Args: - searched_str (str): String that will be searched - case_sensitive (bool): If True, search will be case sensitive - enable_regex (bool): If True, searched_str will be treated as a regex expression - - Returns: - list: [[referenced_address1, found_string1], ...] - None: If enable_regex is True and searched_str isn't a valid regex expression - """ - if enable_regex: - try: - if case_sensitive: - regex = re.compile(searched_str) - else: - regex = re.compile(searched_str, re.IGNORECASE) - except Exception: - logger.exception(f"An exception occurred while trying to compile the given regex '{searched_str}'") - return - call_dict = get_dissect_code_data(False, False, True)[0] - returned_list = [] - try: - addresses = list(call_dict) - # Resolved in one batch because each symbol lookup is a gdb evaluation - for address, examine_result in zip(addresses, examine_expressions(addresses)): - symbol = examine_result.all - if not symbol: - continue - if enable_regex: - if not regex.search(symbol): - continue - else: - if case_sensitive: - if symbol.find(searched_str) == -1: - continue - else: - if symbol.lower().find(searched_str.lower()) == -1: - continue - returned_list.append((symbol, len(call_dict[address]))) - except Exception: - logger.exception("Caught exception while searching referenced calls!") - finally: - call_dict.close() - return returned_list - - -def complete_command(gdb_command: str) -> list[str]: - """Tries to complete the given gdb command and returns completion possibilities - - Args: - gdb_command (str): The gdb command that'll be completed - - Returns: - list: Possible completions as a list of str - """ - returned_list = [] - for item in send_command("complete " + gdb_command, cli_output=True).splitlines(): - if not regexes.max_completions_reached.search(item): - returned_list.append(item) - return returned_list diff --git a/libpince/gdb_python_scripts/.gitignore b/libpince/gdb_python_scripts/.gitignore deleted file mode 100644 index 04462b7a..00000000 --- a/libpince/gdb_python_scripts/.gitignore +++ /dev/null @@ -1,51 +0,0 @@ -# Prerequisites -*.d - -# Object files -*.o -*.ko -*.obj -*.elf - -# Linker output -*.ilk -*.map -*.exp - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -modules.order -Module.symvers -Mkfile.old -dkms.conf \ No newline at end of file diff --git a/libpince/gdb_python_scripts/gdbextensions.py b/libpince/gdb_python_scripts/gdbextensions.py deleted file mode 100644 index e1ebb2a0..00000000 --- a/libpince/gdb_python_scripts/gdbextensions.py +++ /dev/null @@ -1,445 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -import gdb, pickle, sys, struct, importlib -from collections import OrderedDict -from typing import Any - -PINCE_PATH = gdb.parse_and_eval("$PINCE_PATH").string() -sys.path.append(PINCE_PATH) # Adds the PINCE directory to PYTHONPATH to import libraries from PINCE - -from libpince.gdb_python_scripts import gdbutils -from libpince import utils, typedefs, regexes -from libpince.utils import logger - -utils.init_logging() - -importlib.reload(gdbutils) -pid = gdbutils.pid -recv_file = utils.get_from_pince_file(pid) -send_file = utils.get_to_pince_file(pid) - -# Format of info_list: [count, previous_pc_address, register_info, float_info, disas_info] -# Format of watchpoint_dict: {address1:info_list1, address2:info_list2, ...} -# Format of watchpoint_numbers: str([1,2,3,4,..]) -# Format: {watchpoint_numbers1:watchpoint_dict1, watchpoint_numbers2:track_watchpoint_dict2, ...} -track_watchpoint_dict = {} - -# Format of expression_info_dict: {value1:count1, value2:count2, ...} -# Format of register_expression_dict: {expression1:expression_info_dict1, expression2:expression_info_dict2, ...} -# Format: {breakpoint_number1:register_expression_dict1, breakpoint_number2:register_expression_dict2, ...} -track_breakpoint_dict = {} - - -def receive_from_pince() -> Any: - with open(recv_file, "rb") as recv_file_handle: - return pickle.load(recv_file_handle) - - -def send_to_pince(contents_send: Any) -> None: - with open(send_file, "wb") as send_file_handle: - pickle.dump(contents_send, send_file_handle) - - -gdbutils.gdbinit() - - -class CLIOutput(gdb.Command): - def __init__(self) -> None: - super(CLIOutput, self).__init__("cli-output", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - try: - contents_send = gdb.execute(argument, from_tty, to_string=True) - except Exception as e: - contents_send = str(e) - logger.debug(contents_send) - send_to_pince(contents_send) - - -class HandleSignals(gdb.Command): - def __init__(self) -> None: - super().__init__("pince-handle-signals", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - signal_data = receive_from_pince() - for signal, stop, pass_to_program in signal_data: - stop = "stop print" if stop else "nostop noprint" - pass_to_program = "pass" if pass_to_program else "nopass" - gdb.execute(f"handle {signal} {stop} {pass_to_program}", from_tty, to_string=True) - - -class ParseAndEval(gdb.Command): - def __init__(self) -> None: - super(ParseAndEval, self).__init__("pince-parse-and-eval", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - expression, cast = receive_from_pince() - try: - value = gdb.parse_and_eval(expression) - parsed_value = cast(value) - except Exception: - logger.exception(f"An exception occurred while trying to parse expression '{expression}' and cast to type '{str(cast)}'") - parsed_value = None - send_to_pince(parsed_value) - - -class ReadRegisters(gdb.Command): - def __init__(self) -> None: - super(ReadRegisters, self).__init__("pince-read-registers", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - registers = gdbutils.get_general_registers() - for key, value in registers.items(): - registers[key] = utils.upper_hex(value) - registers.update(gdbutils.get_flag_registers()) - registers.update(gdbutils.get_segment_registers()) - send_to_pince(registers) - - -class ReadFloatRegisters(gdb.Command): - def __init__(self) -> None: - super(ReadFloatRegisters, self).__init__("pince-read-float-registers", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - send_to_pince(gdbutils.get_float_registers()) - - -class GetStackTraceInfo(gdb.Command): - def __init__(self) -> None: - super(GetStackTraceInfo, self).__init__("pince-get-stack-trace-info", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - stacktrace_info_list = [] - if gdbutils.current_arch == typedefs.INFERIOR_ARCH.ARCH_64: - sp_register = "rsp" - else: - sp_register = "esp" - stack_pointer = gdbutils.examine_expression(f"${sp_register}").address - if not stack_pointer: - logger.error(f"Cannot get the value of ${sp_register}") - send_to_pince(stacktrace_info_list) - return - stack_pointer = int(stack_pointer, 16) - result = gdb.execute("bt", from_tty, to_string=True) - frame_matches = regexes.max_frame_count.findall(result) - if not frame_matches: - send_to_pince(stacktrace_info_list) - return - max_frame = frame_matches[-1] - - # +1 because frame numbers start from 0 - for item in range(int(max_frame) + 1): - try: - result = gdb.execute(f"info frame {item}", from_tty, to_string=True) - except Exception: - break - frame_address = regexes.frame_address.search(result) - if not frame_address: - continue - frame_address = frame_address.group(1) - difference = hex(int(frame_address, 16) - stack_pointer) - frame_address_with_difference = frame_address + "(" + sp_register + "+" + difference + ")" - return_address = regexes.return_address.search(result) - if return_address: - return_address_with_info = gdbutils.examine_expression(return_address.group(1)).all - else: - return_address_with_info = "<>" - stacktrace_info_list.append([return_address_with_info, frame_address_with_difference]) - send_to_pince(stacktrace_info_list) - - -class GetStackInfo(gdb.Command): - def __init__(self) -> None: - super(GetStackInfo, self).__init__("pince-get-stack-info", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - stack_info_list = [] - # x32 has 64 bits registers but 32 bits pointers so select these widths independently. - chunk_size = gdbutils.void_ptr.sizeof - int_format = "Q" if chunk_size == 8 else "I" - if gdbutils.current_arch == typedefs.INFERIOR_ARCH.ARCH_64: - if argument == "from-base-pointer": - stack_register = "rbp" - else: - stack_register = "rsp" - else: - if argument == "from-base-pointer": - stack_register = "ebp" - else: - stack_register = "esp" - - sp_address = gdbutils.examine_expression(f"${stack_register}").address - if not sp_address: - logger.error(f"Cannot get the value of ${stack_register}") - send_to_pince(stack_info_list) - return - sp_address = int(sp_address, 16) - with open(gdbutils.mem_file, "rb") as FILE: - try: - old_position = FILE.seek(sp_address) - except (OSError, ValueError): - logger.exception(f"Cannot access the memory at {hex(sp_address)}") - send_to_pince(stack_info_list) - return - for index in range(int(4096 / chunk_size)): - current_offset = chunk_size * index - stack_indicator = hex(sp_address + current_offset) + "(" + stack_register + "+" + hex(current_offset) + ")" - try: - FILE.seek(old_position) - read = FILE.read(chunk_size) - if len(read) < chunk_size: - break - except (OSError, ValueError): - logger.exception(f"Can't access the stack after address {stack_indicator}") - break - old_position = FILE.tell() - int_addr = struct.unpack_from(int_format, read)[0] - hex_repr = hex(int_addr) - try: - FILE.seek(int_addr) - read_pointer = FILE.read(20) - except (OSError, ValueError): - pointer_data = "" - else: - symbol = gdbutils.examine_expression(hex_repr).symbol - if not symbol: - pointer_data = "(str)" + read_pointer.decode("utf-8", "ignore") - else: - pointer_data = "(ptr)" + symbol - stack_info_list.append([stack_indicator, hex_repr, pointer_data]) - send_to_pince(stack_info_list) - - -class GetFrameReturnAddresses(gdb.Command): - def __init__(self) -> None: - super(GetFrameReturnAddresses, self).__init__("pince-get-frame-return-addresses", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - return_address_list = [] - result = gdb.execute("bt", from_tty, to_string=True) - frame_matches = regexes.max_frame_count.findall(result) - if not frame_matches: - send_to_pince(return_address_list) - return - max_frame = frame_matches[-1] - - # +1 because frame numbers start from 0 - for item in range(int(max_frame) + 1): - try: - result = gdb.execute(f"info frame {item}", from_tty, to_string=True) - except Exception: - break - return_address = regexes.return_address.search(result) - if return_address: - return_address_with_info = gdbutils.examine_expression(return_address.group(1)).all - else: - return_address_with_info = "<>" - return_address_list.append(return_address_with_info) - send_to_pince(return_address_list) - - -class GetFrameInfo(gdb.Command): - def __init__(self) -> None: - super(GetFrameInfo, self).__init__("pince-get-frame-info", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - frame_number = receive_from_pince() - result = gdb.execute("bt", from_tty, to_string=True) - frame_matches = regexes.max_frame_count.findall(result) - if not frame_matches: - send_to_pince(None) - return - max_frame = frame_matches[-1] - if 0 <= int(frame_number) <= int(max_frame): - frame_info = gdb.execute("info frame " + frame_number, from_tty, to_string=True) - else: - logger.error(f"Frame {frame_number} doesn't exist") - frame_info = None - send_to_pince(frame_info) - - -class GetTrackWatchpointInfo(gdb.Command): - def __init__(self) -> None: - super(GetTrackWatchpointInfo, self).__init__("pince-get-track-watchpoint-info", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - breakpoints = argument - current_pc = str(gdb.parse_and_eval("$pc")) - current_pc_addr = utils.extract_hex_address(current_pc) - # Sometimes GDB will return a decimal address str instead of a hex str - if current_pc_addr is None: - result = regexes.decimal_number.search(current_pc) - if result: - current_pc_addr = result.group(0) - else: - logger.error("Failed to grab address from $pc") - return - current_pc_int = int(current_pc_addr, 0) - try: - disas_output = gdb.execute("disas $pc-30,$pc", to_string=True) - - # Just before the line "End of assembler dump" - last_instruction = disas_output.splitlines()[-2] - previous_pc_address = utils.extract_hex_address(last_instruction) or hex(current_pc_int) - except Exception: - previous_pc_address = hex(current_pc_int) - global track_watchpoint_dict - try: - count = track_watchpoint_dict[breakpoints][current_pc_int][0] + 1 - except KeyError: - if breakpoints not in track_watchpoint_dict: - track_watchpoint_dict[breakpoints] = OrderedDict() - count = 1 - register_info = gdbutils.get_general_registers() - register_info.update(gdbutils.get_flag_registers()) - register_info.update(gdbutils.get_segment_registers()) - float_info = gdbutils.get_float_registers() - try: - disas_info = gdb.execute("disas " + previous_pc_address + ",+40", to_string=True).replace("=>", " ") - except Exception: - disas_info = "" - track_watchpoint_dict[breakpoints][current_pc_int] = [ - count, - previous_pc_address, - register_info, - float_info, - disas_info, - ] - track_watchpoint_file = utils.get_track_watchpoint_file(pid, breakpoints) - with open(track_watchpoint_file, "wb") as track_watchpoint_handle: - pickle.dump(track_watchpoint_dict[breakpoints], track_watchpoint_handle) - - -class GetTrackBreakpointInfo(gdb.Command): - def __init__(self) -> None: - super(GetTrackBreakpointInfo, self).__init__("pince-get-track-breakpoint-info", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - arg_list = argument.split(",") - breakpoint_number = arg_list.pop() - register_expressions = arg_list - global track_breakpoint_dict - if not breakpoint_number in track_breakpoint_dict: - track_breakpoint_dict[breakpoint_number] = OrderedDict() - for register_expression in register_expressions: - if not register_expression: - continue - if not register_expression in track_breakpoint_dict[breakpoint_number]: - track_breakpoint_dict[breakpoint_number][register_expression] = OrderedDict() - try: - address = gdbutils.examine_expression(register_expression).address - except Exception: - address = None - if address: - if address not in track_breakpoint_dict[breakpoint_number][register_expression]: - track_breakpoint_dict[breakpoint_number][register_expression][address] = 1 - else: - track_breakpoint_dict[breakpoint_number][register_expression][address] += 1 - track_breakpoint_file = utils.get_track_breakpoint_file(pid, breakpoint_number) - with open(track_breakpoint_file, "wb") as track_breakpoint_handle: - pickle.dump(track_breakpoint_dict[breakpoint_number], track_breakpoint_handle) - - -class PhaseOut(gdb.Command): - def __init__(self) -> None: - super(PhaseOut, self).__init__("phase-out", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - gdb.execute("detach") - gdb.execute("echo Successfully detached from the target pid: " + str(pid)) - - -class PhaseIn(gdb.Command): - def __init__(self) -> None: - super(PhaseIn, self).__init__("phase-in", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - gdb.execute("attach " + str(pid)) - gdb.execute("echo Successfully attached back to the target pid: " + str(pid)) - - -class TraceInstructions(gdb.Command): - def __init__(self) -> None: - super(TraceInstructions, self).__init__("pince-trace-instructions", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - utils.change_trace_status(pid, typedefs.TRACE_STATUS.TRACING) - - -class ExamineExpressions(gdb.Command): - def __init__(self) -> None: - super(ExamineExpressions, self).__init__("pince-examine-expressions", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - data_read_list = [] - contents_recv = receive_from_pince() - # contents_recv format: [expression1, expression2, ...] - - memory_regions = utils.get_regions(pid) - regions = utils.get_region_dict(memory_regions) - module_bases = utils.get_module_dict(memory_regions) - for expression in contents_recv: - result_tuple = gdbutils.examine_expression(expression, regions, module_bases) - data_read_list.append(result_tuple) - send_to_pince(data_read_list) - - -class SearchFunctions(gdb.Command): - def __init__(self) -> None: - super(SearchFunctions, self).__init__("pince-search-functions", gdb.COMMAND_USER) - - def invoke(self, argument: str, from_tty: bool) -> None: - expression, case_sensitive = receive_from_pince() - function_list = [] - if case_sensitive: - gdb.execute("set case-sensitive on") - else: - gdb.execute("set case-sensitive off") - try: - output = gdb.execute("info functions " + expression, to_string=True) - except Exception: - logger.exception("An exception occurred while trying to search functions") - output = "" - gdb.execute("set case-sensitive auto") - for line in output.splitlines(): - non_debugging = regexes.info_functions_non_debugging.search(line) - if non_debugging: - function_list.append((non_debugging.group(1), non_debugging.group(2))) - else: - if line.endswith(";"): # defined - function_list.append((None, line[:-1])) - send_to_pince(function_list) - - -CLIOutput() -HandleSignals() -ParseAndEval() -ReadRegisters() -ReadFloatRegisters() -GetStackTraceInfo() -GetStackInfo() -GetFrameReturnAddresses() -GetFrameInfo() -GetTrackWatchpointInfo() -GetTrackBreakpointInfo() -PhaseOut() -PhaseIn() -TraceInstructions() -ExamineExpressions() -SearchFunctions() diff --git a/libpince/gdb_python_scripts/gdbutils.py b/libpince/gdb_python_scripts/gdbutils.py deleted file mode 100644 index b355ade6..00000000 --- a/libpince/gdb_python_scripts/gdbutils.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -import gdb, sys, re -from collections import OrderedDict - -PINCE_PATH = gdb.parse_and_eval("$PINCE_PATH").string() -GDBINIT_AA_PATH = gdb.parse_and_eval("$GDBINIT_AA_PATH").string() -sys.path.append(PINCE_PATH) # Adds the PINCE directory to PYTHONPATH to import libraries from PINCE - -from libpince import typedefs, regexes, utils - -inferior = gdb.selected_inferior() -pid = -1 if inferior.pid == 0 else inferior.pid -mem_file = "/proc/" + str(pid) + "/mem" - -try: - arch = gdb.selected_frame().architecture() -except gdb.error: - arch = inferior.architecture() - -# Wine's segment selectors can make GDB mistake normal Win64 for x32, truncating pointers to 32 bits. -if ( - pid != -1 - and arch.name().startswith("i386:x64-32") - and utils.is_wine_process(pid) - and utils.get_effective_arch(pid) == typedefs.INFERIOR_ARCH.ARCH_64 -): - gdb.execute("set architecture i386:x86-64", to_string=True) - try: - arch = gdb.selected_frame().architecture() - except gdb.error: - arch = inferior.architecture() - -try: - void_ptr = gdb.lookup_type("void").pointer() -except gdb.error: - void_ptr = gdb.parse_and_eval("0").type.pointer() - -if arch.registers().find("rax") is not None: - current_arch = typedefs.INFERIOR_ARCH.ARCH_64 -else: - current_arch = typedefs.INFERIOR_ARCH.ARCH_32 - - -# Use this function instead of the .gdbinit file -# If you have to load a .gdbinit file, just load it in this function with command "source" -def gdbinit() -> None: - try: - gdb.execute("source " + GDBINIT_AA_PATH) - except Exception: - utils.logger.exception("An exception occurred while trying to source gdbinit") - gdb.execute("set disassembly-flavor intel") - gdb.execute("set case-sensitive auto") - gdb.execute("set code-cache off") - gdb.execute("set stack-cache off") - - -def get_general_registers() -> OrderedDict[str, str | None]: - contents_send = OrderedDict() - if current_arch == typedefs.INFERIOR_ARCH.ARCH_64: - general_register_list = typedefs.REGISTERS.GENERAL_64 - else: - general_register_list = typedefs.REGISTERS.GENERAL_32 - for item in general_register_list: - contents_send[item] = examine_expression("$" + item).address - return contents_send - - -def get_flag_registers() -> OrderedDict[str, str]: - contents_send = OrderedDict() - flags = int(gdb.parse_and_eval("$eflags")) & 0xFFFFFFFF - contents_send["cf"] = str((flags >> 0) & 1) - contents_send["pf"] = str((flags >> 2) & 1) - contents_send["af"] = str((flags >> 4) & 1) - contents_send["zf"] = str((flags >> 6) & 1) - contents_send["sf"] = str((flags >> 7) & 1) - contents_send["tf"] = str((flags >> 8) & 1) - contents_send["if"] = str((flags >> 9) & 1) - contents_send["df"] = str((flags >> 10) & 1) - contents_send["of"] = str((flags >> 11) & 1) - return contents_send - - -def get_segment_registers() -> OrderedDict[str, str | None]: - contents_send = OrderedDict() - for item in typedefs.REGISTERS.SEGMENT: - contents_send[item] = examine_expression("$" + item).address - return contents_send - - -def get_float_registers() -> OrderedDict[str, str]: - contents_send = OrderedDict() - for register in typedefs.REGISTERS.FLOAT.ST: - value = gdb.parse_and_eval("$" + register) - contents_send[register] = str(value) - if current_arch == typedefs.INFERIOR_ARCH.ARCH_64: - xmm_registers = typedefs.REGISTERS.FLOAT.XMM_64 - else: - xmm_registers = typedefs.REGISTERS.FLOAT.XMM_32 - for register in xmm_registers: - value = gdb.parse_and_eval("$" + register + ".v4_float") - contents_send[register] = str(value) - return contents_send - - -def examine_expression( - expression: str, regions: dict[str, list[str]] | None = None, module_bases: dict[str, str] | None = None -) -> typedefs.tuple_examine_expression: - # Resolve one candidate through GDB's evaluator. Return None if it yields no address. - def via_gdb(expr): - try: - value = gdb.parse_and_eval(expr) - try: - value = value.cast(void_ptr) - except gdb.error: - value = str(value) - match = regexes.address_with_symbol.search(str(value)) - except Exception: - return None - return typedefs.tuple_examine_expression(*match.groups()) if match else None - - none = typedefs.tuple_examine_expression(None, None, None) - # Try the expression first so real symbols win. - resolved = via_gdb(expression) - if resolved: - return resolved - if not regions and not module_bases: - return none - - # Bare module names use logical load bases. - # Explicit module[n] names retain raw VMA indexing. - # Longest names match first so libc.so.6 wins over libc.so. - names = "|".join(re.escape(name) for name in sorted(set(regions or ()) | set(module_bases or ()), key=len, reverse=True)) - - def resolve_module(match): - name, index = match.groups() - if index is None: - return module_bases.get(name, match.group(0)) if module_bases else match.group(0) - addresses = regions.get(name, ()) if regions else () - index = int(index) - return addresses[index] if index < len(addresses) else match.group(0) - - substituted = re.sub( - regexes.module_reference.format(names), - resolve_module, - expression, - ) - if substituted == expression: - return none - - # Plain module+offset is now pure arithmetic so we'll evaluate in-process to skip a second gdb parse. - # The whitelist keeps eval injection-safe and sends anything with a deref/cast/register to gdb instead. - if regexes.hex_arithmetic.fullmatch(substituted) and "**" not in substituted.replace(" ", ""): - try: - address = hex(eval(substituted)) - return typedefs.tuple_examine_expression(address, address, None) - except Exception: - pass - return via_gdb(substituted) or none diff --git a/libpince/gdbinit_venv b/libpince/gdbinit_venv deleted file mode 100644 index 567262c2..00000000 --- a/libpince/gdbinit_venv +++ /dev/null @@ -1,14 +0,0 @@ -# Update GDB's Python paths with the `sys.path` values of the local -# Python installation, whether that is brew'ed Python, a virtualenv, -# or another system python. - -# Convert GDB to interpret in Python -python -import os,subprocess,sys - -# Execute a Python using the user's shell and pull out the sys.path (for site-packages) -paths = subprocess.check_output('python3 -c "import os,sys;print(os.linesep.join(sys.path).strip())"',shell=True).decode("utf-8").split() - -# Replace GDB's Python's search paths with venv ones -sys.path = paths -end diff --git a/libpince/monocore.py b/libpince/monocore.py deleted file mode 100644 index f5b5f848..00000000 --- a/libpince/monocore.py +++ /dev/null @@ -1,485 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) 2026 brkzlr - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -import os -import socket -import struct -from dataclasses import dataclass -from time import sleep -from typing import Any - -import msgpack - -from . import debugcore, utils, typedefs -from .utils import logger -from .libmemscan.memscan import Libmemscan, DataType, MatchType, ScanLevel - -# The active collector connection for the current process or None. -_client: "MonoClient | None" = None - -_RUNTIME_PATTERNS = [ - ("mono", "elf", r"libmono(sgen|bdwgc)?-2\.0\.so"), - ("mono", "elf", r"^mono-sgen$|^mono-boehm$|^mono$"), - ("mono", "pe", r"mono-2\.0-bdwgc\.dll"), - ("il2cpp", "elf", r"GameAssembly\.so"), - ("il2cpp", "pe", r"GameAssembly\.dll"), -] - - -@dataclass -class RuntimeInfo: - kind: str # "mono" || "il2cpp" - module_format: str # "elf" || "pe" - load_bias: int - module_path: str - - -class MonoError(Exception): - """Raised when the collector returns an error response.""" - - -def detect_runtime(pid: int) -> RuntimeInfo | None: - """Detect the managed runtime mapped into the given process - - Args: - pid (int): PID of the process - - Returns: - RuntimeInfo: kind/module_format/load_bias/module_path of the detected runtime - None: If no supported managed runtime is mapped - """ - for kind, module_format, pattern in _RUNTIME_PATTERNS: - module = utils.get_module_load_bias(pid, pattern) - if module is not None: - load_bias, path = module - return RuntimeInfo(kind, module_format, load_bias, path) - return None - - -def _collector_path(wine: bool, arch32: bool) -> str: - """Returns the collector agent path for the given format / bitness.""" - bits = "x86" if arch32 else "x64" - name = f"mono_collector{'_wine' if wine else ''}_{bits}.{'dll' if wine else 'so'}" - src = os.path.join(os.path.dirname(__file__), "libmono_collector", name) - - # AppImage FUSE paths may be inaccessible to the target process. - appdir = os.environ.get("APPDIR") - if appdir and os.path.commonpath([src, appdir]) == appdir: - import shutil - import tempfile - - dst = os.path.join(tempfile.gettempdir(), os.path.basename(src)) - if not os.path.exists(dst) or os.path.getmtime(src) > os.path.getmtime(dst): - shutil.copy2(src, dst) - os.chmod(dst, 0o755) - return dst - return src - - -def _abstract_address(pid: int) -> bytes: - """Abstract namespace Unix socket address that the agent binds to.""" - return b"\x00pince-mono-" + str(pid).encode("ascii") - - -def _connect(family: int, address, retries: int = 1, delay: float = 0.05) -> "MonoClient | None": - """Connects to a resident collector: abstract Unix socket (native) or loopback TCP (WINE/Proton).""" - for _ in range(retries): - sock = socket.socket(family, socket.SOCK_STREAM) - try: - sock.connect(address) - if family == socket.AF_INET: - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # frames are tiny header + body - return MonoClient(sock) - except OSError: - sock.close() - sleep(delay) - return None - - -def _wine_port_addr(mem, base: int) -> int: - def u(addr: int, n: int) -> int: - mem.seek(addr) - return int.from_bytes(mem.read(n), "little") - - try: - if u(base, 2) != 0x5A4D: - return 0 - pe = base + u(base + 0x3C, 4) - if u(pe, 4) != 0x4550: - return 0 - opt = pe + 0x18 - dd = opt + (0x70 if u(opt, 2) == 0x20B else 0x60) - ed_rva, ed_size = u(dd, 4), u(dd + 4, 4) - if not ed_rva: - return 0 - ed = base + ed_rva - funcs, names, ords = (base + u(ed + off, 4) for off in (0x1C, 0x20, 0x24)) - want = b"pince_mono_port\x00" - for i in range(u(ed + 0x18, 4)): - mem.seek(base + u(names + i * 4, 4)) - if mem.read(len(want)) == want: - rva = u(funcs + u(ords + i * 2, 2) * 4, 4) - return 0 if ed_rva <= rva < ed_rva + ed_size else base + rva - except (OSError, ValueError): - pass - return 0 - - -def _connect_wine(pid: int, retries: int = 1, delay: float = 0.05) -> "MonoClient | None": - """Locate the WINE/Proton collector via its exported port then connect.""" - for _ in range(retries): - module = utils.get_module_load_bias(pid, r"mono_collector_wine_(x86|x64)\.dll") - if module is not None: - try: - with debugcore.memory_handle() as mem: - port_addr = _wine_port_addr(mem, module[0]) - if port_addr: - mem.seek(port_addr) - port = int.from_bytes(mem.read(2), "little") - if port: - client = _connect(socket.AF_INET, ("127.0.0.1", port), delay=0) - if client is not None: - return client - except (OSError, ValueError): - pass - sleep(delay) - return None - - -def init_mono() -> bool: - """Ensure a collector agent is injected and connected for the current process - - Reuses an existing connection/agent if present. - Acts on native Linux Mono/IL2CPP and Wine/Proton targets, both x64 and x86. - - Returns: - bool: True if a connected MonoClient is ready, False otherwise - """ - global _client - pid = debugcore.currentpid - if pid == -1: - return False - - info = detect_runtime(pid) - if info is None: - return False # GUI decides the message - wine = info.module_format == "pe" - - # Agent may already be resident from a previous attach/dissect. - client = _connect_wine(pid) if wine else _connect(socket.AF_UNIX, _abstract_address(pid)) - - if client is None: - arch32 = debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 - if wine: - # The runtime PE magic is read after the runtime is fully loaded, - # so trust it over effective_arch in case that detection fell back to the host arch. - try: - with debugcore.memory_handle() as mem: - mem.seek(info.load_bias + 0x3C) - mem.seek(info.load_bias + int.from_bytes(mem.read(4), "little") + 0x18) - magic = int.from_bytes(mem.read(2), "little") - if magic in (0x10B, 0x20B): - arch32 = magic == 0x10B - except (OSError, ValueError): - pass - - lib_path = _collector_path(wine, arch32) - if not os.path.exists(lib_path): - logger.error(f"Mono collector not built: {lib_path}") - return False - try: - injected = debugcore.inject_dll(lib_path) if wine else debugcore.inject_so(lib_path) - if not injected: - logger.error("Failed to inject Mono collector!") - return False - # LoadLibraryW injection runs after resume, so WINE gets a longer poll window. - client = _connect_wine(pid, retries=160) if wine else _connect(socket.AF_UNIX, _abstract_address(pid), retries=80) - except typedefs.GDBInitializeException: - logger.error("GDB became unavailable while injecting the Mono collector") - return False - if client is None: - logger.error("Mono collector did not come up!") - return False - - _client = client - return True - - -def get_client() -> "MonoClient | None": - """Returns the active MonoClient or None if init_mono() hasn't succeeded.""" - return _client - - -def reset() -> None: - """Drop the active collector connection. - - Call when the inferior changes/exits so get_client() doesn't hand back a client - whose socket points at a process that's gone. - """ - global _client - if _client is not None: - _client.close() - _client = None - - -# Invoke argument marshalling. -# Value type args/returns travel as a type tag + raw bit pattern (a uint) but the collector -# writes/reads the native bytes. -# Mirrors the tags emitted by the collector's signature op (see mono_api.zig typeTag). -_INT_WIDTH = {"i1": 1, "u1": 1, "i2": 2, "u2": 2, "char": 2, "i4": 4, "u4": 4, "i8": 8, "u8": 8} - - -def _arg_to_bits(tag: str, value: Any) -> int: - """Encode a Python value into the raw bit pattern the collector expects for tag.""" - try: - if tag == "nil": - return 0 - if tag == "object": - return int(value) & 0xFFFFFFFFFFFFFFFF - if tag == "bool": - return 1 if value else 0 - if tag == "r4": - return struct.unpack(" Any: - """Reinterpret a raw bit pattern from the collector back into a Python value.""" - if tag == "r4": - return struct.unpack("= (1 << (8 * width - 1)): - value -= 1 << (8 * width) - return value - - -# Struct (value type) marshalling: a struct travels as the raw bytes of its unboxed value. -_PACKABLE_TAGS = set(_INT_WIDTH) | {"r4", "r8", "bool"} - - -def _value_width(tag: str) -> int: - if tag == "r4": - return 4 - if tag == "r8": - return 8 - if tag == "bool": - return 1 - width = _INT_WIDTH.get(tag) - if width is None: - raise MonoError(f"cannot size value of type {tag}") - return width - - -def pack_value(tag: str, value: Any) -> bytes: - """Little-endian bytes for a primitive value (assembling a struct argument).""" - return _arg_to_bits(tag, value).to_bytes(_value_width(tag), "little") - - -def unpack_value(tag: str, raw: bytes) -> Any: - """A primitive value read back from its little-endian bytes (a struct field).""" - return _bits_to_value(tag, int.from_bytes(raw, "little")) - - -def object_header_size() -> int: - """Bytes of the object header (vtable/klass + sync word) prefixing a boxed value type. - Value type field offsets from the fields op include it, so subtract it for the unboxed value.""" - ptr = 4 if debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 else 8 - return 2 * ptr - - -class MonoClient: - """Msgpack request/response client to the collector agent.""" - - def __init__(self, sock: socket.socket) -> None: - self.sock = sock - - def _recv_exact(self, n: int) -> bytes: - chunks = [] - got = 0 - while got < n: - chunk = self.sock.recv(n - got) - if not chunk: - raise MonoError("connection closed") - chunks.append(chunk) - got += len(chunk) - return b"".join(chunks) - - def request(self, op: str, **args: Any) -> Any: - """Send one request frame, return the decoded "data" (or raise MonoError)""" - payload = msgpack.packb({"op": op, **args}, use_bin_type=False) - try: - self.sock.sendall(struct.pack(">I", len(payload)) + payload) - (length,) = struct.unpack(">I", self._recv_exact(4)) - response = msgpack.unpackb(self._recv_exact(length), raw=False) - except OSError as e: - raise MonoError(f"collector connection lost: {e}") - if not isinstance(response, dict): - raise MonoError("malformed response from collector") - if not response.get("ok"): - raise MonoError(response.get("error", "unknown error")) - return response.get("data") - - def assemblies(self) -> list[dict]: - return self.request("assemblies") - - def classes(self, image: int) -> list[dict]: - return self.request("classes", image=image) - - def fields(self, klass: int) -> list[dict]: - return self.request("fields", klass=klass) - - def methods(self, klass: int) -> list[dict]: - return self.request("methods", klass=klass) - - def compile_method(self, method: int) -> int: - result = self.request("compile", method=method) - addr = result.get("native_addr") if isinstance(result, dict) else None - if addr is None: - raise MonoError("malformed response: missing 'native_addr'") - return addr - - def static_field_address(self, klass: int, field: int) -> int: - result = self.request("static_addr", klass=klass, field=field) - addr = result.get("address") if isinstance(result, dict) else None - if addr is None: - raise MonoError("malformed response: missing 'address'") - return addr - - def class_info(self, klass: int) -> dict: - """Return {namespace, name, parent} for a class handle.""" - return self.request("class_info", klass=klass) - - def type_klass(self, field: int) -> int: - """Return the klass handle of a field's declared type or 0 if unresolvable.""" - result = self.request("type_klass", field=field) - klass = result.get("klass") if isinstance(result, dict) else None - if klass is None: - raise MonoError("malformed response: missing 'klass'") - return klass - - def instance_marker(self, klass: int) -> int: - """Return the marker every live instance carries in word 0 (Mono: MonoVTable*, IL2CPP: klass).""" - result = self.request("instance_marker", klass=klass) - marker = result.get("marker") if isinstance(result, dict) else None - if marker is None: - raise MonoError("malformed response: missing 'marker'") - return marker - - def signature(self, method: int) -> dict: - """Return {ret:{tag,name}, params:[{name,tag,type}]} for a method handle. - struct (value-type) params/ret also carry {klass, size} for marshalling. - """ - return self.request("signature", method=method) - - def struct_fields(self, klass: int) -> list[dict] | None: - """Instance fields of a value type, offsets relative to the unboxed value. - None if any field isn't a packable primitive (caller falls back to raw bytes). - """ - header = object_header_size() - layout = [] - try: - for fld in self.fields(klass): - if fld["is_static"]: - continue - if fld["tag"] not in _PACKABLE_TAGS: - return None - layout.append( - { - "name": fld["name"], - "tag": fld["tag"], - "type": fld["type"], - "offset": fld["offset"] - header, - "width": _value_width(fld["tag"]), - } - ) - except (KeyError, TypeError) as e: - raise MonoError(f"malformed field in collector response: {e}") from e - return layout - - def invoke(self, method: int, obj: int = 0, args: list[tuple[str, Any]] | None = None) -> dict: - """Invoke a managed method. args is a list of (type_tag, value) pairs. - A "struct" arg's value is the raw bytes of its unboxed value. - - Returns {"result": , "tag": , "exception": }. - """ - wire_args = [[tag, value if tag in ("str", "struct") else _arg_to_bits(tag, value)] for tag, value in (args or [])] - response = self.request("invoke", method=method, obj=obj, args=wire_args) - result = response.get("result") - decoded, tag = None, None - if result is not None: - tag = result.get("tag") - if tag == "str": - decoded = result.get("val") - elif tag == "struct": - decoded = result.get("bytes", b"") - else: - decoded = _bits_to_value(tag, result.get("bits", 0)) - return {"result": decoded, "tag": tag, "exception": response.get("exception", 0)} - - def close(self) -> None: - try: - self.sock.close() - except OSError: - pass - - -def find_instances(klass: int) -> list[int]: - """Find live instance addresses of a class. - Scan target memory for its instance marker (an object's header word) via a private Libmemscan - so the main window scan is left intact (if any). - - Raises MonoError if the marker can't be resolved. - Returns [] if none are mapped. - """ - client = get_client() - if client is None or debugcore.currentpid == -1: - return [] - marker = client.instance_marker(klass) - if not marker: - raise MonoError("instance marker unavailable") - arch32 = debugcore.effective_arch == typedefs.INFERIOR_ARCH.ARCH_32 - so_path = os.path.join(utils.get_libpince_directory(), "libmemscan", "libmemscan.so") - scanner = Libmemscan(so_path) - try: - scanner.attach(debugcore.currentpid) - scanner.set_data_type(DataType.INTEGER32 if arch32 else DataType.INTEGER64) - scanner.set_scan_level(ScanLevel.ALL_RW) - scanner.set_alignment(4 if arch32 else 8) - scanner.reset() - scanner.scan(MatchType.MATCHEQUALTO, marker) - return [match.address for match in scanner.matches()] - finally: - scanner.close() diff --git a/libpince/regexes.py b/libpince/regexes.py deleted file mode 100644 index d01474f8..00000000 --- a/libpince/regexes.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) 2016-2017 Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from re import compile, VERBOSE, MULTILINE, Pattern - -# The comments near regular expressions shows the expected gdb output, hope it helps to the future developers - -# --------------------------------------------debugcore---------------------------------------------------------------- - -gdb_state_observe = compile(r"^\*(stopped.+)|^\*(running)", MULTILINE) -gdb_error = compile(r"\^error") -hex_plain = compile(r"[0-9a-fA-F]+") -hex_number = compile(r"0x" + hex_plain.pattern) -hex_number_grouped = compile(r"(" + hex_number.pattern + r")") -symbol = compile(r"<(.+?)>") -address_with_symbol = compile(r"(" + hex_number_grouped.pattern + r"\s*(<.+>)?)") # 0x7f3067f1174d \n -thread_info = compile(r"\*\s+\d+\s+(.*)\\n") -inferior_pid = compile(r"process\s+(\d+)") -hw_breakpoint_count = compile(r"(hw|read|acc)") -breakpoint_size = compile(r"char\[(\d+)\]") -breakpoint_created = compile(r"breakpoint-created") -breakpoint_number = compile(r"(?:number|bkptno)=\"(\d+)\"") -convenience_variable = compile(r'"(\$\d+)\s+=\s+(.*)"') # "$26 = 3" -entry_point = compile(r"Entry\s+point:\s+" + hex_number_grouped.pattern) - - -# The command will always start with the word "source", check debugcore.send_command function for the cause -def gdb_command_source(command_file: str) -> Pattern[str]: - return compile(r"&\".*source\s" + command_file + r"\\n\"") # &"command\n" - - -# This will only match hex patterns without 0x and ignore the ones below: -# Hex patterns with 0x such as 0x5123 -# Map symbols of PINCE, such as kmines[2] -# Dotted map symbols without explicit indices, such as d3d11.dll -expression_with_hex = compile(r"\b0x[0-9a-fA-F]+|[\w.]*\[\d+\]|\b(?:\t48 81 ec d8 00 00 00\tsub rsp,0xd8\n -disassemble_output = compile( - r""" - ([0-9a-fA-F]+.*)\\t # Address with symbol - (.*?[0-9a-fA-F]{2})\s*\\t # Bytes, ignore padding - (.+)\\n # Instruction -""", - VERBOSE, -) -info_functions_non_debugging = compile(hex_number_grouped.pattern + r"\s+(.*)") -max_completions_reached = compile(r"\*\*\*\s+List\s+may\s+be\s+truncated,\s+max-completions\s+reached\.\s+\*\*\*") - -# --------------------------------------------utils------------------------------------------------------------------ - -instruction_follow = compile(r"(j|call|loop).*\s+" + hex_number_grouped.pattern) -docstring_variable = compile(r"(\w+)\s*=") -docstring_function_or_variable = compile(r"def\s+(\w+)|" + docstring_variable.pattern) -whitespaces = compile(r"\s+") -ps = compile( - r""" - \s+(\d+)\s+ # PID - (\S+)\s+ # Username - (.*)$ # Process name -""", - VERBOSE, -) -maps = compile( - r""" - ([0-9a-f]+)-([0-9a-f]+)\s+ # Address (start-end) - (\S+)\s+ # Permissions - ([0-9a-f]+)\s+ # Map offset - (\S+)\s+ # Device node - (\d+)\s* # Inode - (.*)$ # Pathname -""", - VERBOSE, -) - -# --------------------------------------------guiutils------------------------------------------------------------------ - -reference_mark = compile(r"\{\d*\}") -float_number = compile(r"-?(?:\d+[.,]?\d*|[.,]\d+)(?:[eE][-+]?\d+)?") -bytearray_input = compile(r"^[A-Fa-f0-9?]{2}(\s+[A-Fa-f0-9?]{2})*\s*$") -decimal_number = compile(r"-?\d+") -hex_number_gui = compile(r"^-?(?:0x)?[0-9a-fA-F]+$") # contains optional 0x prefix - -# --------------------------------------------gdbextensions------------------------------------------------------ - -max_frame_count = compile(r"#(\d+)\s+.*") -frame_address = compile(r"frame\s+at\s+" + hex_number_grouped.pattern) # frame at 0x7ffe1e989950 -return_address = compile(r"saved.*=\s+" + hex_number_grouped.pattern) # saved rip = 0x7f633a853fe4 -trace_instructions_ret = compile(r":\s+ret") # 0x7f71a4dc5ff8 : ret -trace_instructions_call = compile(r":\s+call") # 0x7f71a4dc5fe4 : call 0x7f71a4de1100 -dissect_code_valid_address = compile(r"(\s+|\[|,)" + hex_number.pattern + r"(\s+|\]|,|$)") -alphanumerics = compile(r"\w+") -file_with_extension = compile(r".+?\.\w+") -module_reference = r"(? - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -import collections, os -from . import utils, typedefs -from .libmemscan.memscan import Libmemscan, MatchType, DataType - -memscan = Libmemscan(os.path.join(utils.get_libpince_directory(), "libmemscan", "libmemscan.so")) - -# Used in set_data_type function of memscan -scan_index_to_memscan_dict = collections.OrderedDict( - [ - (typedefs.SCAN_INDEX.INT_ANY, DataType.ANYINTEGER), - (typedefs.SCAN_INDEX.INT8, DataType.INTEGER8), - (typedefs.SCAN_INDEX.INT16, DataType.INTEGER16), - (typedefs.SCAN_INDEX.INT32, DataType.INTEGER32), - (typedefs.SCAN_INDEX.INT64, DataType.INTEGER64), - (typedefs.SCAN_INDEX.FLOAT_ANY, DataType.ANYFLOAT), - (typedefs.SCAN_INDEX.FLOAT32, DataType.FLOAT32), - (typedefs.SCAN_INDEX.FLOAT64, DataType.FLOAT64), - (typedefs.SCAN_INDEX.ANY, DataType.ANYNUMBER), - (typedefs.SCAN_INDEX.STRING, DataType.STRING), - (typedefs.SCAN_INDEX.AOB, DataType.BYTEARRAY), - ] -) - -scan_type_to_memscan_dict = collections.OrderedDict( - [ - (typedefs.SCAN_TYPE.EXACT, MatchType.MATCHEQUALTO), - (typedefs.SCAN_TYPE.NOT, MatchType.MATCHNOTEQUALTO), - (typedefs.SCAN_TYPE.INCREASED, MatchType.MATCHINCREASED), - (typedefs.SCAN_TYPE.INCREASED_BY, MatchType.MATCHINCREASEDBY), - (typedefs.SCAN_TYPE.DECREASED, MatchType.MATCHDECREASED), - (typedefs.SCAN_TYPE.DECREASED_BY, MatchType.MATCHDECREASEDBY), - (typedefs.SCAN_TYPE.LESS, MatchType.MATCHLESSTHAN), - (typedefs.SCAN_TYPE.MORE, MatchType.MATCHGREATERTHAN), - (typedefs.SCAN_TYPE.BETWEEN, MatchType.MATCHRANGE), - (typedefs.SCAN_TYPE.CHANGED, MatchType.MATCHCHANGED), - (typedefs.SCAN_TYPE.UNCHANGED, MatchType.MATCHNOTCHANGED), - (typedefs.SCAN_TYPE.UNKNOWN, MatchType.MATCHANY), - ] -) diff --git a/libpince/speedhack.py b/libpince/speedhack.py deleted file mode 100644 index bbd9f2a1..00000000 --- a/libpince/speedhack.py +++ /dev/null @@ -1,1381 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) 2026 brkzlr - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -from __future__ import annotations - -from dataclasses import dataclass -from fractions import Fraction -from typing import Callable -import capstone -from capstone import Cs -from capstone import x86 as cs_x86 -import io -import os -import re -import struct -import time - -from . import debugcore, typedefs, utils -from .utils import logger - -CAVE_SIZE = 0x1000 -CAVE_MARKER = b"PINCE_SPEEDHACK\0" -STEP = 0.1 -DEFAULT_SPEED = 1.0 -_U64_LE = typedefs.IntegerValueType(64, endian=typedefs.ENDIANNESS.LITTLE) - -# Only the four wall/uptime clocks are scaled. -# CPU clocks (2, 3) and coarse clocks (5, 6) are passed through. -SCALED_CLOCK_IDS = ( - time.CLOCK_REALTIME, # 0 - time.CLOCK_MONOTONIC, # 1 - time.CLOCK_MONOTONIC_RAW, # 4 - time.CLOCK_BOOTTIME, # 7 -) -CLOCK_SLOT_SIZE = 16 -NUM_OFFSET = (max(SCALED_CLOCK_IDS) + 1) * CLOCK_SLOT_SIZE -DEN_OFFSET = NUM_OFFSET + 8 -BUFFER_SIZE = DEN_OFFSET + 8 -ACTIVE_OFFSET = BUFFER_SIZE * 2 -STATE_SIZE = ACTIVE_OFFSET + 8 - -WINE_NUM_OFFSET = 0 -WINE_DEN_OFFSET = 8 -WINE_INIT_OFFSET = 16 -WINE_REAL_BASE_OFFSET = 24 -WINE_FAKE_BASE_OFFSET = 32 -WINE_LAST_REAL_OFFSET = 40 -WINE_LAST_FAKE_OFFSET = 48 -WINE_STATE_SIZE = 56 - -# Absolute jump: movabs rax, imm64; jmp rax (12 bytes). -JUMP_SIZE = 12 - -# x86_64 syscall numbers. clock_gettime/gettimeofday use the syscall only as a vDSO fallback. -# nanosleep has no vDSO entry so it always goes through the syscall. -SYS_CLOCK_GETTIME = 228 -SYS_GETTIMEOFDAY = 96 -SYS_NANOSLEEP = 35 - -# i386 detour: mov eax, imm32 (5 bytes); jmp eax (2 bytes). -JUMP_SIZE_32 = 7 - -# i386 syscall numbers (differ from x86_64). nanosleep has no vDSO entry on either arch. -SYS_CLOCK_GETTIME_32 = 265 -SYS_GETTIMEOFDAY_32 = 78 -SYS_NANOSLEEP_32 = 162 - -_cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64) -_cs.detail = True -_cs_32 = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32) -_cs_32.detail = True - - -@dataclass -class _LinuxSession: - enabled: bool = False - num: int = 1 - den: int = 1 - state_address: int = 0 - - -@dataclass -class _WineSession: - enabled: bool = False - state_address: int = 0 - - -def _run_stopped(callback: Callable[[], bool]) -> bool: - was_running = debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING - if was_running and not debugcore.interrupt_inferior(typedefs.STOP_REASON.PAUSE): - logger.error("Speedhack requires stopping the inferior, but interrupt timed out") - return False - if debugcore.inferior_status != typedefs.INFERIOR_STATUS.STOPPED: - logger.error("Speedhack requires a stopped inferior") - return False - try: - return callback() - finally: - if was_running: - debugcore.continue_inferior() - resumed = False - for _ in range(10_000): - if debugcore.inferior_status == typedefs.INFERIOR_STATUS.RUNNING or debugcore.currentpid == -1: - resumed = True - break - time.sleep(0.0001) - if not resumed: - logger.error("Speedhack continue did not report RUNNING within 1s") - - -class _Speedhack: - def __init__(self) -> None: - self._session = self._session_type() - - def is_installed(self) -> bool: - return self._session.enabled - - def _install(self, speed: float) -> bool: - return _run_stopped(lambda: self._install_stopped(speed)) - - def _install_ratio(self, speed: float) -> Fraction | None: - if self._session.enabled: - logger.error("%s speedhack is already installed", self._name) - return None - if debugcore.currentpid == -1: - logger.error("%s speedhack requires an attached process", self._name) - return None - if self._alloc_name in debugcore.allocated_cave_chunks: - logger.error("%s speedhack memory is already allocated", self._name) - return None - return _speed_to_ratio(speed) - - def reset(self) -> None: - self._session = self._session_type() - debugcore.allocated_cave_chunks.pop(self._alloc_name, None) - - -class LinuxSpeedhack(_Speedhack): - _name = "Linux" - _alloc_name = "PINCE_linux_speedhack" - _session_type = _LinuxSession - - def _install_stopped(self, speed: float) -> bool: - ratio = self._install_ratio(speed) - if ratio is None: - return False - - arch64 = debugcore.inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 - vdso_clock_gettime = _resolve_vdso_function(debugcore.currentpid, "__vdso_clock_gettime", arch64) - vdso_gettimeofday = _resolve_vdso_function(debugcore.currentpid, "__vdso_gettimeofday", arch64) - - if arch64: - builders = ( - ("clock_gettime", _build_clock_gettime_hook, vdso_clock_gettime), - ("gettimeofday", _build_gettimeofday_hook, vdso_gettimeofday), - ("nanosleep", lambda cave, _: _build_nanosleep_hook(cave), None), - ) - else: - builders = ( - ("clock_gettime", _build_clock_gettime_hook_32, vdso_clock_gettime), - ("gettimeofday", _build_gettimeofday_hook_32, vdso_gettimeofday), - ("nanosleep", lambda cave, _: _build_nanosleep_hook_32(cave), None), - ) - disassembler = utils.cs_64 if arch64 else utils.cs_32 - jump_size = JUMP_SIZE if arch64 else JUMP_SIZE_32 - targets = [] - caves = set() - for symbol, build, call_target in builders: - hex_addr = utils.extract_hex_address(debugcore.get_symbol_info(symbol)) - entry_address = utils.safe_str_to_int(hex_addr, 16) if hex_addr else debugcore.resolve_libc_symbol(symbol) - if not entry_address: - continue - needs_trampoline = call_target == entry_address - patch_address = _get_patch_address(entry_address, arch64) - if (target := _detour_target(patch_address, arch64)) is not None: - if not _has_marker(target): - logger.error("%s is already hooked", symbol) - return False - caves.add(target & -CAVE_SIZE) - continue - original_aob, patch_size = _read_patch_bytes(symbol, patch_address, disassembler, jump_size) - if original_aob is None: - continue - targets.append((symbol, patch_address, build, call_target, needs_trampoline, original_aob, patch_size)) - - if caves: - if len(caves) != 1 or targets: - logger.error("Linux speedhack hooks don't match") - return False - cave = caves.pop() - state = cave + (_read_u64(cave + ACTIVE_OFFSET) & 1) * BUFFER_SIZE - num, den = _read_u64(state + NUM_OFFSET), _read_u64(state + DEN_OFFSET) - if not num or not den: - logger.error("Linux speedhack state is invalid") - return False - self._session = _LinuxSession(True, num, den, cave) - self._rebase_state(ratio.numerator, ratio.denominator) - return True - - if not targets: - logger.error("Linux speedhack couldn't locate any time functions to hook") - return False - - cave = debugcore.allocate_cave(CAVE_SIZE, self._alloc_name) - if not cave: - logger.error("Failed to allocate Linux speedhack memory") - return False - - installed = [] - try: - self._initialize_state(cave, ratio.numerator, ratio.denominator) - cursor = (cave + STATE_SIZE + 15) & ~15 - for symbol, address, build, call_target, needs_trampoline, original_aob, patch_size in targets: - if needs_trampoline: - call_target = cursor - trampoline = _build_trampoline(address, bytes.fromhex(original_aob), arch64, call_target) - if trampoline is None: - raise RuntimeError(f"Linux speedhack can't safely relocate the {symbol} prologue") - cursor = _write_cave(cave, cursor, trampoline, symbol) - hook_address = cursor + len(CAVE_MARKER) - cursor = _write_cave(cave, cursor, CAVE_MARKER + build(cave, call_target), symbol) - if arch64: - patch = b"\x48\xb8" + struct.pack(" bool: - """Change the speed multiplier without re-patching anything.""" - if not self._session.enabled: - return self._install(speed) - ratio = _speed_to_ratio(speed) - if ratio is None: - return False - self._rebase_state(ratio.numerator, ratio.denominator) - return True - - def _initialize_state(self, state_addr: int, num: int, den: int) -> None: - buffer = bytearray(BUFFER_SIZE) - struct.pack_into(" None: - state_addr = self._session.state_address - active = _read_u64(state_addr + ACTIVE_OFFSET) & 1 - inactive = active ^ 1 - active_base = state_addr + active * BUFFER_SIZE - inactive_base = state_addr + inactive * BUFFER_SIZE - old_num = _read_u64(active_base + NUM_OFFSET) or self._session.num - old_den = _read_u64(active_base + DEN_OFFSET) or self._session.den - blob = bytearray(BUFFER_SIZE) - struct.pack_into(" bool: - ratio = self._install_ratio(speed) - if ratio is None: - return False - - arch64 = host_arch64 = debugcore.inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 - if host_arch64: - process_name = utils.get_process_name(debugcore.currentpid).lower() - exes = sorted( - (os.path.basename(path).lower() != process_name, int(start, 16)) - for start, _, _, offset, _, _, path in utils.get_regions(debugcore.currentpid) - if path and int(offset, 16) == 0 and path.lower().endswith(".exe") - ) - try: - with debugcore.memory_handle() as mem: - for _, base in exes: - mem.seek(base) - if mem.read(2) != b"MZ": - continue - mem.seek(base + 0x3C) - pe = base + int.from_bytes(mem.read(4), "little") - mem.seek(pe) - if mem.read(4) != b"PE\x00\x00": - continue - mem.seek(pe + 0x18) - magic = int.from_bytes(mem.read(2), "little") - if magic in (0x10B, 0x20B): - arch64 = magic == 0x20B - break - except (OSError, ValueError): - pass - symbol = "RtlQueryPerformanceCounter" - address = _resolve_ntdll_export(debugcore.currentpid, symbol, arch64) - if not address: - logger.error("Wine speedhack couldn't resolve %s", symbol) - return False - address = _get_patch_address(address, arch64) - if (target := _detour_target(address, arch64)) is not None: - cave = target & -CAVE_SIZE - if not _has_marker(target): - logger.error("%s is already hooked", symbol) - return False - if not _read_u64(cave + WINE_NUM_OFFSET) or not _read_u64(cave + WINE_DEN_OFFSET): - logger.error("Wine speedhack state is invalid") - return False - self._session = _WineSession(True, cave) - self._rebase_state(ratio.numerator, ratio.denominator) - return True - if arch64: - original_aob, patch_size = _read_patch_bytes(symbol, address) - else: - original_aob, patch_size = _read_patch_bytes(symbol, address, utils.cs_32, JUMP_SIZE_32) - if original_aob is None: - return False - raw = bytes.fromhex(original_aob.replace(" ", "")) - - cave = debugcore.allocate_cave(CAVE_SIZE, self._alloc_name, 0x50000000 if host_arch64 and not arch64 else None) - if not cave: - logger.error("Failed to allocate Wine speedhack memory") - return False - - installed = [] - try: - self._initialize_state(cave, ratio.numerator, ratio.denominator) - _ensure_writable(address) - if not _step_threads_out_of_range(address, address + patch_size): - raise RuntimeError("Couldn't step all threads out of the patch site") - - tramp_addr = (cave + WINE_STATE_SIZE + 15) & ~15 - trampoline = _build_trampoline(address, raw, arch64, tramp_addr) - if trampoline is None: - raise RuntimeError(f"Wine speedhack can't safely relocate the {symbol} prologue") - wrapper_start = _write_cave(cave, tramp_addr, trampoline, symbol) - wrapper_addr = wrapper_start + len(CAVE_MARKER) - wrapper = (_build_qpc_wrapper if arch64 else _build_qpc_wrapper_32)(cave, tramp_addr) - _write_cave(cave, wrapper_start, CAVE_MARKER + wrapper, symbol) - - if arch64: - jump = b"\x48\xb8" + struct.pack(" bool: - """Change the speed multiplier without re-patching anything.""" - if not self._session.enabled: - return self._install(speed) - ratio = _speed_to_ratio(speed) - if ratio is None: - return False - return _run_stopped(lambda: self._rebase_state(ratio.numerator, ratio.denominator)) - - def _initialize_state(self, state_addr: int, num: int, den: int) -> None: - blob = bytearray(WINE_STATE_SIZE) - struct.pack_into(" bool: - state_addr = self._session.state_address - if _read_u64(state_addr + WINE_INIT_OFFSET): - _write_u64(state_addr + WINE_REAL_BASE_OFFSET, _read_u64(state_addr + WINE_LAST_REAL_OFFSET)) - _write_u64(state_addr + WINE_FAKE_BASE_OFFSET, _read_u64(state_addr + WINE_LAST_FAKE_OFFSET)) - _write_u64(state_addr + WINE_NUM_OFFSET, new_num) - _write_u64(state_addr + WINE_DEN_OFFSET, new_den) - return True - - -def _speed_to_ratio(speed: float) -> Fraction | None: - try: - ratio = Fraction(str(speed)).limit_denominator(1_000_000) - except Exception: - logger.exception("Invalid speedhack speed: %s", speed) - return None - if ratio <= 0: - logger.error("Speedhack speed must be greater than zero: %s", speed) - return None - return ratio - - -def _resolve_vdso_function(pid: int, symbol: str, arch64: bool = True) -> int | None: - # Locate "[vdso]" in the inferior, parse its ELF, and return the absolute address of "symbol". - # Returns None if the lookup fails. The hook builder then falls back to issuing the syscall itself. - if pid <= 0: - return None - vdso_range = None - try: - with open(f"/proc/{pid}/maps") as maps: - for line in maps: - if "[vdso]" not in line: - continue - addr_range = line.split(maxsplit=1)[0] - start_s, end_s = addr_range.split("-") - vdso_range = (int(start_s, 16), int(end_s, 16)) - break - except OSError: - return None - if vdso_range is None: - return None - base, end = vdso_range - try: - with debugcore.memory_handle() as mem: - mem.seek(base) - blob = mem.read(end - base) - except OSError: - return None - try: - expected_class = 2 if arch64 else 1 # ELFCLASS64 vs ELFCLASS32 - if len(blob) < 64 or blob[:4] != b"\x7fELF" or blob[4] != expected_class: - return None - # The vDSO is linked at vaddr 0, so dynamic-segment offsets are direct blob indices. - if arch64: - e_phoff = struct.unpack_from(" len(blob): - break - st_name = struct.unpack_from(" tuple[str | None, int]: - # Disassemble enough whole instructions at "address" to host a jump of "jump_size" bytes. - # The defaults patch x86_64, Wine passes cs_32 for i386 inferiors. - dump = debugcore.hex_dump(address, 32) - if not dump or "??" in dump: - logger.error("Failed to read %s instructions at 0x%x", symbol, address) - return None, 0 - code = bytes(int(b, 16) for b in dump) - disassembler.skipdata = False - consumed = 0 - for _, size, _, _ in disassembler.disasm_lite(code, address): - consumed += size - if consumed >= jump_size: - return _bytes_to_aob(code[:consumed]), consumed - logger.error("Failed to find enough whole instructions to patch %s", symbol) - return None, 0 - - -def _get_patch_address(address: int, arch64: bool) -> int: - endbr = ["F3", "0F", "1E", "FA" if arch64 else "FB"] - return address + 4 if debugcore.hex_dump(address, 4) == endbr else address - - -def _detour_target(address: int, arch64: bool) -> int | None: - raw = debugcore.hex_dump(address, JUMP_SIZE if arch64 else JUMP_SIZE_32) - if not raw or "??" in raw: - return None - code = bytes(int(byte, 16) for byte in raw) - prefix = b"\x48\xb8" if arch64 else b"\xb8" - if code.startswith(prefix) and code.endswith(b"\xff\xe0"): - return int.from_bytes(code[len(prefix) : -2], "little") - return None - - -def _has_marker(target: int) -> bool: - return debugcore.hex_dump(target - len(CAVE_MARKER), len(CAVE_MARKER)) == [f"{byte:02X}" for byte in CAVE_MARKER] - - -def _build_trampoline(address: int, raw: bytes, arch64: bool, tramp_addr: int) -> bytes | None: - for insn in (_cs if arch64 else _cs_32).disasm(raw, address): - if ( - insn.group(capstone.CS_GRP_JUMP) - or insn.group(capstone.CS_GRP_CALL) - or insn.group(capstone.CS_GRP_RET) - or insn.group(capstone.CS_GRP_BRANCH_RELATIVE) - ): - return None - if arch64: - for op in insn.operands: - if op.type == cs_x86.X86_OP_MEM and op.mem.base == cs_x86.X86_REG_RIP: - return None - prologue = (b"\xf3\x0f\x1e\xfa" if arch64 else b"\xf3\x0f\x1e\xfb") + raw - target = address + len(raw) - if arch64: - return prologue + b"\x3e\xff\x25\x00\x00\x00\x00" + struct.pack(" int: - if address + len(blob) > cave + CAVE_SIZE: - raise RuntimeError(f"Speedhack code cave is too small for {symbol}") - _write_verified(address, _bytes_to_aob(blob)) - return (address + len(blob) + 15) & ~15 - - -def _step_threads_out_of_range(low: int, high: int, max_steps: int = 64) -> bool: - info = debugcore.send_command("-thread-info") - if not info: - logger.error("Speedhack couldn't query thread info") - return False - offenders = [tid for tid, addr in re.findall(r'id="(\d+)",[^}]*?frame=\{[^}]*?addr="(0x[0-9a-fA-F]+)"', info) if low <= int(addr, 16) < high] - if not offenders: - return True - current_match = re.search(r'current-thread-id="(\d+)"', info) - scheduler_match = re.search(r'value="(\w+)"', debugcore.send_command("-gdb-show scheduler-locking")) - if not current_match or not scheduler_match: - logger.error("Speedhack couldn't query GDB thread state") - return False - current_thread = current_match.group(1) - scheduler_mode = scheduler_match.group(1) - - success = True - debugcore.send_command("-gdb-set scheduler-locking step") - try: - for tid in offenders: - debugcore.send_command(f"thread {tid}") - for _ in range(max_steps): - pc = _current_pc() - if pc is None: - success = False - break - if not low <= pc < high: - break - debugcore.step_instruction() - if not debugcore.wait_for_stop(2): - debugcore.interrupt_inferior(typedefs.STOP_REASON.PAUSE) - success = False - break - else: - success = False - if not success: - logger.error("Speedhack couldn't step thread %s out of the patch site", tid) - break - finally: - debugcore.send_command(f"thread {current_thread}") - debugcore.send_command(f"-gdb-set scheduler-locking {scheduler_mode}") - return success - - -def _current_pc() -> int | None: - registers = debugcore.read_registers() - if not registers: - return None - raw = registers.get("rip") or registers.get("eip") - pc = utils.extract_hex_address(str(raw)) if raw is not None else None - return int(pc, 16) if pc else None - - -def _vdso_call_or_syscall(vdso_addr: int | None, syscall_nr: int, saves: tuple[str, ...]) -> str: - # Emit asm that invokes the underlying time function. - # If "vdso_addr" is set, we call it as a normal C function where the caller-saved regs in "saves" (rdi/rsi) are - # pushed across the call. - # SysV ABI needs rsp % 16 == 0 before "call" so we pad with 8 only when an even number of regs are saved. - # Otherwise we issue the raw syscall, which preserves rdi/rsi for free. - if vdso_addr is not None: - saves_push = "\n".join(f"push {r}" for r in saves) - saves_pop = "\n".join(f"pop {r}" for r in reversed(saves)) - align_pad = 8 if len(saves) % 2 == 0 else 0 - return f""" - {saves_push} - sub rsp, {align_pad} - mov r11, {hex(vdso_addr)} - call r11 - add rsp, {align_pad} - {saves_pop} - """ - return f""" - mov rax, {syscall_nr} - syscall - """ - - -def _vdso_call_or_syscall_32(vdso_addr: int | None, syscall_nr: int, arg_offsets: tuple[int, ...], syscall_regs: tuple[str, ...]) -> str: - # i386 analogue of _vdso_call_or_syscall. - # The hooked functions are cdecl so their args sit on the caller's stack, - # reachable at the ebp-relative "arg_offsets" (8 and 12) once the prologue runs. - # If "vdso_addr" is set, we push the args right-to-left, call it as a cdecl function and clean the - # stack afterwards. - # esp must be 16-aligned before "call", and the shared hook prologue (push ebp/ebx/esi/edi; sub esp, 64) - # leaves esp % 16 == 12 here, so we pad by (12 - 4 * argc) % 16. - # Otherwise we issue the raw int 0x80, which preserves every register but eax so the frame survives. - if vdso_addr is not None: - argc = len(arg_offsets) - pad = (12 - 4 * argc) % 16 - pad_in = f"sub esp, {pad}" if pad else "" - pushes = "\n".join(f"push dword ptr [ebp + {off}]" for off in reversed(arg_offsets)) - return f""" - {pad_in} - {pushes} - mov eax, {hex(vdso_addr)} - call eax - add esp, {pad + 4 * argc} - """ - loads = "\n".join(f"mov {reg}, dword ptr [ebp + {off}]" for reg, off in zip(syscall_regs, arg_offsets)) - return f""" - {loads} - mov eax, {syscall_nr} - int 0x80 - """ - - -def _scale64_asm(mul_off: int, div_off: int) -> str: - # Shared 64-bit scaling kernel for the i386 hooks. - # Requires esi == state block base. Computes: OUT (64-bit) = VAL (64-bit) * dword[esi + mul_off] / dword[esi + div_off] - # via a 96-bit product divided word-by-word by the 32-bit divisor. - # The top quotient word is dropped because the scaled result fits 64 bits for any real session (num/den keep it in range). - # Fixed ebp-relative scratch slots, shared with the callers' surrounding asm: - # VAL = [ebp-16/-20] (input), OUT = [ebp-36/-40] (result), 96-bit product = [ebp-24/-28/-32]. - # Clobbers eax, ebx, ecx, edx. Leaves esi/edi/ebp untouched. OUT may alias VAL (VAL is fully read before OUT is written). - return f""" - mov eax, dword ptr [ebp - 16] - mov ebx, dword ptr [esi + {mul_off}] - mul ebx - mov dword ptr [ebp - 24], eax - mov ecx, edx - mov eax, dword ptr [ebp - 20] - mul ebx - add eax, ecx - mov dword ptr [ebp - 28], eax - adc edx, 0 - mov dword ptr [ebp - 32], edx - mov ebx, dword ptr [esi + {div_off}] - xor edx, edx - mov eax, dword ptr [ebp - 32] - div ebx - mov eax, dword ptr [ebp - 28] - div ebx - mov dword ptr [ebp - 40], eax - mov eax, dword ptr [ebp - 24] - div ebx - mov dword ptr [ebp - 36], eax - """ - - -def _build_clock_gettime_hook(state_addr: int, vdso_addr: int | None) -> bytes: - # rdi = clockid_t, rsi = struct timespec*. - # endbr64 is there because libc's entry may be reached via an indirect branch on CET-enabled processes. - invoke = _vdso_call_or_syscall(vdso_addr, SYS_CLOCK_GETTIME, ("rdi", "rsi")) - # For some stupid reason, keystone can't assemble "endbr64" so we just write the bytes directly: - # 0xF3 0x0F 0x1E 0xFA - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfa - {invoke} - test eax, eax - jne done - cmp edi, 7 - ja done - cmp edi, 2 - je done - cmp edi, 3 - je done - cmp edi, 5 - je done - cmp edi, 6 - je done - mov r11, {hex(state_addr)} - mov r10, qword ptr [r11 + {ACTIVE_OFFSET}] - and r10, 1 - imul r10, r10, {BUFFER_SIZE} - add r11, r10 - mov r10d, edi - shl r10, 4 - add r10, r11 - mov r8, qword ptr [rsi] - imul r8, r8, 1000000000 - add r8, qword ptr [rsi + 8] - sub r8, qword ptr [r10] - jae delta_ok - xor r8d, r8d - delta_ok: - mov rax, r8 - mov rcx, qword ptr [r11 + {NUM_OFFSET}] - mul rcx - mov rcx, qword ptr [r11 + {DEN_OFFSET}] - div rcx - add rax, qword ptr [r10 + 8] - mov rcx, 1000000000 - xor rdx, rdx - div rcx - mov qword ptr [rsi], rax - mov qword ptr [rsi + 8], rdx - xor eax, eax - done: - ret - """ - return _assemble_hook(asm) - - -def _build_gettimeofday_hook(state_addr: int, vdso_addr: int | None) -> bytes: - # rdi = struct timeval*, rsi = struct timezone* (unused). - invoke = _vdso_call_or_syscall(vdso_addr, SYS_GETTIMEOFDAY, ("rdi",)) - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfa - {invoke} - test eax, eax - jne done - test rdi, rdi - jz done - mov r11, {hex(state_addr)} - mov r10, qword ptr [r11 + {ACTIVE_OFFSET}] - and r10, 1 - imul r10, r10, {BUFFER_SIZE} - add r11, r10 - mov r8, qword ptr [rdi] - imul r8, r8, 1000000000 - mov rax, qword ptr [rdi + 8] - imul rax, rax, 1000 - add r8, rax - sub r8, qword ptr [r11] - jae delta_ok - xor r8d, r8d - delta_ok: - mov rax, r8 - mov rcx, qword ptr [r11 + {NUM_OFFSET}] - mul rcx - mov rcx, qword ptr [r11 + {DEN_OFFSET}] - div rcx - add rax, qword ptr [r11 + 8] - mov rcx, 1000000000 - xor rdx, rdx - div rcx - mov qword ptr [rdi], rax - mov rax, rdx - mov rcx, 1000 - xor rdx, rdx - div rcx - mov qword ptr [rdi + 8], rax - xor eax, eax - done: - ret - """ - return _assemble_hook(asm) - - -def _build_nanosleep_hook(state_addr: int) -> bytes: - # rdi = const struct timespec* req, rsi = struct timespec* rem. - # Scales req by den/num, retries on EINTR until the full real duration elapses, - # then zeros the caller's rem (the game perceives a complete sleep). - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfa - push rsi - sub rsp, 16 - mov r11, {hex(state_addr)} - mov r10, qword ptr [r11 + {ACTIVE_OFFSET}] - and r10, 1 - imul r10, r10, {BUFFER_SIZE} - add r11, r10 - mov r8, qword ptr [rdi] - imul r8, r8, 1000000000 - add r8, qword ptr [rdi + 8] - mov rax, r8 - mov rcx, qword ptr [r11 + {DEN_OFFSET}] - mul rcx - mov rcx, qword ptr [r11 + {NUM_OFFSET}] - test rcx, rcx - jz cleanup - div rcx - mov rcx, 1000000000 - xor rdx, rdx - div rcx - mov qword ptr [rsp], rax - mov qword ptr [rsp + 8], rdx - retry: - mov rdi, rsp - mov rsi, rsp - mov rax, {SYS_NANOSLEEP} - syscall - test rax, rax - jz cleanup - cmp rax, -4 - je retry - cleanup: - add rsp, 16 - pop rsi - test rsi, rsi - jz done - mov qword ptr [rsi], 0 - mov qword ptr [rsi + 8], 0 - done: - xor eax, eax - ret - """ - return _assemble_hook(asm) - - -def _build_clock_gettime_hook_32(state_addr: int, vdso_addr: int | None) -> bytes: - # i386 cdecl: [ebp+8] = clockid_t clk, [ebp+12] = struct timespec* tp (32-bit tv_sec/tv_nsec). - # endbr32 so the jmp-eax detour lands on a valid IBT endbranch under CET. - invoke = _vdso_call_or_syscall_32(vdso_addr, SYS_CLOCK_GETTIME_32, (8, 12), ("ebx", "ecx")) - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfb - push ebp - mov ebp, esp - push ebx - push esi - push edi - sub esp, 64 - {invoke} - test eax, eax - jne done - mov ecx, dword ptr [ebp + 8] - cmp ecx, 7 - ja done - cmp ecx, 2 - je done - cmp ecx, 3 - je done - cmp ecx, 5 - je done - cmp ecx, 6 - je done - mov esi, {hex(state_addr)} - mov eax, dword ptr [esi + {ACTIVE_OFFSET}] - and eax, 1 - imul eax, eax, {BUFFER_SIZE} - add esi, eax - mov edi, dword ptr [ebp + 12] - mov eax, dword ptr [edi] - mov ebx, 1000000000 - mul ebx - add eax, dword ptr [edi + 4] - adc edx, 0 - mov dword ptr [ebp - 16], eax - mov dword ptr [ebp - 20], edx - mov eax, dword ptr [ebp + 8] - shl eax, 4 - add eax, esi - mov dword ptr [ebp - 44], eax - mov ecx, dword ptr [ebp - 44] - mov eax, dword ptr [ebp - 16] - sub eax, dword ptr [ecx] - mov dword ptr [ebp - 16], eax - mov eax, dword ptr [ebp - 20] - sbb eax, dword ptr [ecx + 4] - mov dword ptr [ebp - 20], eax - jnc delta_ok - mov dword ptr [ebp - 16], 0 - mov dword ptr [ebp - 20], 0 - delta_ok: - {_scale64_asm(NUM_OFFSET, DEN_OFFSET)} - mov ecx, dword ptr [ebp - 44] - mov eax, dword ptr [ebp - 36] - add eax, dword ptr [ecx + 8] - mov dword ptr [ebp - 36], eax - mov eax, dword ptr [ebp - 40] - adc eax, dword ptr [ecx + 12] - mov dword ptr [ebp - 40], eax - mov ecx, 1000000000 - xor edx, edx - mov eax, dword ptr [ebp - 40] - div ecx - mov eax, dword ptr [ebp - 36] - div ecx - mov dword ptr [edi], eax - mov dword ptr [edi + 4], edx - xor eax, eax - done: - add esp, 64 - pop edi - pop esi - pop ebx - pop ebp - ret - """ - return _assemble_hook(asm, typedefs.INFERIOR_ARCH.ARCH_32) - - -def _build_gettimeofday_hook_32(state_addr: int, vdso_addr: int | None) -> bytes: - # i386 cdecl: [ebp+8] = struct timeval* tv (32-bit tv_sec/tv_usec), [ebp+12] = struct timezone* tz (unused). - # Scales around the CLOCK_REALTIME base stored at state+0 (real) / state+8 (fake), like the x64 hook. - invoke = _vdso_call_or_syscall_32(vdso_addr, SYS_GETTIMEOFDAY_32, (8, 12), ("ebx", "ecx")) - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfb - push ebp - mov ebp, esp - push ebx - push esi - push edi - sub esp, 64 - {invoke} - test eax, eax - jne done - mov edi, dword ptr [ebp + 8] - test edi, edi - jz done - mov esi, {hex(state_addr)} - mov eax, dword ptr [esi + {ACTIVE_OFFSET}] - and eax, 1 - imul eax, eax, {BUFFER_SIZE} - add esi, eax - mov eax, dword ptr [edi] - mov ebx, 1000000000 - mul ebx - mov dword ptr [ebp - 16], eax - mov dword ptr [ebp - 20], edx - mov eax, dword ptr [edi + 4] - mov ebx, 1000 - mul ebx - add dword ptr [ebp - 16], eax - adc dword ptr [ebp - 20], edx - mov eax, dword ptr [ebp - 16] - sub eax, dword ptr [esi] - mov dword ptr [ebp - 16], eax - mov eax, dword ptr [ebp - 20] - sbb eax, dword ptr [esi + 4] - mov dword ptr [ebp - 20], eax - jnc delta_ok - mov dword ptr [ebp - 16], 0 - mov dword ptr [ebp - 20], 0 - delta_ok: - {_scale64_asm(NUM_OFFSET, DEN_OFFSET)} - mov eax, dword ptr [ebp - 36] - add eax, dword ptr [esi + 8] - mov dword ptr [ebp - 36], eax - mov eax, dword ptr [ebp - 40] - adc eax, dword ptr [esi + 12] - mov dword ptr [ebp - 40], eax - mov ecx, 1000000000 - xor edx, edx - mov eax, dword ptr [ebp - 40] - div ecx - mov eax, dword ptr [ebp - 36] - div ecx - mov dword ptr [edi], eax - mov eax, edx - xor edx, edx - mov ecx, 1000 - div ecx - mov dword ptr [edi + 4], eax - xor eax, eax - done: - add esp, 64 - pop edi - pop esi - pop ebx - pop ebp - ret - """ - return _assemble_hook(asm, typedefs.INFERIOR_ARCH.ARCH_32) - - -def _build_nanosleep_hook_32(state_addr: int) -> bytes: - # i386 cdecl: [ebp+8] = const struct timespec* req, [ebp+12] = struct timespec* rem (32-bit fields). - # No vDSO entry for nanosleep, so always int 0x80 (syscall 162). - # Scales the requested duration by den/num (inverse of the read scaling), - # retries on EINTR until the full real duration elapses, then zeros the caller's rem. - # Local kernel timespec at [ebp-48]=tv_sec / [ebp-44]=tv_nsec. - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfb - push ebp - mov ebp, esp - push ebx - push esi - push edi - sub esp, 64 - mov esi, {hex(state_addr)} - mov eax, dword ptr [esi + {ACTIVE_OFFSET}] - and eax, 1 - imul eax, eax, {BUFFER_SIZE} - add esi, eax - mov edi, dword ptr [ebp + 8] - mov eax, dword ptr [edi] - mov ebx, 1000000000 - mul ebx - add eax, dword ptr [edi + 4] - adc edx, 0 - mov dword ptr [ebp - 16], eax - mov dword ptr [ebp - 20], edx - mov eax, dword ptr [esi + {NUM_OFFSET}] - test eax, eax - jz cleanup - {_scale64_asm(DEN_OFFSET, NUM_OFFSET)} - mov ecx, 1000000000 - xor edx, edx - mov eax, dword ptr [ebp - 40] - div ecx - mov eax, dword ptr [ebp - 36] - div ecx - mov dword ptr [ebp - 48], eax - mov dword ptr [ebp - 44], edx - retry: - lea ebx, [ebp - 48] - lea ecx, [ebp - 48] - mov eax, {SYS_NANOSLEEP_32} - int 0x80 - test eax, eax - jz cleanup - cmp eax, -4 - je retry - cleanup: - mov edx, dword ptr [ebp + 12] - test edx, edx - jz done - mov dword ptr [edx], 0 - mov dword ptr [edx + 4], 0 - done: - xor eax, eax - add esp, 64 - pop edi - pop esi - pop ebx - pop ebp - ret - """ - return _assemble_hook(asm, typedefs.INFERIOR_ARCH.ARCH_32) - - -def _write_verified(address: int, aob: str) -> None: - """write_memory swallows OSError/ValueError, so confirm the patch actually landed. - Raises RuntimeError on mismatch so install/restore can detect a failed write.""" - debugcore.write_memory(address, typedefs.ByteArrayValueType(len(aob.split())), aob) - expected = aob.split() - readback = debugcore.hex_dump(address, len(expected)) - if [b.lower() for b in readback] != [b.lower() for b in expected]: - raise RuntimeError(f"Speedhack write verification failed at {hex(address)}") - - -def _restore_hook(symbol: str, address: int, original_aob: str) -> None: - try: - _write_verified(address, original_aob) - except Exception: - logger.exception("Failed to restore %s", symbol) - - -def _assemble_hook(asm: str, arch: int = typedefs.INFERIOR_ARCH.ARCH_64) -> bytes: - encoded = utils.assemble(asm, 0, arch) - if encoded is None: - raise RuntimeError("Failed to assemble speedhack hook") - return bytes(encoded[0]) - - -def _bytes_to_aob(data: bytes) -> str: - return " ".join(f"{b:02x}" for b in data) - - -def _read_u64(address: int) -> int: - result = debugcore.read_memory(address, _U64_LE) - return int(result) if result is not None else 0 - - -def _mprotect_cave(address: int) -> None: - # malloc only guarantees 16-byte alignment, so the cave can start anywhere within a page and straddle into the next. - # We mprotect both pages unconditionally, which is cheaper than checking and harmless if only one is used. - page = os.sysconf("SC_PAGE_SIZE") - start = address & ~(page - 1) - if not debugcore.mprotect_memory(start, 2 * page): - logger.error(f"Failed to change protection for speedhack memory at {hex(address)}") - - -def _ensure_writable(address: int) -> None: - region = utils.get_region_info(debugcore.currentpid, address) - if region is not None and region.perms and "w" in region.perms and "x" in region.perms: - return - _mprotect_cave(address) - - -def _build_qpc_wrapper(state_addr: int, tramp_addr: int) -> bytes: - # RtlQueryPerformanceCounter(LARGE_INTEGER *counter) -> BOOLEAN, - # Microsoft x64 ABI: rcx = counter, returns TRUE. - # Call the original (it fills *counter with the real value V), - # then overwrite *counter with fake = fake_base + (V - real_base) * num / den. - # Base is captured on the first call (INIT). - # rsp is 16-byte aligned before the call (entry+8, push rbp, push rcx, sub 40). - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfa - push rbp - mov rbp, rsp - push rcx - sub rsp, 40 - mov r11, {hex(tramp_addr)} - call r11 - add rsp, 40 - pop rcx - mov rax, qword ptr [rcx] - mov r11, {hex(state_addr)} - mov r8, qword ptr [r11 + {WINE_INIT_OFFSET}] - test r8, r8 - jnz scale - mov qword ptr [r11 + {WINE_REAL_BASE_OFFSET}], rax - mov qword ptr [r11 + {WINE_FAKE_BASE_OFFSET}], rax - mov qword ptr [r11 + {WINE_INIT_OFFSET}], 1 - scale: - mov r9, rax - sub rax, qword ptr [r11 + {WINE_REAL_BASE_OFFSET}] - jae delta_ok - xor eax, eax - delta_ok: - mov r10, qword ptr [r11 + {WINE_NUM_OFFSET}] - mul r10 - mov r10, qword ptr [r11 + {WINE_DEN_OFFSET}] - div r10 - add rax, qword ptr [r11 + {WINE_FAKE_BASE_OFFSET}] - mov qword ptr [r11 + {WINE_LAST_REAL_OFFSET}], r9 - mov qword ptr [r11 + {WINE_LAST_FAKE_OFFSET}], rax - mov qword ptr [rcx], rax - mov eax, 1 - pop rbp - ret - """ - return _assemble_hook(asm) - - -def _build_qpc_wrapper_32(state_addr: int, tramp_addr: int) -> bytes: - # Same idea as the x64 wrapper for i386 __stdcall: - # the counter pointer is the one stack arg and the callee pops it (ret 4). - # The 64-bit math (fake = fake_base + (V - real_base) * num / den) runs on 32-bit ops: - # a 96-bit product (delta_lo*num and delta_hi*num combined) divided word by word by den. - # num/den fit 32 bits (speeds 0.2-10.0) and the result fits 64 bits for any real session, - # so the top division word is dropped. - asm = f""" - .byte 0xf3, 0x0f, 0x1e, 0xfb - push ebp - mov ebp, esp - push ebx - push esi - push edi - push dword ptr [ebp + 8] - mov eax, {hex(tramp_addr)} - call eax - sub esp, 48 - mov edi, dword ptr [ebp + 8] - mov eax, dword ptr [edi] - mov dword ptr [ebp - 40], eax - mov eax, dword ptr [edi + 4] - mov dword ptr [ebp - 44], eax - mov esi, {hex(state_addr)} - mov eax, dword ptr [esi + {WINE_INIT_OFFSET}] - or eax, dword ptr [esi + {WINE_INIT_OFFSET + 4}] - jnz do_scale - mov eax, dword ptr [ebp - 40] - mov dword ptr [esi + {WINE_REAL_BASE_OFFSET}], eax - mov dword ptr [esi + {WINE_FAKE_BASE_OFFSET}], eax - mov eax, dword ptr [ebp - 44] - mov dword ptr [esi + {WINE_REAL_BASE_OFFSET + 4}], eax - mov dword ptr [esi + {WINE_FAKE_BASE_OFFSET + 4}], eax - mov dword ptr [esi + {WINE_INIT_OFFSET}], 1 - mov dword ptr [esi + {WINE_INIT_OFFSET + 4}], 0 - do_scale: - mov eax, dword ptr [ebp - 40] - sub eax, dword ptr [esi + {WINE_REAL_BASE_OFFSET}] - mov dword ptr [ebp - 16], eax - mov eax, dword ptr [ebp - 44] - sbb eax, dword ptr [esi + {WINE_REAL_BASE_OFFSET + 4}] - mov dword ptr [ebp - 20], eax - jnc delta_ok - mov dword ptr [ebp - 16], 0 - mov dword ptr [ebp - 20], 0 - delta_ok: - mov eax, dword ptr [ebp - 16] - mov ebx, dword ptr [esi + {WINE_NUM_OFFSET}] - mul ebx - mov dword ptr [ebp - 24], eax - mov ecx, edx - mov eax, dword ptr [ebp - 20] - mul ebx - add eax, ecx - mov dword ptr [ebp - 28], eax - adc edx, 0 - mov dword ptr [ebp - 32], edx - mov ebx, dword ptr [esi + {WINE_DEN_OFFSET}] - xor edx, edx - mov eax, dword ptr [ebp - 32] - div ebx - mov eax, dword ptr [ebp - 28] - div ebx - mov dword ptr [ebp - 28], eax - mov eax, dword ptr [ebp - 24] - div ebx - mov dword ptr [ebp - 24], eax - mov eax, dword ptr [ebp - 24] - add eax, dword ptr [esi + {WINE_FAKE_BASE_OFFSET}] - mov ecx, eax - mov eax, dword ptr [ebp - 28] - adc eax, dword ptr [esi + {WINE_FAKE_BASE_OFFSET + 4}] - mov dword ptr [edi], ecx - mov dword ptr [edi + 4], eax - mov edx, dword ptr [ebp - 40] - mov dword ptr [esi + {WINE_LAST_REAL_OFFSET}], edx - mov edx, dword ptr [ebp - 44] - mov dword ptr [esi + {WINE_LAST_REAL_OFFSET + 4}], edx - mov dword ptr [esi + {WINE_LAST_FAKE_OFFSET}], ecx - mov dword ptr [esi + {WINE_LAST_FAKE_OFFSET + 4}], eax - mov eax, 1 - add esp, 48 - pop edi - pop esi - pop ebx - pop ebp - ret 4 - """ - return _assemble_hook(asm, typedefs.INFERIOR_ARCH.ARCH_32) - - -def _write_u64(address: int, value: int) -> None: - debugcore.write_memory(address, _U64_LE, value) - - -def _resolve_ntdll_export(pid: int, symbol: str, arch64: bool = True) -> int | None: - # Resolve a named ntdll.dll export to its runtime address. - # gdb doesn't know PE exports, so we parse the export directory out of inferior memory. - # A loaded PE spans several mappings, the one at file offset 0 holds the headers and its start is the image base. - # A WoW64 prefix can map both a 32 and 64-bits ntdll, - # so try each and let _parse_pe_export drop the one whose bitness doesn't match. - if pid <= 0: - return None - try: - bases = [ - int(start, 16) - for start, _, _, map_offset, _, _, path in utils.get_regions(pid) - if path and os.path.basename(path).lower() == "ntdll.dll" and int(map_offset, 16) == 0 - ] - with debugcore.memory_handle() as mem: - for base in bases: - address = _parse_pe_export(mem, base, symbol, arch64) - if address: - return address - except OSError: - return None - return None - - -def _parse_pe_export(mem: io.BufferedReader, base: int, symbol: str, arch64: bool = True) -> int | None: - # Walk a loaded PE's export directory. - # In a loaded image an RVA is just an offset from the base. - # The data directory sits at optional-header offset 112 on PE32+ (x86_64) but 96 on PE32 (i386), - # since PE32's ImageBase/pointers are 4 bytes instead of 8. - def read(addr: int, size: int) -> bytes: - mem.seek(addr) - return mem.read(size) - - header = read(base, 0x400) - if len(header) < 0x40 or header[:2] != b"MZ": - return None - e_lfanew = struct.unpack_from(" len(header) or header[e_lfanew : e_lfanew + 4] != b"PE\x00\x00": - return None - opt = e_lfanew + 24 - if struct.unpack_from(" len(header): - return None - export_rva = struct.unpack_from("= num_funcs: - return None - func_rva = struct.unpack_from(" - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -# IMPORTANT: Any constant involving only the GUI should be declared within the GUI folder - -import collections, logging, queue, struct, sys -from typing import Any, Callable, Literal -from libpince import regexes - -_logger = logging.getLogger("PINCE") - - -class PATHS: - GDB = "/bin/gdb" # Use utils.get_default_gdb_path() - TMP = "/tmp/PINCE/" # Use utils.get_tmp_path() - IPC = "/dev/shm/PINCE_IPC/" # Use utils.get_ipc_path() - FROM_PINCE = "/from_PINCE" # Use utils.get_from_pince_file() - TO_PINCE = "/to_PINCE" # Use utils.get_to_pince_file() - - -class USER_PATHS: - # Use utils.get_user_path() to make use of these - CONFIG = ".config/" - ROOT = CONFIG + "PINCE/" - GDBINIT = ROOT + "gdbinit" - GDBINIT_AA = ROOT + "gdbinit_after_attach" - PINCEINIT = ROOT + "pinceinit.py" - PINCEINIT_AA = ROOT + "pinceinit_after_attach.py" - - @staticmethod - def get_init_files() -> tuple[str, str, str, str]: - return ( - USER_PATHS.GDBINIT, - USER_PATHS.GDBINIT_AA, - USER_PATHS.PINCEINIT, - USER_PATHS.PINCEINIT_AA, - ) - - -class INFERIOR_STATUS: - RUNNING = 1 - STOPPED = 2 - - -class INFERIOR_ARCH: - ARCH_32 = 1 - ARCH_64 = 2 - - -class BREAKPOINT_TYPE: - HARDWARE = 1 - SOFTWARE = 2 - - -class WATCHPOINT_TYPE: - WRITE_ONLY = 1 - READ_ONLY = 2 - BOTH = 3 - - -class BREAKPOINT_ON_HIT: - BREAK = 1 - FIND_CODE = 2 - FIND_ADDR = 3 - TRACE = 4 - - -class BREAKPOINT_MODIFY: - CONDITION = 1 - ENABLE = 2 - DISABLE = 3 - ENABLE_ONCE = 4 - ENABLE_COUNT = 5 - ENABLE_DELETE = 6 - - -class STEP_MODE: - SINGLE_STEP = 1 - STEP_OVER = 2 - - -class TRACE_STATUS: - IDLE = 1 - TRACING = 2 - FINISHED = 3 - - -class STOP_REASON: - PAUSE = 1 - DEBUG = 2 - - -class ATTACH_RESULT: - ATTACH_SELF = 1 - SUCCESSFUL = 2 - PROCESS_NOT_VALID = 3 - ALREADY_DEBUGGING = 4 - ALREADY_TRACED = 5 - PERM_DENIED = 6 - - -class TOGGLE_ATTACH: - ATTACHED = 1 - DETACHED = 2 - - -class REGISTERS: - GENERAL_32 = ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp", "eip"] - GENERAL_64 = [ - "rax", - "rbx", - "rcx", - "rdx", - "rsi", - "rdi", - "rbp", - "rsp", - "rip", - "r8", - "r9", - "r10", - "r11", - "r12", - "r13", - "r14", - "r15", - ] - SEGMENT = ["cs", "ss", "ds", "es", "fs", "gs"] - FLAG = ["cf", "pf", "af", "zf", "sf", "tf", "if", "df", "of"] - - class FLOAT: - ST = ["st" + str(i) for i in range(8)] - XMM_32 = ["xmm" + str(i) for i in range(8)] - XMM_64 = ["xmm" + str(i) for i in range(16)] - - -class FREEZE_TYPE: - DEFAULT = 0 - ALLOW_INCREMENT = 1 - ALLOW_DECREMENT = 2 - - -class VALUE_REPR: - UNSIGNED = 0 - SIGNED = 1 - HEX = 2 - - -class SCAN_INDEX: - INT_ANY = 0 - INT8 = 1 - INT16 = 2 - INT32 = 3 - INT64 = 4 - FLOAT_ANY = 5 - FLOAT32 = 6 - FLOAT64 = 7 - ANY = 8 - STRING = 9 - AOB = 10 # Array of Bytes - - -# GDB already provides breakpoint info in English, no need to make these translatable -on_hit_to_text_dict = { - BREAKPOINT_ON_HIT.BREAK: "Break", - BREAKPOINT_ON_HIT.FIND_CODE: "Find Code", - BREAKPOINT_ON_HIT.FIND_ADDR: "Find Address", - BREAKPOINT_ON_HIT.TRACE: "Trace", -} - - -class SCAN_TYPE: - EXACT = 0 - NOT = 1 - INCREASED = 2 - INCREASED_BY = 3 - DECREASED = 4 - DECREASED_BY = 5 - LESS = 6 - MORE = 7 - BETWEEN = 8 - CHANGED = 9 - UNCHANGED = 10 - UNKNOWN = 11 - - -class SCAN_MODE: - NEW = 0 - ONGOING = 1 - - -class ENDIANNESS: - HOST = 0 - LITTLE = 1 - BIG = 2 - - -_HOST_ENDIANNESS = ENDIANNESS.LITTLE if sys.byteorder == "little" else ENDIANNESS.BIG - -# size-->int, any other field-->str -tuple_breakpoint_info = collections.namedtuple( - "tuple_breakpoint_info", - "number breakpoint_type disp enabled address size on_hit hit_count enable_count condition", -) - -# start, end-->int, perms-->str, file_name-->str -tuple_region_info = collections.namedtuple("tuple_region_info", "start end perms file_name region_index") - -# all fields-->str/None -tuple_examine_expression = collections.namedtuple("tuple_examine_expression", "all address symbol") - -# all fields-->bool -gdb_output_mode = collections.namedtuple("gdb_output_mode", "async_output command_output command_info") - - -class GDBInitializeException(Exception): - def __init__(self, message: str = "GDB not initialized") -> None: - super(GDBInitializeException, self).__init__(message) - - -class Frozen: - def __init__(self, value: Any, freeze_type: int = FREEZE_TYPE.DEFAULT) -> None: - self.value = value - self.freeze_type = freeze_type - self.enabled = False - - -class ScriptEntry: - """An address table row that runs a Libpince Engine script when toggled instead of freezing a value. - - Only the script is serialized to the cheat table. - Namespace is built on first enable and kept so variables set by the [ENABLE] section survive - into a later [DISABLE] run within the same session. - """ - - def __init__(self, script: str = "") -> None: - self.script = script - self.namespace: dict[str, Any] | None = None - - -class ValueType: - def __init__(self) -> None: - if type(self) is ValueType: - raise TypeError("ValueType is a base class. Construct a concrete value type") - - def serialize(self) -> tuple[int, ...]: - return ( - _SERIALIZED_IDS_BY_TYPE[type(self), self._serialization_args()], - getattr(self, "length", 10), - getattr(self, "zero_terminate", True), - getattr(self, "value_repr", VALUE_REPR.UNSIGNED), - getattr(self, "endian", ENDIANNESS.HOST), - ) - - @staticmethod - def deserialize(data: tuple | list) -> "ValueType": - if not data or type(data[0]) is not int: - raise TypeError("Serialized value types must start with an integer ID") - serialized_id = data[0] - value_type_class, constructor_args = _SERIALIZED_TYPE_IDS[serialized_id] - if value_type_class is BitFieldValueType: - if len(data) != 4: - raise TypeError("Serialized BitField types must contain four fields") - _, bits, start_bit, value_repr = data - return value_type_class(bits, start_bit, value_repr=value_repr) - if len(data) == 4: - data = (*data, ENDIANNESS.HOST) - elif len(data) != 5: - raise TypeError("Serialized value types must contain four or five fields") - serialized_id, length, zero_terminate, value_repr, endian = data - value_type = value_type_class(*constructor_args) - for name, value in (("length", length), ("zero_terminate", zero_terminate), ("value_repr", value_repr), ("endian", endian)): - if hasattr(value_type, name): - setattr(value_type, name, value) - return value_type - - def _serialization_args(self) -> tuple[Any, ...]: - return () - - def _endian_suffix(self) -> str: - if self.endian == ENDIANNESS.LITTLE: - return "" - if self.endian == ENDIANNESS.BIG: - return "" - return "" - - def _repr_suffix(self) -> str: - if self.value_repr == VALUE_REPR.SIGNED: - return "(s)" - if self.value_repr == VALUE_REPR.HEX: - return "(h)" - return "" - - def _apply_endian(self, data: bytes) -> bytes: - if self.endian != ENDIANNESS.HOST and self.endian != _HOST_ENDIANNESS: - return data[::-1] - return data - - @property - def read_size(self) -> int | None: - """Number of bytes required for a memory read.""" - raise NotImplementedError - - def parse(self, text: str) -> Any | None: - raise NotImplementedError - - def decode(self, data: bytes) -> Any: - raise NotImplementedError - - def encode(self, value: Any) -> bytes | None: - raise NotImplementedError - - def text(self) -> str: - raise NotImplementedError - - -class IntegerValueType(ValueType): - _struct_code_by_bits = {8: "B", 16: "H", 32: "I", 64: "Q"} - - def __init__( - self, - bits: Literal[8, 16, 32, 64] = 32, - *, - value_repr: int = VALUE_REPR.UNSIGNED, - endian: int = ENDIANNESS.HOST, - ) -> None: - if type(bits) is not int or bits not in self._struct_code_by_bits: - raise ValueError("Integer bits must be 8, 16, 32, or 64") - self.bits = bits - self.value_repr = value_repr - self.endian = endian - - def _serialization_args(self) -> tuple[int]: - return (self.bits,) - - @property - def read_size(self) -> int: - return self.bits // 8 - - def parse(self, text: str) -> int | None: - if not text: - _logger.error("Missing string parameter") - return None - text = text.strip() - try: - value = int(text, 0) - except ValueError: - try: - value = int(float(text)) - except (ValueError, TypeError, OverflowError): - try: - if regexes.hex_arithmetic.fullmatch(text) and "**" not in text: - return int(eval(text)) % (1 << self.bits) - except Exception: - pass - _logger.error(f"{text} can't be parsed as integer or hexadecimal") - return None - return value % (1 << self.bits) - - def decode(self, data: bytes) -> str | int: - data_type = self._struct_code_by_bits[self.bits] - if self.value_repr == VALUE_REPR.SIGNED: - data_type = data_type.lower() - result = struct.unpack_from(data_type, self._apply_endian(data))[0] - return hex(result) if self.value_repr == VALUE_REPR.HEX else result - - def encode(self, value: Any) -> bytes | None: - if isinstance(value, str): - value = self.parse(value) - if value is None: - return None - elif isinstance(value, int): - value %= 1 << self.bits - return self._apply_endian(struct.pack(self._struct_code_by_bits[self.bits], value)) - - def text(self) -> str: - return f"Int{self.bits}{self._repr_suffix()}{self._endian_suffix()}" - - -class BitFieldValueType(ValueType): - def __init__( - self, - bits: int = 1, - start_bit: int = 0, - *, - value_repr: int = VALUE_REPR.UNSIGNED, - ) -> None: - if type(bits) is not int or not 1 <= bits <= 64: - raise ValueError("BitField bits must be between 1 and 64") - if type(start_bit) is not int or not 0 <= start_bit <= 7: - raise ValueError("BitField start bit must be between 0 and 7") - if type(value_repr) is not int or value_repr not in (VALUE_REPR.UNSIGNED, VALUE_REPR.SIGNED, VALUE_REPR.HEX): - raise ValueError("Invalid BitField representation") - self.bits = bits - self.start_bit = start_bit - self.value_repr = value_repr - - def serialize(self) -> tuple[int, int, int, int]: - return _SERIALIZED_IDS_BY_TYPE[type(self), self._serialization_args()], self.bits, self.start_bit, self.value_repr - - @property - def read_size(self) -> int: - return (self.start_bit + self.bits + 7) // 8 - - def _validated(self, value: Any) -> int | None: - limit = 1 << self.bits - minimum, maximum = (-limit // 2, limit // 2 - 1) if self.value_repr == VALUE_REPR.SIGNED else (0, limit - 1) - if type(value) is not int or not minimum <= value <= maximum: - _logger.error(f"{value!r} is outside the range [{minimum}, {maximum}] for {self.text()}") - return None - return value - - def parse(self, text: str) -> int | None: - if not text: - _logger.error("Missing string parameter") - return None - try: - value = int(text, 0) - except ValueError: - try: - if any(op in text for op in "+-*/") and regexes.hex_arithmetic.fullmatch(text) and "**" not in text: - return self._validated(int(eval(text))) - except Exception: - pass - _logger.error(f"{text!r} can't be parsed as BitField value") - return None - return self._validated(value) - - def decode(self, data: bytes) -> str | int: - result = (int.from_bytes(data, "little") >> self.start_bit) & ((1 << self.bits) - 1) - if self.value_repr == VALUE_REPR.SIGNED and result >= 1 << (self.bits - 1): - result -= 1 << self.bits - return hex(result) if self.value_repr == VALUE_REPR.HEX else result - - def encode(self, value: Any) -> bytes | None: - raise TypeError("BitField values require existing bytes, use encode_into()") - - def encode_into(self, current: bytes, value: Any) -> bytes | None: - if len(current) != self.read_size: - raise ValueError(f"{self.text()} requires exactly {self.read_size} existing bytes") - value = self.parse(value) if isinstance(value, str) else self._validated(value) - if value is None: - return None - value_mask = (1 << self.bits) - 1 - field_mask = value_mask << self.start_bit - current_value = int.from_bytes(current, "little") - result = (current_value & ~field_mask) | ((value & value_mask) << self.start_bit) - return result.to_bytes(self.read_size, "little") - - def text(self) -> str: - return f"BitField[{self.bits}]@{self.start_bit}{self._repr_suffix()}" - - -class FloatValueType(ValueType): - _struct_code_by_bits = {32: "f", 64: "d"} - - def __init__( - self, - bits: Literal[32, 64] = 32, - *, - endian: int = ENDIANNESS.HOST, - ) -> None: - if type(bits) is not int or bits not in self._struct_code_by_bits: - raise ValueError("Float bits must be 32 or 64") - self.bits = bits - self.endian = endian - - def _serialization_args(self) -> tuple[int]: - return (self.bits,) - - @property - def read_size(self) -> int: - return self.bits // 8 - - def parse(self, text: str) -> float | None: - if not text: - _logger.error("Missing string parameter") - return None - text = text.strip().replace(",", ".") - try: - return float(text) - except ValueError: - try: - return float(int(text, 0)) - except (ValueError, TypeError, OverflowError): - try: - if regexes.hex_arithmetic.fullmatch(text) and "**" not in text: - return float(eval(text)) - except Exception: - pass - _logger.error(f"{text} can't be parsed as floating point variable") - return None - - def decode(self, data: bytes) -> float: - return struct.unpack_from(self._struct_code_by_bits[self.bits], self._apply_endian(data))[0] - - def encode(self, value: Any) -> bytes | None: - if isinstance(value, str): - value = self.parse(value) - if value is None: - return None - return self._apply_endian(struct.pack(self._struct_code_by_bits[self.bits], value)) - - def text(self) -> str: - return f"Float{self.bits}" + self._endian_suffix() - - -class StringValueType(ValueType): - def __init__( - self, - encoding: Literal["ascii", "utf-8", "utf-16", "utf-32"], - *, - length: int = 10, - zero_terminate: bool = True, - endian: int = ENDIANNESS.HOST, - ) -> None: - if encoding not in ("ascii", "utf-8", "utf-16", "utf-32"): - raise ValueError(f"Unsupported string encoding: {encoding}") - self.encoding = encoding - self.length = length - self.zero_terminate = zero_terminate - self.endian = endian - - def _serialization_args(self) -> tuple[str]: - return (self.encoding,) - - @property - def read_size(self) -> int | None: - try: - length = int(self.length) - except (TypeError, ValueError, OverflowError): - return None - if length <= 0: - return None - return length * (1 if self.encoding == "ascii" else 4) - - def parse(self, text: str) -> str | None: - if not text: - _logger.error("Missing string parameter") - return None - return text - - def _codec(self) -> tuple[str, str]: - encoding = self.encoding - if encoding in ("utf-16", "utf-32"): - target_endian = _HOST_ENDIANNESS if self.endian == ENDIANNESS.HOST else self.endian - encoding += "-le" if target_endian == ENDIANNESS.LITTLE else "-be" - errors = "surrogateescape" if self.encoding == "utf-8" else "replace" - return encoding, errors - - def decode(self, data: bytes) -> str: - encoding, errors = self._codec() - result = data.decode(encoding, errors) - if self.zero_terminate: - result = "\x00" if result.startswith("\x00") else result.split("\x00")[0] - return result[: int(self.length)] - - def encode(self, value: Any) -> bytes | None: - if not isinstance(value, str) or self.parse(value) is None: - return None - encoding, errors = self._codec() - result = value.encode(encoding, errors) - if self.zero_terminate: - result += "\x00".encode(encoding, errors) - return result - - def text(self) -> str: - returned_string = f"String_{self.encoding.replace('-', '').upper()}[{self.length}]" - if not self.zero_terminate: - returned_string += ",NZT" - return returned_string + self._endian_suffix() - - -class ByteArrayValueType(ValueType): - def __init__(self, length: int = 10) -> None: - self.length = length - - @property - def read_size(self) -> int | None: - try: - length = int(self.length) - except (TypeError, ValueError, OverflowError): - return None - return length if length > 0 else None - - def parse(self, text: str) -> list[int] | None: - if not text: - _logger.error("Missing string parameter") - return None - tokens = text.split() - if not tokens or any(len(token) > 2 or any(char not in "0123456789abcdefABCDEF" for char in token) for token in tokens): - _logger.error(f"{text.strip()} can't be parsed as array of bytes") - return None - return [int(token, 16) for token in tokens] - - def decode(self, data: bytes) -> str: - return data.hex(" ") - - def encode(self, value: Any) -> bytes | None: - if isinstance(value, str): - value = self.parse(value) - if value is None: - return None - return bytes(value) - - def text(self) -> str: - return f"ByteArray[{self.length}]" - - -class StructValueType(ValueType): - @property - def read_size(self) -> None: - return None - - def parse(self, text: str) -> None: - return None - - def decode(self, data: bytes) -> None: - return None - - def encode(self, value: Any) -> None: - return None - - def text(self) -> str: - return "Struct" - - -# These numeric IDs are stored by existing .pct files. -# Runtime code should use the concrete ValueType families instead. -# NEVER renumber these entries while old tables are supported. -_SERIALIZED_TYPE_IDS: dict[int, tuple[type[ValueType], tuple[Any, ...]]] = { - 0: (IntegerValueType, (8,)), - 1: (IntegerValueType, (16,)), - 2: (IntegerValueType, (32,)), - 3: (IntegerValueType, (64,)), - 4: (FloatValueType, (32,)), - 5: (FloatValueType, (64,)), - 6: (StringValueType, ("ascii",)), - 7: (StringValueType, ("utf-8",)), - 8: (StringValueType, ("utf-16",)), - 9: (StringValueType, ("utf-32",)), - 10: (ByteArrayValueType, ()), - 11: (StructValueType, ()), - 12: (BitFieldValueType, ()), -} -_SERIALIZED_IDS_BY_TYPE = {value: key for key, value in _SERIALIZED_TYPE_IDS.items()} - - -class StructureMember: - """One field of a Structure: a value at an offset or a link to another structure. - - Exactly one of value_type / struct_ref is set. - Nested members (struct_ref set) are pointer members when is_pointer else inline/embedded. - """ - - def __init__( - self, - name: str, - offset: int, - value_type: "ValueType | None" = None, - struct_ref: str | None = None, - is_pointer: bool = False, - ) -> None: - if (value_type is None) == (struct_ref is None): - raise ValueError("StructureMember needs exactly one of value_type or struct_ref") - self.name = name - self.offset = offset - self.value_type = value_type - self.struct_ref = struct_ref - self.is_pointer = is_pointer - - def serialize(self) -> tuple: - vt = self.value_type.serialize() if self.value_type is not None else None - return self.name, self.offset, vt, self.struct_ref, self.is_pointer - - @classmethod - def deserialize(cls, data: tuple) -> "StructureMember": - name, offset, vt, struct_ref, is_pointer = data - return cls(name, offset, ValueType.deserialize(vt) if vt is not None else None, struct_ref, is_pointer) - - -class Structure: - """A named, ordered list of StructureMembers. Offsets are explicit and relative to a base.""" - - def __init__(self, name: str, members: "list[StructureMember] | None" = None) -> None: - self.name = name - self.members = members if members else [] - - def serialize(self) -> tuple: - return self.name, [m.serialize() for m in self.members] - - @classmethod - def deserialize(cls, data: tuple) -> "Structure": - name, members = data - return cls(name, [StructureMember.deserialize(m) for m in members]) - - -class PointerChainResult: - def __init__(self) -> None: - self.pointer_chain: list[int] = [] - - def get_pointer_by_index(self, index: int) -> int | None: - if index >= len(self.pointer_chain): - return None - return self.pointer_chain[index] - - def get_final_address(self) -> int | None: - return self.pointer_chain[-1] if self.pointer_chain else None - - def get_final_address_as_hex(self) -> str | None: - """ - Returns the hex representation of this pointer chain's final/destination address - """ - return hex(self.pointer_chain[-1]) if self.pointer_chain else None - - -class PointerChainRequest: - def __init__(self, base_address: str | int, offsets_list: list[int] | None = None) -> None: - """ - Args: - base_address (str, int): The base address of where this pointer chain starts from. Can be str expression or int. - offsets_list (list): List of offsets to reach the final pointed data. Can be None for no offsets. - Last offset in list won't be dereferenced to emulate CE behaviour. - """ - self.base_address: str | int = base_address - self.offsets_list: list[int] = [] if not offsets_list else offsets_list - - def serialize(self) -> tuple[str | int, list[int]]: - return self.base_address, self.offsets_list - - def get_base_address_as_str(self) -> str: - """ - Returns the text representation of this pointer's base address - """ - return hex(self.base_address) if type(self.base_address) != str else self.base_address - - -class RegisterQueue: - def __init__(self) -> None: - self.queue_list: list[queue.Queue] = [] - - def register_queue(self) -> queue.Queue: - new_queue = queue.Queue() - self.queue_list.append(new_queue) - return new_queue - - def broadcast_message(self, message: Any) -> None: - for item in self.queue_list: - item.put(message) - - def delete_queue(self, queue_instance: queue.Queue) -> None: - try: - self.queue_list.remove(queue_instance) - except ValueError: - pass - - -class Signal: - def __init__(self) -> None: - self.callbacks: list[Callable] = [] - - def connect(self, callback: Callable) -> None: - if callback not in self.callbacks: - self.callbacks.append(callback) - - def disconnect(self, callback: Callable) -> None: - try: - self.callbacks.remove(callback) - except ValueError: - pass - - def emit(self, *args: Any, **kwargs: Any) -> None: - for callback in self.callbacks.copy(): - callback(*args, **kwargs) - - -class AllocatedMemory: - def __init__(self, address: int, size: int, identity: tuple[int, int | None] | None = None) -> None: - self.address = address - self.size = size - self.identity = identity - # TODO BRK: Maybe expand with starting page address and old protection to restore state after deleting allocated memory diff --git a/libpince/utils.py b/libpince/utils.py deleted file mode 100644 index f44cf356..00000000 --- a/libpince/utils.py +++ /dev/null @@ -1,1257 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Copyright (C) Korcan Karaokçu - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -""" - -import os, shutil, sys, binascii, pickle, json, traceback, re, pwd, pathlib, logging, subprocess, shlex, struct -from . import typedefs, regexes -from capstone import Cs, CsError, CS_ARCH_X86, CS_MODE_32, CS_MODE_64 -from keystone import Ks, KsError, KS_ARCH_X86, KS_MODE_32, KS_MODE_64 -from collections import OrderedDict -from importlib import util as importlib_util -from pygdbmi import gdbmiparser -from types import ModuleType -from typing import Any, Callable - -# Capstone initialization -cs_32 = Cs(CS_ARCH_X86, CS_MODE_32) -cs_64 = Cs(CS_ARCH_X86, CS_MODE_64) - -# Keystone initialization -ks_32 = Ks(KS_ARCH_X86, KS_MODE_32) -ks_64 = Ks(KS_ARCH_X86, KS_MODE_64) - -# Initialize logging -logger = logging.getLogger("PINCE") - - -def init_logging() -> None: - global logger - if len(logger.handlers) != 0: - return - logger.setLevel(logging.DEBUG) - log_format = logging.Formatter("[%(levelname)s][%(funcName)s] %(message)s") - # File logging - file_handler = logging.FileHandler("/var/log/pince.log", mode="a") # Maybe change this to be per-process - file_handler.setLevel(logging.INFO) - file_handler.setFormatter(log_format) - # Terminal logging - terminal_handler = logging.StreamHandler(sys.stdout) - terminal_handler.setLevel(logging.DEBUG) - terminal_handler.setFormatter(log_format) - ################## - logger.addHandler(file_handler) - logger.addHandler(terminal_handler) - - -def clear_log() -> None: - open("/var/log/pince.log", "w").close() - - -def get_process_list() -> list[tuple[str, str, str]]: - """Returns a list of processes - - Returns: - list: List of (pid, user, process_name) -> (str, str, str) - """ - process_list = [] - for line in os.popen("ps -eo pid:11,user,comm").read().splitlines(): - info = regexes.ps.match(line) - if info: - process_list.append(info.groups()) - return process_list - - -def get_process_start_time(pid: int | str) -> int | None: - """Returns the process start time (field 22 of /proc//stat, clock ticks since boot). - Combined with pid this uniquely identifies a process instance, guarding against PID reuse. - - Args: - pid (int, str): PID of the process - - Returns: - int: starttime field, or None on error - """ - try: - with open(f"/proc/{pid}/stat") as stat_file: - stat = stat_file.read() - return int(stat[stat.rindex(")") + 2 :].split()[19]) # field 22 == index 19 after "(comm) " - except (OSError, ValueError, IndexError): - return None - - -def get_process_name(pid: int | str) -> str: - """Returns the process name of given pid - - Args: - pid (int, str): PID of the process - - Returns: - str: Process name - """ - try: - with open(f"/proc/{pid}/comm") as f: - return f.read().splitlines()[0] - except (FileNotFoundError, IndexError): - return "" - - -def search_processes(name_or_pid: str | int) -> list[tuple[str, str, str]]: - """Searches processes and returns a list of the ones that contain given process name or pid - - Args: - name_or_pid (str): Name or PID of the process that'll be searched for - - Returns: - list: List of (pid, user, process_name) -> (str, str, str) - """ - needle = str(name_or_pid).lower() - processlist = [] - for pid, user, name in get_process_list(): - if needle in name.lower() or needle == pid: - processlist.append((pid, user, name)) - return processlist - - -def get_regions(pid: int) -> list[tuple[str, ...]]: - """Returns memory regions of a process - - Args: - pid (int): PID of the process - - Returns: - list: List of (start_address, end_address, permissions, map_offset, device_node, inode, path) -> all str - """ - try: - with open("/proc/" + str(pid) + "/maps") as f: - regions = [] - for line in f.read().splitlines(): - match = regexes.maps.match(line) - if match: - regions.append(match.groups()) - return regions - except FileNotFoundError: - return [] - - -def get_effective_arch(pid: int) -> int: - """Returns the arch of the code the debugged program actually executes, unlike the arch of the host process. - - They can differ in WINE processes, particularly with New-WoW64 where 32 bits PE programs run inside a 64 bits host process. - - Args: - pid (int): PID of the process - - Returns: - int: A member of typedefs.INFERIOR_ARCH, -1 if detection fails - """ - - def pe_magic(path: str) -> int: - # Optional header magic: 0x10B -> PE32, 0x20B -> PE32+, 0 -> not a readable PE. - try: - with open(path, "rb") as pe_file: - if pe_file.read(2) != b"MZ": - return 0 - pe_file.seek(0x3C) - pe_file.seek(int.from_bytes(pe_file.read(4), "little")) - if pe_file.read(4) != b"PE\x00\x00": - return 0 - pe_file.seek(0x14, os.SEEK_CUR) # skip the COFF header to reach the optional header magic. - return int.from_bytes(pe_file.read(2), "little") - except OSError: - return 0 - - if is_wine_process(pid): - # The launched exe decides the effective bitness, first valid PE wins like in _refresh_main_module_info. - for _, _, _, _, _, _, path in get_regions(pid): - if path.lower().endswith(".exe"): - resolved_path = resolve_mapped_path(pid, path) - arch = {0x10B: typedefs.INFERIOR_ARCH.ARCH_32, 0x20B: typedefs.INFERIOR_ARCH.ARCH_64}.get(pe_magic(resolved_path)) - if arch: - return arch - return -1 - # Native processes follow the ELF class of the main binary. - try: - with open(f"/proc/{pid}/exe", "rb") as exe_file: - elf_class = exe_file.read(5) - except OSError: - return -1 - return {b"\x7fELF\x01": typedefs.INFERIOR_ARCH.ARCH_32, b"\x7fELF\x02": typedefs.INFERIOR_ARCH.ARCH_64}.get(elf_class, -1) - - -def get_module_load_bias(pid: int, name_regex: str) -> tuple[int, str] | None: - """Finds the first mapped file whose basename matches name_regex and returns its load bias and absolute path. - - Args: - pid (int): PID of the process - name_regex (str): Regular expression to match against the basename of mapped files - - Returns: - tuple: (load_bias, absolute_path) where load_bias is an int and absolute_path is a str - None: If no matching module is found - """ - compiled = re.compile(name_regex) - per_file: dict[str, list[tuple[int, int]]] = {} - for start, _, _, offset, _, _, path in get_regions(pid): - if not path: - continue - if compiled.search(os.path.basename(path)): - per_file.setdefault(path, []).append((int(start, 16), int(offset, 16))) - for path, mappings in per_file.items(): - return min(start - offset for start, offset in mappings), path - return None - - -def get_module_dict(pid_or_memory_regions: int | list[tuple[str, ...]]) -> dict[str, str]: - """Returns logical module bases keyed by basename, or by full path when a basename is ambiguous. - Unique shortcuts for versioned sonames are also included. Empty paths are ignored. - - Args: - pid_or_memory_regions (int, list): PID of the process or output from get_regions - - Returns: - dict: {module_name_or_path:load_base} - """ - memory_regions = get_regions(pid_or_memory_regions) if isinstance(pid_or_memory_regions, int) else pid_or_memory_regions - modules_by_name: dict[str, dict[str, int]] = {} - for start, _, _, offset, _, _, path in memory_regions: - if path: - modules = modules_by_name.setdefault(os.path.basename(path), {}) - base = int(start, 16) - int(offset, 16) - modules[path] = min(base, modules.get(path, base)) - - module_dict: dict[str, str] = {} - for name, modules in modules_by_name.items(): - for path, base in modules.items(): - module_dict[name if len(modules) == 1 else path] = hex(base) - - aliases: dict[str, list[int]] = {} - for name, modules in modules_by_name.items(): - short_name = regexes.file_with_extension.search(name) - if short_name and short_name.group(0) != name: - aliases.setdefault(short_name.group(0), []).extend(modules.values()) - for name, bases in aliases.items(): - if name not in modules_by_name and len(bases) == 1: - module_dict[name] = hex(bases[0]) - return module_dict - - -def resolve_mapped_path(pid: int, mapped_path: str) -> str: - """Resolves a path from an inferior's /proc/PID/maps into one PINCE can open. - - Sandboxed inferiors (Flatpak, Steam pressure-vessel) report library paths in their own mount namespace - (e.g. /run/host/usr/lib/libc.so.6) which don't exist in PINCE's namespace. - Going through /proc/PID/root resolves the exact file the inferior mapped regardless of the sandbox. - - Args: - pid (int): PID of the inferior - mapped_path (str): A file path as it appears in the inferior's /proc/PID/maps - - Returns: - str: mapped_path if it's directly readable, else the /proc/PID/root path to the same file, - falling back to mapped_path if neither exists. - """ - if os.path.exists(mapped_path): - return mapped_path - proc_root_path = f"/proc/{pid}/root{mapped_path}" - return proc_root_path if os.path.exists(proc_root_path) else mapped_path - - -def get_defined_dynamic_symbols(elf_path: str, symbol_names: list[str]) -> dict[str, int]: - """Parses the .dynsym/.dynstr of an ELF file and returns {name: st_value} for each - requested symbol that is defined in the file. - Handles ELFCLASS32/64 and both endiannesses. - - Args: - elf_path (str): Path to the ELF file on disk - symbol_names (list[str]): List of symbol names to look up - - Returns: - dict: {symbol_name: st_value} for each defined symbol found - Empty dict on failure or if no section headers are present - """ - try: - with open(elf_path, "rb") as elf_file: - data = elf_file.read() - except OSError: - return {} - if len(data) < 6 or data[:4] != b"\x7fELF": - return {} - try: - is64 = data[4] == 2 - endian = "<" if data[5] == 1 else ">" - if is64: - e_shoff = struct.unpack_from(endian + "Q", data, 0x28)[0] - e_shentsize, e_shnum, e_shstrndx = struct.unpack_from(endian + "HHH", data, 0x3A) - shdr_fmt, sym_fmt, default_sym_size = endian + "IIQQQQIIQQ", endian + "IBBHQQ", 24 - else: - e_shoff = struct.unpack_from(endian + "I", data, 0x20)[0] - e_shentsize, e_shnum, e_shstrndx = struct.unpack_from(endian + "HHH", data, 0x2E) - shdr_fmt, sym_fmt, default_sym_size = endian + "IIIIIIIIII", endian + "IIIBBH", 16 - if e_shoff == 0 or e_shnum == 0: - return {} - - def read_shdr(i): - return struct.unpack_from(shdr_fmt, data, e_shoff + i * e_shentsize) - - def read_cstr(base): - try: - return data[base : data.index(b"\x00", base)].decode("latin-1") - except (ValueError, IndexError): - return "" - - shstr_offset = read_shdr(e_shstrndx)[4] - dynsym = dynstr = None - for i in range(e_shnum): - sh = read_shdr(i) - nm = read_cstr(shstr_offset + sh[0]) - if nm == ".dynsym": - dynsym = sh - elif nm == ".dynstr": - dynstr = sh - if dynsym is None or dynstr is None: - return {} - dynsym_offset, dynsym_size, dynsym_entsize = dynsym[4], dynsym[5], dynsym[9] - dynstr_offset = dynstr[4] - sym_size = dynsym_entsize or default_sym_size - wanted, found = set(symbol_names), {} - for i in range(dynsym_size // sym_size): - f = struct.unpack_from(sym_fmt, data, dynsym_offset + i * sym_size) - st_name, st_value, st_shndx = (f[0], f[4], f[3]) if is64 else (f[0], f[1], f[5]) - if st_shndx == 0 or st_value == 0: - continue - name = read_cstr(dynstr_offset + st_name) - if name in wanted: - found[name] = st_value - if len(found) == len(wanted): - break - except (struct.error, IndexError, ValueError): - return {} - return found - - -def get_region_dict(pid_or_memory_regions: int | list[tuple[str, ...]]) -> dict[str, list[str]]: - """Returns memory regions of a process as a dictionary where key is the path tail and value is the list of the - corresponding start addresses of the tail, empty paths will be ignored. - Also adds shortcuts for file extensions. - Returned dict will include both sonames, with and without version information. - - Args: - pid_or_memory_regions (int, list): PID of the process or output from get_regions - - Returns: - dict: {file_name:start_address_list} - """ - memory_regions = get_regions(pid_or_memory_regions) if isinstance(pid_or_memory_regions, int) else pid_or_memory_regions - region_dict: dict[str, list[str]] = {} - for item in memory_regions: - start_addr, _, _, _, _, _, path = item - if not path: - continue - _, tail = os.path.split(path) - start_addr = "0x" + start_addr - # Always append, never assign: a versioned soname's unversioned alias (e.g. libEGL.so.1 -> libEGL.so) - # must not clobber the list of a different file that has the same basename - region_dict.setdefault(tail, []).append(start_addr) - short_name = regexes.file_with_extension.search(tail) - if short_name: - short_name = short_name.group(0) - if short_name != tail: - region_dict.setdefault(short_name, []).append(start_addr) - return region_dict - - -def get_region_info(pid: int | str, address: int | str) -> typedefs.tuple_region_info | None: - """Finds the closest valid starting/ending address and region to given address, assuming given address is in the - valid address range - - Args: - pid (int): PID of the process - address (int,str): Can be an int or a hex str - - Returns: - list: List of (start_address, end_address, permissions, file_name) -> (int, int, str, str) - None: If the given address isn't in any valid address range - """ - if type(pid) != int: - pid = safe_int_cast(pid) - if type(address) != int: - address = safe_str_to_int(address, 0) - region_list = get_regions(pid) - region_dict = get_region_dict(region_list) - for start, end, perms, _, _, _, path in region_list: - start_int = safe_str_to_int(start, 16) - end_int = safe_str_to_int(end, 16) - if start_int <= address < end_int: - file_name = os.path.split(path)[1] - address_list = region_dict.get(file_name, []) - try: - region_index = address_list.index("0x" + start) - except ValueError: - region_index = 0 - return typedefs.tuple_region_info(start_int, end_int, perms, file_name, region_index) - - -def filter_regions(pid: int, attribute: str, regex: str, case_sensitive: bool = False) -> list[tuple[str, ...]]: - """Filters memory regions by searching for the given regex within the given attribute - - Args: - pid (int): PID of the process - attribute (str): The attribute that'll be filtered. Can be one of the below - start_address, end_address, permissions, map_offset, device_node, inode, path - regex (str): Regex statement that'll be searched - case_sensitive (bool): If True, search will be case sensitive - - Returns: - list: List of (start_address, end_address, permissions, map_offset, device_node, inode, path) -> all str - """ - attributes = ["start_address", "end_address", "permissions", "map_offset", "device_node", "inode", "path"] - if attribute not in attributes: - raise Exception("Invalid attribute") - index = attributes.index(attribute) - if case_sensitive: - compiled_regex = re.compile(regex) - else: - compiled_regex = re.compile(regex, re.IGNORECASE) - filtered_regions = [] - for region in get_regions(pid): - if compiled_regex.search(region[index]): - filtered_regions.append(region) - return filtered_regions - - -def is_traced(pid: int) -> str | None: - """Check if the process corresponding to given pid traced by any other process - - Args: - pid (int): PID of the process - - Returns: - str: Name of the tracer if the specified process is being traced - None: if the specified process is not being traced or the process doesn't exist anymore - """ - try: - status_file = open(f"/proc/{pid}/status") - except OSError: - return - with status_file: - for line in status_file: - if line.startswith("TracerPid:"): - tracer_pid = line.split(":", 1)[1].strip() - if tracer_pid != "0": - return get_process_name(tracer_pid) - return - - -def is_process_valid(pid: int) -> bool: - """Check if the process corresponding to given pid is valid - - Args: - pid (int): PID of the process - - Returns: - bool: True if the process is still running, False if not - """ - return os.path.exists("/proc/%d" % pid) - - -def is_wine_process(pid: int) -> bool: - """Check if the inferior is running under Wine or Proton. - - Scans /proc//maps for WINE or Proton libraries. - Mostly used to gate features that don't yet work reliably under WINE in the GUI. - - Args: - pid (int): PID of the process - - Returns: - bool: True if Wine/Proton libraries are mapped into the process - """ - if pid <= 0: - return False - try: - with open(f"/proc/{pid}/maps", "r") as maps_file: - for line in maps_file: - lower = line.lower() - if any(marker in lower for marker in ("wine", "proton")): - return True - except OSError: - pass - return False - - -def get_script_directory() -> str: - """Get main script directory - - Returns: - str: A string pointing to the main script directory - """ - return sys.path[0] - - -def get_media_directory() -> str: - """Get media directory - - Returns: - str: A string pointing to the media directory - """ - return get_script_directory() + "/media" - - -def get_logo_directory() -> str: - """Get logo directory - - Returns: - str: A string pointing to the logo directory - """ - return get_script_directory() + "/media/logo" - - -def get_libpince_directory() -> str: - """Get libpince directory - - Returns: - str: A string pointing to the libpince directory - - Note: - In fact this function returns the directory where utils in and considering the fact that utils resides in - libpince, it works. So, please don't move out utils outside of libpince folder! - """ - return os.path.dirname(os.path.realpath(__file__)) - - -def delete_ipc_path(pid: int | str) -> None: - """Deletes the IPC directory of given pid - - Args: - pid (int,str): PID of the process - """ - path = get_ipc_path(pid) - if os.path.exists(path): - shutil.rmtree(path) - - -def create_ipc_path(pid: int | str) -> None: - """Creates the IPC directory of given pid - - Args: - pid (int,str): PID of the process - """ - path = get_ipc_path(pid) - if os.path.exists(path): - shutil.rmtree(path) - os.makedirs(path) - - # Opening the command file with 'w' each time debugcore.send_command() gets invoked slows down the process - # Instead, here we create the command file for only once when IPC path gets initialized - # Then, open the command file with 'r' in debugcore.send_command() to get a better performance - command_file = get_gdb_command_file(pid) - open(command_file, "w").close() - - -def create_tmp_path(pid: int | str) -> None: - """Creates the tmp directory of given pid - - Args: - pid (int,str): PID of the process - """ - path = get_tmp_path(pid) - if os.path.exists(path): - shutil.rmtree(path) - os.makedirs(path) - - -def get_ipc_path(pid: int | str) -> str: - """Get the IPC directory of given pid - - Args: - pid (int): PID of the process - - Returns: - str: Path of IPC directory - """ - return typedefs.PATHS.IPC + str(pid) - - -def get_tmp_path(pid: int | str) -> str: - """Get the tmp directory of given pid - - Args: - pid (int): PID of the process - - Returns: - str: Path of tmp directory - """ - return typedefs.PATHS.TMP + str(pid) - - -def get_logging_file(pid: int | str) -> str: - """Get the path of gdb logfile of given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of gdb logfile - """ - return get_tmp_path(pid) + "/gdb_log.txt" - - -def get_gdb_command_file(pid: int | str) -> str: - """Get the path of gdb command file of given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of gdb command file - """ - return get_ipc_path(pid) + "/gdb_command.txt" - - -def get_track_watchpoint_file(pid: int | str, watchpoint_list: list | str) -> str: - """Get the path of track watchpoint file for given pid and watchpoint - - Args: - pid (int,str): PID of the process - watchpoint_list (list,str): Numbers of the watchpoints - - Returns: - str: Path of track watchpoint file - """ - return get_ipc_path(pid) + "/" + str(watchpoint_list) + "_track_watchpoint.txt" - - -def get_track_breakpoint_file(pid: int | str, breakpoint_number: int | str) -> str: - """Get the path of track breakpoint file for given pid and breakpoint - - Args: - pid (int,str): PID of the process - breakpoint_number (int) - - Returns: - str: Path of track breakpoint file - """ - return f"{get_ipc_path(pid)}/{breakpoint_number}_track_breakpoint.txt" - - -def append_file_extension(string: str, extension: str) -> str: - """Appends the given extension to the given string if it doesn't end with the given extension - - Args: - string (str): Self-explanatory - extension (str): Self-explanatory, you don't have to include the dot - - Returns: - str: Given string with the extension - """ - extension = extension.strip(".") - return string if string.endswith("." + extension) else string + "." + extension - - -def save_file(data: Any, file_path: str, save_method: str = "json") -> bool: - """Saves the specified data to given path - - Args: - data (??): Saved data, can be anything, must be supported by save_method - file_path (str): Path of the saved file - save_method (str): Can be "json" or "pickle" - - Returns: - bool: True if saved successfully, False if not - """ - if save_method == "json": - try: - dir_name = os.path.dirname(file_path) - if dir_name: - os.makedirs(dir_name, exist_ok=True) - with open(file_path, "w") as save_file: - json.dump(data, save_file) - return True - except Exception: - logger.exception("Encountered an exception while dumping the data in JSON format\n") - return False - elif save_method == "pickle": - try: - dir_name = os.path.dirname(file_path) - if dir_name: - os.makedirs(dir_name, exist_ok=True) - with open(file_path, "wb") as save_file: - pickle.dump(data, save_file) - return True - except Exception: - logger.exception("Encountered an exception while pickling the data\n") - return False - else: - logger.error("Unsupported save_method, bailing out...") - return False - - -def load_file(file_path: str, load_method: str = "json") -> Any: - """Loads data from the given path - - Args: - file_path (str): Path of the saved file - load_method (str): Can be "json" or "pickle" - - Returns: - ??: file_path is like a box of chocolates, you never know what you're gonna get - None: If loading fails - """ - if load_method == "json": - try: - with open(file_path, "r") as load_file: - return json.load(load_file, object_pairs_hook=OrderedDict) - except Exception: - logger.exception("Encountered an exception while loading the JSON data") - return - elif load_method == "pickle": - try: - with open(file_path, "rb") as load_file: - return pickle.load(load_file) - except Exception: - logger.exception("Encountered an exception while unpickling the data") - return - else: - logger.error("Unsupported load_method, bailing out...") - return - - -def get_trace_status_file(pid: int | str) -> str: - """Get the path of trace status file for given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of trace status file - """ - return get_ipc_path(pid) + "/_trace_status.txt" - - -def change_trace_status(pid: int | str, trace_status: int) -> None: - """Change trace status for given pid - - Args: - pid (int,str): PID of the process - trace_status (int): New trace status, can be a member of typedefs.TRACE_STATUS - """ - trace_status_file = get_trace_status_file(pid) - with open(trace_status_file, "w") as trace_file: - trace_file.write(str(trace_status)) - - -def get_referenced_strings_file(pid: int | str) -> str: - """Get the path of referenced strings dict file for given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of referenced strings dict file - """ - return get_tmp_path(pid) + "/referenced_strings_dict.txt" - - -def get_referenced_jumps_file(pid: int | str) -> str: - """Get the path of referenced jumps dict file for given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of referenced jumps dict file - """ - return get_tmp_path(pid) + "/referenced_jumps_dict.txt" - - -def get_referenced_calls_file(pid: int | str) -> str: - """Get the path of referenced calls dict file for given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of referenced calls dict file - """ - return get_tmp_path(pid) + "/referenced_calls_dict.txt" - - -def get_from_pince_file(pid: int | str) -> str: - """Get the path of IPC file sent to custom gdb commands from PINCE for given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of IPC file - """ - return get_ipc_path(pid) + typedefs.PATHS.FROM_PINCE - - -def get_to_pince_file(pid: int | str) -> str: - """Get the path of IPC file sent to PINCE from custom gdb commands for given pid - - Args: - pid (int,str): PID of the process - - Returns: - str: Path of IPC file - """ - return get_ipc_path(pid) + typedefs.PATHS.TO_PINCE - - -def instruction_follow_address(string: str) -> str | None: - """Searches for the location changing instructions such as Jcc, CALL and LOOPcc in the given string. Returns the hex - address the instruction jumps to - - Args: - string (str): An assembly expression - - Returns: - str: Hex address - None: If no hex address is found or no location changing instructions found - """ - result = regexes.instruction_follow.search(string) - if result: - return result.group(2) - - -def extract_hex_address(string: str) -> str | None: - """Extracts hex address from the given string - - Args: - string (str): The string that the hex address will be extracted from - - Returns: - str: Hex address - None: If no hex address is found - """ - if type(string) != str: - return - result = regexes.hex_number.search(string) - if result: - return result.group(0) - - -def modulo_address(int_address: int, arch_type: int) -> int: - """Calculates the modulo of the given integer based on the given architecture type to make sure that it doesn't - exceed the borders of the given architecture type (0xffffffff->x86, 0xffffffffffffffff->x64) - - Args: - int_address (int): Self-explanatory - arch_type (int): Architecture type (x86, x64). Can be a member of typedefs.INFERIOR_ARCH - - Returns: - int: Modulo of the given integer based on the given architecture type - """ - if arch_type == typedefs.INFERIOR_ARCH.ARCH_32: - return int_address % 0x100000000 - elif arch_type == typedefs.INFERIOR_ARCH.ARCH_64: - return int_address % 0x10000000000000000 - raise Exception("arch_type must be a member of typedefs.INFERIOR_ARCH") - - -def disassemble(aob: str, address: int, inferior_arch: int) -> str | None: - """Returns the instructions from the given array of bytes - - Args: - aob (str): Opcode bytes of the instruction as an array of bytes - address (int): The address where the instruction starts from - inferior_arch (int): Architecture type (x86, x64). Can be a member of typedefs.INFERIOR_ARCH - - Returns: - str: Instructions, multiple entries are separated with ; - None: If there was an error - """ - if inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64: - disassembler = cs_64 - else: - disassembler = cs_32 - disassembler.skipdata = True - try: - bytecode = bytes.fromhex(aob.replace(" ", "")) - except ValueError: - return - try: - disas_data = disassembler.disasm_lite(bytecode, address) - return "; ".join([f"{data[2]} {data[3]}" if data[3] != "" else data[2] for data in disas_data]) - except CsError: - logger.exception("Failed to disassemble bytes") - - -def instruction_aligned_size(aob: bytes, minimum_bytes: int, inferior_arch: int) -> int: - """Walks instructions from offset 0 of `aob` until cumulative size meets - or exceeds `minimum_bytes`. Used by code-injection hooks where the patch - must end on an instruction boundary so the next instruction decodes cleanly. - - Args: - aob (bytes): Instruction stream starting at offset 0. - minimum_bytes (int): Minimum number of bytes the result must cover. - inferior_arch (int): Member of typedefs.INFERIOR_ARCH. - - Returns: - int: Smallest instruction-aligned size >= minimum_bytes, or 0 if the - bytes couldn't be decoded far enough. - """ - if minimum_bytes <= 0: - return 0 - disassembler = cs_64 if inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64 else cs_32 - disassembler.skipdata = True - size = 0 - try: - for _, instr_size, _, _ in disassembler.disasm_lite(bytes(aob), 0): - size += instr_size - if size >= minimum_bytes: - return size - except CsError: - return 0 - return 0 - - -def assemble(instructions: str, address: int, inferior_arch: int) -> tuple[list[int], int] | None: - """Assembles the given instructions - - Args: - instructions (str): A string of instructions, multiple entries separated by ; - address (int): Starting address of the instructions - inferior_arch (int): Can be a member of typedefs.INFERIOR_ARCH - - Returns: - tuple: A tuple of (list, int) --> Assembled bytes (list of int) and instruction count (int) - None: If there was an error - """ - try: - if inferior_arch == typedefs.INFERIOR_ARCH.ARCH_64: - return ks_64.asm(instructions, address) - else: - return ks_32.asm(instructions, address) - except KsError: - logger.exception("Failed to assemble bytes") - - -def aob_to_str(list_of_bytes: list[int | str] | int | str, encoding: str = "ascii", replace_unprintable: bool = True) -> str: - """Converts given array of hex strings to str - - Args: - list_of_bytes (list): Must be returned from debugcore.hex_dump() - encoding (str): See here-->https://docs.python.org/3/library/codecs.html#standard-encodings - replace_unprintable (bool): If True, replaces non-printable characters with a period (.) - - Returns: - str: str equivalent of array - """ - - ### make an actual list of bytes - hexString = "" - byteList = list_of_bytes - if isinstance(list_of_bytes, list): - byteList = list_of_bytes - else: - byteList = [] - byteList.append(list_of_bytes) - for sByte in byteList: - if sByte == "??": - hexString += f"{63:02x}" # replace ?? with a single ? - else: - if isinstance(sByte, int): - byte = sByte - else: - byte = safe_str_to_int(sByte, 16) - if replace_unprintable and ((byte < 32) or (byte > 126)): - hexString += f"{46:02x}" # replace non-printable chars with a period (.) - else: - hexString += f"{byte:02x}" - hexBytes = bytes.fromhex(hexString) - return hexBytes.decode(encoding, "surrogateescape") - - -def str_to_aob(string: str, encoding: str = "ascii") -> str: - """Converts given string to aob string - - Args: - string (str): Any string - encoding (str): See here-->https://docs.python.org/3/library/codecs.html#standard-encodings - - Returns: - str: AoB equivalent of the given string - """ - s = str(binascii.hexlify(string.encode(encoding, "surrogateescape")), encoding).upper() - return " ".join(s[i : i + 2] for i in range(0, len(s), 2)) - - -def split_symbol(symbol_string: str) -> list[str]: - """Splits symbol part of typedefs.tuple_function_info into smaller fractions - Fraction count depends on the symbol_string. See Examples section for demonstration - - Args: - symbol_string (str): symbol part of typedefs.tuple_function_info - - Returns: - list: A list containing parts of the split symbol - - Examples: - symbol_string-->"func(param)@plt" - returned_list-->["func","func(param)","func(param)@plt"] - - symbol_string-->"malloc@plt" - returned_list-->["malloc", "malloc@plt"] - - symbol_string-->"printf" - returned_list-->["printf"] - """ - returned_list = [] - p_count = 0 - # this algorithm searches for balanced parentheses and removes the outer group - # using string reversing with recursive re.split makes the code confusing as hell, going with this one instead - # searching for balanced parentheses works because apparently no demangled symbol can finish with <.*> - # XXX: run this code to test while attached to a process and open a detailed issue if you get a result - """ - from libpince import debugcore - import re - result=debugcore.search_functions("") - for address, symbol in result: - if re.search("<.*>[^()]+$", symbol): - print(symbol) - """ - for index, letter in enumerate(symbol_string[::-1]): - if letter == ")": - p_count += 1 - elif letter == "(": - p_count -= 1 - if p_count == 0: - returned_list.append((symbol_string[: -(index + 1)])) - break - if p_count < 0: - raise ValueError( - symbol_string + " contains unhealthy amount of left parentheses\nGotta give him some" - ' right parentheses. Like Bob always says "everyone needs a friend"' - ) - if p_count != 0: - raise ValueError(symbol_string + " contains unbalanced parentheses") - if "@plt" in symbol_string: - returned_list.append(symbol_string.rsplit("@plt", maxsplit=1)[0]) - returned_list.append(symbol_string) - return returned_list - - -def extract_symbol_name(symbol_string: str) -> str: - """Extract symbol name from examine_expression result - - Args: - symbol_string (str): A string that contains a symbol in format - - Returns: - str: Symbol name without brackets or empty string if no symbol is found - """ - result = regexes.symbol.search(symbol_string) - return result.group(1) if result else "" - - -def execute_command_as_user(command: str) -> None: - """Executes given command as the original user who invoked PINCE - - Args: - command (str): Command that'll be invoked from the shell - """ - uid, _ = get_user_ids() - if not uid.isdigit(): - logger.error(f"Invalid uid {uid!r}, refusing to drop privileges") - return - subprocess.run(["sudo", "-Eu", f"#{uid}"] + shlex.split(command), check=False) - - -def init_user_files() -> None: - """Initializes user files""" - root_path = get_user_path(typedefs.USER_PATHS.ROOT) - if not os.path.exists(root_path): - os.makedirs(root_path) - for file in typedefs.USER_PATHS.get_init_files(): - file = get_user_path(file) - pathlib.Path(file).touch(exist_ok=True) - - -def get_user_ids() -> tuple[str, str]: - """Gets uid and gid of the user who invoked PINCE/libpince. Resolves real user if invoked through sudo/pkexec. - - Returns: - tuple (str, str): uid and gid of the real invoking user. - """ - # pkexec before polkit version 127 (Dec 2025) would only set "PKEXEC_UID" and nothing else, - # but starting with that version they do set both "SUDO_UID" and "SUDO_GID" for sudo compatibility reasons. - # If we're using an older polkit and don't have "SUDO_GID" set, we'll resolve the gid from user's passwd entry. - uid = os.getenv("SUDO_UID") or os.getenv("PKEXEC_UID") or str(os.getuid()) - gid = os.getenv("SUDO_GID") - if not gid: - try: - gid = str(pwd.getpwuid(int(uid)).pw_gid) - except (KeyError, ValueError): - gid = str(os.getgid()) - return uid, gid - - -def get_user_home_dir() -> str: - """Returns the home directory of the current user - - Returns: - str: Home directory of the current user - """ - uid, _ = get_user_ids() - try: - return pwd.getpwuid(int(uid)).pw_dir - except (KeyError, ValueError): - return os.path.expanduser("~") - - -def get_user_path(user_path: str) -> str: - """Returns the specified user path for the current user - - Args: - user_path (str): Can be a member of typedefs.USER_PATHS - - Returns: - str: Specified user path of the current user - """ - # TODO: Use XDG specification - homedir = get_user_home_dir() - return os.path.join(homedir, user_path) - - -def get_default_gdb_path() -> str: - appdir = os.environ.get("APPDIR") - if appdir: - return appdir + "/usr/bin/gdb" - return typedefs.PATHS.GDB - - -def execute_script(file_path: str) -> tuple[ModuleType | None, str | None]: - """Loads and executes the script in the given path - - Args: - file_path (str): Self-explanatory - - Returns: - tuple: (module, exception) - module--> Loaded script as module - exception--> traceback as str - - Returns (None, exception) if fails to load the script - Returns (module, None) if script gets loaded successfully - """ - _, tail = os.path.split(file_path) - file_name = tail.split(".", maxsplit=1)[0] - spec = importlib_util.spec_from_file_location(file_name, file_path) - if spec is None or spec.loader is None: - logger.error(f"Failed to create module spec for {file_path}") - return None, f"Failed to create module spec for {file_path}" - module = importlib_util.module_from_spec(spec) - sys.modules[file_name] = module - try: - spec.loader.exec_module(module) - except Exception as e: - logger.error(f"Encountered an exception while loading the script located at {file_path}") - tb = traceback.format_exception(None, e, e.__traceback__) - tb.insert(0, "------->You can ignore the importlib part if the source file is valid<-------\n") - tb = "".join(tb) - logger.error(tb) - sys.modules.pop(file_name, None) - return None, tb - return module, None - - -def parse_response(response: str, line_num: int = 0) -> dict: - """Parses the given GDB/MI output. Wraps gdbmiparser.parse_response - debugcore.send_command returns an additional "^done" output because of the "source" command - This function is used to get rid of that output before parsing - - Args: - response (str): GDB/MI response - line_num (int): Which line of the response will be parsed - - Returns: - dict: Contents of the dict depends on the response - """ - return gdbmiparser.parse_response(response.splitlines()[line_num]) - - -def search_files(directory: str, regex: str) -> list[str]: - """Searches the files in given directory for given regex recursively - - Args: - directory (str): Directory to search for - regex (str): Regex to search for - - Returns: - list: Sorted list of the relative paths(to the given directory) of the files found - """ - file_list = [] - for file in pathlib.Path(directory).rglob("*"): - if not file.is_file(): - continue - result = re.search(regex, file.name, re.IGNORECASE) - if result: - file_list.append(str(file.relative_to(directory))) - return sorted(file_list) - - -def ignore_exceptions(func: Callable) -> Callable: - """A decorator to ignore exceptions""" - - def wrapper(*args: Any, **kwargs: Any) -> Any: - try: - return func(*args, **kwargs) - except Exception: - traceback.print_exc() - - return wrapper - - -def upper_hex(hex_str: str) -> str: - """Converts the given hex string to uppercase while keeping the 'x' character lowercase""" - # check if the given string is a hex string, if not return the string as is - if not regexes.hex_number_gui.match(hex_str): - return hex_str - return hex_str.upper().replace("X", "x") - - -def return_optional_int(val: int) -> int | None: - return None if val == 0 else val - - -# This is the main int() cast for strings that should be used until you're certain that the cast can never fail or has explicit handling. -# The reason for this is that you can catch stray errors or edge cases by safely returning a value and outputting useful log info -# instead of failing with an exception that will propagate upwards. -def safe_str_to_int(input: Any, base: int) -> int: - try: - return int(input, base) - except ValueError: - logger.error(f"ValueError: Tried to convert input '{input}' to base {base} for caller '{sys._getframe().f_back.f_code.co_qualname}'") - return 0 - except TypeError: - logger.error(f"TypeError: Tried to convert input '{input}' to base {base} for caller '{sys._getframe().f_back.f_code.co_qualname}'") - return 0 - - -# This is the non-base version of the above. -def safe_int_cast(input: Any) -> int: - try: - return int(input) - except ValueError: - logger.error(f"ValueError: Tried to convert input '{input}' for caller '{sys._getframe().f_back.f_code.co_qualname}'") - return 0 - except TypeError: - logger.error(f"TypeError: Tried to convert input '{input}' for caller '{sys._getframe().f_back.f_code.co_qualname}'") - return 0 diff --git a/media/.directory b/media/.directory new file mode 100644 index 00000000..5f470cc5 --- /dev/null +++ b/media/.directory @@ -0,0 +1,4 @@ +[Dolphin] +PreviewsShown=true +Timestamp=2016,6,23,3,15,40 +Version=3 diff --git a/media/LoadingDialog/ajax-loader.gif b/media/LoadingDialog/ajax-loader.gif deleted file mode 100644 index 3288d103..00000000 Binary files a/media/LoadingDialog/ajax-loader.gif and /dev/null differ diff --git a/media/TraceInstructionsWaitWidget/ajax-loader.gif b/media/TraceInstructionsWaitWidget/ajax-loader.gif deleted file mode 100644 index de2e8b6c..00000000 Binary files a/media/TraceInstructionsWaitWidget/ajax-loader.gif and /dev/null differ diff --git a/media/icons/.directory b/media/icons/.directory new file mode 100644 index 00000000..67794714 --- /dev/null +++ b/media/icons/.directory @@ -0,0 +1,4 @@ +[Dolphin] +PreviewsShown=true +Timestamp=2016,6,23,3,15,44 +Version=3 diff --git a/media/loading_widget_alternative.gif b/media/loading_widget_alternative.gif new file mode 100644 index 00000000..cb964dac Binary files /dev/null and b/media/loading_widget_alternative.gif differ diff --git a/media/loading_widget_gondola.gif b/media/loading_widget_gondola.gif new file mode 100644 index 00000000..80fd3373 Binary files /dev/null and b/media/loading_widget_gondola.gif differ diff --git a/media/logo/.gitkeep b/media/logo/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/media/logo/ozgurozbek/pince_appimage.png b/media/logo/ozgurozbek/pince_appimage.png deleted file mode 100644 index 33528d01..00000000 Binary files a/media/logo/ozgurozbek/pince_appimage.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_cyan.png b/media/logo/ozgurozbek/pince_big_cyan.png deleted file mode 100644 index 39ab9602..00000000 Binary files a/media/logo/ozgurozbek/pince_big_cyan.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_gray.png b/media/logo/ozgurozbek/pince_big_gray.png deleted file mode 100644 index 3af5ecf7..00000000 Binary files a/media/logo/ozgurozbek/pince_big_gray.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_green.png b/media/logo/ozgurozbek/pince_big_green.png deleted file mode 100644 index 8a6284b9..00000000 Binary files a/media/logo/ozgurozbek/pince_big_green.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_neon_blue.png b/media/logo/ozgurozbek/pince_big_neon_blue.png deleted file mode 100644 index 9a0891b5..00000000 Binary files a/media/logo/ozgurozbek/pince_big_neon_blue.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_neon_orange.png b/media/logo/ozgurozbek/pince_big_neon_orange.png deleted file mode 100644 index dd874d6a..00000000 Binary files a/media/logo/ozgurozbek/pince_big_neon_orange.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_orange.png b/media/logo/ozgurozbek/pince_big_orange.png deleted file mode 100644 index e7316dcc..00000000 Binary files a/media/logo/ozgurozbek/pince_big_orange.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_red.png b/media/logo/ozgurozbek/pince_big_red.png deleted file mode 100644 index 54b227be..00000000 Binary files a/media/logo/ozgurozbek/pince_big_red.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_tan.png b/media/logo/ozgurozbek/pince_big_tan.png deleted file mode 100644 index 4aa42ff9..00000000 Binary files a/media/logo/ozgurozbek/pince_big_tan.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_transparent.png b/media/logo/ozgurozbek/pince_big_transparent.png deleted file mode 100644 index 1bf02d18..00000000 Binary files a/media/logo/ozgurozbek/pince_big_transparent.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_white.png b/media/logo/ozgurozbek/pince_big_white.png deleted file mode 100644 index 54b6b903..00000000 Binary files a/media/logo/ozgurozbek/pince_big_white.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_big_yellow.png b/media/logo/ozgurozbek/pince_big_yellow.png deleted file mode 100644 index 78303a4d..00000000 Binary files a/media/logo/ozgurozbek/pince_big_yellow.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_carved_cyan.png b/media/logo/ozgurozbek/pince_small_carved_cyan.png deleted file mode 100644 index 63bd71d4..00000000 Binary files a/media/logo/ozgurozbek/pince_small_carved_cyan.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_carved_orange.png b/media/logo/ozgurozbek/pince_small_carved_orange.png deleted file mode 100644 index efaf9f04..00000000 Binary files a/media/logo/ozgurozbek/pince_small_carved_orange.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_cyan.png b/media/logo/ozgurozbek/pince_small_cyan.png deleted file mode 100644 index 9a6926cc..00000000 Binary files a/media/logo/ozgurozbek/pince_small_cyan.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_gray.png b/media/logo/ozgurozbek/pince_small_gray.png deleted file mode 100644 index 3538edc3..00000000 Binary files a/media/logo/ozgurozbek/pince_small_gray.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_green.png b/media/logo/ozgurozbek/pince_small_green.png deleted file mode 100644 index f7e7b89c..00000000 Binary files a/media/logo/ozgurozbek/pince_small_green.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_orange.png b/media/logo/ozgurozbek/pince_small_orange.png deleted file mode 100644 index 7d9b01bb..00000000 Binary files a/media/logo/ozgurozbek/pince_small_orange.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_red.png b/media/logo/ozgurozbek/pince_small_red.png deleted file mode 100644 index a7959f7b..00000000 Binary files a/media/logo/ozgurozbek/pince_small_red.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_tan.png b/media/logo/ozgurozbek/pince_small_tan.png deleted file mode 100644 index aa57e385..00000000 Binary files a/media/logo/ozgurozbek/pince_small_tan.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_transparent.png b/media/logo/ozgurozbek/pince_small_transparent.png deleted file mode 100644 index b0c98831..00000000 Binary files a/media/logo/ozgurozbek/pince_small_transparent.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_white.png b/media/logo/ozgurozbek/pince_small_white.png deleted file mode 100644 index dfddf793..00000000 Binary files a/media/logo/ozgurozbek/pince_small_white.png and /dev/null differ diff --git a/media/logo/ozgurozbek/pince_small_yellow.png b/media/logo/ozgurozbek/pince_small_yellow.png deleted file mode 100644 index 52f348b2..00000000 Binary files a/media/logo/ozgurozbek/pince_small_yellow.png and /dev/null differ diff --git a/mono_collector/build.zig b/mono_collector/build.zig deleted file mode 100644 index 1076bb49..00000000 --- a/mono_collector/build.zig +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -const std = @import("std"); - -pub fn build(b: *std.Build) void { - const target = b.standardTargetOptions(.{}); - const optimize = b.standardOptimizeOption(.{}); - - const mod = b.createModule(.{ - .root_source_file = b.path("main.zig"), - .target = target, - .optimize = optimize, - .link_libc = target.result.os.tag != .windows, - }); - - const lib = b.addLibrary(.{ - .name = "mono_collector", - .linkage = .dynamic, - .root_module = mod, - }); - - b.installArtifact(lib); -} diff --git a/mono_collector/common.zig b/mono_collector/common.zig deleted file mode 100644 index a77b58b3..00000000 --- a/mono_collector/common.zig +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Helpers shared by the mono and il2cpp backends. -const std = @import("std"); -const builtin = @import("builtin"); -const Encoder = @import("msgpack.zig").Encoder; - -// x86 WINE also uses cdecl. -pub const is_windows = builtin.os.tag == .windows; -pub const win64_abi = is_windows and builtin.cpu.arch == .x86_64; -pub const CC: std.builtin.CallingConvention = if (win64_abi) .winapi else .c; -pub const CStr = [*:0]const u8; - -pub inline fn cspan(p: ?CStr) []const u8 { - return if (p) |s| std.mem.span(s) else ""; -} - -pub inline fn eql(a: []const u8, b: []const u8) bool { - return std.mem.eql(u8, a, b); -} - -// Resolve a symbol through the bound module (dlsym natively, PE export under WINE). -pub inline fn req(comptime T: type, mod: anytype, name: [*:0]const u8) !T { - const p = mod.lookup(name) orelse return error.SymbolMissing; - return @ptrCast(p); -} -pub inline fn opt(comptime T: type, mod: anytype, name: [*:0]const u8) ?T { - const p = mod.lookup(name) orelse return null; - return @ptrCast(p); -} - -// MONO_TYPE_* / Il2CppTypeEnum -> our wire type tag (the two runtimes share these numeric values). -// "unsupported" = a type we can't marshal yet. -pub inline fn typeTag(t: c_int) []const u8 { - return switch (t) { - 0x01 => "void", - 0x02 => "bool", - 0x03 => "char", - 0x04 => "i1", - 0x05 => "u1", - 0x06 => "i2", - 0x07 => "u2", - 0x08 => "i4", - 0x09 => "u4", - 0x0a => "i8", - 0x0b => "u8", - 0x0c => "r4", - 0x0d => "r8", - 0x0e => "str", - 0x0f, 0x18, 0x19 => if (@sizeOf(usize) == 8) "u8" else "u4", // PTR, I, U - 0x11 => "struct", // VALUETYPE: marshalled by value (raw bytes) - 0x12, 0x14, 0x1c, 0x1d => "object", // CLASS, ARRAY, OBJECT, SZARRAY - else => "unsupported", - }; -} - -pub inline fn typeWidth(tag: []const u8) usize { - if (eql(tag, "i1") or eql(tag, "u1") or eql(tag, "bool")) return 1; - if (eql(tag, "i2") or eql(tag, "u2") or eql(tag, "char")) return 2; - if (eql(tag, "i4") or eql(tag, "u4") or eql(tag, "r4")) return 4; - return 8; -} - -pub inline fn emitBits(e: *Encoder, tag: []const u8, bits: u64) !void { - try e.mapHeader(2); - try e.str("tag"); - try e.str(tag); - try e.str("bits"); - try e.uint(bits); -} - -// klass handle + unboxed size for a value-type (struct) or null if we can't resolve them. -pub const StructInfo = struct { klass: ?*anyopaque, size: u64 }; -pub fn structInfo(m: anytype, t: ?*anyopaque) StructInfo { - const cft = m.class_from_type orelse return .{ .klass = null, .size = 0 }; - const vs = m.class_value_size orelse return .{ .klass = null, .size = 0 }; - const klass = cft(t) orelse return .{ .klass = null, .size = 0 }; - const sz = vs(klass, null); - return .{ .klass = klass, .size = if (sz > 0) @intCast(sz) else 0 }; -} - -// Encode a type ref: normally {tag, name}, plus {klass, size} when it's a struct (for marshalling). -pub fn encodeTypeRef(m: anytype, e: *Encoder, t: ?*anyopaque) !void { - const tname = m.type_get_name(t); - const tag = typeTag(m.type_get_type(t)); - if (eql(tag, "struct")) { - const si = structInfo(m, t); - try e.mapHeader(4); - try e.str("tag"); - try e.str(tag); - try e.str("name"); - try e.str(cspan(tname)); - try e.str("klass"); - try e.uint(@intFromPtr(si.klass)); - try e.str("size"); - try e.uint(si.size); - } else { - try e.mapHeader(2); - try e.str("tag"); - try e.str(tag); - try e.str("name"); - try e.str(cspan(tname)); - } - if (m.free) |fr| if (tname) |p| fr(@ptrCast(@constCast(p))); -} diff --git a/mono_collector/il2cpp_api.zig b/mono_collector/il2cpp_api.zig deleted file mode 100644 index 0046c5d6..00000000 --- a/mono_collector/il2cpp_api.zig +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! IL2CPP embedding API backend. -//! Resolves il2cpp_* via dlsym from the already loaded runtime, attaches the worker thread and implements the runtime.Backend vtable. -//! Unity's IL2CPP exports a C API deliberately modeled on Mono's embedding API. -//! Differences handled here vs mono_api.zig: -//! - assemblies arrive as an array (il2cpp_domain_get_assemblies), not via a foreach callback. -//! - classes are enumerated by index (il2cpp_image_get_class), not by metadata token. -//! - there is NO JIT: the native code pointer is read from MethodInfo.methodPointer (offset 0) which is version-sensitive, see il2cppCompile. -//! - IL2CPP exposes no static field base getter so il2cppStaticAddr auto-calibrates the Il2CppClass.static_fields offset once at load (calibrateStaticFields), returning Unsupported when calibration is ambiguous. -//! - signature enumerates params by index (il2cpp_method_get_param) with staticness from the method flags. -const std = @import("std"); -const rt = @import("runtime.zig"); -const Encoder = @import("msgpack.zig").Encoder; -const resolver = @import("resolver.zig"); -const common = @import("common.zig"); - -const CC = common.CC; -const CStr = common.CStr; -const cspan = common.cspan; -const eql = common.eql; -const typeTag = common.typeTag; -const typeWidth = common.typeWidth; -const StructInfo = common.StructInfo; -const structInfo = common.structInfo; -const encodeTypeRef = common.encodeTypeRef; -const req = common.req; -const opt = common.opt; - -// il2cpp_* function pointer types (taken from il2cpp-api-functions.h) -const FnDomain = *const fn () callconv(CC) ?*anyopaque; -const FnThreadAttach = *const fn (?*anyopaque) callconv(CC) ?*anyopaque; -const FnGetAssemblies = *const fn (?*anyopaque, *usize) callconv(CC) ?[*]const ?*anyopaque; -const FnP_P = *const fn (?*anyopaque) callconv(CC) ?*anyopaque; -const FnP_CStr = *const fn (?*anyopaque) callconv(CC) ?CStr; -const FnImgCount = *const fn (?*anyopaque) callconv(CC) usize; -const FnImgClass = *const fn (?*anyopaque, usize) callconv(CC) ?*anyopaque; -const FnIter = *const fn (?*anyopaque, *?*anyopaque) callconv(CC) ?*anyopaque; -const FnFieldOffset = *const fn (?*anyopaque) callconv(CC) usize; -const FnFieldFlags = *const fn (?*anyopaque) callconv(CC) c_int; -const FnTypeName = *const fn (?*anyopaque) callconv(CC) ?CStr; -const FnParamCount = *const fn (?*anyopaque) callconv(CC) u32; -const FnClassInit = *const fn (?*anyopaque) callconv(CC) void; -const FnFromName = *const fn (?*anyopaque, CStr, CStr) callconv(CC) ?*anyopaque; -const FnFree = *const fn (?*anyopaque) callconv(CC) void; -const FnInvoke = *const fn (?*anyopaque, ?*anyopaque, ?[*]?*anyopaque, *?*anyopaque) callconv(CC) ?*anyopaque; -const FnTypeType = *const fn (?*anyopaque) callconv(CC) c_int; -const FnMethodParam = *const fn (?*anyopaque, u32) callconv(CC) ?*anyopaque; -const FnMethodParamName = *const fn (?*anyopaque, u32) callconv(CC) ?CStr; -const FnStringNew = *const fn (CStr) callconv(CC) ?*anyopaque; // no domain arg, unlike mono_string_new -const FnMethodFlags = *const fn (?*anyopaque, *u32) callconv(CC) u32; -const FnGetCorlib = *const fn () callconv(CC) ?*anyopaque; -const FnFieldFromName = *const fn (?*anyopaque, CStr) callconv(CC) ?*anyopaque; -const FnFieldStaticGet = *const fn (?*anyopaque, *anyopaque) callconv(CC) void; -const FnValueSize = *const fn (?*anyopaque, ?*u32) callconv(CC) c_int; - -const Il2CppApi = struct { - allocator: std.mem.Allocator, - root_domain: ?*anyopaque = null, - static_fields_offset: ?usize = null, - - domain_get: FnDomain, - thread_attach: FnThreadAttach, - domain_get_assemblies: FnGetAssemblies, - assembly_get_image: FnP_P, - image_get_name: FnP_CStr, - image_get_filename: ?FnP_CStr, // optional because IL2CPP export sets vary by Unity version - image_get_class_count: FnImgCount, - image_get_class: FnImgClass, - class_get_name: FnP_CStr, - class_get_namespace: FnP_CStr, - class_get_parent: FnP_P, - class_get_fields: FnIter, - field_get_name: FnP_CStr, - field_get_type: FnP_P, - type_get_name: FnTypeName, - field_get_offset: FnFieldOffset, - field_get_flags: FnFieldFlags, - class_get_methods: FnIter, - method_get_name: FnP_CStr, - method_get_param_count: FnParamCount, - method_get_param: FnMethodParam, - method_get_param_name: ?FnMethodParamName, - method_get_return_type: FnP_P, - method_get_flags: ?FnMethodFlags, - type_get_type: FnTypeType, - string_new: ?FnStringNew, - string_to_utf8: ?FnP_CStr, - object_unbox: ?FnP_P, - runtime_class_init: ?FnClassInit, - class_from_name: FnFromName, - class_from_type: ?FnP_P, - class_value_size: ?FnValueSize, - free: ?FnFree, - runtime_invoke: ?FnInvoke = null, - get_corlib: ?FnGetCorlib, - class_get_field_from_name: ?FnFieldFromName, - field_static_get_value: ?FnFieldStaticGet, -}; - -pub fn load(allocator: std.mem.Allocator) !?rt.Backend { - // Bind the runtime module using the resolver. - // ELF -> dlopen/dlsym, PE -> export parsing. - const substr = if (common.is_windows) "GameAssembly.dll" else "GameAssembly"; - const mod = resolver.open(allocator, "il2cpp_domain_get", substr) orelse return null; - - const api = try allocator.create(Il2CppApi); - api.* = .{ - .allocator = allocator, - .domain_get = try req(FnDomain, mod, "il2cpp_domain_get"), - .thread_attach = try req(FnThreadAttach, mod, "il2cpp_thread_attach"), - .domain_get_assemblies = try req(FnGetAssemblies, mod, "il2cpp_domain_get_assemblies"), - .assembly_get_image = try req(FnP_P, mod, "il2cpp_assembly_get_image"), - .image_get_name = try req(FnP_CStr, mod, "il2cpp_image_get_name"), - .image_get_filename = opt(FnP_CStr, mod, "il2cpp_image_get_filename"), - .image_get_class_count = try req(FnImgCount, mod, "il2cpp_image_get_class_count"), - .image_get_class = try req(FnImgClass, mod, "il2cpp_image_get_class"), - .class_get_name = try req(FnP_CStr, mod, "il2cpp_class_get_name"), - .class_get_namespace = try req(FnP_CStr, mod, "il2cpp_class_get_namespace"), - .class_get_parent = try req(FnP_P, mod, "il2cpp_class_get_parent"), - .class_get_fields = try req(FnIter, mod, "il2cpp_class_get_fields"), - .field_get_name = try req(FnP_CStr, mod, "il2cpp_field_get_name"), - .field_get_type = try req(FnP_P, mod, "il2cpp_field_get_type"), - .type_get_name = try req(FnTypeName, mod, "il2cpp_type_get_name"), - .field_get_offset = try req(FnFieldOffset, mod, "il2cpp_field_get_offset"), - .field_get_flags = try req(FnFieldFlags, mod, "il2cpp_field_get_flags"), - .class_get_methods = try req(FnIter, mod, "il2cpp_class_get_methods"), - .method_get_name = try req(FnP_CStr, mod, "il2cpp_method_get_name"), - .method_get_param_count = try req(FnParamCount, mod, "il2cpp_method_get_param_count"), - .method_get_param = try req(FnMethodParam, mod, "il2cpp_method_get_param"), - .method_get_param_name = opt(FnMethodParamName, mod, "il2cpp_method_get_param_name"), - .method_get_return_type = try req(FnP_P, mod, "il2cpp_method_get_return_type"), - .method_get_flags = opt(FnMethodFlags, mod, "il2cpp_method_get_flags"), - .type_get_type = try req(FnTypeType, mod, "il2cpp_type_get_type"), - .string_new = opt(FnStringNew, mod, "il2cpp_string_new"), - .string_to_utf8 = opt(FnP_CStr, mod, "il2cpp_string_to_utf8"), - .object_unbox = opt(FnP_P, mod, "il2cpp_object_unbox"), - .runtime_class_init = opt(FnClassInit, mod, "il2cpp_runtime_class_init"), - .class_from_name = try req(FnFromName, mod, "il2cpp_class_from_name"), - .class_from_type = opt(FnP_P, mod, "il2cpp_class_from_type"), - .class_value_size = opt(FnValueSize, mod, "il2cpp_class_value_size"), - .free = opt(FnFree, mod, "il2cpp_free"), - .runtime_invoke = opt(FnInvoke, mod, "il2cpp_runtime_invoke"), - .get_corlib = opt(FnGetCorlib, mod, "il2cpp_get_corlib"), - .class_get_field_from_name = opt(FnFieldFromName, mod, "il2cpp_class_get_field_from_name"), - .field_static_get_value = opt(FnFieldStaticGet, mod, "il2cpp_field_static_get_value"), - }; - - api.root_domain = api.domain_get(); - _ = api.thread_attach(api.root_domain); - api.static_fields_offset = calibrateStaticFields(api); - - return rt.Backend{ - .ctx = api, - .kind = .il2cpp, - .assembliesFn = il2cppAssemblies, - .classesFn = il2cppClasses, - .fieldsFn = il2cppFields, - .methodsFn = il2cppMethods, - .compileFn = il2cppCompile, - .staticAddrFn = il2cppStaticAddr, - .invokeFn = il2cppInvoke, - .signatureFn = il2cppSignature, - .classInfoFn = il2cppClassInfo, - .typeKlassFn = il2cppTypeKlass, - .instanceMarkerFn = il2cppInstanceMarker, - }; -} - -inline fn self(ctx: *anyopaque) *Il2CppApi { - return @ptrCast(@alignCast(ctx)); -} - -fn il2cppAssemblies(ctx: *anyopaque, e: *Encoder) !void { - const m = self(ctx); - var count: usize = 0; - const arr = m.domain_get_assemblies(m.root_domain, &count); - try e.arrayHeader(if (arr == null) 0 else count); - if (arr) |list| { - var i: usize = 0; - while (i < count) : (i += 1) { - const asm_ptr = list[i]; - const img = m.assembly_get_image(asm_ptr); - try e.mapHeader(4); - try e.str("assembly"); - try e.uint(@intFromPtr(asm_ptr)); - try e.str("image"); - try e.uint(@intFromPtr(img)); - try e.str("name"); - try e.str(cspan(m.image_get_name(img))); - try e.str("filename"); - try e.str(if (m.image_get_filename) |f| cspan(f(img)) else ""); - } - } -} - -fn il2cppClasses(ctx: *anyopaque, image_u: u64, e: *Encoder) !void { - const m = self(ctx); - const image: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(image_u))); - const count = m.image_get_class_count(image); - - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - var i: usize = 0; - while (i < count) : (i += 1) { - const klass = m.image_get_class(image, i); - if (klass != null) try list.append(m.allocator, @intFromPtr(klass)); - } - try e.arrayHeader(list.items.len); - - for (list.items) |ku| { - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(ku))); - try e.mapHeader(4); - try e.str("klass"); - try e.uint(ku); - try e.str("namespace"); - try e.str(cspan(m.class_get_namespace(klass))); - try e.str("name"); - try e.str(cspan(m.class_get_name(klass))); - try e.str("parent"); - try e.uint(@intFromPtr(m.class_get_parent(klass))); - } -} - -const FIELD_ATTRIBUTE_STATIC: u32 = 0x10; -fn il2cppFields(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - var iter: ?*anyopaque = null; - while (m.class_get_fields(klass, &iter)) |fld| try list.append(m.allocator, @intFromPtr(fld)); - try e.arrayHeader(list.items.len); - - for (list.items) |fu| { - const fld: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(fu))); - const ftype = m.field_get_type(fld); - const tname = m.type_get_name(ftype); - const flags: u32 = @bitCast(m.field_get_flags(fld)); - try e.mapHeader(7); - try e.str("field"); - try e.uint(fu); - try e.str("name"); - try e.str(cspan(m.field_get_name(fld))); - try e.str("type"); - try e.str(cspan(tname)); - try e.str("tag"); - try e.str(typeTag(m.type_get_type(ftype))); - try e.str("offset"); - try e.uint(@intCast(m.field_get_offset(fld))); - try e.str("flags"); - try e.uint(flags); - try e.str("is_static"); - try e.boolean((flags & FIELD_ATTRIBUTE_STATIC) != 0); - if (m.free) |fr| if (tname) |p| fr(@ptrCast(@constCast(p))); - } -} - -inline fn appendName(buf: []u8, off: *usize, s: []const u8) void { - const n = @min(s.len, buf.len - off.*); - @memcpy(buf[off.* .. off.* + n], s[0..n]); - off.* += n; -} - -fn formatFullName(m: *Il2CppApi, meth: ?*anyopaque, buf: []u8) []const u8 { - var off: usize = 0; - const rname = m.type_get_name(m.method_get_return_type(meth)); - appendName(buf, &off, cspan(rname)); - if (m.free) |fr| if (rname) |p| fr(@ptrCast(@constCast(p))); - appendName(buf, &off, " "); - appendName(buf, &off, cspan(m.method_get_name(meth))); - appendName(buf, &off, "("); - const pc = m.method_get_param_count(meth); - var i: u32 = 0; - while (i < pc) : (i += 1) { - if (i != 0) appendName(buf, &off, ", "); - const pname = m.type_get_name(m.method_get_param(meth, i)); - appendName(buf, &off, cspan(pname)); - if (m.free) |fr| if (pname) |p| fr(@ptrCast(@constCast(p))); - } - appendName(buf, &off, ")"); - return buf[0..off]; -} - -fn il2cppMethods(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - var iter: ?*anyopaque = null; - while (m.class_get_methods(klass, &iter)) |meth| try list.append(m.allocator, @intFromPtr(meth)); - try e.arrayHeader(list.items.len); - - for (list.items) |mu| { - // Still not the drug... - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(mu))); - const nm = cspan(m.method_get_name(meth)); - const pc: u64 = m.method_get_param_count(meth); - - try e.mapHeader(4); - try e.str("method"); - try e.uint(mu); - try e.str("name"); - try e.str(nm); - var fnbuf: [512]u8 = undefined; - try e.str("full_name"); - try e.str(formatFullName(m, meth, &fnbuf)); - try e.str("param_count"); - try e.uint(pc); - } -} - -fn il2cppCompile(ctx: *anyopaque, method_u: u64, e: *Encoder) !void { - _ = ctx; - // IL2CPP is AOT (ahead of time) compilation so there is no JIT/compile step. - // MethodInfo.methodPointer is the first struct field (offset 0) across known IL2CPP versions, - // so the native code address is the pointer sized value stored at the MethodInfo handle. - if (method_u == 0) return error.CompileFailed; - const mi: *const usize = @ptrFromInt(@as(usize, @intCast(method_u))); - const addr = mi.*; - if (addr == 0) return error.CompileFailed; // null methodPointer (not AOT'd) -> 0 would SIGSEGV the target - - try e.mapHeader(1); - try e.str("native_addr"); - try e.uint(addr); -} - -inline fn classWord(klass: ?*anyopaque, off: usize) usize { - const p: [*]const u8 = @ptrCast(klass); - return @as(*align(1) const usize, @ptrCast(p + off)).*; -} - -// Fault-safe word read via /proc/self/mem so an unmapped address errors instead of faulting. -inline fn calibReadWord(mem: anytype, io: anytype, addr: usize) ?usize { - var out: usize = 0; - const n = mem.readPositionalAll(io, std.mem.asBytes(&out), addr) catch return null; - if (n != @sizeOf(usize)) return null; - return out; -} - -const SF_SCAN_WINDOW: usize = 0x280; -fn calibrateStaticFields(m: *Il2CppApi) ?usize { - const get_corlib = m.get_corlib orelse return null; - const get_field = m.class_get_field_from_name orelse return null; - const static_get = m.field_static_get_value orelse return null; - const class_init = m.runtime_class_init orelse return null; - - const corlib = get_corlib() orelse return null; - const str_klass = m.class_from_name(corlib, "System", "String") orelse return null; - class_init(str_klass); - const empty = get_field(str_klass, "Empty") orelse return null; - var empty_val: usize = 0; - static_get(empty, @ptrCast(&empty_val)); - if (empty_val == 0) return null; - const empty_off: usize = @intCast(m.field_get_offset(empty)); - const obj_klass = m.class_from_name(corlib, "System", "Object") orelse return null; - - const io = std.Io.Threaded.global_single_threaded.io(); - const mem = std.Io.Dir.openFileAbsolute(io, "/proc/self/mem", .{}) catch return null; - defer mem.close(io); - - // static_fields offset in Il2CppClass varies by Unity version so we find it at load. - // No unique match -> leave it null so static_addr never returns a wrong address. - const str_addr = @intFromPtr(str_klass); - const obj_addr = @intFromPtr(obj_klass); - var found: ?usize = null; - var k: usize = 0; - while (k <= SF_SCAN_WINDOW) : (k += @sizeOf(usize)) { - const cand = calibReadWord(mem, io, str_addr + k) orelse break; // ran off the struct - if (cand == 0) continue; - const got = calibReadWord(mem, io, cand + empty_off) orelse continue; - if (got != empty_val) continue; - const ow = calibReadWord(mem, io, obj_addr + k) orelse continue; - if (ow != 0) continue; - if (found != null) return null; // ambiguous - found = k; - } - return found; -} - -fn il2cppStaticAddr(ctx: *anyopaque, klass_u: u64, field_u: u64, e: *Encoder) !void { - const m = self(ctx); - const sf_off = m.static_fields_offset orelse return error.Unsupported; - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - const fld: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(field_u))); - - if (m.runtime_class_init) |ci| ci(klass); - const base: u64 = classWord(klass, sf_off); - if (base == 0) return error.Unsupported; - - const addr: u64 = base +% @as(u64, @intCast(m.field_get_offset(fld))); - try e.mapHeader(1); - try e.str("address"); - try e.uint(addr); -} - -// An IL2CPP object's first word is its Il2CppClass* (the klass handle), so the marker is just that handle. -fn il2cppInstanceMarker(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - _ = ctx; - try e.mapHeader(1); - try e.str("marker"); - try e.uint(klass_u); -} - -fn il2cppClassInfo(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - try e.mapHeader(3); - try e.str("namespace"); - try e.str(cspan(m.class_get_namespace(klass))); - try e.str("name"); - try e.str(cspan(m.class_get_name(klass))); - try e.str("parent"); - try e.uint(@intFromPtr(m.class_get_parent(klass))); -} - -fn il2cppTypeKlass(ctx: *anyopaque, field_u: u64, e: *Encoder) !void { - const m = self(ctx); - const fld: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(field_u))); - var kptr: ?*anyopaque = null; - if (m.class_from_type) |cft| { - if (m.field_get_type(fld)) |t| kptr = cft(t); - } - try e.mapHeader(1); - try e.str("klass"); - try e.uint(@intFromPtr(kptr)); -} - -// Same wire shape as monoSignature, but IL2CPP enumerates params by index and not an iterator. -// Static-ness is carried in the method flags (no signature object). -fn il2cppSignature(ctx: *anyopaque, method_u: u64, e: *Encoder) !void { - const m = self(ctx); - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(method_u))); - const pc = m.method_get_param_count(meth); - - var is_static = false; - if (m.method_get_flags) |gf| { - var iflags: u32 = 0; - const flags = gf(meth, &iflags); - is_static = (flags & 0x10) != 0; // METHOD_ATTRIBUTE_STATIC - } - - try e.mapHeader(3); - try e.str("static"); - try e.boolean(is_static); - try e.str("ret"); - try encodeTypeRef(m, e, m.method_get_return_type(meth)); - try e.str("params"); - try e.arrayHeader(pc); - var i: u32 = 0; - while (i < pc) : (i += 1) { - const ptype = m.method_get_param(meth, i); - const tname = m.type_get_name(ptype); - const tag = typeTag(m.type_get_type(ptype)); - const is_struct = eql(tag, "struct"); - const si = if (is_struct) structInfo(m, ptype) else StructInfo{ .klass = null, .size = 0 }; - try e.mapHeader(if (is_struct) 5 else 3); - try e.str("name"); - const pname = if (m.method_get_param_name) |gpn| gpn(meth, i) else null; - if (pname != null) { - try e.str(cspan(pname)); - } else { - var nb: [16]u8 = undefined; - try e.str(std.fmt.bufPrint(&nb, "arg{d}", .{i}) catch "arg"); - } - try e.str("tag"); - try e.str(tag); - try e.str("type"); - try e.str(cspan(tname)); - if (is_struct) { - try e.str("klass"); - try e.uint(@intFromPtr(si.klass)); - try e.str("size"); - try e.uint(si.size); - } - if (m.free) |fr| if (tname) |p| fr(@ptrCast(@constCast(p))); - } -} - -fn il2cppInvoke(ctx: *anyopaque, method_u: u64, obj_u: u64, args: []const rt.Arg, e: *Encoder) !void { - const m = self(ctx); - const invoke = m.runtime_invoke orelse return error.Unsupported; - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(method_u))); - const obj: ?*anyopaque = if (obj_u == 0) null else @ptrFromInt(@as(usize, @intCast(obj_u))); - - if (args.len > 32) return error.TooManyArgs; // Make sure this is sync'd with main.zig's dispatcher args_buf[32] cap. - var slots: [32]u64 = undefined; - var argv: [32]?*anyopaque = undefined; - - for (args, 0..) |a, i| { - if (eql(a.tag, "str")) { - const sn = m.string_new orelse return error.Unsupported; - var sbuf: [1024]u8 = undefined; - if (a.str.len >= sbuf.len) return error.NameTooLong; - @memcpy(sbuf[0..a.str.len], a.str); - sbuf[a.str.len] = 0; - argv[i] = sn(@ptrCast(&sbuf)); // il2cpp_string_new takes no domain (unlike mono) - } else if (eql(a.tag, "object")) { - argv[i] = @ptrFromInt(@as(usize, @intCast(a.bits))); - } else if (eql(a.tag, "nil")) { - argv[i] = null; - } else if (eql(a.tag, "struct")) { - argv[i] = @constCast(a.str.ptr); // value type: raw bytes live in the request frame for the call - } else { - slots[i] = a.bits; // little-endian native, low N bytes are the value - argv[i] = &slots[i]; // value type: pointer to the value - } - } - const argv_ptr: ?[*]?*anyopaque = if (args.len == 0) null else &argv; - - var exc: ?*anyopaque = null; - const ret = invoke(meth, obj, argv_ptr, &exc); - - try e.mapHeader(2); - try e.str("result"); - if (exc != null) { - try e.nil(); - } else { - const rtype = m.method_get_return_type(meth); - const renum: c_int = if (rtype != null) m.type_get_type(rtype) else 0x01; // void if no return type - const rtag = typeTag(renum); - if (renum == 0x01 or ret == null) { // void / null - try e.nil(); - } else if (eql(rtag, "str")) { - if (m.string_to_utf8) |conv| { - const c = conv(ret); - try e.mapHeader(2); - try e.str("tag"); - try e.str("str"); - try e.str("val"); - try e.str(cspan(c)); - if (m.free) |fr| if (c) |p| fr(@ptrCast(@constCast(p))); - } else { - try e.mapHeader(2); - try e.str("tag"); - try e.str("object"); - try e.str("bits"); - try e.uint(@intFromPtr(ret)); - } - } else if (eql(rtag, "object")) { - try e.mapHeader(2); - try e.str("tag"); - try e.str("object"); - try e.str("bits"); - try e.uint(@intFromPtr(ret)); - } else if (eql(rtag, "struct")) { // value type by value: unbox and ship its raw bytes - const ub = m.object_unbox orelse return error.Unsupported; - const si = structInfo(m, rtype); - const vp = ub(ret); - if (vp == null or si.size == 0) { - try e.nil(); - } else { - try e.mapHeader(2); - try e.str("tag"); - try e.str("struct"); - try e.str("bytes"); - const src: [*]const u8 = @ptrCast(vp); - try e.bin(src[0..@intCast(si.size)]); - } - } else if (eql(rtag, "unsupported")) { - return error.Unsupported; - } else { // primitive value type: unbox and read its bytes - const ub = m.object_unbox orelse return error.Unsupported; - const vp = ub(ret); - var bits: u64 = 0; - const w = typeWidth(rtag); - if (vp) |p| { - const src: [*]const u8 = @ptrCast(p); - @memcpy(std.mem.asBytes(&bits)[0..w], src[0..w]); - } - try e.mapHeader(2); - try e.str("tag"); - try e.str(rtag); - try e.str("bits"); - try e.uint(bits); - } - } - try e.str("exception"); - try e.uint(@intFromPtr(exc)); -} diff --git a/mono_collector/main.zig b/mono_collector/main.zig deleted file mode 100644 index 36e740eb..00000000 --- a/mono_collector/main.zig +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Entry + worker thread + request server + op dispatch. -//! The worker attaches to the Mono domain and serves frames over a socket. -const std = @import("std"); -const linux = std.os.linux; -const common = @import("common.zig"); -const rt = @import("runtime.zig"); -const msgpack = @import("msgpack.zig"); -const Encoder = msgpack.Encoder; -const eql = common.eql; - -const EINTR = -@as(isize, @intFromEnum(linux.E.INTR)); -const ws = std.os.windows.ws2_32; - -var started = std.atomic.Value(bool).init(false); - -// Transport: ELF uses a raw syscall abstract Unix socket while the PE DLL uses Winsock TCP on 127.0.0.1, -// because WINE's seccomp filter kills direct Linux syscalls from PE code (SIGSYS). -const Sock = if (common.is_windows) usize else i32; - -var wine_port: u16 = 0; -comptime { - if (common.is_windows) @export(&wine_port, .{ .name = "pince_mono_port" }); -} - -const win = if (common.is_windows) struct { - extern "ws2_32" fn WSAStartup(version: u16, data: *anyopaque) callconv(.winapi) c_int; - extern "ws2_32" fn socket(af: c_int, kind: c_int, protocol: c_int) callconv(.winapi) usize; - extern "ws2_32" fn bind(s: usize, name: *const anyopaque, namelen: c_int) callconv(.winapi) c_int; - extern "ws2_32" fn listen(s: usize, backlog: c_int) callconv(.winapi) c_int; - extern "ws2_32" fn accept(s: usize, addr: ?*anyopaque, addrlen: ?*c_int) callconv(.winapi) usize; - extern "ws2_32" fn getsockname(s: usize, name: *anyopaque, namelen: *c_int) callconv(.winapi) c_int; - extern "ws2_32" fn setsockopt(s: usize, level: c_int, optname: c_int, optval: [*]const u8, optlen: c_int) callconv(.winapi) c_int; - extern "ws2_32" fn recv(s: usize, buf: [*]u8, len: c_int, flags: c_int) callconv(.winapi) c_int; - extern "ws2_32" fn send(s: usize, buf: [*]const u8, len: c_int, flags: c_int) callconv(.winapi) c_int; - extern "ws2_32" fn closesocket(s: usize) callconv(.winapi) c_int; -} else struct {}; - -fn setupListener() ?Sock { - if (common.is_windows) { - var wsadata: [512]u8 = undefined; - if (win.WSAStartup(0x0202, &wsadata) != 0) return null; // request Winsock 2.2 - const s = win.socket(ws.AF.INET, ws.SOCK.STREAM, ws.IPPROTO.TCP); - if (s == std.math.maxInt(usize)) return null; - var addr = ws.sockaddr.in{ - .port = 0, // kernel-assigned free port - .addr = std.mem.nativeToBig(u32, 0x7F00_0001), // 127.0.0.1, loopback only - }; - if (win.bind(s, &addr, @sizeOf(ws.sockaddr.in)) != 0 or win.listen(s, 1) != 0) { - _ = win.closesocket(s); - return null; - } - var slen: c_int = @sizeOf(ws.sockaddr.in); - if (win.getsockname(s, &addr, &slen) != 0) { - _ = win.closesocket(s); - return null; - } - wine_port = std.mem.bigToNative(u16, addr.port); - return s; - } - const rc = linux.socket(linux.AF.UNIX, linux.SOCK.STREAM, 0); - if (@as(isize, @bitCast(rc)) < 0) return null; - const fd: i32 = @intCast(rc); - var namebuf: [64]u8 = undefined; - const name = std.fmt.bufPrint(&namebuf, "pince-mono-{d}", .{linux.getpid()}) catch { - _ = linux.close(fd); - return null; - }; - var addr = std.mem.zeroes(linux.sockaddr.un); - addr.family = linux.AF.UNIX; - addr.path[0] = 0; // leading NUL -> abstract namespace - @memcpy(addr.path[1 .. 1 + name.len], name); - const addrlen: linux.socklen_t = @intCast(@offsetOf(linux.sockaddr.un, "path") + 1 + name.len); - if (linux.bind(fd, @ptrCast(&addr), addrlen) != 0 or linux.listen(fd, 1) != 0) { - _ = linux.close(fd); - return null; - } - return fd; -} - -fn startWorker() void { - if (started.swap(true, .seq_cst)) return; - // PE build must spawn a real WINE thread so Mono's GC can suspend it. - (std.Thread.spawn(.{}, workerMain, .{}) catch return).detach(); -} - -// PE entry point loaded via kernel32!LoadLibraryW. -pub fn DllMain( - _: std.os.windows.HINSTANCE, - reason: std.os.windows.DWORD, - _: std.os.windows.LPVOID, -) callconv(.winapi) std.os.windows.BOOL { - if (reason == 1) startWorker(); // DLL_PROCESS_ATTACH - return .TRUE; -} - -fn ctor() callconv(.c) void { - startWorker(); -} -const ctor_ptr: *const fn () callconv(.c) void = &ctor; -comptime { - if (!common.is_windows) @export(&ctor_ptr, .{ .name = "_pince_mono_ctor", .section = ".init_array" }); -} - -fn readN(s: Sock, buf: []u8) !void { - var off: usize = 0; - while (off < buf.len) { - const n = if (common.is_windows) - win.recv(s, buf[off..].ptr, @intCast(buf.len - off), 0) - else blk: { - const rc: isize = @bitCast(linux.read(s, buf[off..].ptr, buf.len - off)); - if (rc == EINTR) continue; - break :blk rc; - }; - if (n < 0) return error.ReadError; - if (n == 0) return error.Eof; - off += @intCast(n); - } -} - -fn writeN(s: Sock, buf: []const u8) !void { - var off: usize = 0; - while (off < buf.len) { - const n = if (common.is_windows) - win.send(s, buf[off..].ptr, @intCast(buf.len - off), 0) - else blk: { - const rc: isize = @bitCast(linux.write(s, buf[off..].ptr, buf.len - off)); - if (rc == EINTR) continue; - break :blk rc; - }; - if (n < 0) return error.WriteError; - if (n == 0) return error.Closed; - off += @intCast(n); - } -} - -fn dispatch(allocator: std.mem.Allocator, backend: *const rt.Backend, req_bytes: []const u8, out: *Encoder) !void { - var dec = msgpack.Decoder{ .data = req_bytes }; - const n = dec.mapLen() catch return writeErr(out, "bad request"); - - var op: []const u8 = ""; - var image: u64 = 0; - var klass: u64 = 0; - var field: u64 = 0; - var method: u64 = 0; - var obj: u64 = 0; - var args_buf: [32]rt.Arg = undefined; - var args_len: usize = 0; - - for (0..n) |_| { - const key = dec.str() catch return writeErr(out, "bad key"); - if (eql(key, "op")) { - op = dec.str() catch return writeErr(out, "bad op"); - } else if (eql(key, "image")) { - image = dec.uint() catch return writeErr(out, "bad image"); - } else if (eql(key, "klass")) { - klass = dec.uint() catch return writeErr(out, "bad klass"); - } else if (eql(key, "field")) { - field = dec.uint() catch return writeErr(out, "bad field"); - } else if (eql(key, "method")) { - method = dec.uint() catch return writeErr(out, "bad method"); - } else if (eql(key, "obj")) { - obj = dec.uint() catch return writeErr(out, "bad obj"); - } else if (eql(key, "args")) { - const count = dec.arrayLen() catch return writeErr(out, "bad args"); - args_len = 0; - for (0..count) |_| { - if (args_len >= args_buf.len) return writeErr(out, "too many args"); - if ((dec.arrayLen() catch return writeErr(out, "bad arg")) != 2) return writeErr(out, "bad arg"); - const tag = dec.str() catch return writeErr(out, "bad arg tag"); - var a = rt.Arg{ .tag = tag }; - if (eql(tag, "str") or eql(tag, "struct")) { - a.str = dec.str() catch return writeErr(out, "bad arg str"); // struct: raw value bytes - } else { - a.bits = dec.uint() catch return writeErr(out, "bad arg val"); - } - args_buf[args_len] = a; - args_len += 1; - } - } else { - return writeErr(out, "unknown key"); // PINCE should only send known keys - } - } - - // Run the op into a temp buffer and then wrap success/failure afterwards. - var tmp: std.ArrayList(u8) = .empty; - defer tmp.deinit(allocator); - var tenc = Encoder{ .list = &tmp, .allocator = allocator }; - - const result: anyerror!void = if (eql(op, "assemblies")) - backend.assemblies(&tenc) - else if (eql(op, "classes")) - backend.classes(image, &tenc) - else if (eql(op, "fields")) - backend.fields(klass, &tenc) - else if (eql(op, "methods")) - backend.methods(klass, &tenc) - else if (eql(op, "compile")) - backend.compile(method, &tenc) - else if (eql(op, "static_addr")) - backend.staticAddr(klass, field, &tenc) - else if (eql(op, "class_info")) - backend.classInfo(klass, &tenc) - else if (eql(op, "type_klass")) - backend.typeKlass(field, &tenc) - else if (eql(op, "instance_marker")) - backend.instanceMarker(klass, &tenc) - else if (eql(op, "invoke")) - backend.invoke(method, obj, args_buf[0..args_len], &tenc) - else if (eql(op, "signature")) - backend.signature(method, &tenc) - else - error.UnknownOp; - - if (result) |_| { - try out.mapHeader(2); - try out.str("ok"); - try out.boolean(true); - try out.str("data"); - try out.raw(tmp.items); - } else |err| { - try writeErr(out, @errorName(err)); - } -} - -fn writeErr(out: *Encoder, msg: []const u8) !void { - out.list.clearRetainingCapacity(); - try out.mapHeader(2); - try out.str("ok"); - try out.boolean(false); - try out.str("error"); - try out.str(msg); -} - -fn handleConn(allocator: std.mem.Allocator, backend: *const rt.Backend, conn: Sock) void { - defer { - if (common.is_windows) _ = win.closesocket(conn) else _ = linux.close(conn); - } - while (true) { - var len_buf: [4]u8 = undefined; - readN(conn, &len_buf) catch return; - const len = std.mem.readInt(u32, &len_buf, .big); - if (len > (16 * 1024 * 1024)) return; - - const req_bytes = allocator.alloc(u8, len) catch return; - defer allocator.free(req_bytes); - readN(conn, req_bytes) catch return; - - var out: std.ArrayList(u8) = .empty; - defer out.deinit(allocator); - - var enc = Encoder{ .list = &out, .allocator = allocator }; - dispatch(allocator, backend, req_bytes, &enc) catch { - writeErr(&enc, "internal") catch return; - }; - std.mem.writeInt(u32, &len_buf, @intCast(out.items.len), .big); - writeN(conn, &len_buf) catch return; - writeN(conn, out.items) catch return; - } -} - -fn workerMain() void { - // The PE build links no libc, so use the libc-free general allocator there. - const allocator = if (common.is_windows) std.heap.smp_allocator else std.heap.c_allocator; - const backend = (rt.detectAndLoad(allocator) catch return) orelse return; - - const listener = setupListener() orelse return; - while (true) { - const conn = if (common.is_windows) blk: { - const c = win.accept(listener, null, null); - if (c == std.math.maxInt(usize)) continue; - const one: u32 = 1; // TCP_NODELAY: our frames are a 4 bytes header + body, so avoid Nagle delays - _ = win.setsockopt(c, ws.IPPROTO.TCP, ws.TCP.NODELAY, std.mem.asBytes(&one), @sizeOf(u32)); - break :blk c; - } else blk: { - const c = linux.accept(listener, null, null); - if (@as(isize, @bitCast(c)) < 0) continue; - break :blk @as(i32, @intCast(c)); - }; - handleConn(allocator, &backend, conn); - } -} diff --git a/mono_collector/mono_api.zig b/mono_collector/mono_api.zig deleted file mode 100644 index e78f5459..00000000 --- a/mono_collector/mono_api.zig +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Mono embedding API backend. -//! Resolves mono_* via dlsym from the already loaded runtime, attaches the worker thread and implements the runtime.Backend vtable. -const std = @import("std"); -const rt = @import("runtime.zig"); -const Encoder = @import("msgpack.zig").Encoder; -const resolver = @import("resolver.zig"); -const common = @import("common.zig"); - -const CC = common.CC; -const CStr = common.CStr; -const cspan = common.cspan; -const eql = common.eql; -const typeTag = common.typeTag; -const typeWidth = common.typeWidth; -const emitBits = common.emitBits; -const StructInfo = common.StructInfo; -const structInfo = common.structInfo; -const encodeTypeRef = common.encodeTypeRef; -const req = common.req; -const opt = common.opt; - -// mono_* function pointer types -const FnDomain = *const fn () callconv(CC) ?*anyopaque; -const FnP_P = *const fn (?*anyopaque) callconv(CC) ?*anyopaque; -const ForeachCb = *const fn (?*anyopaque, ?*anyopaque) callconv(CC) void; -const FnForeach = *const fn (ForeachCb, ?*anyopaque) callconv(CC) void; -const FnP_CStr = *const fn (?*anyopaque) callconv(CC) ?CStr; -const FnImgTable = *const fn (?*anyopaque, c_int) callconv(CC) ?*anyopaque; -const FnRows = *const fn (?*anyopaque) callconv(CC) c_int; -const FnClassGet = *const fn (?*anyopaque, u32) callconv(CC) ?*anyopaque; -const FnIter = *const fn (?*anyopaque, *?*anyopaque) callconv(CC) ?*anyopaque; -const FnFieldOffset = *const fn (?*anyopaque) callconv(CC) c_int; -const FnFieldFlags = *const fn (?*anyopaque) callconv(CC) u32; -const FnTypeName = *const fn (?*anyopaque) callconv(CC) ?CStr; -const FnFullName = *const fn (?*anyopaque, c_int) callconv(CC) ?CStr; -const FnParamCount = *const fn (?*anyopaque) callconv(CC) u32; -const FnVtable = *const fn (?*anyopaque, ?*anyopaque) callconv(CC) ?*anyopaque; -const FnStaticData = *const fn (?*anyopaque) callconv(CC) ?*anyopaque; -const FnValueSize = *const fn (?*anyopaque, ?*u32) callconv(CC) c_int; -const FnClassInit = *const fn (?*anyopaque) callconv(CC) void; -const FnFree = *const fn (?*anyopaque) callconv(CC) void; -const FnInvoke = *const fn (?*anyopaque, ?*anyopaque, ?[*]?*anyopaque, *?*anyopaque) callconv(CC) ?*anyopaque; -const FnTypeType = *const fn (?*anyopaque) callconv(CC) c_int; -const FnStringNew = *const fn (?*anyopaque, CStr) callconv(CC) ?*anyopaque; -const FnParamNames = *const fn (?*anyopaque, [*]?CStr) callconv(CC) void; - -const MonoApi = struct { - allocator: std.mem.Allocator, - root_domain: ?*anyopaque = null, - - get_root_domain: FnDomain, - thread_attach: FnP_P, - assembly_foreach: FnForeach, - assembly_get_image: FnP_P, - image_get_name: FnP_CStr, - image_get_filename: FnP_CStr, - image_get_table_info: FnImgTable, - table_info_get_rows: FnRows, - class_get: FnClassGet, - class_get_name: FnP_CStr, - class_get_namespace: FnP_CStr, - class_get_parent: FnP_P, - class_get_fields: FnIter, - field_get_name: FnP_CStr, - field_get_type: FnP_P, - type_get_name: FnTypeName, - field_get_offset: FnFieldOffset, - field_get_flags: FnFieldFlags, - class_get_methods: FnIter, - method_get_name: FnP_CStr, - method_full_name: FnFullName, - method_signature: FnP_P, - signature_get_param_count: FnParamCount, - signature_get_params: FnIter, - signature_get_return_type: FnP_P, - signature_is_instance: ?FnTypeType, - type_get_type: FnTypeType, - method_get_param_names: ?FnParamNames, - string_new: ?FnStringNew, - string_to_utf8: ?FnP_CStr, - object_unbox: ?FnP_P, - compile_method: FnP_P, - class_vtable: FnVtable, - vtable_get_static_field_data: FnStaticData, - class_value_size: ?FnValueSize, - runtime_class_init: ?FnClassInit, - class_from_type: ?FnP_P, - free: ?FnFree, - runtime_invoke: ?FnInvoke = null, -}; - -pub fn load(allocator: std.mem.Allocator) !?rt.Backend { - // Bind the runtime module using the resolver. - // ELF -> dlopen/dlsym, PE -> export parsing. - const substr = if (common.is_windows) "mono-2.0-bdwgc.dll" else "libmono"; - const mod = resolver.open(allocator, "mono_get_root_domain", substr) orelse return null; - - const api = try allocator.create(MonoApi); - api.* = .{ - .allocator = allocator, - .get_root_domain = try req(FnDomain, mod, "mono_get_root_domain"), - .thread_attach = try req(FnP_P, mod, "mono_thread_attach"), - .assembly_foreach = try req(FnForeach, mod, "mono_assembly_foreach"), - .assembly_get_image = try req(FnP_P, mod, "mono_assembly_get_image"), - .image_get_name = try req(FnP_CStr, mod, "mono_image_get_name"), - .image_get_filename = try req(FnP_CStr, mod, "mono_image_get_filename"), - .image_get_table_info = try req(FnImgTable, mod, "mono_image_get_table_info"), - .table_info_get_rows = try req(FnRows, mod, "mono_table_info_get_rows"), - .class_get = try req(FnClassGet, mod, "mono_class_get"), - .class_get_name = try req(FnP_CStr, mod, "mono_class_get_name"), - .class_get_namespace = try req(FnP_CStr, mod, "mono_class_get_namespace"), - .class_get_parent = try req(FnP_P, mod, "mono_class_get_parent"), - .class_get_fields = try req(FnIter, mod, "mono_class_get_fields"), - .field_get_name = try req(FnP_CStr, mod, "mono_field_get_name"), - .field_get_type = try req(FnP_P, mod, "mono_field_get_type"), - .type_get_name = try req(FnTypeName, mod, "mono_type_get_name"), - .field_get_offset = try req(FnFieldOffset, mod, "mono_field_get_offset"), - .field_get_flags = try req(FnFieldFlags, mod, "mono_field_get_flags"), - .class_get_methods = try req(FnIter, mod, "mono_class_get_methods"), - .method_get_name = try req(FnP_CStr, mod, "mono_method_get_name"), - .method_full_name = try req(FnFullName, mod, "mono_method_full_name"), - .method_signature = try req(FnP_P, mod, "mono_method_signature"), - .signature_get_param_count = try req(FnParamCount, mod, "mono_signature_get_param_count"), - .signature_get_params = try req(FnIter, mod, "mono_signature_get_params"), - .signature_get_return_type = try req(FnP_P, mod, "mono_signature_get_return_type"), - .signature_is_instance = opt(FnTypeType, mod, "mono_signature_is_instance"), - .type_get_type = try req(FnTypeType, mod, "mono_type_get_type"), - .method_get_param_names = opt(FnParamNames, mod, "mono_method_get_param_names"), - .string_new = opt(FnStringNew, mod, "mono_string_new"), - .string_to_utf8 = opt(FnP_CStr, mod, "mono_string_to_utf8"), - .object_unbox = opt(FnP_P, mod, "mono_object_unbox"), - .compile_method = try req(FnP_P, mod, "mono_compile_method"), - .class_vtable = try req(FnVtable, mod, "mono_class_vtable"), - .vtable_get_static_field_data = try req(FnStaticData, mod, "mono_vtable_get_static_field_data"), - .class_value_size = opt(FnValueSize, mod, "mono_class_value_size"), - .runtime_class_init = opt(FnClassInit, mod, "mono_runtime_class_init"), - .class_from_type = opt(FnP_P, mod, "mono_class_from_mono_type"), - .free = opt(FnFree, mod, "mono_free"), - .runtime_invoke = opt(FnInvoke, mod, "mono_runtime_invoke"), - }; - - api.root_domain = api.get_root_domain(); - _ = api.thread_attach(api.root_domain); - - return rt.Backend{ - .ctx = api, - .kind = .mono, - .assembliesFn = monoAssemblies, - .classesFn = monoClasses, - .fieldsFn = monoFields, - .methodsFn = monoMethods, - .compileFn = monoCompile, - .staticAddrFn = monoStaticAddr, - .invokeFn = monoInvoke, - .signatureFn = monoSignature, - .classInfoFn = monoClassInfo, - .typeKlassFn = monoTypeKlass, - .instanceMarkerFn = monoInstanceMarker, - }; -} - -inline fn self(ctx: *anyopaque) *MonoApi { - return @ptrCast(@alignCast(ctx)); -} - -const CollectCtx = struct { list: *std.ArrayList(u64), allocator: std.mem.Allocator, oom: bool }; -fn collectAssembly(asm_ptr: ?*anyopaque, user: ?*anyopaque) callconv(CC) void { - const c: *CollectCtx = @ptrCast(@alignCast(user.?)); - c.list.append(c.allocator, @intFromPtr(asm_ptr)) catch { - c.oom = true; - }; -} - -fn monoAssemblies(ctx: *anyopaque, e: *Encoder) !void { - const m = self(ctx); - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - - var cc = CollectCtx{ .list = &list, .allocator = m.allocator, .oom = false }; - m.assembly_foreach(collectAssembly, &cc); - if (cc.oom) return error.OutOfMemory; - - try e.arrayHeader(list.items.len); - for (list.items) |au| { - const asm_ptr: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(au))); - const img = m.assembly_get_image(asm_ptr); - try e.mapHeader(4); - try e.str("assembly"); - try e.uint(au); - try e.str("image"); - try e.uint(@intFromPtr(img)); - try e.str("name"); - try e.str(cspan(m.image_get_name(img))); - try e.str("filename"); - try e.str(cspan(m.image_get_filename(img))); - } -} - -const MONO_TABLE_TYPEDEF: c_int = 2; -const MONO_TOKEN_TYPE_DEF: u32 = 0x02000000; -fn monoClasses(ctx: *anyopaque, image_u: u64, e: *Encoder) !void { - const m = self(ctx); - const image: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(image_u))); - const tinfo = m.image_get_table_info(image, MONO_TABLE_TYPEDEF); - const rows: usize = @intCast(@max(@as(c_int, 0), m.table_info_get_rows(tinfo))); - - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - var i: usize = 0; - while (i < rows) : (i += 1) { - const token = MONO_TOKEN_TYPE_DEF | @as(u32, @intCast(i + 1)); - const klass = m.class_get(image, token); - if (klass != null) try list.append(m.allocator, @intFromPtr(klass)); - } - try e.arrayHeader(list.items.len); - - for (list.items) |ku| { - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(ku))); - try e.mapHeader(4); - try e.str("klass"); - try e.uint(ku); - try e.str("namespace"); - try e.str(cspan(m.class_get_namespace(klass))); - try e.str("name"); - try e.str(cspan(m.class_get_name(klass))); - try e.str("parent"); - try e.uint(@intFromPtr(m.class_get_parent(klass))); - } -} - -const FIELD_ATTRIBUTE_STATIC: u32 = 0x10; -fn monoFields(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - var iter: ?*anyopaque = null; - while (m.class_get_fields(klass, &iter)) |fld| try list.append(m.allocator, @intFromPtr(fld)); - try e.arrayHeader(list.items.len); - - for (list.items) |fu| { - const fld: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(fu))); - const ftype = m.field_get_type(fld); - const tname = m.type_get_name(ftype); - const flags = m.field_get_flags(fld); - try e.mapHeader(7); - try e.str("field"); - try e.uint(fu); - try e.str("name"); - try e.str(cspan(m.field_get_name(fld))); - try e.str("type"); - try e.str(cspan(tname)); - try e.str("tag"); - try e.str(typeTag(m.type_get_type(ftype))); - try e.str("offset"); - try e.int(m.field_get_offset(fld)); - try e.str("flags"); - try e.uint(flags); - try e.str("is_static"); - try e.boolean((flags & FIELD_ATTRIBUTE_STATIC) != 0); - if (m.free) |fr| if (tname) |p| fr(@ptrCast(@constCast(p))); - } -} - -fn monoMethods(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - - var list: std.ArrayList(u64) = .empty; - defer list.deinit(m.allocator); - var iter: ?*anyopaque = null; - while (m.class_get_methods(klass, &iter)) |meth| try list.append(m.allocator, @intFromPtr(meth)); - try e.arrayHeader(list.items.len); - - for (list.items) |mu| { - // No, not the drug... - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(mu))); - const sig = m.method_signature(meth); - const pc: u64 = if (sig != null) m.signature_get_param_count(sig) else 0; - const fnm = m.method_full_name(meth, 1); - - try e.mapHeader(4); - try e.str("method"); - try e.uint(mu); - try e.str("name"); - try e.str(cspan(m.method_get_name(meth))); - try e.str("full_name"); - try e.str(cspan(fnm)); - try e.str("param_count"); - try e.uint(pc); - if (m.free) |fr| if (fnm) |p| fr(@ptrCast(@constCast(p))); - } -} - -fn monoCompile(ctx: *anyopaque, method_u: u64, e: *Encoder) !void { - const m = self(ctx); - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(method_u))); - const addr = m.compile_method(meth); - if (addr == null) return error.CompileFailed; // 0 would SIGSEGV the target on disas/breakpoint - - try e.mapHeader(1); - try e.str("native_addr"); - try e.uint(@intFromPtr(addr)); -} - -fn monoStaticAddr(ctx: *anyopaque, klass_u: u64, field_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - const fld: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(field_u))); - const vt = m.class_vtable(m.root_domain, klass); - - if (vt == null) return error.NoVtable; - if (m.runtime_class_init) |ci| ci(vt); - - const base = m.vtable_get_static_field_data(vt); - const off = m.field_get_offset(fld); - if (off < 0) return error.Unsupported; - const addr = @intFromPtr(base) +% @as(u64, @intCast(off)); - - try e.mapHeader(1); - try e.str("address"); - try e.uint(addr); -} - -// A Mono object's first word is its MonoVTable*, so that's the marker we scan for. -// No class init needed as the vtable is the same whether the .ctor ran or not. -fn monoInstanceMarker(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - const vt = m.class_vtable(m.root_domain, klass); - if (vt == null) return error.NoVtable; - - try e.mapHeader(1); - try e.str("marker"); - try e.uint(@intFromPtr(vt)); -} - -fn monoClassInfo(ctx: *anyopaque, klass_u: u64, e: *Encoder) !void { - const m = self(ctx); - const klass: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(klass_u))); - try e.mapHeader(3); - try e.str("namespace"); - try e.str(cspan(m.class_get_namespace(klass))); - try e.str("name"); - try e.str(cspan(m.class_get_name(klass))); - try e.str("parent"); - try e.uint(@intFromPtr(m.class_get_parent(klass))); -} - -fn monoTypeKlass(ctx: *anyopaque, field_u: u64, e: *Encoder) !void { - const m = self(ctx); - const fld: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(field_u))); - var kptr: ?*anyopaque = null; - if (m.class_from_type) |cft| { - if (m.field_get_type(fld)) |t| kptr = cft(t); - } - try e.mapHeader(1); - try e.str("klass"); - try e.uint(@intFromPtr(kptr)); -} - -fn monoSignature(ctx: *anyopaque, method_u: u64, e: *Encoder) !void { - const m = self(ctx); - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(method_u))); - const sig = m.method_signature(meth); - if (sig == null) return error.NoSignature; - const pc = m.signature_get_param_count(sig); - - var name_buf: [64]?CStr = undefined; - var have_names = false; - if (m.method_get_param_names) |gpn| { - if (pc <= name_buf.len) { - @memset(name_buf[0..pc], null); - gpn(meth, &name_buf); - have_names = true; - } - } - - const is_instance = if (m.signature_is_instance) |f| f(sig) != 0 else true; - try e.mapHeader(3); - try e.str("static"); - try e.boolean(!is_instance); - try e.str("ret"); - try encodeTypeRef(m, e, m.signature_get_return_type(sig)); - try e.str("params"); - try e.arrayHeader(pc); - var iter: ?*anyopaque = null; - var idx: usize = 0; - while (m.signature_get_params(sig, &iter)) |ptype| : (idx += 1) { - const tname = m.type_get_name(ptype); - const tag = typeTag(m.type_get_type(ptype)); - const is_struct = eql(tag, "struct"); - const si = if (is_struct) structInfo(m, ptype) else StructInfo{ .klass = null, .size = 0 }; - try e.mapHeader(if (is_struct) 5 else 3); - try e.str("name"); - if (have_names and idx < pc and name_buf[idx] != null) { - try e.str(cspan(name_buf[idx])); - } else { - var nb: [16]u8 = undefined; - try e.str(std.fmt.bufPrint(&nb, "arg{d}", .{idx}) catch "arg"); - } - try e.str("tag"); - try e.str(tag); - try e.str("type"); - try e.str(cspan(tname)); - if (is_struct) { - try e.str("klass"); - try e.uint(@intFromPtr(si.klass)); - try e.str("size"); - try e.uint(si.size); - } - if (m.free) |fr| if (tname) |p| fr(@ptrCast(@constCast(p))); - } -} - -fn monoInvoke(ctx: *anyopaque, method_u: u64, obj_u: u64, args: []const rt.Arg, e: *Encoder) !void { - const m = self(ctx); - const invoke = m.runtime_invoke orelse return error.Unsupported; - const meth: ?*anyopaque = @ptrFromInt(@as(usize, @intCast(method_u))); - const obj: ?*anyopaque = if (obj_u == 0) null else @ptrFromInt(@as(usize, @intCast(obj_u))); - - if (args.len > 32) return error.TooManyArgs; // Make sure this is sync'd with main.zig's dispatcher args_buf[32] cap. - var slots: [32]u64 = undefined; - var argv: [32]?*anyopaque = undefined; - - for (args, 0..) |a, i| { - if (eql(a.tag, "str")) { - const sn = m.string_new orelse return error.Unsupported; - var sbuf: [1024]u8 = undefined; - if (a.str.len >= sbuf.len) return error.NameTooLong; - @memcpy(sbuf[0..a.str.len], a.str); - sbuf[a.str.len] = 0; - argv[i] = sn(m.root_domain, @ptrCast(&sbuf)); // reference type: object pointer - } else if (eql(a.tag, "object")) { - argv[i] = @ptrFromInt(@as(usize, @intCast(a.bits))); - } else if (eql(a.tag, "nil")) { - argv[i] = null; - } else if (eql(a.tag, "struct")) { - argv[i] = @constCast(a.str.ptr); // value type: raw bytes live in the request frame for the call - } else { - slots[i] = a.bits; // little-endian native, low N bytes are the value - argv[i] = &slots[i]; // value type: pointer to the value - } - } - const argv_ptr: ?[*]?*anyopaque = if (args.len == 0) null else &argv; - - var exc: ?*anyopaque = null; - const ret = invoke(meth, obj, argv_ptr, &exc); - - try e.mapHeader(2); - try e.str("result"); - if (exc != null) { - try e.nil(); - } else { - const sig = m.method_signature(meth); - const rtype = if (sig != null) m.signature_get_return_type(sig) else null; - const renum: c_int = if (rtype != null) m.type_get_type(rtype) else 0x01; - const rtag = typeTag(renum); - if (renum == 0x01 or ret == null) { // void / null - try e.nil(); - } else if (eql(rtag, "str") and m.string_to_utf8 != null) { - const c = m.string_to_utf8.?(ret); - try e.mapHeader(2); - try e.str("tag"); - try e.str("str"); - try e.str("val"); - try e.str(cspan(c)); - if (m.free) |fr| if (c) |p| fr(@ptrCast(@constCast(p))); - } else if (eql(rtag, "object") or eql(rtag, "str")) { - try emitBits(e, "object", @intFromPtr(ret)); // object handle / unconvertible string - } else if (eql(rtag, "struct")) { // value type by value: unbox and ship its raw bytes - const ub = m.object_unbox orelse return error.Unsupported; - const si = structInfo(m, rtype); - const vp = ub(ret); - if (vp == null or si.size == 0) { - try e.nil(); - } else { - try e.mapHeader(2); - try e.str("tag"); - try e.str("struct"); - try e.str("bytes"); - const src: [*]const u8 = @ptrCast(vp); - try e.bin(src[0..@intCast(si.size)]); - } - } else if (eql(rtag, "unsupported")) { - return error.Unsupported; - } else { // primitive value type: unbox and read its raw bytes - const ub = m.object_unbox orelse return error.Unsupported; - const vp = ub(ret); - var bits: u64 = 0; - if (vp) |p| { - const w = typeWidth(rtag); - const src: [*]const u8 = @ptrCast(p); - @memcpy(std.mem.asBytes(&bits)[0..w], src[0..w]); - } - try emitBits(e, rtag, bits); - } - } - try e.str("exception"); - try e.uint(@intFromPtr(exc)); -} diff --git a/mono_collector/msgpack.zig b/mono_collector/msgpack.zig deleted file mode 100644 index 7ff85488..00000000 --- a/mono_collector/msgpack.zig +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Minimal MessagePack implementation. -//! Some things are omitted as they're not relevant to PINCE, like int decoding (but we encode to prevent issues while serializing) -//! Msgpack is better than JSON for our specific needs: -//! - Tiny implementation and no dependency on JSON libraries which can be beefy. -//! - Much more compact structure, useful for enumerating thousands of classes and fields in Mono. -//! - Good integration with msgpack Python lib. -//! Encoder writes into a std.ArrayList(u8). -//! Decoder reads from a byte slice. -const std = @import("std"); - -pub const Encoder = struct { - list: *std.ArrayList(u8), - allocator: std.mem.Allocator, - - fn byte(self: *Encoder, b: u8) !void { - try self.list.append(self.allocator, b); - } - fn beN(self: *Encoder, comptime T: type, v: T) !void { - var tmp: [@sizeOf(T)]u8 = undefined; - std.mem.writeInt(T, &tmp, v, .big); - try self.list.appendSlice(self.allocator, &tmp); - } - - pub fn nil(self: *Encoder) !void { - try self.byte(0xc0); - } - pub fn boolean(self: *Encoder, v: bool) !void { - try self.byte(if (v) 0xc3 else 0xc2); - } - pub fn uint(self: *Encoder, v: u64) !void { - if (v < 0x80) { - try self.byte(@intCast(v)); - } else if (v <= 0xff) { - try self.byte(0xcc); - try self.byte(@intCast(v)); - } else if (v <= 0xffff) { - try self.byte(0xcd); - try self.beN(u16, @intCast(v)); - } else if (v <= 0xffffffff) { - try self.byte(0xce); - try self.beN(u32, @intCast(v)); - } else { - try self.byte(0xcf); - try self.beN(u64, v); - } - } - pub fn int(self: *Encoder, v: i64) !void { - if (v >= 0) return self.uint(@intCast(v)); - // negative: use int64 form for simplicity - try self.byte(0xd3); - try self.beN(i64, v); - } - pub fn str(self: *Encoder, s: []const u8) !void { - const n = s.len; - if (n < 32) { - try self.byte(0xa0 | @as(u8, @intCast(n))); - } else if (n <= 0xff) { - try self.byte(0xd9); - try self.byte(@intCast(n)); - } else if (n <= 0xffff) { - try self.byte(0xda); - try self.beN(u16, @intCast(n)); - } else { - try self.byte(0xdb); - try self.beN(u32, @intCast(n)); - } - try self.list.appendSlice(self.allocator, s); - } - pub fn arrayHeader(self: *Encoder, n: usize) !void { - if (n < 16) { - try self.byte(0x90 | @as(u8, @intCast(n))); - } else if (n <= 0xffff) { - try self.byte(0xdc); - try self.beN(u16, @intCast(n)); - } else { - try self.byte(0xdd); - try self.beN(u32, @intCast(n)); - } - } - pub fn mapHeader(self: *Encoder, n: usize) !void { - if (n < 16) { - try self.byte(0x80 | @as(u8, @intCast(n))); - } else if (n <= 0xffff) { - try self.byte(0xde); - try self.beN(u16, @intCast(n)); - } else { - try self.byte(0xdf); - try self.beN(u32, @intCast(n)); - } - } - pub fn bin(self: *Encoder, bytes: []const u8) !void { - const n = bytes.len; - if (n <= 0xff) { - try self.byte(0xc4); - try self.byte(@intCast(n)); - } else if (n <= 0xffff) { - try self.byte(0xc5); - try self.beN(u16, @intCast(n)); - } else { - try self.byte(0xc6); - try self.beN(u32, @intCast(n)); - } - try self.list.appendSlice(self.allocator, bytes); - } - pub fn raw(self: *Encoder, bytes: []const u8) !void { - try self.list.appendSlice(self.allocator, bytes); - } -}; - -pub const Decoder = struct { - data: []const u8, - pos: usize = 0, - - fn take(self: *Decoder) !u8 { - if (self.pos >= self.data.len) return error.Eof; - const b = self.data[self.pos]; - self.pos += 1; - return b; - } - fn beN(self: *Decoder, comptime T: type) !T { - const sz = @sizeOf(T); - if (self.pos + sz > self.data.len) return error.Eof; - const v = std.mem.readInt(T, self.data[self.pos..][0..sz], .big); - self.pos += sz; - return v; - } - pub fn mapLen(self: *Decoder) !usize { - const b = try self.take(); - if (b & 0xf0 == 0x80) return b & 0x0f; - if (b == 0xde) return try self.beN(u16); - if (b == 0xdf) return try self.beN(u32); - return error.NotMap; - } - pub fn arrayLen(self: *Decoder) !usize { - const b = try self.take(); - if (b & 0xf0 == 0x90) return b & 0x0f; - if (b == 0xdc) return try self.beN(u16); - if (b == 0xdd) return try self.beN(u32); - return error.NotArray; - } - pub fn str(self: *Decoder) ![]const u8 { - const b = try self.take(); - var n: usize = undefined; - if (b & 0xe0 == 0xa0) { - n = b & 0x1f; - } else if (b == 0xd9) { - n = try self.take(); - } else if (b == 0xda) { - n = try self.beN(u16); - } else if (b == 0xdb) { - n = try self.beN(u32); - } else return error.NotStr; - if (self.pos + n > self.data.len) return error.Eof; - const s = self.data[self.pos .. self.pos + n]; - self.pos += n; - return s; - } - pub fn uint(self: *Decoder) !u64 { - const b = try self.take(); - if (b < 0x80) return b; - if (b == 0xcc) return try self.take(); - if (b == 0xcd) return try self.beN(u16); - if (b == 0xce) return try self.beN(u32); - if (b == 0xcf) return try self.beN(u64); - return error.NotUint; - } -}; diff --git a/mono_collector/resolver.zig b/mono_collector/resolver.zig deleted file mode 100644 index 07c37ac6..00000000 --- a/mono_collector/resolver.zig +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Runtime module symbol resolution. -//! -//! Native ELF builds resolve mono_*/il2cpp_* via dlopen/dlsym. -//! The WINE/Proton PE variant parses the mapped runtime DLL's PE export directory instead. -//! WINE maps the DLL as an image but does NOT register its exports with the glibc dynamic linker, so dlsym can't see them. -const std = @import("std"); -const common = @import("common.zig"); - -pub const Module = if (common.is_windows) WINEModule else NativeModule; - -/// Find + bind the runtime module and confirm "core" resolves through it. -/// - core: a symbol that must exist (proves it is the expected runtime). -/// - substr: identifies the mapped module file in /proc/self/maps. -/// Returns null when the module isn't present or isn't the expected runtime. -pub fn open( - allocator: std.mem.Allocator, - core: [*:0]const u8, - substr: []const u8, -) ?Module { - return if (common.is_windows) openWindows(core, substr) else openNative(allocator, core, substr); -} - -// native (ELF) -const NativeModule = struct { - handle: ?*anyopaque, - - pub fn lookup(self: NativeModule, name: [*:0]const u8) ?*anyopaque { - return std.c.dlsym(self.handle, name); - } -}; - -// Find the path of the mapped module whose maps line contains "substr", NUL-terminated in "buf". -fn findModulePath(allocator: std.mem.Allocator, substr: []const u8, buf: []u8) ?[:0]const u8 { - const io = std.Io.Threaded.global_single_threaded.io(); - const f = std.Io.Dir.openFileAbsolute(io, "/proc/self/maps", .{}) catch return null; - defer f.close(io); - - var contents: std.ArrayList(u8) = .empty; - defer contents.deinit(allocator); - var chunk: [1 << 16]u8 = undefined; - var offset: u64 = 0; - while (true) { - const n = f.readPositionalAll(io, &chunk, offset) catch return null; - if (n == 0) break; - contents.appendSlice(allocator, chunk[0..n]) catch return null; - offset += n; - if (n < chunk.len) break; // short read -> EOF - } - - var it = std.mem.splitScalar(u8, contents.items, '\n'); - while (it.next()) |line| { - const start = std.mem.indexOfScalar(u8, line, '/') orelse continue; - const path = line[start..]; - if (std.mem.indexOf(u8, std.fs.path.basename(path), substr) == null) continue; - if (path.len == 0 or path.len >= buf.len) return null; - @memcpy(buf[0..path.len], path); - buf[path.len] = 0; - return buf[0..path.len :0]; - } - return null; -} - -fn openNative( - allocator: std.mem.Allocator, - core: [*:0]const u8, - substr: []const u8, -) ?NativeModule { - // Try the global scope first, works when the runtime is linked into the executable or was loaded RTLD_GLOBAL. - var h = std.c.dlopen(null, std.c.RTLD{ .NOW = true }); - if (std.c.dlsym(h, core) == null) { - // Unity usually loads its runtime with RTLD_LOCAL so the exports aren't global. - // Attach to the already mapped copy by path (NOLOAD won't map a second). - var find_buf: [4096]u8 = undefined; - const path = findModulePath(allocator, substr, &find_buf) orelse return null; - h = std.c.dlopen(path.ptr, std.c.RTLD{ .NOW = true, .NOLOAD = true }); - if (h == null or std.c.dlsym(h, core) == null) return null; - } - return .{ .handle = h }; -} - -// WINE (PE) -inline fn peRead(comptime T: type, base: [*]const u8, off: usize) T { - return @as(*align(1) const T, @ptrCast(base + off)).*; -} - -const WINEModule = struct { - base: [*]const u8, - number_of_names: u32, - name_rvas: usize, // base relative offset of AddressOfNames[] (u32 each) - ordinals: usize, // base relative offset of AddressOfNameOrdinals[] (u16 each) - func_rvas: usize, // base relative offset of AddressOfFunctions[] (u32 each) - - pub fn lookup(self: WINEModule, name: [*:0]const u8) ?*anyopaque { - const want = std.mem.span(name); - var i: u32 = 0; - while (i < self.number_of_names) : (i += 1) { - const name_rva = peRead(u32, self.base, self.name_rvas + i * 4); - const sym: [*:0]const u8 = @ptrCast(self.base + name_rva); - if (std.mem.eql(u8, std.mem.span(sym), want)) { - // AddressOfNameOrdinals[i] is already the index into AddressOfFunctions (the export Base is NOT added here). - const ord = peRead(u16, self.base, self.ordinals + i * 2); - const func_rva = peRead(u32, self.base, self.func_rvas + @as(usize, ord) * 4); - return @ptrCast(@constCast(self.base + func_rva)); - } - } - return null; - } -}; - -// Parse a mapped PE image's export directory. -// Returns null if "base" is not a PE image or has no export directory. -fn parsePe(base: [*]const u8) ?WINEModule { - if (peRead(u16, base, 0x00) != 0x5A4D) return null; // "MZ" - const e_lfanew: usize = peRead(u32, base, 0x3C); - if (peRead(u32, base, e_lfanew) != 0x0000_4550) return null; // "PE\0\0" - // Optional header begins at NT + 0x18. - // Its DataDirectory starts at +0x60 for PE32 (Magic 0x10B) and +0x70 for PE32+ (Magic 0x20B). - // ImageBase widens to u64 in PE32+, shifting the fields after it. - // Export = DataDirectory[0]. - const opt = e_lfanew + 0x18; - const dd_off: usize = if (peRead(u16, base, opt) == 0x20B) 0x70 else 0x60; - const export_dir_rva: usize = peRead(u32, base, opt + dd_off); - if (export_dir_rva == 0) return null; // no export directory - return WINEModule{ - .base = base, - .number_of_names = peRead(u32, base, export_dir_rva + 0x18), - .func_rvas = peRead(u32, base, export_dir_rva + 0x1C), - .name_rvas = peRead(u32, base, export_dir_rva + 0x20), - .ordinals = peRead(u32, base, export_dir_rva + 0x24), - }; -} - -extern "kernel32" fn GetModuleHandleW(lpModuleName: ?[*:0]const u16) callconv(.winapi) ?*anyopaque; - -fn openWindows(core: [*:0]const u8, substr: []const u8) ?WINEModule { - var wbuf: [256]u16 = undefined; - if (substr.len >= wbuf.len) return null; - for (substr, 0..) |c, i| wbuf[i] = c; // runtime DLL names are ASCII - wbuf[substr.len] = 0; - const handle = GetModuleHandleW(@ptrCast(&wbuf)) orelse return null; // HMODULE == image base - const mod = parsePe(@ptrCast(handle)) orelse return null; - if (mod.lookup(core) == null) return null; // mapped but not the expected runtime - return mod; -} diff --git a/mono_collector/runtime.zig b/mono_collector/runtime.zig deleted file mode 100644 index 290fe6a8..00000000 --- a/mono_collector/runtime.zig +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (C) 2026 brkzlr -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Runtime backend interface. -//! The Mono implementation lives in mono_api.zig. -//! Each *fn writes exactly one MessagePack value (the response "data") into enc. -const std = @import("std"); -const Encoder = @import("msgpack.zig").Encoder; - -pub const RuntimeKind = enum { mono, il2cpp }; - -/// One marshalled argument for "invoke". -/// "tag" is the wire type tag ("i4","r4","str",…). -/// Value types carry their raw bit pattern in "bits". -/// Strings carry UTF-8 in "str". -pub const Arg = struct { tag: []const u8, bits: u64 = 0, str: []const u8 = "" }; - -pub const Backend = struct { - ctx: *anyopaque, - kind: RuntimeKind, - - assembliesFn: *const fn (*anyopaque, *Encoder) anyerror!void, - classesFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - fieldsFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - methodsFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - compileFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - staticAddrFn: *const fn (*anyopaque, u64, u64, *Encoder) anyerror!void, - invokeFn: *const fn (*anyopaque, u64, u64, []const Arg, *Encoder) anyerror!void, - signatureFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - classInfoFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - typeKlassFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - instanceMarkerFn: *const fn (*anyopaque, u64, *Encoder) anyerror!void, - - pub fn assemblies(self: *const Backend, e: *Encoder) !void { - return self.assembliesFn(self.ctx, e); - } - pub fn classes(self: *const Backend, image: u64, e: *Encoder) !void { - return self.classesFn(self.ctx, image, e); - } - pub fn fields(self: *const Backend, klass: u64, e: *Encoder) !void { - return self.fieldsFn(self.ctx, klass, e); - } - pub fn methods(self: *const Backend, klass: u64, e: *Encoder) !void { - return self.methodsFn(self.ctx, klass, e); - } - pub fn compile(self: *const Backend, method: u64, e: *Encoder) !void { - return self.compileFn(self.ctx, method, e); - } - pub fn staticAddr(self: *const Backend, klass: u64, field: u64, e: *Encoder) !void { - return self.staticAddrFn(self.ctx, klass, field, e); - } - pub fn invoke(self: *const Backend, method: u64, obj: u64, args: []const Arg, e: *Encoder) !void { - return self.invokeFn(self.ctx, method, obj, args, e); - } - pub fn signature(self: *const Backend, method: u64, e: *Encoder) !void { - return self.signatureFn(self.ctx, method, e); - } - pub fn classInfo(self: *const Backend, klass: u64, e: *Encoder) !void { - return self.classInfoFn(self.ctx, klass, e); - } - pub fn typeKlass(self: *const Backend, field: u64, e: *Encoder) !void { - return self.typeKlassFn(self.ctx, field, e); - } - pub fn instanceMarker(self: *const Backend, klass: u64, e: *Encoder) !void { - return self.instanceMarkerFn(self.ctx, klass, e); - } -}; - -/// We don't need fancy checking and switching because we can just try to import each backend -/// and see which is the first one that's valid. -pub fn detectAndLoad(allocator: std.mem.Allocator) !?Backend { - if (try @import("mono_api.zig").load(allocator)) |b| return b; - if (try @import("il2cpp_api.zig").load(allocator)) |b| return b; - return null; -} diff --git a/pince-non-stop-files/.directory b/pince-non-stop-files/.directory new file mode 100644 index 00000000..5a84e58f --- /dev/null +++ b/pince-non-stop-files/.directory @@ -0,0 +1,3 @@ +[Dolphin] +Timestamp=2016,6,16,22,4,4 +Version=3 diff --git a/pince-non-stop-files/InitialCodeInjections.c b/pince-non-stop-files/InitialCodeInjections.c new file mode 100644 index 00000000..d88288f1 --- /dev/null +++ b/pince-non-stop-files/InitialCodeInjections.c @@ -0,0 +1,115 @@ +#include +#include +#include + +void *infinite_thread(void *a); +void *table_update_thread(void *a); + +//Injects a thread that runs forever at the background, PINCE will switch to that thread when attached +//__attribute__((constructor)) +void inject_infinite_thread() +{ + int *a=1; + pthread_t* threadinf=(pthread_t*) malloc(sizeof(pthread_t)); + pthread_create(threadinf, NULL, infinite_thread, (void*) a); +} + +void *infinite_thread(void *a) +{ + int milliseconds=500; + struct timespec ts; + ts.tv_sec = milliseconds / 1000; + ts.tv_nsec = (milliseconds % 1000) * 1000000; + int selfpid=getpid(); + char abort_file[100]; + sprintf(abort_file, "/tmp/PINCE-connection/%d/abort.txt", selfpid); + FILE *exit; + while(1) + { + nanosleep(&ts, NULL); + exit = fopen(abort_file, "r"); + if(exit!=NULL){ + fclose(exit); + return 0; + } + } +} + +//Injects a thread that updates the address table constantly +void inject_table_update_thread() +{ + int *a=1; + pthread_t* threadinf=(pthread_t*) malloc(sizeof(pthread_t)); + pthread_create(threadinf, NULL, table_update_thread, (void*) a); +} + +void *table_update_thread(void *a) +{ + int milliseconds=10; + struct timespec ts; + ts.tv_sec = milliseconds / 1000; + ts.tv_nsec = (milliseconds % 1000) * 1000000; + int selfpid=getpid(); + char directory_path[100]; + char status_file[100]; + char recv_file[100]; + char send_file[100]; + char abort_file[100]; + sprintf(directory_path, "/tmp/PINCE-connection/%d", selfpid); + sprintf(recv_file, "%s/PINCE-to-Inferior.txt", directory_path); + sprintf(send_file, "%s/Inferior-to-PINCE.txt", directory_path); + sprintf(status_file, "%s/status.txt", directory_path); + sprintf(abort_file, "%s/abort.txt", directory_path); + DIR* PINCE_dir; + FILE *fp; + FILE *status; + FILE *exit; + FILE *initialize; + //char buff[255]=""; + char status_word[100]=""; + char PINCE_pid[10]=""; + char PINCE_proc_directory[100]; + while(!strcmp(PINCE_pid, "")){ + nanosleep(&ts, NULL); + initialize = fopen(status_file, "r"); + if (initialize!=NULL){ + fscanf(initialize, "%s", PINCE_pid); + fclose(initialize); + } + } + sprintf(PINCE_proc_directory, "/proc/%s/", PINCE_pid); + milliseconds=400; + ts.tv_sec = milliseconds / 1000; + ts.tv_nsec = (milliseconds % 1000) * 1000000; + while(1){ + status = fopen(status_file, "w"); + fputs("sync-request-recieve", status); + fclose(status); + nanosleep(&ts, NULL); + + //abort.txt is created by PINCE to tell the inferior to quit + exit = fopen(abort_file, "r"); + if(exit!=NULL){ + fclose(exit); + return 0; + } + + //check if PINCE is still alive + PINCE_dir = opendir(PINCE_proc_directory); + if(PINCE_dir){ + closedir(PINCE_dir); + } + else{ + exit = fopen(abort_file, "w"); + fclose(exit); + return 0; + } + fp = fopen(recv_file, "r"); + //fscanf(fp, "%s", buff); + //printf("%s\n", buff ); + fclose(fp); + fp = fopen(send_file, "w"); + fputs(PINCE_pid, fp); + fclose(fp); + } +} diff --git a/pince-non-stop-files/InitialCodeInjections.so b/pince-non-stop-files/InitialCodeInjections.so new file mode 100755 index 00000000..4448a713 Binary files /dev/null and b/pince-non-stop-files/InitialCodeInjections.so differ diff --git a/pince-non-stop-files/old_gdbinit b/pince-non-stop-files/old_gdbinit new file mode 100644 index 00000000..092c1bc3 --- /dev/null +++ b/pince-non-stop-files/old_gdbinit @@ -0,0 +1,5 @@ +set disassembly-flavor intel +set target-async 1 +set pagination off +set non-stop on +set $pince_debugging_mode = 0 \ No newline at end of file diff --git a/pince-non-stop-files/on_code_injection_failure b/pince-non-stop-files/on_code_injection_failure new file mode 100644 index 00000000..a27f85db --- /dev/null +++ b/pince-non-stop-files/on_code_injection_failure @@ -0,0 +1,18 @@ +# PINCE usually can run commands without having need to stop but it's good to take precaution in case of failure +define hook-x + if $pince_debugging_mode == 0 + interrupt + end +end + +define hook-set + if $pince_debugging_mode == 0 + interrupt + end +end + +define hook-stop + if $pince_debugging_mode == 0 + c & + end +end \ No newline at end of file diff --git a/pince-non-stop-files/pince-non-stop-mode.py b/pince-non-stop-files/pince-non-stop-mode.py new file mode 100644 index 00000000..d4b05900 --- /dev/null +++ b/pince-non-stop-files/pince-non-stop-mode.py @@ -0,0 +1,327 @@ +# Old codes that'll be used again when pince-non-stop-mode gets reworked&implemented + + +#!/usr/bin/python3 +from re import search, split, findall +from threading import Lock, Thread +from time import sleep +import pexpect +import os +import ctypes +import struct + +libc = ctypes.CDLL('libc.so.6') +is_32bit = struct.calcsize("P") * 8 == 32 + +import SysUtils +import type_defs + +COMBOBOX_BYTE = type_defs.COMBOBOX_BYTE +COMBOBOX_2BYTES = type_defs.COMBOBOX_2BYTES +COMBOBOX_4BYTES = type_defs.COMBOBOX_4BYTES +COMBOBOX_8BYTES = type_defs.COMBOBOX_8BYTES +COMBOBOX_FLOAT = type_defs.COMBOBOX_FLOAT +COMBOBOX_DOUBLE = type_defs.COMBOBOX_DOUBLE +COMBOBOX_STRING = type_defs.COMBOBOX_STRING +COMBOBOX_AOB = type_defs.COMBOBOX_AOB + +currentpid = 0 +child = object # this object will be used with pexpect operations +codes_injected = False + +infinite_thread_location = str # location of the injected thread that runs forever at background +infinite_thread_id = str # id of the injected thread that runs forever at background +lock = Lock() + +index_to_gdbcommand_dict = type_defs.index_to_gdbcommand_dict + + +# The comments next to the regular expressions shows the expected gdb output, an elucidating light for the future developers + + +# issues the command sent +def send_command(command): + global child + with lock: + child.sendline(command) + child.expect_exact("(gdb) ") + output = split(r"&\".*\\n\"", child.before, 1)[1] # &"command\n" + print(child.before) # debug mode on! + # print(output) + return output + + +# check if we can attach to the target +def can_attach(pid=str): + result = libc.ptrace(16, int(pid), 0, 0) # 16 is PTRACE_ATTACH, check ptrace.h for details + if result is -1: + return False + os.waitpid(int(pid), 0) + libc.ptrace(17, int(pid), 0, 17) # 17 is PTRACE_DETACH, check ptrace.h for details + sleep(0.01) + return True + +def state_observe_thread(): + +# Attaches gdb to the target pid +# Returns False if the thread injection fails, True otherwise +# Also saves the injected thread's location and ID as strings, then switches to that thread and stops it +def attach(pid=str, injection_method=0): + global currentpid + global child + global infinite_thread_location + global infinite_thread_id + global codes_injected + SysUtils.create_PINCE_IPC_PATH(pid) + currentdir = SysUtils.get_current_script_directory() + child = pexpect.spawnu('sudo LC_NUMERIC=C gdb --interpreter=mi', cwd=currentdir) + child.setecho(False) + child.logfile=open(SysUtils.get_gdb_async_file(pid),"w") + + # a creative and meaningful number for such a marvelous and magnificent program PINCE is + child.timeout = 900000 + child.expect_exact("(gdb)") + + # gdb scripts needs to know PINCE directory, unfortunately they don't start from the place where script exists + send_command('set $PINCE_PATH=' + '"' + currentdir + '"') + send_command("source gdb_python_scripts/GDBCommandExtensions.py") + if injection_method is 1: # linux-inject + codes_injected = inject_with_linux_inject(pid) + send_command("attach " + pid + " &") + send_command("interrupt") + currentpid = int(pid) + if injection_method is 0: # simple dlopen call + injectionpath = currentdir + "/Injection/InitialCodeInjections.so" + codes_injected = inject_with_dlopen_call(injectionpath) + if codes_injected: + # address_table_update_thread = PINCE.UpdateAddressTable(pid) # planned for future + # address_table_update_thread.start() + result = send_command("call inject_infinite_thread()") + filtered_result = search(r"New Thread\s*0x\w+", result) # New Thread 0x7fab41ffb700 (LWP 7944) + send_command("c &") + + # Return True if the injection is successful, False if not + if not filtered_result: + return False + threadaddress = split(" ", filtered_result.group(0))[-1] + match_from_info_threads = search(r"\d+\s*Thread\s*" + threadaddress, + send_command("info threads")).group(0) # 1 Thread 0x7fab41ffb700 + infinite_thread_id = split(" ", match_from_info_threads)[0] + infinite_thread_location = threadaddress + send_command("thread " + infinite_thread_id) + send_command("interrupt") + # send_command("call inject_table_update_thread()") # planned for future + else: + send_command("source gdb_python_scripts/on_code_injection_failure") + send_command("c &") + return codes_injected + + +# Farewell... +def detach(): + global child + global currentpid + global codes_injected + #abort_file = type_defs.PINCE_IPC_PATH + str(currentpid) + "/abort.txt" + #try: + # open(abort_file, "w").close() + # SysUtils.fix_path_permissions(abort_file) # planned for future + #except: + # pass + child.sendline("q") + currentpid = 0 + child.close() + codes_injected = False + + +# Injects a thread that runs forever at the background, it'll be used to execute GDB commands on +# FIXME: linux-inject is insufficient for big games, it makes big titles such as Torchlight to segfault +def inject_with_linux_inject(pid=str): + scriptdirectory = SysUtils.get_current_script_directory() + injectionpath = scriptdirectory + "/Injection/InitialCodeInjections.so" + if is_32bit: + result = pexpect.run("sudo ./inject32 -p " + pid + " " + injectionpath, cwd=scriptdirectory + "/linux-inject") + else: + result = pexpect.run("sudo ./inject -p " + pid + " " + injectionpath, cwd=scriptdirectory + "/linux-inject") + print(result) # for debug + if search(b"successfully injected", result): # literal string + return True + return False + + +# variant of inject_with_linux_inject +def inject_with_dlopen_call(library_path): + injectionpath = '"' + library_path + '"' + result = send_command("call dlopen(" + injectionpath + ", 1)") + filtered_result = search(r"\$\d+\s*=\s*\-*\d+", result) # $1 = -1633996800 + if filtered_result: + dlopen_return_value = split(" ", filtered_result.group(0))[-1] + if dlopen_return_value is "0": + result = send_command("call __libc_dlopen_mode(" + injectionpath + ", 1)") + filtered_result = search(r"\$\d+\s*=\s*\-*\d+", result) # $1 = -1633996800 + if filtered_result: + dlopen_return_value = split(" ", filtered_result.group(0))[-1] + if dlopen_return_value is "0": + return False + return True + return False + return True + result = send_command("call __libc_dlopen_mode(" + injectionpath + ", 1)") + filtered_result = search(r"\$\d+\s*=\s*\-*\d+", result) # $1 = -1633996800 + if filtered_result: + dlopen_return_value = split(" ", filtered_result.group(0))[-1] + if dlopen_return_value is "0": + return False + return True + return False + + +# return a string corresponding to the selected index +# returns "out of bounds" string if the index doesn't match the dictionary +def valuetype_to_gdbcommand(index=int): + return index_to_gdbcommand_dict.get(index, "out of bounds") + + +def check_for_restricted_gdb_symbols(string): + if string is "": + return True + if search(r"\".*\"", string) or search(r"\{.*\}", string): # For string and array expressions + return False + if search(r'\$|\s', string): # These characters make gdb show it's value history, so they should be avoided + return True + return False + + +# returns the value of the expression if it is valid, return the string "??" if not +# this function is mainly used for display in AddAddressManually dialog +# this function also can read symbols such as "_start", "malloc", "printf" and "scanf" as addresses +# typeofaddress is derived from valuetype_to_gdbcommand +# length parameter only gets passed when reading strings or array of bytes +# unicode and zero_terminate parameters are only for strings +# if you just want to get the value of an address, use the function read_value_from_single_address() instead +def read_single_address(address, typeofaddress, length=None, is_unicode=False, zero_terminate=True): + if check_for_restricted_gdb_symbols(address): + return "??" + if length is "": + return "??" + if typeofaddress is COMBOBOX_AOB: + typeofaddress = valuetype_to_gdbcommand(typeofaddress) + try: + expectedlength = str(int(length)) # length must be a legit number, so had to do this trick + except: + return "??" + result = send_command("x/" + expectedlength + typeofaddress + " " + address) + filteredresult = findall(r"\\t0x[0-9a-fA-F]+", result) # 0x40c431:\t0x31\t0xed\t0x49\t... + if filteredresult: + returned_string = ''.join(filteredresult) # combine all the matched results + return returned_string.replace(r"\t0x", " ") + return "??" + elif typeofaddress is COMBOBOX_STRING: + typeofaddress = valuetype_to_gdbcommand(typeofaddress) + if not is_unicode: + try: + expectedlength = str(int(length)) + except: + return "??" + result = send_command("x/" + expectedlength + typeofaddress + " " + address) + else: + try: + expectedlength = str(int(length) * 2) + except: + return "??" + result = send_command("x/" + expectedlength + typeofaddress + " " + address) + filteredresult = findall(r"\\t0x[0-9a-fA-F]+", result) # 0x40c431:\t0x31\t0xed\t0x49\t... + if filteredresult: + filteredresult = ''.join(filteredresult) + returned_string = filteredresult.replace(r"\t0x", "") + if not is_unicode: + returned_string = bytes.fromhex(returned_string).decode("ascii", "replace") + else: + returned_string = bytes.fromhex(returned_string).decode("utf-8", "replace") + if zero_terminate: + if returned_string.startswith('\x00'): + returned_string = '\x00' + else: + returned_string = returned_string.split('\x00')[0] + return returned_string[0:int(length)] + return "??" + else: + typeofaddress = valuetype_to_gdbcommand(typeofaddress) + result = send_command("x/" + typeofaddress + " " + address) + filteredresult = search(r":\\t[0-9a-fA-F-,]+", result) # 0x400000:\t1,3961517377359369e-309 + if filteredresult: + return split("t", filteredresult.group(0))[-1] + return "??" + + +# This function is the same with the read_single_address but it reads values from proc/pid/maps instead +# This function is usable even when thread injection fails but it's more primitive than read_single_address +# Use this if you only want to read some values from an address +# If you want PINCE to parse expressions, use read_single_address instead +def read_value_from_single_address(address, typeofaddress, length, unicode, zero_terminate): + readed = send_command( + "pince-read-single-address " + str(address) + "," + str(typeofaddress) + "," + str(length) + "," + str( + unicode) + "," + str(zero_terminate)) + result = search(r"~\".*\\n\"", readed).group(0) # ~"result\n" + result = split(r'\"', result)[1] # result\n" + result = split(r"\\", result)[0] # result + + # check ReadSingleAddress class in GDBCommandExtensions.py to understand why do we separate this parsing from others + if typeofaddress is COMBOBOX_STRING: + returned_string = result.replace(" ", "") + if not unicode: + returned_string = bytes.fromhex(returned_string).decode("ascii", "replace") + else: + returned_string = bytes.fromhex(returned_string).decode("utf-8", "replace") + if zero_terminate: + if returned_string.startswith('\x00'): + returned_string = '\x00' + else: + returned_string = returned_string.split('\x00')[0] + return returned_string[0:int(length)] + return result + + +# Converts the given address to symbol if any symbol exists for it +# TODO: Implement a loop-version +def convert_address_to_symbol(string): + if check_for_restricted_gdb_symbols(string): + return string + result = send_command("x/x " + string) + filteredresult = search(r"<.+>:\\t", result) # 0x40c435 <_start+4>:\t0x89485ed1\n + if filteredresult: + return split(">:", filteredresult.group(0))[0].split("<")[1] + return string + + +# Converts the given symbol to address if symbol is valid +# TODO: Implement a loop-version +def convert_symbol_to_address(string): + if check_for_restricted_gdb_symbols(string): + return string + result = send_command("x/x " + string) + filteredresult = search(r"0x[0-9a-fA-F]+\s+<.+>:\\t", result) # 0x40c435 <_start+4>:\t0x89485ed1\n + if filteredresult: + return split(" ", filteredresult.group(0))[0] + else: + filteredresult = search(r"0x[0-9a-fA-F]+:\\t", result) # 0x1f58010:\t0x00647361\n + if filteredresult: + return split(":", filteredresult.group(0))[0] + return string + + +def test(): + for x in range(0, 10): + print(send_command('x/x _start')) + + +def test2(): + for x in range(0, 10): + print(send_command("disas /r 0x00400000,+10")) + + +def test3(): + global child + while True: + sleep(1) + print(child.stdout) diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 088330fb..00000000 --- a/pyproject.toml +++ /dev/null @@ -1,4 +0,0 @@ -[tool.black] -line-length = 150 -[tool.isort] -skip_glob = ["*"] diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 9561411a..00000000 --- a/requirements.txt +++ /dev/null @@ -1,8 +0,0 @@ -PyQt6==6.11.0 -PyQt6-Qt6==6.11.1 -pexpect==4.9.0 -capstone==5.0.9 -keystone-engine==0.9.2 -pygdbmi==0.11.0.0 -keyboard==0.13.5 -msgpack==1.2.1 diff --git a/screenshots/pince.png b/screenshots/pince.png new file mode 100644 index 00000000..b97e25b6 Binary files /dev/null and b/screenshots/pince.png differ diff --git a/screenshots/pince1.png b/screenshots/pince1.png new file mode 100644 index 00000000..06701f7d Binary files /dev/null and b/screenshots/pince1.png differ diff --git a/screenshots/pince2.png b/screenshots/pince2.png new file mode 100644 index 00000000..d98fd762 Binary files /dev/null and b/screenshots/pince2.png differ diff --git a/screenshots/pince3.png b/screenshots/pince3.png new file mode 100644 index 00000000..df3d31c6 Binary files /dev/null and b/screenshots/pince3.png differ diff --git a/tr/tr.py b/tr/tr.py deleted file mode 100644 index a322e104..00000000 --- a/tr/tr.py +++ /dev/null @@ -1,427 +0,0 @@ -from PyQt6.QtCore import QObject, QLocale, QT_TR_NOOP -from collections import OrderedDict - -language_list = OrderedDict([("en_US", "English"), ("it_IT", "Italiano"), ("zh_CN", "简体中文")]) - - -def get_locale() -> str: - system_locale = QLocale.system().name() - return system_locale if system_locale in language_list else "en_US" - - -class TranslationConstants(QObject): - @staticmethod - def translate() -> None: - for key, value in vars(TranslationConstants).items(): - if not key.startswith("__") and isinstance(value, str): - setattr(TranslationConstants, key, TranslationConstants.tr(value)) - - PAUSE_HOTKEY = QT_TR_NOOP("Pause the process") - BREAK_HOTKEY = QT_TR_NOOP("Break the process") - CONTINUE_HOTKEY = QT_TR_NOOP("Continue the process") - CANCEL_HOTKEY = QT_TR_NOOP("Cancel ongoing GDB command") - TOGGLE_ATTACH_HOTKEY = QT_TR_NOOP("Toggle attach/detach") - SPEEDHACK_TOGGLE_HOTKEY = QT_TR_NOOP("Toggle speedhack") - SPEEDHACK_SPEED_UP_HOTKEY = QT_TR_NOOP("Speedhack - Increase speed") - SPEEDHACK_SPEED_DOWN_HOTKEY = QT_TR_NOOP("Speedhack - Decrease speed") - EXACT_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Exact") - NOT_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Not") - INC_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Increased") - INC_BY_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Increased By") - DEC_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Decreased") - DEC_BY_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Decreased By") - LESS_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Less Than") - MORE_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - More Than") - BETWEEN_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Between") - CHANGED_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Changed") - UNCHANGED_SCAN_HOTKEY = QT_TR_NOOP("Next Scan - Unchanged") - ERROR = QT_TR_NOOP("Error") - SUCCESS = QT_TR_NOOP("Success") - INFO = QT_TR_NOOP("Information") - UPDATE_CHECK_FAILED = QT_TR_NOOP("Could not check for updates.") - UPDATE_AVAILABLE_MESSAGE = QT_TR_NOOP( - "A newer PINCE AppImage is available.\n\n" - "You can grab it from PINCE's GitHub releases or update this AppImage with AppImageUpdate/appimageupdatetool." - ) - UPDATE_CHECK_ON_STARTUP_PROMPT = QT_TR_NOOP( - "PINCE can check for AppImage updates on startup. This contacts the configured release host to download update metadata." - ) - CHECK_FOR_UPDATES_ON_STARTUP = QT_TR_NOOP("Allow startup update checks") - UPDATE_NOT_AVAILABLE = QT_TR_NOOP("This PINCE AppImage is up to date.") - DISABLED_UNDER_WINE = QT_TR_NOOP("This feature is not available while attached to a WINE/Proton process!") - SPEEDHACK_UNAVAILABLE = QT_TR_NOOP("Speedhack couldn't be enabled for this process.") - GDB_INIT = QT_TR_NOOP("GDB isn't initialized yet") - GDB_INIT_ERROR = QT_TR_NOOP( - "Unable to initialize GDB\n" "You might want to reinstall GDB or use the system GDB\n" "To change the current GDB path, check Settings->Debug" - ) - EDIT = QT_TR_NOOP("Edit") - SHOW_HEX = QT_TR_NOOP("Show as hexadecimal") - SHOW_DEC = QT_TR_NOOP("Show as decimal") - SHOW_UNSIGNED = QT_TR_NOOP("Show as unsigned") - SHOW_SIGNED = QT_TR_NOOP("Show as signed") - TOGGLE = QT_TR_NOOP("Toggle") - TOGGLE_CHILDREN = QT_TR_NOOP("Toggle including children") - AUTO = QT_TR_NOOP("Auto") - BROWSE_MEMORY_REGION = QT_TR_NOOP("Browse this memory region") - DISASSEMBLE_ADDRESS = QT_TR_NOOP("Disassemble this address") - DELETE = QT_TR_NOOP("Delete") - DELETE_SELECTION = QT_TR_NOOP("Delete selection") - CUT = QT_TR_NOOP("Cut") - COPY = QT_TR_NOOP("Copy") - PASTE = QT_TR_NOOP("Paste") - STOP = QT_TR_NOOP("Stop") - STOPPING = QT_TR_NOOP("Stopping") - PASTE_INSIDE = QT_TR_NOOP("Paste inside") - POINTER_SCAN = QT_TR_NOOP("Pointer scan for this address") - POINTER_SCANNER = QT_TR_NOOP("Open pointer scanner") - POINTER_SCAN_SUCCESS = QT_TR_NOOP("Pointer scan finished. Found {} valid pointer paths.") - POINTER_FILTER_SUCCESS = QT_TR_NOOP("Pointer filtering finished. Found {} stable pointer paths.") - SCANNING_POINTERS = QT_TR_NOOP("Scanning for pointers") - RESOLVING_POINTERS = QT_TR_NOOP("Resolving pointer paths") - BASE_ADDRESS = QT_TR_NOOP("Base Address") - OFFSET = QT_TR_NOOP("Offset") - POINTER_PATH_COUNT = QT_TR_NOOP("Pointer paths count: {}") - WHAT_WRITES = QT_TR_NOOP("Find out what writes to this address") - WHAT_READS = QT_TR_NOOP("Find out what reads this address") - WHAT_ACCESSES = QT_TR_NOOP("Find out what accesses this address") - ADD_GROUP = QT_TR_NOOP("Add to a new group") - CREATE_GROUP = QT_TR_NOOP("Create a new group") - GROUP = QT_TR_NOOP("Group") - INVALID_CLIPBOARD = QT_TR_NOOP("Invalid clipboard content") - NEW_SCAN = QT_TR_NOOP("New Scan") - MATCH_COUNT_LIMITED = QT_TR_NOOP("Match count: {} ({} shown)") - MATCH_COUNT = QT_TR_NOOP("Match count: {}") - NO_DESCRIPTION = QT_TR_NOOP("No Description") - OPEN_PCT_FILE = QT_TR_NOOP("Open PCT file(s)") - OPEN_SCRIPT_FILE = QT_TR_NOOP("Open script file") - SAVE_SCRIPT_FILE = QT_TR_NOOP("Save script file") - UNTITLED = QT_TR_NOOP("(untitled)") - SCRIPT_FAILED = QT_TR_NOOP("Script execution failed") - UNSAVED_SCRIPT = QT_TR_NOOP("Unsaved script") - SAVE_SCRIPT_CHANGES = QT_TR_NOOP("Save changes to {}?") - SCRIPT_RUNNING = QT_TR_NOOP("--- Running {} ---") - SCRIPT_FINISHED = QT_TR_NOOP("--- Finished ---") - SCRIPT_NO_DISABLE = QT_TR_NOOP("This script has no [DISABLE] section") - SEND_TO_TABLE = QT_TR_NOOP("Send to cheat table") - SENT_TO_TABLE = QT_TR_NOOP("Sent to the cheat table") - SCRIPT = QT_TR_NOOP("Script") - EDIT_SCRIPT = QT_TR_NOOP("Edit script") - SCRIPT_RUN_FAILED = QT_TR_NOOP("Running the script failed, see the details below.\n\n{}") - REMEMBER_MY_DECISION = QT_TR_NOOP("Remember my decision for all sessions") - ALWAYS_ASK = QT_TR_NOOP("Always ask") - ALWAYS_SAVE = QT_TR_NOOP("Always save") - ALWAYS_DISCARD = QT_TR_NOOP("Always discard") - - # Keep file extensions such as (*.pct) while translating, it doesn't matter where it stays within the sentence - # For instance, you can keep (*.pct) in the beginning of the sentence for right-to-left languages like Arabic - # Apply the same to similar entries below - FILE_TYPES_PCT = QT_TR_NOOP("PINCE Cheat Table (*.pct)") - FILE_TYPES_SCRIPT = QT_TR_NOOP("Python Scripts (*.py)") - SHARED_OBJECT_TYPE = QT_TR_NOOP("Shared object library (*.so)") - DLL_TYPE = QT_TR_NOOP("Dynamic-link library (*.dll)") - FILE_TYPES_TRACE = QT_TR_NOOP("Trace File (*.trace)") - FILE_TYPES_POINTER_MAP = QT_TR_NOOP("Pointer Scan Map (*.lmptr)") - ADD_TO_ADDRESS_TABLE = QT_TR_NOOP("Add to address table") - FILE_LOAD_ERROR = QT_TR_NOOP("File {} is inaccessible or contains invalid content") - SAVE_PCT_FILE = QT_TR_NOOP("Save PCT file") - FILE_SAVE_ERROR = QT_TR_NOOP("Cannot save to file") - SMARTASS = QT_TR_NOOP("Nice try, smartass") - PROCESS_NOT_VALID = QT_TR_NOOP("Selected process is not valid") - ALREADY_DEBUGGING = QT_TR_NOOP("You're debugging this process already") - ALREADY_TRACED = QT_TR_NOOP("That process is already being traced by {}, could not attach to the process") - PERM_DENIED = QT_TR_NOOP("Permission denied, could not attach to the process") - CREATE_PROCESS_ERROR = QT_TR_NOOP("An error occurred while trying to create process") - SCAN_FOR = QT_TR_NOOP("Scan for") - FIRST_SCAN = QT_TR_NOOP("First Scan") - NO_PROCESS_SELECTED = QT_TR_NOOP("No Process Selected") - STATUS_DETACHED = QT_TR_NOOP("[detached]") - STATUS_STOPPED = QT_TR_NOOP("[stopped]") - REQUIRE_PROCESS_STOP = QT_TR_NOOP("This requires the process to be stopped") - ENTER_VALUE = QT_TR_NOOP("Enter the new value") - ENTER_DESCRIPTION = QT_TR_NOOP("Enter the new description") - ENTER_ADDRESS = QT_TR_NOOP("Enter the new address") - EDIT_ADDRESS = QT_TR_NOOP("Edit Address") - SELECT_PROCESS = QT_TR_NOOP("Please select a process first") - SELECT_BINARY = QT_TR_NOOP("Select the target binary") - ENTER_OPTIONAL_ARGS = QT_TR_NOOP("Enter the optional arguments") - LD_PRELOAD_OPTIONAL = QT_TR_NOOP("LD_PRELOAD .so path (optional)") - REFRESH = QT_TR_NOOP("Refresh") - LENGTH_NOT_VALID = QT_TR_NOOP("Length is not valid") - LENGTH_GT = QT_TR_NOOP("Length must be greater than 0") - PARSE_ERROR = QT_TR_NOOP("Can't parse the input") - IS_INVALID_REGEX = QT_TR_NOOP("{} isn't a valid regex") - LANG_RESET = QT_TR_NOOP("Language settings will take effect upon the next restart") - GDB_RESET = QT_TR_NOOP("You have changed the GDB path, reset GDB now?") - RESET_DEFAULT_SETTINGS = QT_TR_NOOP("This will reset to the default settings\n" "Proceed?") - MOUSE_OVER_EXAMPLES = QT_TR_NOOP("Mouse over on this text for examples") - AUTO_ATTACH_TOOLTIP = QT_TR_NOOP( - "asdf|qwer --> search for asdf or qwer\n" "[as]df --> search for both adf and sdf\n" "Use the char \\ to escape special chars such as [\n" - ) - SEPARATE_PROCESSES_WITH = QT_TR_NOOP("Separate processes with {}") - UNUSED_APPIMAGE_SETTING = QT_TR_NOOP("This setting is unused in AppImage builds") - SELECT_GDB_BINARY = QT_TR_NOOP("Select the gdb binary") - QUIT_SESSION_CRASH = QT_TR_NOOP("Quitting current session will crash PINCE") - CONT_SESSION_CRASH = QT_TR_NOOP("Use global hotkeys or the commands 'interrupt' and 'c&' to stop/run the inferior") - - # For some languages, it might be hard to keep the pipe characters balanced - # You are free to modify pipes and dashes as you like when translating - # Check Chinese translation for an example - GDB_CONSOLE_INIT = QT_TR_NOOP( - "Hotkeys:\n" - "-----------------------------\n" - "Send: Enter |\n" - "Multi-line mode: Ctrl+Enter |\n" - "Complete command: Tab |\n" - "-----------------------------\n" - "Commands:\n" - "----------------------------------------------------------\n" - "/clear: Clear the console |\n" - "phase-out: Detach from the current process |\n" - "phase-in: Attach back to the previously detached process |\n" - "---------------------------------------------------------------------------------------------------\n" - "You can change the output mode from bottom right\n" - "Changing output mode only affects commands sent. Any other output coming from external sources" - "(e.g async output) will be shown in MI format" - ) - BREAK = QT_TR_NOOP("Break[{}]") - RUN = QT_TR_NOOP("Run[{}]") - TOGGLE_ATTACH = QT_TR_NOOP("Toggle Attach[{}]") - BREAKPOINT_FAILED = QT_TR_NOOP("Failed to set breakpoint at address {}") - WATCHPOINT_FAILED = QT_TR_NOOP("Failed to set watchpoint at address {}") - COPY_CLIPBOARD = QT_TR_NOOP("Copy to Clipboard") - GO_TO_EXPRESSION = QT_TR_NOOP("Go to expression") - ADD_TO_ADDRESS_LIST = QT_TR_NOOP("Add this address to address list") - SET_WATCHPOINT = QT_TR_NOOP("Set Watchpoint") - WRITE_ONLY = QT_TR_NOOP("Write Only") - READ_ONLY = QT_TR_NOOP("Read Only") - BOTH = QT_TR_NOOP("Both") - CHANGE_BREAKPOINT_CONDITION = QT_TR_NOOP("Add/Change condition for breakpoint") - SET_BREAKPOINT = QT_TR_NOOP("Set Breakpoint") - TOGGLE_BREAKPOINT = QT_TR_NOOP("Toggle Breakpoint") - DELETE_BREAKPOINT = QT_TR_NOOP("Delete Breakpoint") - ENTER_EXPRESSION = QT_TR_NOOP("Enter the expression") - INVALID = QT_TR_NOOP("{} is invalid") - REGION_INFO = QT_TR_NOOP("Protection:{} | Base:{}-{} | Module:{}") - INVALID_REGION = QT_TR_NOOP("Invalid Region") - EXPRESSION_ACCESS_ERROR = QT_TR_NOOP("Cannot access memory at expression {}") - REFERENCED_BY = QT_TR_NOOP("Referenced by:") - SEE_REFERRERS = QT_TR_NOOP("Press 'Ctrl+E' to see a detailed list of referrers") - MV_PAUSED = QT_TR_NOOP("Memory Viewer - Paused") - MV_DEBUGGING = QT_TR_NOOP("Memory Viewer - Currently debugging {}") - MV_RUNNING = QT_TR_NOOP("Memory Viewer - Running") - ENTER_BP_CONDITION = QT_TR_NOOP( - "Enter the expression for condition, for instance:\n\n" "$eax==0x523\n" "$rax>0 && ($rbp<0 || $rsp==0)\n" "printf($r10)==3" - ) - BP_CONDITION_FAILED = QT_TR_NOOP("Failed to set condition for address {}\n" "Check terminal for details") - FULL_STACK = QT_TR_NOOP("Full Stack") - COPY_RETURN_ADDRESS = QT_TR_NOOP("Copy Return Address") - COPY_FRAME_ADDRESS = QT_TR_NOOP("Copy Frame Address") - STACKTRACE = QT_TR_NOOP("Stacktrace") - TOGGLE_STACK_FROM_SP_BP = QT_TR_NOOP("Toggle stack from BP/SP register") - COPY_ADDRESS = QT_TR_NOOP("Copy Address") - COPY_VALUE = QT_TR_NOOP("Copy Value") - COPY_POINTS_TO = QT_TR_NOOP("Copy Points to") - DISASSEMBLE_VALUE_POINTER = QT_TR_NOOP("Disassemble 'value' pointer address") - HEXVIEW_VALUE_POINTER = QT_TR_NOOP("Show 'value' pointer in HexView") - BACK = QT_TR_NOOP("Back") - HEXVIEW_ADDRESS = QT_TR_NOOP("Show this address in HexView") - FOLLOW = QT_TR_NOOP("Follow") - EXAMINE_REFERRERS = QT_TR_NOOP("Examine Referrers") - BOOKMARK_ADDRESS = QT_TR_NOOP("Bookmark this address") - DELETE_BOOKMARK = QT_TR_NOOP("Delete this bookmark") - CHANGE_COMMENT = QT_TR_NOOP("Change comment") - GO_TO_BOOKMARK_ADDRESS = QT_TR_NOOP("Go to bookmarked address") - EDIT_INSTRUCTION = QT_TR_NOOP("Edit instruction") - REPLACE_WITH_NOPS = QT_TR_NOOP("Replace instruction with NOPs") - WHAT_ACCESSES_INSTRUCTION = QT_TR_NOOP("Find out which addresses this instruction accesses") - TRACE_INSTRUCTION = QT_TR_NOOP("Break and trace instructions") - DISSECT_REGION = QT_TR_NOOP("Dissect this region") - COPY_BYTES = QT_TR_NOOP("Copy Bytes") - COPY_INSTR = QT_TR_NOOP("Copy Instruction") - COPY_COMMENT = QT_TR_NOOP("Copy Comment") - COPY_ALL = QT_TR_NOOP("Copy All") - ENTER_TRACK_BP_EXPRESSION = QT_TR_NOOP( - "Enter the register expression(s) you want to track\n" - "Register names must start with $\n" - "Each expression must be separated with a comma\n\n" - "For instance:\n" - "Let's say the instruction is mov [rax+rbx],30\n" - "Then you should enter $rax+$rbx\n" - "So PINCE can track address [rax+rbx]\n\n" - "Another example:\n" - "If you enter $rax,$rbx*$rcx+4,$rbp\n" - "PINCE will track down addresses [rax],[rbx*rcx+4] and [rbp]" - ) - ALREADY_BOOKMARKED = QT_TR_NOOP("This address has already been bookmarked") - ENTER_BOOKMARK_COMMENT = QT_TR_NOOP("Enter the comment for bookmarked address") - SELECT_SO_FILE = QT_TR_NOOP("Select the shared object (.so) file") - SO_INJECTED = QT_TR_NOOP("The shared object (.so) file has been injected") - SO_INJECT_FAILED = QT_TR_NOOP("Failed to inject the shared object (.so) file") - SELECT_DLL_FILE = QT_TR_NOOP("Select the DLL file") - DLL_INJECT_STARTED = QT_TR_NOOP("DLL injection thread started. The DLL may still fail to load due to bitness mismatch or missing dependencies.") - DLL_INJECT_FAILED = QT_TR_NOOP("Failed to inject the DLL") - DLL_INJECT_WINE_ONLY = QT_TR_NOOP("DLL injection is only supported for WINE/Proton processes") - ENTER_CALL_EXPRESSION = QT_TR_NOOP( - "Enter the expression for the function that'll be called from the inferior\n" - "You can view functions list from View->Functions\n\n" - "For instance:\n" - 'Calling printf("1234") will yield something like this\n' - "↓\n" - "$28 = 4\n\n" - "$28 is the assigned convenience variable\n" - "4 is the result\n" - "You can use the assigned variable from the GDB Console" - ) - CALL_EXPRESSION_FAILED = QT_TR_NOOP("Failed to call the expression {}") - INVALID_EXPRESSION = QT_TR_NOOP("Invalid expression or address") - INVALID_ENTRY = QT_TR_NOOP("Invalid entries detected, refreshing the page") - ADD_ENTRY = QT_TR_NOOP("Add new entry") - ENTER_REGISTER_VALUE = QT_TR_NOOP("Enter the new value of register {}") - ENTER_FLAG_VALUE = QT_TR_NOOP("Enter the new value of flag {}") - RESTORE_INSTRUCTION = QT_TR_NOOP("Restore this instruction") - ENTER_HIT_COUNT = QT_TR_NOOP("Enter the hit count({} or higher)") - HIT_COUNT_ASSERT_INT = QT_TR_NOOP("Hit count must be an integer") - HIT_COUNT_ASSERT_LT = QT_TR_NOOP("Hit count can't be lower than {}") - CHANGE_CONDITION = QT_TR_NOOP("Change condition") - ENABLE = QT_TR_NOOP("Enable") - DISABLE = QT_TR_NOOP("Disable") - DISABLE_AFTER_HIT = QT_TR_NOOP("Disable after hit") - DISABLE_AFTER_COUNT = QT_TR_NOOP("Disable after X hits") - DELETE_AFTER_HIT = QT_TR_NOOP("Delete after hit") - INSTR_WRITING_TO = QT_TR_NOOP("Instructions writing to the address {}") - INSTR_READING_FROM = QT_TR_NOOP("Instructions reading from the address {}") - INSTR_ACCESSING_TO = QT_TR_NOOP("Instructions accessing to the address {}") - TRACK_WATCHPOINT_FAILED = QT_TR_NOOP("Unable to track watchpoint at expression {}") - DELETE_WATCHPOINT_FAILED = QT_TR_NOOP("Unable to delete watchpoint at expression {}") - CLOSE = QT_TR_NOOP("Close") - ACCESSED_BY_INSTRUCTION = QT_TR_NOOP("Addresses accessed by instruction {}") - TRACK_BREAKPOINT_FAILED = QT_TR_NOOP("Unable to track breakpoint at expression {}") - ACCESSED_BY = QT_TR_NOOP("Accessed by {}") - DELETE_BREAKPOINT_FAILED = QT_TR_NOOP("Unable to delete breakpoint at expression {}") - MAX_TRACE_COUNT_ASSERT_GT = QT_TR_NOOP("Max trace count must be greater than or equal to {}") - SAVE_TRACE_FILE = QT_TR_NOOP("Save trace file") - OPEN_TRACE_FILE = QT_TR_NOOP("Open trace file") - EXPAND_ALL = QT_TR_NOOP("Expand All") - COLLAPSE_ALL = QT_TR_NOOP("Collapse All") - SELECT_POINTER_MAP = QT_TR_NOOP("Select a pointer map file") - SCAN = QT_TR_NOOP("Scan") - SCANNING = QT_TR_NOOP("Scanning") - FILTER = QT_TR_NOOP("Filter") - FILTERING = QT_TR_NOOP("Filtering") - DEFINED = QT_TR_NOOP("DEFINED") - DEFINED_SYMBOL = QT_TR_NOOP( - "This symbol is defined. You can use its body as a gdb expression. For instance:\n\n" - "void func(param) can be used as 'func' as a gdb expression" - ) - COPY_SYMBOL = QT_TR_NOOP("Copy Symbol") - FUNCTIONS_INFO_HELPER = QT_TR_NOOP( - "\tHere's some useful regex tips:\n" - "^quaso --> search for everything that starts with quaso\n" - "[ab]cd --> search for both acd and bcd\n\n" - "\tHow to interpret symbols:\n" - "A symbol that looks like 'func(param)@plt' consists of 3 pieces\n" - "func, func(param), func(param)@plt\n" - "These 3 functions will have different addresses\n" - "@plt means this function is a subroutine for the original one\n" - "There can be more than one of the same function\n" - "It means that the function is overloaded" - ) - NEW_INSTR = QT_TR_NOOP("New instruction is {} bytes long but old instruction is only {} bytes long\n" "This will cause an overflow, proceed?") - IS_INVALID_EXPRESSION = QT_TR_NOOP("{} isn't a valid expression") - LOG_FILE = QT_TR_NOOP("Log File of PID {}") - LOG_CONTENTS = QT_TR_NOOP("Contents of {} (only last {} bytes are shown)") - ON = QT_TR_NOOP("ON") - OFF = QT_TR_NOOP("OFF") - LOG_STATUS = QT_TR_NOOP("LOGGING: {}") - LOG_READ_ERROR = QT_TR_NOOP("Unable to read log file at {}") - SETTINGS_ENABLE_LOG = QT_TR_NOOP("Go to Settings->Debug to enable logging") - INVALID_REGEX = QT_TR_NOOP("Invalid Regex") - SEARCH_INSTR_HELPER = QT_TR_NOOP( - "\tHere's some useful regex examples:\n" - "call|rax --> search for instructions that contain call or rax\n" - "[re]cx --> search for both rcx and ecx\n" - "Use the char \\ to escape special chars such as [\n" - r"\[rsp\] --> search for instructions that contain [rsp]" - ) - COPY_ADDRESSES = QT_TR_NOOP("Copy Addresses") - COPY_OFFSET = QT_TR_NOOP("Copy Offset") - COPY_PATH = QT_TR_NOOP("Copy Path") - START = QT_TR_NOOP("Start") - CURRENT_SCAN_REGION = QT_TR_NOOP("Currently scanning region:") - CANCEL = QT_TR_NOOP("Cancel") - SCAN_FINISHED = QT_TR_NOOP("Scan finished") - SCAN_CANCELED = QT_TR_NOOP("Scan was canceled") - SELECT_ONE_REGION = QT_TR_NOOP("Select at least one region") - DISSECT_CODE = QT_TR_NOOP("You need to dissect code first\n" "Proceed?") - WAITING_FOR_BREAKPOINT = QT_TR_NOOP("Waiting for breakpoint to trigger") - TRACING_COMPLETED = QT_TR_NOOP("Tracing has been completed") - NOT = QT_TR_NOOP("Not") - EXACT = QT_TR_NOOP("Exact") - INCREASED = QT_TR_NOOP("Increased") - INCREASED_BY = QT_TR_NOOP("Increased by") - DECREASED = QT_TR_NOOP("Decreased") - DECREASED_BY = QT_TR_NOOP("Decreased by") - LESS_THAN = QT_TR_NOOP("Less Than") - MORE_THAN = QT_TR_NOOP("More Than") - BETWEEN = QT_TR_NOOP("Between") - CHANGED = QT_TR_NOOP("Changed") - UNCHANGED = QT_TR_NOOP("Unchanged") - UNKNOWN_VALUE = QT_TR_NOOP("Unknown Value") - BASIC = QT_TR_NOOP("Basic") - NORMAL = QT_TR_NOOP("Normal") - RW = QT_TR_NOOP("Read+Write") - FULL = QT_TR_NOOP("Full") - HOST = QT_TR_NOOP("Host") - LITTLE = QT_TR_NOOP("Little") - BIG = QT_TR_NOOP("Big") - SHOW_HEXVIEW = QT_TR_NOOP("Show in HexView") - SHOW_DISASSEMBLER = QT_TR_NOOP("Show in Disassembler") - DARK = QT_TR_NOOP("Dark") - LIGHT = QT_TR_NOOP("Light") - SYSTEM_DEFAULT = QT_TR_NOOP("System Default") - WONG = QT_TR_NOOP("Wong (Colorblind Friendly)") - SAVE_SESSION_QUESTION_TITLE = QT_TR_NOOP("Session - Unsaved changes") - SAVE_SESSION_QUESTION_PROMPT = QT_TR_NOOP("You have unsaved changes.\nDo you want to save the current session?") - SESSION_RESET_CANCELLED = QT_TR_NOOP("The session reset was cancelled because the current session was not saved.") - SESSION_PROCESS_CHANGED_TITLE = QT_TR_NOOP("Session - Process changed") - SESSION_PROCESS_CHANGED_PROMPT = QT_TR_NOOP("The process name has changed.\n" "Do you want to keep the current session with the new process?") - MONO_NOT_READY = QT_TR_NOOP("Mono collector is not connected") - MONO_NO_RUNTIME = QT_TR_NOOP("No supported managed runtime found in this process") - MONO_INVOKE = QT_TR_NOOP("Invoke...") - MONO_INVOKE_INSTANCE = QT_TR_NOOP("Instance (this)") - MONO_INVOKE_RESULT = QT_TR_NOOP("Result: {}") - MONO_INVOKE_VOID = QT_TR_NOOP("Returned (void)") - MONO_INVOKE_EXCEPTION = QT_TR_NOOP("Exception thrown (object @ {})") - MONO_INVOKE_BAD_ARG = QT_TR_NOOP("Could not parse the argument values") - MONO_INVOKE_BAD_INSTANCE = QT_TR_NOOP("Invalid instance pointer") - MONO_INVOKE_UNSUPPORTED = QT_TR_NOOP("This method has a parameter type that can't be marshalled yet") - MONO_INVOKE_STRUCT_HINT = QT_TR_NOOP("{} raw bytes (hex)") - MONO_INVOKE_FIND_INSTANCE = QT_TR_NOOP("Find instance...") - MONO_INVOKE_PICK_INSTANCE = QT_TR_NOOP("Select a live instance:") - MONO_STATIC_UNAVAILABLE = QT_TR_NOOP("Static field address is unavailable for this runtime") - MONO_DRILL_UNRESOLVABLE = QT_TR_NOOP("(type could not be resolved)") - MONO_DRILL_MAX_DEPTH = QT_TR_NOOP("(maximum drill depth reached)") - MONO_FIND_INSTANCES = QT_TR_NOOP("Find Instances") - MONO_FIND_INSTANCES_TITLE = QT_TR_NOOP("Find Instances - {}") - MONO_INSTANCES_FOUND = QT_TR_NOOP("{} instance(s) found") - MONO_INSTANCES_TRUNCATED = QT_TR_NOOP("(showing first {})") - MONO_NO_INSTANCES = QT_TR_NOOP("No live instances found") - MONO_INSTANCE_MARKER_UNAVAILABLE = QT_TR_NOOP("Could not resolve an instance marker for this class") - FIELDS = QT_TR_NOOP("Fields") - METHODS = QT_TR_NOOP("Methods") - DISASSEMBLE = QT_TR_NOOP("Disassemble") - VIEW_AT_ADDRESS = QT_TR_NOOP("View at address…") - DELETE_STRUCTURE = QT_TR_NOOP("Delete structure") - DELETE_STRUCTURE_PROMPT = QT_TR_NOOP("Delete structure '{}'?") - VIEW_AS_STRUCT = QT_TR_NOOP("View as structure") - ENTER_BASE_ADDRESS = QT_TR_NOOP("Enter base address") - VALUE_MEMBER = QT_TR_NOOP("Value") - POINTER_MEMBER = QT_TR_NOOP("Pointer") - INLINE_MEMBER = QT_TR_NOOP("Inline") - STRUCTURE_NAME_TAKEN = QT_TR_NOOP("A structure with this name already exists") - STRUCTURE_NAME_EMPTY = QT_TR_NOOP("Structure name cannot be empty") - REPR_UNSIGNED = QT_TR_NOOP("Unsigned") - REPR_SIGNED = QT_TR_NOOP("Signed") - REPR_HEX = QT_TR_NOOP("Hex") - EXPORT_AS_STRUCTURE = QT_TR_NOOP("Export as structure") - DISSECT_AS_STRUCTURE = QT_TR_NOOP("Dissect as structure")