Compare commits

...

208 Commits

Author SHA1 Message Date
WerWolv
a09aec032f Bump version to 1.6.1 2021-01-11 09:56:09 +01:00
WerWolv
7784fca0d4 Always display Pattern Data table header 2021-01-11 09:53:20 +01:00
WerWolv
68bd5569ce Don't show Plugin Views menu if there are no views 2021-01-11 09:50:51 +01:00
WerWolv
60e1c23a6b Fixed pattern format strings 2021-01-11 09:14:32 +01:00
WerWolv
77fbb54ebc Added dlsym to msys2 PKGBUILD 2021-01-11 08:54:23 +01:00
WerWolv
9b7b782020 Fixed cmake error when build type was left unset 2021-01-11 08:46:51 +01:00
WerWolv
bb3e0c126f CI steps naming consistency 2021-01-11 00:44:20 +01:00
WerWolv
3aeb9f31b0 Mark toEngineeringString inline to prevent linker errors 2021-01-11 00:36:24 +01:00
WerWolv
8b19f0c3c0 Improved UTF-8 display in data inspector 2021-01-11 00:34:50 +01:00
WerWolv
73e259d6e7 Added engineering display mode to calculator 2021-01-11 00:27:00 +01:00
WerWolv
f9039f4b34 Added hex editor view right click context menu 2021-01-10 23:59:36 +01:00
George Hopkins
5fb046ad1f Show commit on about page only if available (#132) 2021-01-10 22:57:57 +01:00
WerWolv
7b089a1f2f Fixed unions not advancing offset 2021-01-10 22:57:04 +01:00
WerWolv
867faef496 Fixed invalid applying of define replacements 2021-01-10 22:52:58 +01:00
WerWolv
557313ae1e Fixed boolean OR never being parsed 2021-01-10 22:52:28 +01:00
WerWolv
e4c2049975 Fixed off-by-one error for array bound check 2021-01-10 22:52:12 +01:00
WerWolv
b4ef19dac7 Fixed empty struct and union offset display 2021-01-10 19:43:21 +01:00
WerWolv
dc6c1fa622 Fixed issues with struct and union members when using conditionals 2021-01-10 19:40:44 +01:00
Nobutaka Mantani
d9db8401e2 Fix build on FreeBSD (#126)
* Fix build on FreeBSD

* Use more generic way to search libcrypto

* Integrate macro for FreeBSD
2021-01-10 18:52:00 +01:00
WerWolv
9fe8a0f491 Fixed enums not counting towards size of structs / enums 2021-01-10 18:24:58 +01:00
WerWolv
43d6b48cab Fixed rvalue endianess 2021-01-10 17:18:14 +01:00
WerWolv
ad40c53eb2 Fixed enum parse/evaluate error and crash 2021-01-10 17:14:38 +01:00
Robin Lambertz
c71c610eba Windows MSI Installer (#121)
* Create ImHex WIX Installer

* Build Windows Installer in github actions

* Have a single windows step handling MSI and ZIP.

* Properly copy dependencies to portable zip

* Add magicdb to zip/msi

* Use arial font and smaller text in license
2021-01-10 14:22:34 +01:00
WerWolv
cf1fe04431 Fixed invalid type name in bitfields 2021-01-10 13:50:34 +01:00
WerWolv
8f16a733b9 Fixed bitfields behaving like they have no size. Fixes #127 2021-01-10 13:40:07 +01:00
WerWolv
bc4991f915 Improved type consistency throughout the language 2021-01-10 00:40:57 +01:00
WerWolv
7a8e923b41 Added print & warnAssert functions and a colored console 2021-01-09 23:48:42 +01:00
WerWolv
e54dbcf574 Added assert function. Resolves #123 2021-01-09 21:47:52 +01:00
WerWolv
c5d023822d Added functions with string literals as parameter 2021-01-09 21:47:52 +01:00
WerWolv
e28d6e7451 Added string literals and improved character parsing 2021-01-09 21:47:52 +01:00
WerWolv
9f275cc84f Show evaluator errors in a console window instead of the first line 2021-01-09 21:47:52 +01:00
Philipp Kovalev
575903f921 fix(lang): fixes occurrence index in findSequnce built-in fucntion (#120) 2021-01-09 18:48:34 +01:00
WerWolv
02b3b94804 Increased ImHex to version 1.6.0 2021-01-08 22:09:08 +01:00
WerWolv
17ecdbf8ec Allow accessing of pointer values in mathematical expressions 2021-01-08 20:12:16 +01:00
WerWolv
80e0782fdb Various UI/UX improvements 2021-01-08 19:34:29 +01:00
WerWolv
c505b5b9cb Fixed non-native endian on floats 2021-01-08 17:46:31 +01:00
WerWolv
99f37504de Force reload the current pattern when loading a new file 2021-01-08 17:38:43 +01:00
WerWolv
69f4c6e5e9 Allow global variables to be accessed and used in expressions 2021-01-08 17:37:05 +01:00
WerWolv
fd98db1b70 Fixed error line number mismatch when including files or using comments 2021-01-08 17:14:35 +01:00
WerWolv
205f3a327e Fixed endian specifier not applying 2021-01-08 16:56:39 +01:00
WerWolv
750f7463cc Nightly support for Windows and Linux (#119) 2021-01-08 16:25:12 +01:00
WerWolv
f84b661af7 Fixed pointers to built-in types and endian handling 2021-01-08 15:03:53 +01:00
WerWolv
56330686be Fixed crash when creating an enum 2021-01-08 11:58:07 +01:00
WerWolv
a41e91a731 Fixed floating point pattern displaying 2021-01-08 11:57:28 +01:00
WerWolv
e758b16ba3 Added Pattern Language Guide to the Readme 2021-01-08 01:36:17 +01:00
WerWolv
e48c61cf27 Hopefully fixed macos compile finally 2021-01-07 21:52:03 +01:00
WerWolv
08c802f733 Added unbounded char arrays for null-terminated strings 2021-01-07 21:16:34 +01:00
WerWolv
7e4babaca8 Use custom versions of concepts for macos support 2021-01-07 20:06:28 +01:00
WerWolv
f65c792191 Include unordered_map instead of map 2021-01-07 18:12:02 +01:00
WerWolv
e572c5776d Only define is_integral and is_signed for 128 bit types on non-apple
Clang on macos already defines is_integral and is_signed for 128 bit types
2021-01-07 18:07:56 +01:00
WerWolv
5d1e53f469 Added boolean patterns 2021-01-07 17:34:50 +01:00
WerWolv
bef20f7808 Added function calling as well as a few builtin functions 2021-01-07 15:37:37 +01:00
WerWolv
b47736b595 Properly include headers for memcpy 2021-01-07 01:58:56 +01:00
WerWolv
2dbfbe70af Fixed rvalue value evaluation 2021-01-07 01:56:15 +01:00
WerWolv
3f1d9ed366 Added ternary condition operator 2021-01-07 01:19:54 +01:00
WerWolv
b30bb21646 Added unary operators +, -, ~ and ! 2021-01-07 00:41:06 +01:00
WerWolv
acfd5aa02f Added if, else and else if to pattern language 2021-01-07 00:02:51 +01:00
WerWolv
d8b16766f5 Force Release build type if none was specified 2021-01-07 00:02:33 +01:00
WerWolv
b902cc6531 Go back to static linking on WIndows
Everything except python is once again statically linked
2021-01-06 19:19:01 +01:00
WerWolv
2248cd96b1 Fixed opening of files with non-ASCII characters in path
Fixes #116
2021-01-06 17:22:12 +01:00
WerWolv
01b7059582 Dynamically link everything on Windows as well 2021-01-06 16:30:30 +01:00
WerWolv
7fd0d87d56 Allow enum entries to be accessed via the scope resolution operator 2021-01-06 16:30:30 +01:00
Nicolas Noble
be515d4c40 Proper permission on get_deps_debian.sh script. (#100) 2021-01-06 14:14:47 +01:00
WerWolv
ceee311efa Added support for more literal types and scope resolution operator parsing 2021-01-05 14:42:08 +01:00
WerWolv
f137d759c8 Allow zero-sized arrays again 2021-01-04 16:25:03 +01:00
WerWolv
f5250d6bcf Fixed rvalues not evaluating correctly in nested structs 2021-01-04 16:13:03 +01:00
WerWolv
af42d2ff66 Properly convert rvalue to mathematical expression 2021-01-04 14:10:59 +01:00
WerWolv
f1339f8b4a Fixed crash on load when no plugin folder was present 2021-01-04 13:52:49 +01:00
WerWolv
eed7ef1ac3 Make sure important data is synchronized between ImHex and plugins 2021-01-04 00:19:56 +01:00
WerWolv
c7c654d310 Improved data inspector displaying, added additional number formats 2021-01-03 17:12:20 +01:00
WerWolv
94a7d3116a Fix mac build with missing concepts header 2021-01-03 16:20:28 +01:00
WerWolv
e770fcd197 Fixed includes on unix 2021-01-03 15:09:12 +01:00
WerWolv
5a0f965125 Use file mapping instead of of normal file IO
This drastically reduces disk reads and improves performance
2021-01-03 15:00:16 +01:00
WerWolv
206be8b110 Greatly improved hex editor byte highlighting performance 2021-01-03 02:37:37 +01:00
WerWolv
4189700a3b Use hex::integral instead of std::integral concept 2021-01-02 22:24:52 +01:00
WerWolv
9a968674d6 Fixed compile on macos 2021-01-02 20:49:55 +01:00
WerWolv
18c9340950 Removed duplicated code from hex.hpp 2021-01-02 20:46:44 +01:00
WerWolv
78ef07cf0f Pattern Language rewrite (#111)
* Initial parser rewrite effort

Lexer and Token cleanup, Parser started over

* Greatly improved parser syntax

* Reimplemented using declarations and variable placement parsing

* Added back unions and structs

* Added enums as well as mathematical expressions (+, -, *, /, <<, >>, &, |, ^)

* Code style improvement

* Implemented arrays and fixed memory issues

* Fixed more memory issues in parser, reimplemented validator, evaluator and patterns

* Fixed builtin types, arrays and reimplemented strings

* Improved error messages

* Made character a distinct type, used for chars and strings

* Implemented padding, fixed arrays

* Added bitfields

* Added rvalue parsing, no evaluating yet

* Added .idea folder to gitignore

* Fixed build on MacOS

* Added custom implementation of integral concept if not available

* Rebased onto master

* Fixed array variable decl crash

* Added rvalues and dot syntax

* Lower case all pattern language error messages

* Fixed typo in variable name

* Fixed bug where preprocessor would not ignore commented out directives

* Reimplemented pointers

* Fixed rebase issues
2021-01-02 20:27:11 +01:00
Mary
d510f8c7cf Github Actions: Enforce a cache miss on Windows job
Workaround discuted in msys2/setup-msys2#99.
2020-12-30 19:08:40 +01:00
Mary
2180a8faef Github Actions: upload resulting DMG on macOS
Add infos about nightly builds.
2020-12-30 18:56:25 +01:00
Mary
2340ab0518 cmake: Handle code sign and packaging for macOS bundle 2020-12-29 22:50:11 +01:00
Mary
de5c6a4084 cmake Readd CREATE_BUNDLE infos on macOS 2020-12-29 21:00:41 +01:00
Mary
ce06d9bdfb Fix version and vendor in macOS bundle 2020-12-29 20:41:43 +01:00
Mary
33c11baca9 clean up after previous commit 2020-12-29 02:07:26 +01:00
Mary
8fbdcd54aa Make macOS bundle works!
TODO: codesign
2020-12-29 01:59:28 +01:00
Mary
20d3a84fc0 Fix creation of macOS bundle
Still need to find a way to handle the deps madness
2020-12-28 23:37:51 +01:00
Mary
58a65b0004 cmake: Do not ship resource.rc on non WIN32 systems
Also add some very early macOS bundle definitions.
2020-12-28 20:03:50 +01:00
Mary
bbd00a6020 Ignore .DS_Store in gitignore 2020-12-28 18:52:42 +01:00
Mary
63f544918d Fix build instruction to add CMAKE_BUILD_TYPE 2020-12-28 18:52:22 +01:00
WerWolv
93938d6090 external: glfw3 -> glfw 2020-12-27 15:57:59 +01:00
WerWolv
144e30775f Fixed duplicated utils.hpp 2020-12-27 15:54:12 +01:00
WerWolv
f74eff8934 Add support for custom providers via plugins 2020-12-27 15:39:06 +01:00
WerWolv
8ba96904a6 More plugin support work 2020-12-27 14:12:53 +01:00
WerWolv
dbbc525174 Added Plugin support (#102)
* Build refactoring and initial plugin support

* Possibly fixed linux / mac build

* Added libdl to libglad build script

* Add glfw to imgui dependencies

* Refactored common functionality into "libimhex" for plugins

* Added plugin loading and example plugin

* Added proper API for creating a custom view and a custom tools entry with plugins
2020-12-22 18:10:01 +01:00
WerWolv
b9324f44e6 Added selected addresses to hex editor footer
This (and the two previous commits) fixes #99
2020-12-21 15:20:57 +01:00
WerWolv
d6c5e3dc3e Fixed render order of ASCII display in hex editor
Fixes #98
2020-12-21 14:44:01 +01:00
WerWolv
7c350dde90 Added current commit hash and branch to about page 2020-12-21 12:38:50 +01:00
WerWolv
2c1759ce0a Unified OS and arch checking defines 2020-12-21 12:38:30 +01:00
WerWolv
7f5a32a83b Improved hex::format 2020-12-21 12:36:43 +01:00
WerWolv
379f77af48 Cleaned up github actions 2020-12-21 11:54:33 +01:00
WerWolv
4b59d57f89 Added version info to about page 2020-12-21 11:24:27 +01:00
WerWolv
15b3860f83 Fixed data inspector not updating properly in all cases 2020-12-21 11:23:57 +01:00
WerWolv
b71a9b7d14 More centering 2020-12-19 15:15:24 +01:00
WerWolv
85352868ec Cleaned up readme and added link to discord server 2020-12-19 15:14:45 +01:00
Mary
310059f274 Support macOS
This allows building and running under macOS.
There is still some issues with dpi but the application compiles and run now.
2020-12-18 21:44:13 +01:00
Mary
b5cc3b6f1b Make target link and include more generic
This fixes issues with library link and unify support for linking on Linux/macOS/BSD.
2020-12-18 20:04:55 +01:00
Mary
de9421e68f Fix missing dependencies in README and ArchLinux get_deps script 2020-12-18 18:46:20 +01:00
Mary
413443aa95 Build LLVM demangler directly with our sources
This remove dep on LLVM library by building the demangler as part of the
project.

This should help with building on macOS.
2020-12-18 17:56:41 +01:00
Sam Umbach
82d7c54a3d Fix minor typos (#95) 2020-12-17 08:55:40 +01:00
WerWolv
9123b21e18 Added basic command palette (similar to the one in vscode) 2020-12-16 22:43:07 +01:00
averne
56cca88fbd Proper DPI scaling and basic custom font (#85)
* add glm to arch deps

After running got `None of the required 'glm' found`. This fixes that

* dist/fedora: Include file magic headers

Due to differences in package names between Deb based systems, Arch
Linux, and RPM based systems the package containing the development
headers for file were missing from the Fedora dependencies script.

This includes the package `file-devel`, which is the package which
resolves the issue.

In Fedora, one can identify the package providing a specific file using
the verb "whatprovides" with the command dnf, e.g.:

    [~]$ dnf whatprovides /usr/include/magic.h
    Last metadata expiration check: 4 days, 0:23:05 ago on Fri 04 Dec 2020 09:06:53 AM PST.
    file-devel-5.39-3.fc33.i686 : Libraries and header files for file development
    Repo        : fedora
    Matched from:
    Filename    : /usr/include/magic.h

    file-devel-5.39-3.fc33.x86_64 : Libraries and header files for file development
    Repo        : @System
    Matched from:
    Filename    : /usr/include/magic.h

    file-devel-5.39-3.fc33.x86_64 : Libraries and header files for file development
    Repo        : fedora
    Matched from:
    Filename    : /usr/include/magic.h

If one is unsure of the specific path, globbing may be used (but must be
quoted):

    dnf whatprovides "*/magic.h"

Resolves #48

* dist: Prevent already installed packages in ArchLinux and MSYS2.

Use --needed option with pacman to prevent it.

* Add script to install dependencies on Debian/Ubuntu.

Tested with Xubuntu 20.04 and Debian testing
(in today's Docker image bitnami/minideb).

Update README.md.

* ci: rework (#31)

* Support non standard LLVM library names (#86)

This fix openSUSE and Gentoo issue mentioned in https://github.com/WerWolv/ImHex/issues/37#issuecomment-739503138.

(tested on openSUSE tumbleweed via Docker)

I also took the liberty of renaming llvm_lib to llvm_demangle_lib to be more specific in the ``CMakeLists.txt``.

* Implement proper DPI handling

* Implement basic custom font support

* Fix building on windows

* Hopefully fix fonts on Windows

* Fix several scaling issues

* Replace font renderer with freetype

* Updated CI and dependency scripts

* Rebuild default font atlas

* Correct platform detection macro for mingw

* Fixed PKGBUILD

Co-authored-by: brockelmore <31553173+brockelmore@users.noreply.github.com>
Co-authored-by: Brian 'Redbeard' Harrington <redbeard@dead-city.org>
Co-authored-by: Biswapriyo Nath <nathbappai@gmail.com>
Co-authored-by: Stéphane Gourichon <stephane.gourichon@fidergo.fr>
Co-authored-by: umarcor <38422348+umarcor@users.noreply.github.com>
Co-authored-by: Mary <me@thog.eu>
Co-authored-by: WerWolv <werwolv98@gmail.com>
2020-12-11 14:24:42 +01:00
Mary
9b853350f1 Support non standard LLVM library names (#86)
This fix openSUSE and Gentoo issue mentioned in https://github.com/WerWolv/ImHex/issues/37#issuecomment-739503138.

(tested on openSUSE tumbleweed via Docker)

I also took the liberty of renaming llvm_lib to llvm_demangle_lib to be more specific in the ``CMakeLists.txt``.
2020-12-10 22:28:49 +01:00
umarcor
e3b5a55eba ci: rework (#31) 2020-12-09 19:49:56 +01:00
WerWolv
366dc80dc0 Merge pull request #79 from fidergo-stephane-gourichon/dependency_install_script_debian_ubuntu
Add script to install dependencies on Debian/Ubuntu.
2020-12-09 18:51:26 +01:00
Stéphane Gourichon
ba2ee6d6e5 Add script to install dependencies on Debian/Ubuntu.
Tested with Xubuntu 20.04 and Debian testing
(in today's Docker image bitnami/minideb).

Update README.md.
2020-12-09 15:18:18 +01:00
WerWolv
6afcf1a26f Merge pull request #76 from Biswa96/master
dist: Prevent already installed packages in ArchLinux and MSYS2.
2020-12-09 10:33:48 +01:00
Biswapriyo Nath
ee831fbcb6 dist: Prevent already installed packages in ArchLinux and MSYS2.
Use --needed option with pacman to prevent it.
2020-12-09 14:21:36 +05:30
WerWolv
4d87eefbe9 Merge pull request #69 from brianredbeard/issue-48-fix-fedora-error
dist/fedora: Include file magic headers
2020-12-08 18:45:44 +01:00
Brian 'Redbeard' Harrington
ec04fea9be dist/fedora: Include file magic headers
Due to differences in package names between Deb based systems, Arch
Linux, and RPM based systems the package containing the development
headers for file were missing from the Fedora dependencies script.

This includes the package `file-devel`, which is the package which
resolves the issue.

In Fedora, one can identify the package providing a specific file using
the verb "whatprovides" with the command dnf, e.g.:

    [~]$ dnf whatprovides /usr/include/magic.h
    Last metadata expiration check: 4 days, 0:23:05 ago on Fri 04 Dec 2020 09:06:53 AM PST.
    file-devel-5.39-3.fc33.i686 : Libraries and header files for file development
    Repo        : fedora
    Matched from:
    Filename    : /usr/include/magic.h

    file-devel-5.39-3.fc33.x86_64 : Libraries and header files for file development
    Repo        : @System
    Matched from:
    Filename    : /usr/include/magic.h

    file-devel-5.39-3.fc33.x86_64 : Libraries and header files for file development
    Repo        : fedora
    Matched from:
    Filename    : /usr/include/magic.h

If one is unsure of the specific path, globbing may be used (but must be
quoted):

    dnf whatprovides "*/magic.h"

Resolves #48
2020-12-08 09:31:17 -08:00
Mary
1586aee2d2 Merge pull request #59 from brockelmore/patch-1
add glm to arch deps
2020-12-08 13:33:42 +01:00
WerWolv
226169bbbe Merge remote-tracking branch 'origin/master' 2020-12-07 23:49:28 +01:00
WerWolv
e1e73077a1 Improved language parsing and validation. This fixes #58 2020-12-07 23:49:19 +01:00
brockelmore
7b5cfcb817 add glm to arch deps
After running got `None of the required 'glm' found`. This fixes that
2020-12-07 16:51:08 -05:00
WerWolv
b3645ec945 Merge pull request #53 from umarcor/deps
create subdir 'dist', update compiling guidelines
2020-12-07 18:46:25 +01:00
umarcor
7d06460e54 create subdir 'dist', update compiling guidelines 2020-12-07 04:17:17 +01:00
WerWolv
485761f45c Fixed ImHex refusing to be closed in some circumstances 2020-12-07 00:42:52 +01:00
WerWolv
f3d788de16 Fixed bytes not being selectable when a read-only file was loaded
This most likely fixes #49
2020-12-06 23:21:31 +01:00
WerWolv
b06f5630c7 Fixed additional issues with padding and zero sized arrays 2020-12-06 23:15:51 +01:00
WerWolv
5c96a28fb6 Actually fix crash when creating zero sized arrays
If size is zero, the array will be treated as non-existent. This fixes #50
2020-12-06 22:52:15 +01:00
WerWolv
9425569784 Merge pull request #47 from Calinou/readme-add-fedora-package-list
Add a list of packages to install for building on Fedora 33
2020-12-06 22:24:19 +01:00
Hugo Locurcio
8b982b977b Add a list of packages to install for building on Fedora 33
Tested in a fresh Fedora 33 Docker container.
2020-12-06 22:19:52 +01:00
WerWolv
7a9d7b59e8 Added overriding of endianess for individual variables 2020-12-06 21:40:57 +01:00
WerWolv
4720cf9fbe Added possible support for MacOS. Completely untested.
Relevant: #32
2020-12-06 13:48:56 +01:00
WerWolv
68f93c5e3d Fixed possible crash when loading files, relax pattern detection requirements
This fixes #20
2020-12-05 22:30:09 +01:00
WerWolv
7b8330f8f8 Added command line support / dropping files onto executable
Closes #36
2020-12-05 22:10:03 +01:00
WerWolv
63696b9f5f Merge pull request #38 from Thog/feature/linux-ci
CI: Add a GitHub Action to build on Ubuntu 20.04 LTS
2020-12-05 20:32:45 +01:00
Mary
727b3c6b10 CI: Add a GitHub Action to build on Ubuntu 20.04 LTS
Also clean up MSYS2 action.
2020-12-05 20:03:22 +01:00
WerWolv
05cb3831a2 Merge pull request #35 from Thog/fix/llvm-custom-lib-dir
Make sure to add LLVM_LIBRARY_DIR to link directories
2020-12-05 18:55:28 +01:00
Mary
5b51375404 Make sure to add LLVM_LIBRARY_DIR to link directories
This fix build on Debian and Ubuntu systems.

Close #28
Close #8
2020-12-05 18:13:47 +01:00
WerWolv
398e845e8d Merge pull request #33 from Thog/fix/capstone-401-support
Abstract capstone architectures
2020-12-05 17:43:18 +01:00
Mary
45c29888b4 Abstract capstone architectures
This allows to support older version of Capstone (example 4.0.1).

Should help with ubuntu building issues.
2020-12-05 17:32:30 +01:00
WerWolv
82c5bd528c Added more compile information 2020-12-05 15:39:28 +01:00
WerWolv
45d0b614c2 Added sponsoring links to Readme. Thank you <3 2020-12-05 15:10:57 +01:00
WerWolv
4725ff6d5f Don't open a console window in release build
This fixes #21
2020-12-05 14:09:32 +01:00
WerWolv
7158d4d4ad Always allow cursor movement with arrow keys
Implements #22
2020-12-05 12:55:37 +01:00
WerWolv
502d90b117 Merge remote-tracking branch 'origin/master' 2020-12-05 12:54:42 +01:00
WerWolv
f0c95b3f29 Merge pull request #29 from Thog/feature/python3-detect
Detect python version at build time
2020-12-05 12:54:30 +01:00
Mary
d3dccace37 Detect python version at build time
This remove the hardcoded version in CMakeLists.txt and
loader_script_handler.cpp.

Fixing building on Arch Linux and probably other systems.
2020-12-05 12:46:50 +01:00
WerWolv
a30453616b Turned cheat sheet popups into actual windows 2020-12-05 11:34:49 +01:00
WerWolv
168ba2ff9f Denote invalid GUIDs in data inspector
Addresses #24
2020-12-05 11:00:56 +01:00
WerWolv
2ca9a8fc79 Fixed data inspector displaying zero at the end of data
Fixes #25
2020-12-05 10:42:42 +01:00
WerWolv
6456a68805 Fixed crash when array size variable has a value of zero 2020-12-05 10:36:30 +01:00
WerWolv
e82b607fa1 Merge pull request #16 from Thog/feature/github-actions
CI: Add a GitHub Action to build on Windows
2020-12-04 13:40:36 +01:00
Mary
7168c9ed59 Limit make to 4 threads and move build.yml to build_win.yml 2020-12-04 13:17:54 +01:00
WerWolv
d7af6934b6 Added ImHex-Patterns repository to the readme 2020-12-04 09:26:19 +01:00
Mary
b4a5a936a0 CI: Add a GitHub Action to build on Windows
This build in any commits and pull requests.
2020-12-04 01:28:26 +01:00
WerWolv
6129e0d696 Added libwinpthread dll to copy instructions
Because smh not everybody has qemu installed
2020-12-03 23:18:41 +01:00
WerWolv
a0c8424800 Create FUNDING.yml 2020-12-03 21:10:38 +01:00
WerWolv
dc839e1ad1 Fixed typos, love you @foone :P 2020-12-03 20:56:02 +01:00
WerWolv
59155256a9 Create LICENSE 2020-12-03 15:34:58 +01:00
WerWolv
29b7995e7f Formatting 2020-12-03 09:18:55 +01:00
WerWolv
ae9ec8851c Credit where it's due 2020-12-03 09:17:55 +01:00
WerWolv
7c2df736df Improved readme 2020-12-01 20:47:57 +01:00
WerWolv
192e7d5060 Added Python API function to create structs and unions 2020-12-01 18:21:29 +01:00
WerWolv
6aed140ecf Use custom "argc" and "argv" exposing. Fixes #6 2020-12-01 18:19:49 +01:00
WerWolv
76d56c9ed4 Added python version requirement to cmake. Fixes #5 2020-12-01 18:18:15 +01:00
WerWolv
17096055f8 Added create_struct and create_union function to Python API 2020-12-01 16:41:38 +01:00
WerWolv
c6134bc038 Added basic python-based load scripts 2020-12-01 02:21:40 +01:00
WerWolv
16f885f469 Added read/write command to math evaluator 2020-11-30 21:45:48 +01:00
WerWolv
00072d0216 Improved pattern language cheat sheet, added math evaluator cheat sheet 2020-11-30 21:44:40 +01:00
WerWolv
4878f70e58 Added project files 2020-11-30 00:03:12 +01:00
WerWolv
9e8523470d Added applying of IPS and IPS32 patches 2020-11-29 15:09:36 +01:00
WerWolv
7316be0bc2 Added patches display window 2020-11-29 02:06:41 +01:00
WerWolv
8a4b663890 Prevent shortcuts from applying to closed windows 2020-11-29 01:18:12 +01:00
WerWolv
3276ad9979 Open file dialog to not pop up if hex view wasn't open 2020-11-29 01:17:54 +01:00
WerWolv
0890043bf4 Make Help view no longer appear in View menu 2020-11-28 22:01:50 +01:00
WerWolv
c90ef343c1 Added math evaluator / calculator to tools window 2020-11-28 21:55:52 +01:00
WerWolv
0f6e276113 Updated screenshots 2020-11-28 17:21:34 +01:00
WerWolv
1395c95831 Same treatment for the disassembly window 2020-11-28 16:15:12 +01:00
WerWolv
33b70a550f Improved look and feel of hash window. Added "Match selection" feature 2020-11-28 15:53:11 +01:00
WerWolv
985e924e9d Added simple bookmarks / comments feature. No saving yet though 2020-11-28 00:33:26 +01:00
WerWolv
3827919a32 Added error messages and error display to pattern language editor 2020-11-27 21:20:23 +01:00
WerWolv
d55bea7c46 Added character literals to pattern language 2020-11-27 14:18:28 +01:00
WerWolv
2efe326fdb Added Save, Save As and implemented error message for Base64 importing 2020-11-27 13:45:56 +01:00
WerWolv
d43bd23e1a Added default error message window 2020-11-27 13:45:27 +01:00
WerWolv
015ec12215 Improved byte write speed by a lot 2020-11-27 13:44:52 +01:00
WerWolv
fde9dc7961 Various small fixes 2020-11-27 09:09:59 +01:00
WerWolv
ed572ececf Added patching system and IPS/IPS32 patch exporting 2020-11-27 09:09:48 +01:00
WerWolv
fd2b79bea9 Removed cxxabi.h include 2020-11-24 18:12:48 +01:00
WerWolv
acc10930c2 Added MSVC symbol demangling, switched to LLVM libs for demangling 2020-11-24 18:12:08 +01:00
WerWolv
f17d6c2359 Added copy string and copy demangled string to strings window 2020-11-24 02:59:49 +01:00
WerWolv
e21211f3f6 Added back default debug/release specific flags 2020-11-24 02:00:48 +01:00
WerWolv
58deaa6b29 Added importing from base64 encoded file 2020-11-24 02:00:22 +01:00
WerWolv
fcd88b4b3b Shrink the color picker to a bit more reasonable size 2020-11-24 00:01:44 +01:00
WerWolv
3bd987ff2c Streamline view creation, save all view states when quitting 2020-11-23 23:57:19 +01:00
WerWolv
45bcdc8c46 Added toggle for ImGui demo window in Debug mode 2020-11-23 22:23:06 +01:00
WerWolv
0d0b2d6962 Indent variable name instead of color in pattern data view 2020-11-23 22:14:11 +01:00
WerWolv
fd6a41d219 Make selecting memory by clicking on a table item update the inspector 2020-11-23 16:26:01 +01:00
WerWolv
b052429a73 Improved ASCII and Wide char display in data inspector 2020-11-23 16:19:58 +01:00
WerWolv
1996f401e0 Fixed last block searched for strings to yield invalid results 2020-11-23 16:19:31 +01:00
WerWolv
3b3f2226f1 Remove collapse button from all windows 2020-11-23 15:51:58 +01:00
WerWolv
5c0f6a1e50 Enabled ImGui's viewports support 2020-11-23 15:51:40 +01:00
WerWolv
b7438f6ab8 Massively improved look and feel of pattern data, string and disassembly tables 2020-11-23 15:22:26 +01:00
WerWolv
84f80b3e06 Select region when clicking on string, disassembly or pattern data item 2020-11-23 13:10:14 +01:00
WerWolv
c281372b8d Improved table coloring 2020-11-23 13:08:24 +01:00
WerWolv
788a3cfc5e Merge pull request #3 from misson20000/bugfixes
a few bugfixes
2020-11-23 08:25:15 +01:00
misson20000
01eeb53af0 Fix out-of-bounds vector write on copy hex string 2020-11-22 18:00:46 -08:00
misson20000
7cf69128ea Actually fix time_t decoding crash on Linux 2020-11-22 18:00:17 -08:00
147 changed files with 20828 additions and 2582 deletions

5
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,5 @@
# Sponsor links
patreon: werwolv
custom: https://werwolv.net/donate
github: WerWolv

159
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,159 @@
name: Build
on:
push:
pull_request:
env:
BUILD_TYPE: Release
jobs:
linux:
runs-on: ubuntu-20.04
name: 🐧 Ubuntu 20.04
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: ⬇️ Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
gcc-10 \
g++-10 \
pkg-config \
cmake \
make \
libglfw3-dev \
libglm-dev \
libmagic-dev \
libssl-dev \
libcapstone-dev \
nlohmann-json3-dev \
python3-dev \
libfreetype-dev \
- name: ✋ Build
run: |
mkdir build
cd build
CC=gcc-10 CXX=g++-10 cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE ..
make -j 4
- name: 📦 Upload ELF
uses: actions/upload-artifact@v2
with:
name: Linux ELF
path: build/imhex
win:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟦 ${{ matrix.msystem }} · ${{ matrix.arch }}
defaults:
run:
shell: msys2 {0}
env:
MINGW_INSTALLS: ${{ matrix.msystem }}
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: ⬇️ Install dependencies
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
install: >
mingw-w64-${{ matrix.arch }}-gcc
mingw-w64-${{ matrix.arch }}-cmake
mingw-w64-${{ matrix.arch }}-make
mingw-w64-${{ matrix.arch }}-capstone
mingw-w64-${{ matrix.arch }}-glfw
mingw-w64-${{ matrix.arch }}-glm
mingw-w64-${{ matrix.arch }}-file
mingw-w64-${{ matrix.arch }}-nlohmann-json
mingw-w64-${{ matrix.arch }}-openssl
mingw-w64-${{ matrix.arch }}-polly
mingw-w64-${{ matrix.arch }}-python
mingw-w64-${{ matrix.arch }}-dlfcn
mingw-w64-${{ matrix.arch }}-freetype
- name: ✋ Build
run: |
mkdir build
cd build
# Get path to mingw python library
PYTHON_LIB_NAME=$(pkg-config --libs-only-l python3 | sed 's/^-l//')
PYTHON_LIB_PATH=$(cygpath -m $(which lib${PYTHON_LIB_NAME}.dll))
# Get path to magic db
MAGICDB_PATH=$(cygpath -m $(file --version | grep -oP "(?<=magic file from ).+"))
echo Python_LIBRARY: $PYTHON_LIB_PATH
echo MagicDB Path: $MAGICDB_PATH
cmake -G "MinGW Makefiles" \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
-DCMAKE_INSTALL_PREFIX="$PWD/install" \
-DCREATE_PACKAGE=ON \
-DPython_LIBRARY="$PYTHON_LIB_PATH" \
-DEXTRA_MAGICDBS="$MAGICDB_PATH" \
..
mingw32-make -j4
mingw32-make install
cpack
- name: 📦 Upload Portable ZIP
uses: actions/upload-artifact@v2
with:
name: Windows Portable ZIP
path: |
build/install/*
- name: 📦 Upload Windows Installer
uses: actions/upload-artifact@v2
with:
name: Windows Installer
path: |
build/*.msi
macos-build:
runs-on: macos-11.0
name: 🍎 macOS 11.0
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: ⬇️ Install dependencies
run: |
brew bundle --no-lock --file dist/Brewfile
- name: ✋ Build
run: |
mkdir build
cd build
CC=$(brew --prefix llvm)/bin/clang CXX=$(brew --prefix llvm)/bin/clang++ PKG_CONFIG_PATH="$(brew --prefix openssl)/lib/pkgconfig":"$(brew --prefix)/lib/pkgconfig" cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCREATE_BUNDLE=ON -DCREATE_PACKAGE=ON ..
make -j 4 package
- name: 📦 Upload DMG
uses: actions/upload-artifact@v2
with:
name: macOS DMG
path: build/*.dmg

3
.gitignore vendored
View File

@@ -1,3 +1,5 @@
.vscode/
.idea/
cmake-build-debug/
@@ -8,3 +10,4 @@ build/
*.mgc
imgui.ini
.DS_Store

1
.idea/.name generated Normal file
View File

@@ -0,0 +1 @@
imhex

2
.idea/imhex.iml generated Normal file
View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />

2
.idea/modules.xml generated
View File

@@ -2,7 +2,7 @@
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/HexEditor.iml" filepath="$PROJECT_DIR$/.idea/HexEditor.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/imhex.iml" filepath="$PROJECT_DIR$/.idea/imhex.iml" />
</modules>
</component>
</project>

View File

@@ -1,34 +1,167 @@
cmake_minimum_required(VERSION 3.16)
project(HexEditor)
set(CMAKE_CXX_STANDARD 20)
find_package(PkgConfig REQUIRED)
pkg_search_module(GLFW REQUIRED glfw3)
pkg_search_module(GLM REQUIRED glm)
pkg_search_module(CAPSTONE REQUIRED capstone)
find_package(OpenGL REQUIRED)
include_directories(include ${GLFW_INCLUDE_DIRS} ${CAPSTONE_INCLUDE_DIRS} libs/ImGui/include libs/glad/include)
SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -DIMGUI_IMPL_OPENGL_LOADER_GLAD")
project(imhex VERSION 1.6.1)
if (WIN32)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libstdc++ -static-libgcc -static")
endif (WIN32)
set(EXTRA_MAGICDBS "" CACHE STRING "List of compiled magicdb files separated with a ;")
else()
set(EXTRA_MAGICDBS "" CACHE STRING "List of compiled magicdb files separated with a :")
endif()
add_executable(ImHex
if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Using Release build type as it was left unset" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release")
endif()
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules")
option (CREATE_PACKAGE "Create a package with CPack" OFF)
if (APPLE)
option (CREATE_BUNDLE "Create a bundle on macOS" OFF)
endif()
set(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
set(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
set(CMAKE_CXX_STANDARD 20)
# Enforce that we use non system Python 3 on macOS.
set(Python_FIND_FRAMEWORK NEVER)
# Find packages
find_package(PkgConfig REQUIRED)
pkg_search_module(CRYPTO libcrypto)
if(NOT CRYPTO_FOUND)
find_library(CRYPTO crypto REQUIRED)
endif()
pkg_search_module(CAPSTONE REQUIRED capstone)
find_package(OpenGL REQUIRED)
find_package(nlohmann_json REQUIRED)
find_package(Python COMPONENTS Development)
add_subdirectory(external/llvm)
add_subdirectory(plugins/libimhex)
if(Python_VERSION LESS 3)
message(STATUS ${PYTHON_VERSION_MAJOR_MINOR})
message(FATAL_ERROR "No valid version of Python 3 was found.")
endif()
pkg_search_module(MAGIC libmagic)
if(NOT MAGIC_FOUND)
find_library(MAGIC magic REQUIRED)
endif()
# Add include directories
include_directories(include ${CRYPTO_INCLUDE_DIRS} ${CAPSTONE_INCLUDE_DIRS} ${MAGIC_INCLUDE_DIRS} ${Python_INCLUDE_DIRS})
# Get Python major and minor
string(REPLACE "." ";" PYTHON_VERSION_MAJOR_MINOR ${Python_VERSION})
list(REMOVE_AT PYTHON_VERSION_MAJOR_MINOR 2)
list(JOIN PYTHON_VERSION_MAJOR_MINOR "." PYTHON_VERSION_MAJOR_MINOR)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_C_FLAGS} -DPYTHON_VERSION_MAJOR_MINOR=\"\\\"${PYTHON_VERSION_MAJOR_MINOR}\"\\\"")
# Detect current OS / System
if (WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOS_WINDOWS -static-libstdc++ -static-libgcc -Wl,--allow-multiple-definition -static")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wl,-subsystem,windows")
elseif(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOS_MACOS")
elseif(UNIX AND NOT APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOS_LINUX")
else()
message(FATAL_ERROR "Unknown / unsupported system!")
endif()
# Detect 32 vs. 64 bit system
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DARCH_64_BIT")
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DARCH_32_BIT")
endif()
if (IS_DIRECTORY "${CMAKE_SOURCE_DIR}/.git")
# Get the current working branch
execute_process(
COMMAND git rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_BRANCH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# Get the latest abbreviated commit hash of the working branch
execute_process(
COMMAND git log -1 --format=%h
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGIT_COMMIT_HASH=\"\\\"${GIT_COMMIT_HASH}\"\\\"")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGIT_BRANCH=\"\\\"${GIT_BRANCH}\"\\\"")
endif()
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DRELEASE -DIMHEX_VERSION=\"\\\"${PROJECT_VERSION}\"\\\"")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG -DIMHEX_VERSION=\"\\\"${PROJECT_VERSION}-Debug\"\\\"")
if (WIN32)
set(application_type WIN32)
set(imhex_icon resource.rc)
if (CREATE_PACKAGE)
set(CPACK_GENERATOR "WIX")
set(CPACK_PACKAGE_NAME "ImHex")
set(CPACK_WIX_UPGRADE_GUID "05000E99-9659-42FD-A1CF-05C554B39285")
set(CPACK_WIX_PRODUCT_ICON "${PROJECT_SOURCE_DIR}/res/icon.ico")
set(CPACK_PACKAGE_INSTALL_DIRECTORY "ImHex")
set_property(INSTALL "$<TARGET_FILE_NAME:imhex>"
PROPERTY CPACK_START_MENU_SHORTCUTS "ImHex"
)
set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/res/LICENSE.rtf")
endif()
elseif (APPLE)
set (imhex_icon "${PROJECT_SOURCE_DIR}/res/mac/AppIcon.icns")
if (CREATE_BUNDLE)
set(application_type MACOSX_BUNDLE)
set_source_files_properties(${imhex_icon} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
set(MACOSX_BUNDLE_ICON_FILE "AppIcon.icns")
set(MACOSX_BUNDLE_INFO_STRING "WerWolv")
set(MACOSX_BUNDLE_BUNDLE_NAME "ImHex")
set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}")
set(MACOSX_BUNDLE_GUI_IDENTIFIER "WerWolv.ImHex")
set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_VERSION}-${GIT_COMMIT_HASH}")
set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}")
set(MACOSX_BUNDLE_COPYRIGHT "Copyright © 2020 WerWolv and Thog. All rights reserved." )
if ("${CMAKE_GENERATOR}" STREQUAL "Xcode")
set ( bundle_path "${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}/imhex.app" )
else ()
set ( bundle_path "${CMAKE_BINARY_DIR}/imhex.app" )
endif()
endif()
endif()
add_executable(imhex ${application_type}
source/main.cpp
source/window.cpp
source/utils.cpp
source/crypto.cpp
source/helpers/crypto.cpp
source/helpers/patches.cpp
source/helpers/math_evaluator.cpp
source/helpers/project_file_handler.cpp
source/helpers/loader_script_handler.cpp
source/helpers/plugin_handler.cpp
source/lang/preprocessor.cpp
source/lang/lexer.cpp
source/lang/parser.cpp
source/lang/validator.cpp
source/lang/evaluator.cpp
source/lang/builtin_functions.cpp
source/provider/file_provider.cpp
source/providers/file_provider.cpp
source/views/view_hexeditor.cpp
source/views/view_pattern.cpp
@@ -40,25 +173,93 @@ add_executable(ImHex
source/views/view_strings.cpp
source/views/view_data_inspector.cpp
source/views/view_disassembler.cpp
source/views/view_bookmarks.cpp
source/views/view_patches.cpp
source/views/view_command_palette.cpp
libs/glad/source/glad.c
libs/ImGui/source/imgui.cpp
libs/ImGui/source/imgui_draw.cpp
libs/ImGui/source/imgui_widgets.cpp
libs/ImGui/source/imgui_demo.cpp
libs/ImGui/source/imgui_impl_glfw.cpp
libs/ImGui/source/imgui_impl_opengl3.cpp
libs/ImGui/source/ImGuiFileBrowser.cpp
libs/ImGui/source/TextEditor.cpp
resource.rc
${imhex_icon}
)
if (WIN32)
target_link_libraries(ImHex libglfw3.a libgcc.a libstdc++.a libmagic.a libgnurx.a libtre.a libintl.a libiconv.a shlwapi.lib libcrypto.a libwinpthread.a libcapstone.a)
endif (WIN32)
set_target_properties(imhex PROPERTIES CXX_VISIBILITY_PRESET hidden)
if (UNIX)
target_link_libraries(ImHex libglfw.so libmagic.so libcrypto.so libdl.so libcapstone.so)
endif (UNIX)
target_link_directories(imhex PRIVATE ${CRYPTO_LIBRARY_DIRS} ${CAPSTONE_LIBRARY_DIRS} ${MAGIC_LIBRARY_DIRS})
if (WIN32)
target_link_libraries(imhex libdl.a libmagic.a libgnurx.a libtre.a libintl.a libiconv.a libshlwapi.a libcrypto.a libwinpthread.a libcapstone.a LLVMDemangle imgui libimhex ${Python_LIBRARIES} nlohmann_json::nlohmann_json)
elseif (UNIX)
target_link_libraries(imhex magic crypto ${CMAKE_DL_LIBS} capstone LLVMDemangle imgui libimhex ${Python_LIBRARIES} nlohmann_json::nlohmann_json dl)
endif()
if (WIN32)
# Install binaries directly in the prefix, usually C:\Program Files\ImHex.
set(CMAKE_INSTALL_BINDIR ".")
# Grab all dynamically linked dependencies.
INSTALL(CODE "set(CMAKE_INSTALL_BINDIR \"${CMAKE_INSTALL_BINDIR}\")")
INSTALL(CODE "get_filename_component(PY_PARENT ${Python_LIBRARIES} DIRECTORY)")
INSTALL(CODE "LIST(APPEND DEP_FOLDERS \${PY_PARENT})")
install(CODE [[
file(GET_RUNTIME_DEPENDENCIES
EXECUTABLES $<TARGET_FILE:imhex>
RESOLVED_DEPENDENCIES_VAR _r_deps
UNRESOLVED_DEPENDENCIES_VAR _u_deps
CONFLICTING_DEPENDENCIES_PREFIX _c_deps
DIRECTORIES ${DEP_FOLDERS}
POST_EXCLUDE_REGEXES ".*system32/.*\\.dll"
)
if(_u_deps)
message(WARNING "There were unresolved dependencies for binary $<TARGET_FILE:imhex>: \"${_u_deps}\"!")
endif()
if(_c_deps_FILENAMES)
message(WARNING "There were conflicting dependencies for library $<TARGET_FILE:imhex>: \"${_c_deps}\"!")
endif()
foreach(_file ${_r_deps})
file(INSTALL
DESTINATION "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}"
TYPE SHARED_LIBRARY
FOLLOW_SYMLINK_CHAIN
FILES "${_file}"
)
endforeach()
]])
endif()
# Compile the imhex-specific magicdb
add_custom_target(magic_dbs ALL
SOURCES magic_dbs/nintendo_magic
)
add_custom_command(TARGET magic_dbs
COMMAND file -C -m ${CMAKE_SOURCE_DIR}/magic_dbs
)
# Install the magicdb files.
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/magic_dbs.mgc DESTINATION magic/ RENAME imhex.mgc)
install(FILES ${EXTRA_MAGICDBS} DESTINATION magic/)
if (CREATE_BUNDLE)
include(PostprocessBundle)
# Fix rpath
add_custom_command(TARGET imhex POST_BUILD COMMAND ${CMAKE_INSTALL_NAME_TOOL} -add_rpath "@executable_path/../Frameworks/" $<TARGET_FILE:imhex>)
# FIXME: Remove this once we move/integrate the plugins directory.
add_custom_target(build-time-make-plugins-directory ALL COMMAND ${CMAKE_COMMAND} -E make_directory "${bundle_path}/Contents/MacOS/plugins")
# Update library references to make the bundle portable
postprocess_bundle(imhex)
# Enforce DragNDrop packaging.
set(CPACK_GENERATOR "DragNDrop")
install(TARGETS imhex BUNDLE DESTINATION .)
else()
install(TARGETS imhex RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
if (CREATE_PACKAGE)
include(apple)
include(CPack)
endif()

339
LICENSE Normal file
View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

157
README.md
View File

@@ -1,7 +1,158 @@
# ImHex
<h1 align="center">:mag: ImHex</h1>
A Hex editor written in C++ using OpenGL, GLFW and Dear ImGui
<p align="center">A Hex Editor for Reverse Engineers, Programmers and people that value their eye sight when working at 3 AM.</p>
<p align="center">
<a title="'Build' workflow Status" href="https://github.com/WerWolv/ImHex/actions?query=workflow%3ABuild"><img alt="'Build' workflow Status" src="https://img.shields.io/github/workflow/status/WerWolv/ImHex/Build?longCache=true&style=for-the-badge&label=Build&logoColor=fff&logo=GitHub%20Actions"></a>
<a title="Discord Server" href="https://discord.gg/X63jZ36xBY"><img alt="Discord Server" src="https://img.shields.io/discord/789833418631675954?label=Discord&logo=Discord&style=for-the-badge"></a>
</p>
## Supporting
If you like my work, please consider supporting me on GitHub Sponsors, Patreon or PayPal. Thanks a lot!
<p align="center">
<a href="https://github.com/sponsors/WerWolv"><img src="https://werwolv.net/assets/github_banner.png" alt="GitHub donate button" /> </a>
<a href="https://www.patreon.com/werwolv"><img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" alt="Patreon donate button" /> </a>
<a href="https://werwolv.net/donate"><img src="https://werwolv.net/assets/paypal_banner.png" alt="PayPal donate button" /> </a>
</p>
## Features
- Featureful hex view
- Byte patching
- Patch management
- Copy bytes as feature
- Bytes
- Hex string
- C, C++, C#, Rust, Python, Java & JavaScript array
- ASCII-Art hex view
- HTML self contained div
- String and hex search
- Colorful highlighting
- Goto from start, end and current cursor position
- Custom C++-like pattern language for parsing highlighting a file's content
- Automatic loading based on MIME type
- arrays, pointers, structs, unions, enums, bitfields, using declarations, little and big endian support, conditionals and much more!
- Useful error messages, syntax highlighting and error marking
- Data importing
- Base64 files
- IPS and IPS32 patches
- Data exporting
- IPS and IPS32 patches
- Data inspector allowing interpretation of data as many different types (little and big endian)
- Huge file support with fast and efficient loading
- String search
- Copying of strings
- Copying of demangled strings
- File hashing support
- CRC16 and CRC32 with custom initial values and polynomials
- MD4, MD5
- SHA-1, SHA-224, SHA-256, SHA-384, SHA-512
- Disassembler supporting many different architectures
- ARM32 (ARM, Thumb, Cortex-M, AArch32)
- ARM64
- MIPS (MIPS32, MIPS64, MIPS32R6, Micro)
- x86 (16-bit, 32-bit, 64-bit)
- PowerPC (32-bit, 64-bit)
- SPARC
- IBM SystemZ
- xCORE
- M68K
- TMS320C64X
- M680X
- Ethereum
- Bookmarks
- Region highlighting
- Comments
- Data Analyzer
- File magic-based file parser and MIME type database
- Byte distribution graph
- Entropy graph
- Highest and avarage entropy
- Encrypted / Compressed file detection
- Helpful tools
- Itanium and MSVC demangler
- ASCII table
- Regex replacer
- Mathematical expression evaluator (Calculator)
- Hexadecimal Color picker
- Built-in cheat sheet for pattern language and Math evaluator
- Doesn't burn out your retinas when used in late-night sessions
## Screenshots
![](https://i.imgur.com/ClEsNwL.png)
![](https://i.imgur.com/xH7xJ4g.png)
![](https://i.imgur.com/fhVJYEa.png)
## Pattern Language
The custom C-like Pattern Language developed and used by ImHex is easy to read, understand and learn. A guide with all features of the langauge can be found [in the wiki](https://github.com/WerWolv/ImHex/wiki/Pattern-Language-Guide) or a simpler version in ImHex under `Help -> Pattern Language Cheat Sheet`
## Additional Files
For format patterns, includable libraries and magic files, check out the [ImHex-Patterns](https://github.com/WerWolv/ImHex-Patterns) repository. Feel free to PR your own files there as well!
## Nightly builds
See latest nightly builds on the artifacts result of the Build action [here](https://github.com/WerWolv/ImHex/actions?query=workflow%3ABuild).
NOTE: **We currently only provide nightly builds for macOS (x86_64)**
## Compiling
You need a C++20 compatible compiler such as GCC 10.2.0 to compile ImHex. Moreover, the following dependencies are needed for compiling ImHex:
- GLFW3
- libmagic, libgnurx, libtre, libintl, libiconv
- libcrypto
- capstone
- nlohmann json
- Python3
- freetype2
- Brew (macOS only)
### Windows and Linux
Find all-in-one dependency installation scripts for Arch Linux, Fedora, Debian/Ubuntu and/or MSYS2 in [dist](dist).
After all the dependencies are installed, run the following commands to build ImHex:
```sh
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j
```
---
To create a standalone zipfile on Windows, get the Python standard library (e.g. from https://github.com/python/cpython/tree/master/Lib) and place the files and folders in `lib/python3.8` next to your built executable. Don't forget to also copy the `libpython3.8.dll` and `libwinpthread-1.dll` from your mingw setup next to the executable.
On both Windows and Linux:
- Copy the files from `python_libs` in the `lib` folder next to your built executable.
- Place your magic databases in the `magic` folder next to your built executable
- Place your patterns in the `pattern` folder next to your built executable
- Place your include pattern files in the `include` folder next to your built executable
### macOS
To build ImHex on macOS, run the following commands:
```sh
brew bundle --no-lock --file dist/Brewfile
mkdir build
cd build
CC=$(brew --prefix llvm)/bin/clang CXX=$(brew --prefix llvm)/bin/clang++ PKG_CONFIG_PATH="$(brew --prefix openssl)/lib/pkgconfig":"$(brew --prefix)/lib/pkgconfig" cmake -DCMAKE_BUILD_TYPE=Release ..
make -j
```
## Credits
- Thanks a lot to ocornut for their amazing [Dear ImGui](https://github.com/ocornut/imgui) which is used for building the entire interface
- Thanks to orconut as well for their hex editor view used as base for this project.
- Thanks to BalazsJako for their incredible [ImGuiColorTextEdit](https://github.com/BalazsJako/ImGuiColorTextEdit) used for the pattern language syntax highlighting
- Thanks to AirGuanZ for their amazing [imgui-filebrowser](https://github.com/AirGuanZ/imgui-filebrowser) used for loading and saving files
- Thanks to nlohmann for their [json](https://github.com/nlohmann/json) library used for project files
- Thanks to aquynh for [capstone](https://github.com/aquynh/capstone) which is the base of the disassembly window

View File

@@ -0,0 +1,59 @@
# Adapted from the Dolphin project: https://dolphin-emu.org/
# This module can be used in two different ways.
#
# When invoked as `cmake -P PostprocessBundle.cmake`, it fixes up an
# application folder to be standalone. It bundles all required libraries from
# the system and fixes up library IDs. Any additional shared libraries, like
# plugins, that are found under Contents/MacOS/ will be made standalone as well.
#
# When called with `include(PostprocessBundle)`, it defines a helper
# function `postprocess_bundle` that sets up the command form of the
# module as a post-build step.
if(CMAKE_GENERATOR)
# Being called as include(PostprocessBundle), so define a helper function.
set(_POSTPROCESS_BUNDLE_MODULE_LOCATION "${CMAKE_CURRENT_LIST_FILE}")
function(postprocess_bundle target)
add_custom_command(TARGET ${target} POST_BUILD
COMMAND ${CMAKE_COMMAND} -DBUNDLE_PATH="$<TARGET_FILE_DIR:${target}>/../.." -DCODE_SIGN_CERTIFICATE_ID="${CODE_SIGN_CERTIFICATE_ID}"
-P "${_POSTPROCESS_BUNDLE_MODULE_LOCATION}"
)
endfunction()
return()
endif()
get_filename_component(BUNDLE_PATH "${BUNDLE_PATH}" ABSOLUTE)
message(STATUS "Fixing up application bundle: ${BUNDLE_PATH}")
# Make sure to fix up any additional shared libraries (like plugins) that are
# needed.
file(GLOB_RECURSE extra_libs "${BUNDLE_PATH}/Contents/MacOS/*.dylib")
message(STATUS "Fixing up application bundle: ${extra_dirs}")
# BundleUtilities doesn't support DYLD_FALLBACK_LIBRARY_PATH behavior, which
# makes it sometimes break on libraries that do weird things with @rpath. Specify
# equivalent search directories until https://gitlab.kitware.com/cmake/cmake/issues/16625
# is fixed and in our minimum CMake version.
set(extra_dirs "/usr/local/lib" "/lib" "/usr/lib")
# BundleUtilities is overly verbose, so disable most of its messages
function(message)
if(NOT ARGV MATCHES "^STATUS;")
_message(${ARGV})
endif()
endfunction()
include(BundleUtilities)
set(BU_CHMOD_BUNDLE_ITEMS ON)
fixup_bundle("${BUNDLE_PATH}" "${extra_libs}" "${extra_dirs}" IGNORE_ITEM "Python")
if (CODE_SIGN_CERTIFICATE_ID)
# Hack around Apple Silicon signing bugs by copying the real app, signing it and moving it back.
# IMPORTANT: DON'T USE ${CMAKE_COMMAND} -E copy_directory HERE (this follow symbolic links).
execute_process(COMMAND cp -R "${BUNDLE_PATH}" "${BUNDLE_PATH}.temp")
execute_process(COMMAND codesign --deep --force --sign "${CODE_SIGN_CERTIFICATE_ID}" "${BUNDLE_PATH}.temp")
execute_process(COMMAND ${CMAKE_COMMAND} -E remove_directory "${BUNDLE_PATH}")
execute_process(COMMAND ${CMAKE_COMMAND} -E rename "${BUNDLE_PATH}.temp" "${BUNDLE_PATH}")
endif()

View File

@@ -0,0 +1,3 @@
set (CPACK_BUNDLE_NAME "ImHex")
set (CPACK_BUNDLE_ICON "${CMAKE_SOURCE_DIR}/res/mac/AppIcon.icns" )
set (CPACK_BUNDLE_PLIST "${CMAKE_BINARY_DIR}/ImHex.app/Contents/Info.plist")

12
dist/Brewfile vendored Normal file
View File

@@ -0,0 +1,12 @@
brew "glfw3"
brew "openssl@1.1"
brew "capstone"
brew "nlohmann-json"
brew "glm"
brew "cmake"
brew "python3"
brew "freetype2"
brew "libmagic"
# TODO: Remove this when XCode version of clang will support the same level as LLVM 10
brew "llvm"

13
dist/get_deps_archlinux.sh vendored Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/env sh
pacman -S --needed \
cmake \
gcc \
glfw \
file \
openssl \
capstone \
nlohmann-json \
glm \
python3 \
freetype2

29
dist/get_deps_debian.sh vendored Executable file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/env sh
echo "As of 2020-12, Debian stable does not include g++-10, needs debian testing or unstable."
# Tested on 2020-12-09 with Docker image bitnami/minideb:unstable
# Install pkgconf (adds minimum dependencies) only if the equivalent pkf-config is not already installed.
if !which pkg-config
then
PKGCONF="pkgconf"
fi
apt install \
cmake \
g++-10 \
${PKGCONF:-} \
nlohmann-json3-dev \
libcapstone-dev \
libmagic-dev \
libglfw3-dev \
libglm-dev \
libjsoncpp-dev \
libssl-dev \
libstdc++-10-dev \
python3-dev \
libfreetype-dev
echo "Please consider this before running cmake (useful on e.g. Ubuntu 20.04):"
echo "export CXX=g++-10"

14
dist/get_deps_fedora.sh vendored Executable file
View File

@@ -0,0 +1,14 @@
#!/usr/bin/env sh
dnf install \
cmake \
gcc-c++ \
capstone-devel \
file-devel \
glfw-devel \
glm-devel \
json-devel \
mesa-libGL-devel \
openssl-devel \
python-devel \
freetype-devel

16
dist/get_deps_msys2.sh vendored Executable file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/env sh
pacman -S --needed \
mingw-w64-x86_64-gcc \
mingw-w64-x86_64-cmake \
mingw-w64-x86_64-make \
mingw-w64-x86_64-capstone \
mingw-w64-x86_64-glfw \
mingw-w64-x86_64-glm \
mingw-w64-x86_64-file \
mingw-w64-x86_64-nlohmann-json \
mingw-w64-x86_64-openssl \
mingw-w64-x86_64-polly \
mingw-w64-x86_64-python \
mingw-w64-x86_64-freetype \
mingw-w64-x86_64-dlfcn

35
external/ImGui/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,35 @@
cmake_minimum_required(VERSION 3.16)
project(imgui)
set(CMAKE_CXX_STANDARD 17)
find_package(PkgConfig REQUIRED)
find_package(Freetype REQUIRED)
pkg_search_module(GLM REQUIRED glm)
pkg_search_module(GLFW REQUIRED glfw3)
add_library(imgui
source/imgui.cpp
source/imgui_demo.cpp
source/imgui_draw.cpp
source/imgui_freetype.cpp
source/imgui_impl_glfw.cpp
source/imgui_impl_opengl3.cpp
source/imgui_widgets.cpp
source/ImGuiFileBrowser.cpp
source/TextEditor.cpp
)
add_compile_definitions(IMGUI_IMPL_OPENGL_LOADER_GLAD)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../glad ${CMAKE_CURRENT_BINARY_DIR}/external/glad)
target_include_directories(imgui PUBLIC include ${FREETYPE_INCLUDE_DIRS} ${GLFW_INCLUDE_DIRS})
target_link_directories(imgui PUBLIC ${GLM_INCLUDE_DIRS} ${GLFW_LIBRARY_DIRS})
if (WIN32)
target_link_libraries(imgui libstdc++.a libgcc.a libharfbuzz.a libfreetype.a libharfbuzz.a libgraphite2.a libpng.a libbrotlidec-static.a libbrotlicommon-static.a libz.a libbz2.a librpcrt4.a glad libglfw3.a)
elseif (UNIX)
target_link_libraries(imgui Freetype::Freetype glad glfw)
endif()

36
external/ImGui/include/imgui_freetype.h vendored Normal file
View File

@@ -0,0 +1,36 @@
// dear imgui: wrapper to use FreeType (instead of stb_truetype)
// Get latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
// Original code by @Vuhdo (Aleksei Skriabin), maintained by @ocornut
#pragma once
#include "imgui.h" // IMGUI_API, ImFontAtlas
namespace ImGuiFreeType
{
// Hinting greatly impacts visuals (and glyph sizes).
// When disabled, FreeType generates blurrier glyphs, more or less matches the stb's output.
// The Default hinting mode usually looks good, but may distort glyphs in an unusual way.
// The Light hinting mode generates fuzzier glyphs but better matches Microsoft's rasterizer.
// You can set those flags on a per font basis in ImFontConfig::RasterizerFlags.
// Use the 'extra_flags' parameter of BuildFontAtlas() to force a flag on all your fonts.
enum RasterizerFlags
{
// By default, hinting is enabled and the font's native hinter is preferred over the auto-hinter.
NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes.
NoAutoHint = 1 << 1, // Disable auto-hinter.
ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter.
LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text.
MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output.
Bold = 1 << 5, // Styling: Should we artificially embolden the font?
Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style?
Monochrome = 1 << 7 // Disable anti-aliasing. Combine this with MonoHinting for best results!
};
IMGUI_API bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags = 0);
// By default ImGuiFreeType will use IM_ALLOC()/IM_FREE().
// However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired:
IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL);
}

View File

@@ -46,6 +46,7 @@
#include <stdio.h> // sprintf, scanf
#include <stdint.h> // uint8_t, etc.
#include "helpers/utils.hpp"
#include "views/view.hpp"
@@ -75,7 +76,6 @@ struct MemoryEditor
};
// Settings
bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
bool ReadOnly; // = false // disable any editing.
int Cols; // = 16 // number of columns to display.
bool OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
@@ -93,8 +93,10 @@ struct MemoryEditor
// [Internal State]
bool ContentsWidthChanged;
size_t DataPreviewAddr;
size_t DataEditingAddr;
size_t DataPreviewAddrOld;
size_t DataPreviewAddrEnd;
size_t DataPreviewAddrEndOld;
size_t DataEditingAddr;
bool DataEditingTakeFocus;
char DataInputBuf[32];
char AddrInputBuf[32];
@@ -106,7 +108,6 @@ struct MemoryEditor
MemoryEditor()
{
// Settings
Open = true;
ReadOnly = false;
Cols = 16;
OptShowOptions = true;
@@ -181,14 +182,21 @@ struct MemoryEditor
}
// Standalone Memory Editor window
void DrawWindow(const char* title, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
void DrawWindow(const char* title, bool *p_open, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
{
Sizes s;
CalcSizes(s, mem_size, base_display_addr);
ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));
if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))
if (ImGui::Begin(title, p_open, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse))
{
if (DataPreviewAddr != DataPreviewAddrOld || DataPreviewAddrEnd != DataPreviewAddrEndOld) {
hex::Region selectionRegion = { std::min(DataPreviewAddr, DataPreviewAddrEnd), std::max(DataPreviewAddr, DataPreviewAddrEnd) - std::min(DataPreviewAddr, DataPreviewAddrEnd) };
hex::View::postEvent(hex::Events::RegionSelected, &selectionRegion);
}
DataPreviewAddrOld = DataPreviewAddr;
DataPreviewAddrEndOld = DataPreviewAddrEnd;
DrawContents(mem_data, mem_size, base_display_addr);
if (ContentsWidthChanged)
{
@@ -210,14 +218,13 @@ struct MemoryEditor
Sizes s;
CalcSizes(s, mem_size, base_display_addr);
ImGuiStyle& style = ImGui::GetStyle();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
if (mem_size == 0x00) {
constexpr const char *noDataString = "No data loaded!";
auto pos = ImGui::GetCursorScreenPos();
pos.x += (ImGui::GetWindowWidth() - (ImGui::CalcTextSize(noDataString).x)) / 2;
draw_list->AddText(pos, 0xFFFFFFFF, noDataString);
ImGui::GetWindowDrawList()->AddText(pos, 0xFFFFFFFF, noDataString);
return;
}
@@ -229,7 +236,7 @@ struct MemoryEditor
footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1;
ImGui::BeginChild("offset", ImVec2(0, s.LineHeight), false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNav);
ImGui::Text("% *c ", s.AddrDigitsCount, ' ');
ImGui::Text("%*c ", s.AddrDigitsCount, ' ');
for (int i = 0; i < Cols; i++) {
float byte_pos_x = s.PosHexStart + s.HexCellWidth * i;
if (OptMidColsCount > 0)
@@ -247,8 +254,10 @@ struct MemoryEditor
// We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
ImGuiListClipper clipper;
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
clipper.Begin(line_total_count, s.LineHeight);
clipper.Step();
const size_t visible_start_addr = clipper.DisplayStart * Cols;
@@ -256,7 +265,7 @@ struct MemoryEditor
bool data_next = false;
if (ReadOnly || DataEditingAddr >= mem_size)
if (DataEditingAddr >= mem_size)
DataEditingAddr = (size_t)-1;
if (DataPreviewAddr >= mem_size)
DataPreviewAddr = (size_t)-1;
@@ -264,14 +273,34 @@ struct MemoryEditor
DataPreviewAddrEnd = (size_t)-1;
size_t data_editing_addr_backup = DataEditingAddr;
size_t data_preview_addr_backup = DataPreviewAddr;
size_t data_editing_addr_next = (size_t)-1;
if (DataEditingAddr != (size_t)-1)
size_t data_preview_addr_next = (size_t)-1;
if (ImGui::IsWindowFocused()) {
if (DataEditingAddr != (size_t)-1)
{
// Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= (size_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; DataEditingTakeFocus = true; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)) && DataEditingAddr < mem_size - Cols) { data_editing_addr_next = DataEditingAddr + Cols; DataEditingTakeFocus = true; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)) && DataEditingAddr > 0) { data_editing_addr_next = DataEditingAddr - 1; DataEditingTakeFocus = true; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; DataEditingTakeFocus = true; }
} else if (DataPreviewAddr != -1) {
// Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)) && DataPreviewAddr >= (size_t)Cols) { data_preview_addr_next = DataPreviewAddr - Cols; DataPreviewAddr = data_preview_addr_next; if (!ImGui::GetIO().KeyShift) DataPreviewAddrEnd = DataPreviewAddr; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)) && DataPreviewAddr < mem_size - Cols) { data_preview_addr_next = DataPreviewAddr + Cols; DataPreviewAddr = data_preview_addr_next; if (!ImGui::GetIO().KeyShift) DataPreviewAddrEnd = DataPreviewAddr; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)) && DataPreviewAddr > 0) { data_preview_addr_next = DataPreviewAddr - 1; DataPreviewAddr = data_preview_addr_next; if (!ImGui::GetIO().KeyShift) DataPreviewAddrEnd = DataPreviewAddr; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)) && DataPreviewAddr < mem_size - 1) { data_preview_addr_next = DataPreviewAddr + 1; DataPreviewAddr = data_preview_addr_next; if (!ImGui::GetIO().KeyShift) DataPreviewAddrEnd = DataPreviewAddr; }
}
}
if (data_preview_addr_next != (size_t)-1 && (data_preview_addr_next / Cols) != (data_preview_addr_backup / Cols))
{
// Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= (size_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; DataEditingTakeFocus = true; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)) && DataEditingAddr < mem_size - Cols) { data_editing_addr_next = DataEditingAddr + Cols; DataEditingTakeFocus = true; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)) && DataEditingAddr > 0) { data_editing_addr_next = DataEditingAddr - 1; DataEditingTakeFocus = true; }
else if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; DataEditingTakeFocus = true; }
// Track cursor movements
const int scroll_offset = ((int)(data_preview_addr_next / Cols) - (int)(data_preview_addr_backup / Cols));
const bool scroll_desired = (scroll_offset < 0 && data_preview_addr_next < visible_start_addr + Cols * 2) || (scroll_offset > 0 && data_preview_addr_next > visible_end_addr - Cols * 2);
if (scroll_desired)
ImGui::SetScrollY(ImGui::GetScrollY() + scroll_offset * s.LineHeight);
}
if (data_editing_addr_next != (size_t)-1 && (data_editing_addr_next / Cols) != (data_editing_addr_backup / Cols))
{
@@ -413,24 +442,18 @@ struct MemoryEditor
else
ImGui::Text(format_byte_space, b);
}
if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && !ImGui::GetIO().KeyShift)
if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && !ImGui::GetIO().KeyShift)
{
if (ImGui::IsMouseDoubleClicked(0)) {
if (!ReadOnly && ImGui::IsMouseDoubleClicked(0)) {
DataEditingTakeFocus = true;
data_editing_addr_next = addr;
}
DataPreviewAddr = addr;
DataPreviewAddrEnd = addr;
hex::View::postEvent(hex::Events::ByteSelected, &DataPreviewAddr);
}
if (!ReadOnly && ImGui::IsItemHovered() && ((ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyShift) || ImGui::IsMouseDragging(0))) {
if (ImGui::IsItemHovered() && ((ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyShift) || ImGui::IsMouseDragging(0))) {
DataPreviewAddrEnd = addr;
size_t dataPreviewStart = std::min(DataPreviewAddr, DataPreviewAddrEnd);
hex::View::postEvent(hex::Events::ByteSelected, &dataPreviewStart);
}
}
}
@@ -479,9 +502,9 @@ struct MemoryEditor
ImGui::PopID();
if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && !ImGui::GetIO().KeyShift)
if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && !ImGui::GetIO().KeyShift)
{
if (ImGui::IsMouseDoubleClicked(0)) {
if (!ReadOnly && ImGui::IsMouseDoubleClicked(0)) {
DataEditingTakeFocus = true;
data_editing_addr_next = addr;
}
@@ -490,7 +513,7 @@ struct MemoryEditor
DataPreviewAddrEnd = addr;
}
if (!ReadOnly && ImGui::IsItemHovered() && ((ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyShift) || ImGui::IsMouseDragging(0))) {
if (ImGui::IsItemHovered() && ((ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyShift) || ImGui::IsMouseDragging(0))) {
DataPreviewAddrEnd = addr;
}
@@ -510,7 +533,7 @@ struct MemoryEditor
}
else if (data_editing_addr_next != (size_t)-1)
{
DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
DataEditingAddr = DataPreviewAddr = DataPreviewAddrEnd = data_editing_addr_next;
}
if (OptShowOptions)
@@ -528,13 +551,14 @@ struct MemoryEditor
IM_UNUSED(mem_data);
ImGuiStyle& style = ImGui::GetStyle();
const char* format_range = OptUpperCaseHex ? "Range %0*" _PRISizeT "X..%0*" _PRISizeT "X" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x";
const char* format_selection = OptUpperCaseHex ? "Selection %0*" _PRISizeT "X..%0*" _PRISizeT "X (%ld %s)" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x (%ld %s)";
// Options menu
if (ImGui::Button("Options"))
ImGui::OpenPopup("options");
if (ImGui::BeginPopup("options")) {
ImGui::PushItemWidth(56);
ImGui::PushItemWidth(ImGui::CalcTextSize("00 cols").x * 1.1f);
if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; if (Cols < 1) Cols = 1; }
ImGui::PopItemWidth();
ImGui::Checkbox("Show HexII", &OptShowHexII);
@@ -547,6 +571,17 @@ struct MemoryEditor
ImGui::SameLine();
ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
if (DataPreviewAddr != (size_t)-1 && DataPreviewAddrEnd != (size_t)-1) {
ImGui::SameLine();
ImGui::Spacing();
ImGui::SameLine();
auto selectionStart = std::min(DataPreviewAddr, DataPreviewAddrEnd);
auto selectionEnd = std::max(DataPreviewAddr, DataPreviewAddrEnd);
size_t regionSize = (selectionEnd - selectionStart) + 1;
ImGui::Text(format_selection, s.AddrDigitsCount, selectionStart, s.AddrDigitsCount, selectionEnd, regionSize, regionSize == 1 ? "byte" : "bytes");
}
if (GotoAddr != (size_t)-1)
{

View File

@@ -43,7 +43,6 @@ namespace imgui_addons
selected_ext_idx = 0;
ext_box_width = -1.0f;
col_width = 280.0f;
min_size = ImVec2(500,300);
invfile_modal_id = "Invalid File!";
repfile_modal_id = "Replace File?";
@@ -109,11 +108,12 @@ namespace imgui_addons
bool ImGuiFileBrowser::showFileDialog(const std::string& label, const DialogMode mode, const ImVec2& sz_xy, const std::string& valid_types)
{
dialog_mode = mode;
ImGuiIO& io = ImGui::GetIO();
max_size.x = io.DisplaySize.x;
max_size.y = io.DisplaySize.y;
max_size = ImVec2( io.DisplaySize.x, io.DisplaySize.y);
min_size = ImVec2(0.5f * io.DisplaySize.x, 0.5f * io.DisplaySize.y);
ImGui::SetNextWindowSizeConstraints(min_size, max_size);
ImGui::SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f));
ImGui::SetNextWindowSize(ImVec2(std::max(sz_xy.x, min_size.x), std::max(sz_xy.y, min_size.y)), ImGuiCond_Appearing);

View File

@@ -1127,7 +1127,7 @@ void TextEditor::Render(const char* aTitle, const ImVec2& aSize, bool aBorder)
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(mPalette[(int)PaletteIndex::Background]));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
if (!mIgnoreImGuiChild)
ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NoMove);
ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove);
if (mHandleKeyboardInputs)
{

680
external/ImGui/source/imgui_freetype.cpp vendored Normal file
View File

@@ -0,0 +1,680 @@
// dear imgui: wrapper to use FreeType (instead of stb_truetype)
// Get latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
// Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained and v0.60+ by @ocornut.
// Changelog:
// - v0.50: (2017/08/16) imported from https://github.com/Vuhdo/imgui_freetype into http://www.github.com/ocornut/imgui_club, updated for latest changes in ImFontAtlas, minor tweaks.
// - v0.51: (2017/08/26) cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
// - v0.52: (2017/09/26) fixes for imgui internal changes.
// - v0.53: (2017/10/22) minor inconsequential change to match change in master (removed an unnecessary statement).
// - v0.54: (2018/01/22) fix for addition of ImFontAtlas::TexUvscale member.
// - v0.55: (2018/02/04) moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
// - v0.56: (2018/06/08) added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
// - v0.60: (2019/01/10) re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding.
// - v0.61: (2019/01/15) added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
// - v0.62: (2019/02/09) added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
// Gamma Correct Blending:
// FreeType assumes blending in linear space rather than gamma space.
// See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
// For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
// The default imgui styles will be impacted by this change (alpha values will need tweaking).
// FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer).
#include "imgui_freetype.h"
#include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
#include <stdint.h>
#include <ft2build.h>
#include FT_FREETYPE_H // <freetype/freetype.h>
#include FT_MODULE_H // <freetype/ftmodapi.h>
#include FT_GLYPH_H // <freetype/ftglyph.h>
#include FT_SYNTHESIS_H // <freetype/ftsynth.h>
#ifdef _MSC_VER
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#endif
namespace
{
// Glyph metrics:
// --------------
//
// xmin xmax
// | |
// |<-------- width -------->|
// | |
// | +-------------------------+----------------- ymax
// | | ggggggggg ggggg | ^ ^
// | | g:::::::::ggg::::g | | |
// | | g:::::::::::::::::g | | |
// | | g::::::ggggg::::::gg | | |
// | | g:::::g g:::::g | | |
// offsetX -|-------->| g:::::g g:::::g | offsetY |
// | | g:::::g g:::::g | | |
// | | g::::::g g:::::g | | |
// | | g:::::::ggggg:::::g | | |
// | | g::::::::::::::::g | | height
// | | gg::::::::::::::g | | |
// baseline ---*---------|---- gggggggg::::::g-----*-------- |
// / | | g:::::g | |
// origin | | gggggg g:::::g | |
// | | g:::::gg gg:::::g | |
// | | g::::::ggg:::::::g | |
// | | gg:::::::::::::g | |
// | | ggg::::::ggg | |
// | | gggggg | v
// | +-------------------------+----------------- ymin
// | |
// |------------- advanceX ----------->|
/// A structure that describe a glyph.
struct GlyphInfo
{
int Width; // Glyph's width in pixels.
int Height; // Glyph's height in pixels.
FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph.
FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0.
float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0.
};
// Font parameters and metrics.
struct FontInfo
{
uint32_t PixelHeight; // Size this font was generated with.
float Ascender; // The pixel extents above the baseline in pixels (typically positive).
float Descender; // The extents below the baseline in pixels (typically negative).
float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate.
float LineGap; // The spacing in pixels between one row's descent and the next row's ascent.
float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
};
// FreeType glyph rasterizer.
// NB: No ctor/dtor, explicitly call Init()/Shutdown()
struct FreeTypeFont
{
bool InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime.
void CloseFont();
void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size
const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
void BlitGlyph(const FT_Bitmap* ft_bitmap, uint8_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = NULL);
~FreeTypeFont() { CloseFont(); }
// [Internals]
FontInfo Info; // Font descriptor of the current font.
FT_Face Face;
unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
FT_Int32 LoadFlags;
FT_Render_Mode RenderMode;
};
// From SDL_ttf: Handy routines for converting from fixed point
#define FT_CEIL(X) (((X + 63) & -64) / 64)
bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_user_flags)
{
FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)cfg.FontData, (uint32_t)cfg.FontDataSize, (uint32_t)cfg.FontNo, &Face);
if (error != 0)
return false;
error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE);
if (error != 0)
return false;
memset(&Info, 0, sizeof(Info));
SetPixelHeight((uint32_t)cfg.SizePixels);
// Convert to FreeType flags (NB: Bold and Oblique are processed separately)
UserFlags = cfg.RasterizerFlags | extra_user_flags;
LoadFlags = FT_LOAD_NO_BITMAP;
if (UserFlags & ImGuiFreeType::NoHinting)
LoadFlags |= FT_LOAD_NO_HINTING;
if (UserFlags & ImGuiFreeType::NoAutoHint)
LoadFlags |= FT_LOAD_NO_AUTOHINT;
if (UserFlags & ImGuiFreeType::ForceAutoHint)
LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
if (UserFlags & ImGuiFreeType::LightHinting)
LoadFlags |= FT_LOAD_TARGET_LIGHT;
else if (UserFlags & ImGuiFreeType::MonoHinting)
LoadFlags |= FT_LOAD_TARGET_MONO;
else
LoadFlags |= FT_LOAD_TARGET_NORMAL;
if (UserFlags & ImGuiFreeType::Monochrome)
RenderMode = FT_RENDER_MODE_MONO;
else
RenderMode = FT_RENDER_MODE_NORMAL;
return true;
}
void FreeTypeFont::CloseFont()
{
if (Face)
{
FT_Done_Face(Face);
Face = NULL;
}
}
void FreeTypeFont::SetPixelHeight(int pixel_height)
{
// Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
// is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me.
// NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result.
FT_Size_RequestRec req;
req.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
req.width = 0;
req.height = (uint32_t)pixel_height * 64;
req.horiResolution = 0;
req.vertResolution = 0;
FT_Request_Size(Face, &req);
// Update font info
FT_Size_Metrics metrics = Face->size->metrics;
Info.PixelHeight = (uint32_t)pixel_height;
Info.Ascender = (float)FT_CEIL(metrics.ascender);
Info.Descender = (float)FT_CEIL(metrics.descender);
Info.LineSpacing = (float)FT_CEIL(metrics.height);
Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender);
Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance);
}
const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint)
{
uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint);
if (glyph_index == 0)
return NULL;
FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags);
if (error)
return NULL;
// Need an outline for this to work
FT_GlyphSlot slot = Face->glyph;
IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE);
// Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
if (UserFlags & ImGuiFreeType::Bold)
FT_GlyphSlot_Embolden(slot);
if (UserFlags & ImGuiFreeType::Oblique)
{
FT_GlyphSlot_Oblique(slot);
//FT_BBox bbox;
//FT_Outline_Get_BBox(&slot->outline, &bbox);
//slot->metrics.width = bbox.xMax - bbox.xMin;
//slot->metrics.height = bbox.yMax - bbox.yMin;
}
return &slot->metrics;
}
const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info)
{
FT_GlyphSlot slot = Face->glyph;
FT_Error error = FT_Render_Glyph(slot, RenderMode);
if (error != 0)
return NULL;
FT_Bitmap* ft_bitmap = &Face->glyph->bitmap;
out_glyph_info->Width = (int)ft_bitmap->width;
out_glyph_info->Height = (int)ft_bitmap->rows;
out_glyph_info->OffsetX = Face->glyph->bitmap_left;
out_glyph_info->OffsetY = -Face->glyph->bitmap_top;
out_glyph_info->AdvanceX = (float)FT_CEIL(slot->advance.x);
return ft_bitmap;
}
void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint8_t* dst, uint32_t dst_pitch, unsigned char* multiply_table)
{
IM_ASSERT(ft_bitmap != NULL);
const uint32_t w = ft_bitmap->width;
const uint32_t h = ft_bitmap->rows;
const uint8_t* src = ft_bitmap->buffer;
const uint32_t src_pitch = ft_bitmap->pitch;
switch (ft_bitmap->pixel_mode)
{
case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
{
if (multiply_table == NULL)
{
for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
memcpy(dst, src, w);
}
else
{
for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
for (uint32_t x = 0; x < w; x++)
dst[x] = multiply_table[src[x]];
}
break;
}
case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
{
uint8_t color0 = multiply_table ? multiply_table[0] : 0;
uint8_t color1 = multiply_table ? multiply_table[255] : 255;
for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
{
uint8_t bits = 0;
const uint8_t* bits_ptr = src;
for (uint32_t x = 0; x < w; x++, bits <<= 1)
{
if ((x & 7) == 0)
bits = *bits_ptr++;
dst[x] = (bits & 0x80) ? color1 : color0;
}
}
break;
}
default:
IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
}
}
}
#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
#define STBRP_STATIC
#define STB_RECT_PACK_IMPLEMENTATION
#endif
#ifdef IMGUI_STB_RECT_PACK_FILENAME
#include IMGUI_STB_RECT_PACK_FILENAME
#else
#include "imstb_rectpack.h"
#endif
#endif
struct ImFontBuildSrcGlyphFT
{
GlyphInfo Info;
uint32_t Codepoint;
unsigned char* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array
};
struct ImFontBuildSrcDataFT
{
FreeTypeFont Font;
stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
int GlyphsHighest; // Highest requested codepoint
int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
ImVector<ImFontBuildSrcGlyphFT> GlyphsList;
};
// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
struct ImFontBuildDstDataFT
{
int SrcCount; // Number of source fonts targeting this destination font.
int GlyphsHighest;
int GlyphsCount;
ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
};
bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags)
{
IM_ASSERT(atlas->ConfigData.Size > 0);
ImFontAtlasBuildInit(atlas);
// Clear atlas
atlas->TexID = (ImTextureID)NULL;
atlas->TexWidth = atlas->TexHeight = 0;
atlas->TexUvScale = ImVec2(0.0f, 0.0f);
atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
atlas->ClearTexData();
// Temporary storage for building
ImVector<ImFontBuildSrcDataFT> src_tmp_array;
ImVector<ImFontBuildDstDataFT> dst_tmp_array;
src_tmp_array.resize(atlas->ConfigData.Size);
dst_tmp_array.resize(atlas->Fonts.Size);
memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
// 1. Initialize font loading structure, check font data validity
for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
ImFontConfig& cfg = atlas->ConfigData[src_i];
FreeTypeFont& font_face = src_tmp.Font;
IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
// Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
src_tmp.DstIndex = -1;
for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
if (cfg.DstFont == atlas->Fonts[output_i])
src_tmp.DstIndex = output_i;
IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
if (src_tmp.DstIndex == -1)
return false;
// Load font
if (!font_face.InitFont(ft_library, cfg, extra_flags))
return false;
// Measure highest codepoints
ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
dst_tmp.SrcCount++;
dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
}
// 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.
int total_glyphs_count = 0;
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
if (dst_tmp.GlyphsSet.Storage.empty())
dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++)
{
if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite)
continue;
uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..)
if (glyph_index == 0)
continue;
// Add to avail set/counters
src_tmp.GlyphsCount++;
dst_tmp.GlyphsCount++;
src_tmp.GlyphsSet.SetBit(codepoint);
dst_tmp.GlyphsSet.SetBit(codepoint);
total_glyphs_count++;
}
}
// 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32));
const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin();
const ImU32* it_end = src_tmp.GlyphsSet.Storage.end();
for (const ImU32* it = it_begin; it < it_end; it++)
if (ImU32 entries_32 = *it)
for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
if (entries_32 & ((ImU32)1 << bit_n))
{
ImFontBuildSrcGlyphFT src_glyph;
memset(&src_glyph, 0, sizeof(src_glyph));
src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n);
//src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it..
src_tmp.GlyphsList.push_back(src_glyph);
}
src_tmp.GlyphsSet.Clear();
IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
}
for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
dst_tmp_array[dst_i].GlyphsSet.Clear();
dst_tmp_array.clear();
// Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
// (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
ImVector<stbrp_rect> buf_rects;
buf_rects.resize(total_glyphs_count);
memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
// Allocate temporary rasterization data buffers.
// We could not find a way to retrieve accurate glyph size without rendering them.
// (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform)
// We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't find the temporary allocations.
const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024;
int buf_bitmap_current_used_bytes = 0;
ImVector<unsigned char*> buf_bitmap_buffers;
buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
// 4. Gather glyphs sizes so we can pack them in our virtual canvas.
// 8. Render/rasterize font characters into the texture
int total_surface = 0;
int buf_rects_out_n = 0;
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
ImFontConfig& cfg = atlas->ConfigData[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
src_tmp.Rects = &buf_rects[buf_rects_out_n];
buf_rects_out_n += src_tmp.GlyphsCount;
// Compute multiply table if requested
const bool multiply_enabled = (cfg.RasterizerMultiply != 1.0f);
unsigned char multiply_table[256];
if (multiply_enabled)
ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
// Gather the sizes of all rectangles we will need to pack
const int padding = atlas->TexGlyphPadding;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
{
ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint);
if (metrics == NULL)
continue;
// Render glyph into a bitmap (currently held by FreeType)
const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info);
IM_ASSERT(ft_bitmap);
// Allocate new temporary chunk if needed
const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height;
if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE)
{
buf_bitmap_current_used_bytes = 0;
buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
}
// Blit rasterized pixels to our temporary buffer and keep a pointer to it.
src_glyph.BitmapData = buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes;
buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width * 1, multiply_enabled ? multiply_table : NULL);
src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + padding);
src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + padding);
total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
}
}
// We need a width for the skyline algorithm, any width!
// The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
// User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
atlas->TexHeight = 0;
if (atlas->TexDesiredWidth > 0)
atlas->TexWidth = atlas->TexDesiredWidth;
else
atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
// 5. Start packing
// Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
const int TEX_HEIGHT_MAX = 1024 * 32;
const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding;
ImVector<stbrp_node> pack_nodes;
pack_nodes.resize(num_nodes_for_packing_algorithm);
stbrp_context pack_context;
stbrp_init_target(&pack_context, atlas->TexWidth, TEX_HEIGHT_MAX, pack_nodes.Data, pack_nodes.Size);
ImFontAtlasBuildPackCustomRects(atlas, &pack_context);
// 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount);
// Extend texture height and mark missing glyphs as non-packed so we won't render them.
// FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
if (src_tmp.Rects[glyph_i].was_packed)
atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
}
// 7. Allocate texture
atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight);
memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
// 8. Copy rasterized font characters back into the main texture
// 9. Setup ImFont and glyphs for runtime
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
// When merging fonts with MergeMode=true:
// - We can have multiple input fonts writing into a same destination font.
// - dst_font->ConfigData is != from cfg which is our source configuration.
ImFontConfig& cfg = atlas->ConfigData[src_i];
ImFont* dst_font = cfg.DstFont;
const float ascent = src_tmp.Font.Info.Ascender;
const float descent = src_tmp.Font.Info.Descender;
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float font_off_x = cfg.GlyphOffset.x;
const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
const int padding = atlas->TexGlyphPadding;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
{
ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
stbrp_rect& pack_rect = src_tmp.Rects[glyph_i];
IM_ASSERT(pack_rect.was_packed);
if (pack_rect.w == 0 && pack_rect.h == 0)
continue;
GlyphInfo& info = src_glyph.Info;
IM_ASSERT(info.Width + padding <= pack_rect.w);
IM_ASSERT(info.Height + padding <= pack_rect.h);
const int tx = pack_rect.x + padding;
const int ty = pack_rect.y + padding;
// Blit from temporary buffer to final texture
size_t blit_src_stride = (size_t)src_glyph.Info.Width;
size_t blit_dst_stride = (size_t)atlas->TexWidth;
unsigned char* blit_src = src_glyph.BitmapData;
unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx;
for (int y = info.Height; y > 0; y--, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
memcpy(blit_dst, blit_src, blit_src_stride);
// Register glyph
float x0 = info.OffsetX + font_off_x;
float y0 = info.OffsetY + font_off_y;
float x1 = x0 + info.Width;
float y1 = y0 + info.Height;
float u0 = (tx) / (float)atlas->TexWidth;
float v0 = (ty) / (float)atlas->TexHeight;
float u1 = (tx + info.Width) / (float)atlas->TexWidth;
float v1 = (ty + info.Height) / (float)atlas->TexHeight;
dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX);
}
src_tmp.Rects = NULL;
}
// Cleanup
for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++)
IM_FREE(buf_bitmap_buffers[buf_i]);
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
src_tmp_array[src_i].~ImFontBuildSrcDataFT();
ImFontAtlasBuildFinish(atlas);
return true;
}
// Default memory allocators
static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
// Current memory allocators
static void* (*GImFreeTypeAllocFunc)(size_t size, void* user_data) = ImFreeTypeDefaultAllocFunc;
static void (*GImFreeTypeFreeFunc)(void* ptr, void* user_data) = ImFreeTypeDefaultFreeFunc;
static void* GImFreeTypeAllocatorUserData = NULL;
// FreeType memory allocation callbacks
static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
{
return GImFreeTypeAllocFunc((size_t)size, GImFreeTypeAllocatorUserData);
}
static void FreeType_Free(FT_Memory /*memory*/, void* block)
{
GImFreeTypeFreeFunc(block, GImFreeTypeAllocatorUserData);
}
static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
{
// Implement realloc() as we don't ask user to provide it.
if (block == NULL)
return GImFreeTypeAllocFunc((size_t)new_size, GImFreeTypeAllocatorUserData);
if (new_size == 0)
{
GImFreeTypeFreeFunc(block, GImFreeTypeAllocatorUserData);
return NULL;
}
if (new_size > cur_size)
{
void* new_block = GImFreeTypeAllocFunc((size_t)new_size, GImFreeTypeAllocatorUserData);
memcpy(new_block, block, (size_t)cur_size);
GImFreeTypeFreeFunc(block, GImFreeTypeAllocatorUserData);
return new_block;
}
return block;
}
bool ImGuiFreeType::BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags)
{
// FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
FT_MemoryRec_ memory_rec = {};
memory_rec.user = NULL;
memory_rec.alloc = &FreeType_Alloc;
memory_rec.free = &FreeType_Free;
memory_rec.realloc = &FreeType_Realloc;
// https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
FT_Library ft_library;
FT_Error error = FT_New_Library(&memory_rec, &ft_library);
if (error != 0)
return false;
// If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
FT_Add_Default_Modules(ft_library);
bool ret = ImFontAtlasBuildWithFreeType(ft_library, atlas, extra_flags);
FT_Done_Library(ft_library);
return ret;
}
void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImFreeTypeAllocFunc = alloc_func;
GImFreeTypeFreeFunc = free_func;
GImFreeTypeAllocatorUserData = user_data;
}

20
external/glad/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,20 @@
cmake_minimum_required(VERSION 3.16)
project(glad)
set(CMAKE_CXX_STANDARD 17)
if (WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libstdc++ -static-libgcc -static")
endif()
add_library(glad
source/glad.c
)
target_include_directories(glad PUBLIC include)
if (WIN32)
target_link_libraries(glad PRIVATE libdl.a)
else()
target_link_libraries(glad PRIVATE dl)
endif()

17
external/llvm/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.16)
project(LLVMDemangle)
set(CMAKE_CXX_STANDARD 17)
if (WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libstdc++ -static-libgcc -static")
endif()
add_library(LLVMDemangle
Demangle/Demangle.cpp
Demangle/ItaniumDemangle.cpp
Demangle/MicrosoftDemangle.cpp
Demangle/MicrosoftDemangleNodes.cpp
)
target_include_directories(LLVMDemangle PUBLIC include)

36
external/llvm/Demangle/Demangle.cpp vendored Normal file
View File

@@ -0,0 +1,36 @@
//===-- Demangle.cpp - Common demangling functions ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file This file contains definitions of common demangling functions.
///
//===----------------------------------------------------------------------===//
#include "llvm/Demangle/Demangle.h"
#include <cstdlib>
static bool isItaniumEncoding(const std::string &MangledName) {
size_t Pos = MangledName.find_first_not_of('_');
// A valid Itanium encoding requires 1-4 leading underscores, followed by 'Z'.
return Pos > 0 && Pos <= 4 && MangledName[Pos] == 'Z';
}
std::string llvm::demangle(const std::string &MangledName) {
char *Demangled;
if (isItaniumEncoding(MangledName))
Demangled = itaniumDemangle(MangledName.c_str(), nullptr, nullptr, nullptr);
else
Demangled = microsoftDemangle(MangledName.c_str(), nullptr, nullptr,
nullptr, nullptr);
if (!Demangled)
return MangledName;
std::string Ret = Demangled;
free(Demangled);
return Ret;
}

View File

@@ -0,0 +1,577 @@
//===------------------------- ItaniumDemangle.cpp ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// FIXME: (possibly) incomplete list of features that clang mangles that this
// file does not yet support:
// - C++ modules TS
#include "llvm/Demangle/Demangle.h"
#include "llvm/Demangle/ItaniumDemangle.h"
#include <cassert>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <numeric>
#include <utility>
#include <vector>
using namespace llvm;
using namespace llvm::itanium_demangle;
constexpr const char *itanium_demangle::FloatData<float>::spec;
constexpr const char *itanium_demangle::FloatData<double>::spec;
constexpr const char *itanium_demangle::FloatData<long double>::spec;
// <discriminator> := _ <non-negative number> # when number < 10
// := __ <non-negative number> _ # when number >= 10
// extension := decimal-digit+ # at the end of string
const char *itanium_demangle::parse_discriminator(const char *first,
const char *last) {
// parse but ignore discriminator
if (first != last) {
if (*first == '_') {
const char *t1 = first + 1;
if (t1 != last) {
if (std::isdigit(*t1))
first = t1 + 1;
else if (*t1 == '_') {
for (++t1; t1 != last && std::isdigit(*t1); ++t1)
;
if (t1 != last && *t1 == '_')
first = t1 + 1;
}
}
} else if (std::isdigit(*first)) {
const char *t1 = first + 1;
for (; t1 != last && std::isdigit(*t1); ++t1)
;
if (t1 == last)
first = last;
}
}
return first;
}
#ifndef NDEBUG
namespace {
struct DumpVisitor {
unsigned Depth = 0;
bool PendingNewline = false;
template<typename NodeT> static constexpr bool wantsNewline(const NodeT *) {
return true;
}
static bool wantsNewline(NodeArray A) { return !A.empty(); }
static constexpr bool wantsNewline(...) { return false; }
template<typename ...Ts> static bool anyWantNewline(Ts ...Vs) {
for (bool B : {wantsNewline(Vs)...})
if (B)
return true;
return false;
}
void printStr(const char *S) { fprintf(stderr, "%s", S); }
void print(StringView SV) {
fprintf(stderr, "\"%.*s\"", (int)SV.size(), SV.begin());
}
void print(const Node *N) {
if (N)
N->visit(std::ref(*this));
else
printStr("<null>");
}
void print(NodeArray A) {
++Depth;
printStr("{");
bool First = true;
for (const Node *N : A) {
if (First)
print(N);
else
printWithComma(N);
First = false;
}
printStr("}");
--Depth;
}
// Overload used when T is exactly 'bool', not merely convertible to 'bool'.
void print(bool B) { printStr(B ? "true" : "false"); }
template <class T> std::enable_if_t<std::is_unsigned<T>::value> print(T N) {
fprintf(stderr, "%llu", (unsigned long long)N);
}
template <class T> std::enable_if_t<std::is_signed<T>::value> print(T N) {
fprintf(stderr, "%lld", (long long)N);
}
void print(ReferenceKind RK) {
switch (RK) {
case ReferenceKind::LValue:
return printStr("ReferenceKind::LValue");
case ReferenceKind::RValue:
return printStr("ReferenceKind::RValue");
}
}
void print(FunctionRefQual RQ) {
switch (RQ) {
case FunctionRefQual::FrefQualNone:
return printStr("FunctionRefQual::FrefQualNone");
case FunctionRefQual::FrefQualLValue:
return printStr("FunctionRefQual::FrefQualLValue");
case FunctionRefQual::FrefQualRValue:
return printStr("FunctionRefQual::FrefQualRValue");
}
}
void print(Qualifiers Qs) {
if (!Qs) return printStr("QualNone");
struct QualName { Qualifiers Q; const char *Name; } Names[] = {
{QualConst, "QualConst"},
{QualVolatile, "QualVolatile"},
{QualRestrict, "QualRestrict"},
};
for (QualName Name : Names) {
if (Qs & Name.Q) {
printStr(Name.Name);
Qs = Qualifiers(Qs & ~Name.Q);
if (Qs) printStr(" | ");
}
}
}
void print(SpecialSubKind SSK) {
switch (SSK) {
case SpecialSubKind::allocator:
return printStr("SpecialSubKind::allocator");
case SpecialSubKind::basic_string:
return printStr("SpecialSubKind::basic_string");
case SpecialSubKind::string:
return printStr("SpecialSubKind::string");
case SpecialSubKind::istream:
return printStr("SpecialSubKind::istream");
case SpecialSubKind::ostream:
return printStr("SpecialSubKind::ostream");
case SpecialSubKind::iostream:
return printStr("SpecialSubKind::iostream");
}
}
void print(TemplateParamKind TPK) {
switch (TPK) {
case TemplateParamKind::Type:
return printStr("TemplateParamKind::Type");
case TemplateParamKind::NonType:
return printStr("TemplateParamKind::NonType");
case TemplateParamKind::Template:
return printStr("TemplateParamKind::Template");
}
}
void newLine() {
printStr("\n");
for (unsigned I = 0; I != Depth; ++I)
printStr(" ");
PendingNewline = false;
}
template<typename T> void printWithPendingNewline(T V) {
print(V);
if (wantsNewline(V))
PendingNewline = true;
}
template<typename T> void printWithComma(T V) {
if (PendingNewline || wantsNewline(V)) {
printStr(",");
newLine();
} else {
printStr(", ");
}
printWithPendingNewline(V);
}
struct CtorArgPrinter {
DumpVisitor &Visitor;
template<typename T, typename ...Rest> void operator()(T V, Rest ...Vs) {
if (Visitor.anyWantNewline(V, Vs...))
Visitor.newLine();
Visitor.printWithPendingNewline(V);
int PrintInOrder[] = { (Visitor.printWithComma(Vs), 0)..., 0 };
(void)PrintInOrder;
}
};
template<typename NodeT> void operator()(const NodeT *Node) {
Depth += 2;
fprintf(stderr, "%s(", itanium_demangle::NodeKind<NodeT>::name());
Node->match(CtorArgPrinter{*this});
fprintf(stderr, ")");
Depth -= 2;
}
void operator()(const ForwardTemplateReference *Node) {
Depth += 2;
fprintf(stderr, "ForwardTemplateReference(");
if (Node->Ref && !Node->Printing) {
Node->Printing = true;
CtorArgPrinter{*this}(Node->Ref);
Node->Printing = false;
} else {
CtorArgPrinter{*this}(Node->Index);
}
fprintf(stderr, ")");
Depth -= 2;
}
};
}
void itanium_demangle::Node::dump() const {
DumpVisitor V;
visit(std::ref(V));
V.newLine();
}
#endif
namespace {
class BumpPointerAllocator {
struct BlockMeta {
BlockMeta* Next;
size_t Current;
};
static constexpr size_t AllocSize = 4096;
static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
alignas(long double) char InitialBuffer[AllocSize];
BlockMeta* BlockList = nullptr;
void grow() {
char* NewMeta = static_cast<char *>(std::malloc(AllocSize));
if (NewMeta == nullptr)
std::terminate();
BlockList = new (NewMeta) BlockMeta{BlockList, 0};
}
void* allocateMassive(size_t NBytes) {
NBytes += sizeof(BlockMeta);
BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(std::malloc(NBytes));
if (NewMeta == nullptr)
std::terminate();
BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
return static_cast<void*>(NewMeta + 1);
}
public:
BumpPointerAllocator()
: BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
void* allocate(size_t N) {
N = (N + 15u) & ~15u;
if (N + BlockList->Current >= UsableAllocSize) {
if (N > UsableAllocSize)
return allocateMassive(N);
grow();
}
BlockList->Current += N;
return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
BlockList->Current - N);
}
void reset() {
while (BlockList) {
BlockMeta* Tmp = BlockList;
BlockList = BlockList->Next;
if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
std::free(Tmp);
}
BlockList = new (InitialBuffer) BlockMeta{nullptr, 0};
}
~BumpPointerAllocator() { reset(); }
};
class DefaultAllocator {
BumpPointerAllocator Alloc;
public:
void reset() { Alloc.reset(); }
template<typename T, typename ...Args> T *makeNode(Args &&...args) {
return new (Alloc.allocate(sizeof(T)))
T(std::forward<Args>(args)...);
}
void *allocateNodeArray(size_t sz) {
return Alloc.allocate(sizeof(Node *) * sz);
}
};
} // unnamed namespace
//===----------------------------------------------------------------------===//
// Code beyond this point should not be synchronized with libc++abi.
//===----------------------------------------------------------------------===//
using Demangler = itanium_demangle::ManglingParser<DefaultAllocator>;
char *llvm::itaniumDemangle(const char *MangledName, char *Buf,
size_t *N, int *Status) {
if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
if (Status)
*Status = demangle_invalid_args;
return nullptr;
}
int InternalStatus = demangle_success;
Demangler Parser(MangledName, MangledName + std::strlen(MangledName));
OutputStream S;
Node *AST = Parser.parse();
if (AST == nullptr)
InternalStatus = demangle_invalid_mangled_name;
else if (!initializeOutputStream(Buf, N, S, 1024))
InternalStatus = demangle_memory_alloc_failure;
else {
assert(Parser.ForwardTemplateRefs.empty());
AST->print(S);
S += '\0';
if (N != nullptr)
*N = S.getCurrentPosition();
Buf = S.getBuffer();
}
if (Status)
*Status = InternalStatus;
return InternalStatus == demangle_success ? Buf : nullptr;
}
ItaniumPartialDemangler::ItaniumPartialDemangler()
: RootNode(nullptr), Context(new Demangler{nullptr, nullptr}) {}
ItaniumPartialDemangler::~ItaniumPartialDemangler() {
delete static_cast<Demangler *>(Context);
}
ItaniumPartialDemangler::ItaniumPartialDemangler(
ItaniumPartialDemangler &&Other)
: RootNode(Other.RootNode), Context(Other.Context) {
Other.Context = Other.RootNode = nullptr;
}
ItaniumPartialDemangler &ItaniumPartialDemangler::
operator=(ItaniumPartialDemangler &&Other) {
std::swap(RootNode, Other.RootNode);
std::swap(Context, Other.Context);
return *this;
}
// Demangle MangledName into an AST, storing it into this->RootNode.
bool ItaniumPartialDemangler::partialDemangle(const char *MangledName) {
Demangler *Parser = static_cast<Demangler *>(Context);
size_t Len = std::strlen(MangledName);
Parser->reset(MangledName, MangledName + Len);
RootNode = Parser->parse();
return RootNode == nullptr;
}
static char *printNode(const Node *RootNode, char *Buf, size_t *N) {
OutputStream S;
if (!initializeOutputStream(Buf, N, S, 128))
return nullptr;
RootNode->print(S);
S += '\0';
if (N != nullptr)
*N = S.getCurrentPosition();
return S.getBuffer();
}
char *ItaniumPartialDemangler::getFunctionBaseName(char *Buf, size_t *N) const {
if (!isFunction())
return nullptr;
const Node *Name = static_cast<const FunctionEncoding *>(RootNode)->getName();
while (true) {
switch (Name->getKind()) {
case Node::KAbiTagAttr:
Name = static_cast<const AbiTagAttr *>(Name)->Base;
continue;
case Node::KStdQualifiedName:
Name = static_cast<const StdQualifiedName *>(Name)->Child;
continue;
case Node::KNestedName:
Name = static_cast<const NestedName *>(Name)->Name;
continue;
case Node::KLocalName:
Name = static_cast<const LocalName *>(Name)->Entity;
continue;
case Node::KNameWithTemplateArgs:
Name = static_cast<const NameWithTemplateArgs *>(Name)->Name;
continue;
default:
return printNode(Name, Buf, N);
}
}
}
char *ItaniumPartialDemangler::getFunctionDeclContextName(char *Buf,
size_t *N) const {
if (!isFunction())
return nullptr;
const Node *Name = static_cast<const FunctionEncoding *>(RootNode)->getName();
OutputStream S;
if (!initializeOutputStream(Buf, N, S, 128))
return nullptr;
KeepGoingLocalFunction:
while (true) {
if (Name->getKind() == Node::KAbiTagAttr) {
Name = static_cast<const AbiTagAttr *>(Name)->Base;
continue;
}
if (Name->getKind() == Node::KNameWithTemplateArgs) {
Name = static_cast<const NameWithTemplateArgs *>(Name)->Name;
continue;
}
break;
}
switch (Name->getKind()) {
case Node::KStdQualifiedName:
S += "std";
break;
case Node::KNestedName:
static_cast<const NestedName *>(Name)->Qual->print(S);
break;
case Node::KLocalName: {
auto *LN = static_cast<const LocalName *>(Name);
LN->Encoding->print(S);
S += "::";
Name = LN->Entity;
goto KeepGoingLocalFunction;
}
default:
break;
}
S += '\0';
if (N != nullptr)
*N = S.getCurrentPosition();
return S.getBuffer();
}
char *ItaniumPartialDemangler::getFunctionName(char *Buf, size_t *N) const {
if (!isFunction())
return nullptr;
auto *Name = static_cast<FunctionEncoding *>(RootNode)->getName();
return printNode(Name, Buf, N);
}
char *ItaniumPartialDemangler::getFunctionParameters(char *Buf,
size_t *N) const {
if (!isFunction())
return nullptr;
NodeArray Params = static_cast<FunctionEncoding *>(RootNode)->getParams();
OutputStream S;
if (!initializeOutputStream(Buf, N, S, 128))
return nullptr;
S += '(';
Params.printWithComma(S);
S += ')';
S += '\0';
if (N != nullptr)
*N = S.getCurrentPosition();
return S.getBuffer();
}
char *ItaniumPartialDemangler::getFunctionReturnType(
char *Buf, size_t *N) const {
if (!isFunction())
return nullptr;
OutputStream S;
if (!initializeOutputStream(Buf, N, S, 128))
return nullptr;
if (const Node *Ret =
static_cast<const FunctionEncoding *>(RootNode)->getReturnType())
Ret->print(S);
S += '\0';
if (N != nullptr)
*N = S.getCurrentPosition();
return S.getBuffer();
}
char *ItaniumPartialDemangler::finishDemangle(char *Buf, size_t *N) const {
assert(RootNode != nullptr && "must call partialDemangle()");
return printNode(static_cast<Node *>(RootNode), Buf, N);
}
bool ItaniumPartialDemangler::hasFunctionQualifiers() const {
assert(RootNode != nullptr && "must call partialDemangle()");
if (!isFunction())
return false;
auto *E = static_cast<const FunctionEncoding *>(RootNode);
return E->getCVQuals() != QualNone || E->getRefQual() != FrefQualNone;
}
bool ItaniumPartialDemangler::isCtorOrDtor() const {
const Node *N = static_cast<const Node *>(RootNode);
while (N) {
switch (N->getKind()) {
default:
return false;
case Node::KCtorDtorName:
return true;
case Node::KAbiTagAttr:
N = static_cast<const AbiTagAttr *>(N)->Base;
break;
case Node::KFunctionEncoding:
N = static_cast<const FunctionEncoding *>(N)->getName();
break;
case Node::KLocalName:
N = static_cast<const LocalName *>(N)->Entity;
break;
case Node::KNameWithTemplateArgs:
N = static_cast<const NameWithTemplateArgs *>(N)->Name;
break;
case Node::KNestedName:
N = static_cast<const NestedName *>(N)->Name;
break;
case Node::KStdQualifiedName:
N = static_cast<const StdQualifiedName *>(N)->Child;
break;
}
}
return false;
}
bool ItaniumPartialDemangler::isFunction() const {
assert(RootNode != nullptr && "must call partialDemangle()");
return static_cast<const Node *>(RootNode)->getKind() ==
Node::KFunctionEncoding;
}
bool ItaniumPartialDemangler::isSpecialName() const {
assert(RootNode != nullptr && "must call partialDemangle()");
auto K = static_cast<const Node *>(RootNode)->getKind();
return K == Node::KSpecialName || K == Node::KCtorVtableSpecialName;
}
bool ItaniumPartialDemangler::isData() const {
return !isFunction() && !isSpecialName();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,653 @@
//===- MicrosoftDemangle.cpp ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines a demangler for MSVC-style mangled symbols.
//
//===----------------------------------------------------------------------===//
#include "llvm/Demangle/MicrosoftDemangleNodes.h"
#include "llvm/Demangle/DemangleConfig.h"
#include "llvm/Demangle/Utility.h"
#include <cctype>
#include <string>
using namespace llvm;
using namespace ms_demangle;
#define OUTPUT_ENUM_CLASS_VALUE(Enum, Value, Desc) \
case Enum::Value: \
OS << Desc; \
break;
// Writes a space if the last token does not end with a punctuation.
static void outputSpaceIfNecessary(OutputStream &OS) {
if (OS.empty())
return;
char C = OS.back();
if (std::isalnum(C) || C == '>')
OS << " ";
}
static void outputSingleQualifier(OutputStream &OS, Qualifiers Q) {
switch (Q) {
case Q_Const:
OS << "const";
break;
case Q_Volatile:
OS << "volatile";
break;
case Q_Restrict:
OS << "__restrict";
break;
default:
break;
}
}
static bool outputQualifierIfPresent(OutputStream &OS, Qualifiers Q,
Qualifiers Mask, bool NeedSpace) {
if (!(Q & Mask))
return NeedSpace;
if (NeedSpace)
OS << " ";
outputSingleQualifier(OS, Mask);
return true;
}
static void outputQualifiers(OutputStream &OS, Qualifiers Q, bool SpaceBefore,
bool SpaceAfter) {
if (Q == Q_None)
return;
size_t Pos1 = OS.getCurrentPosition();
SpaceBefore = outputQualifierIfPresent(OS, Q, Q_Const, SpaceBefore);
SpaceBefore = outputQualifierIfPresent(OS, Q, Q_Volatile, SpaceBefore);
SpaceBefore = outputQualifierIfPresent(OS, Q, Q_Restrict, SpaceBefore);
size_t Pos2 = OS.getCurrentPosition();
if (SpaceAfter && Pos2 > Pos1)
OS << " ";
}
static void outputCallingConvention(OutputStream &OS, CallingConv CC) {
outputSpaceIfNecessary(OS);
switch (CC) {
case CallingConv::Cdecl:
OS << "__cdecl";
break;
case CallingConv::Fastcall:
OS << "__fastcall";
break;
case CallingConv::Pascal:
OS << "__pascal";
break;
case CallingConv::Regcall:
OS << "__regcall";
break;
case CallingConv::Stdcall:
OS << "__stdcall";
break;
case CallingConv::Thiscall:
OS << "__thiscall";
break;
case CallingConv::Eabi:
OS << "__eabi";
break;
case CallingConv::Vectorcall:
OS << "__vectorcall";
break;
case CallingConv::Clrcall:
OS << "__clrcall";
break;
default:
break;
}
}
std::string Node::toString(OutputFlags Flags) const {
OutputStream OS;
initializeOutputStream(nullptr, nullptr, OS, 1024);
this->output(OS, Flags);
OS << '\0';
return {OS.getBuffer()};
}
void PrimitiveTypeNode::outputPre(OutputStream &OS, OutputFlags Flags) const {
switch (PrimKind) {
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Void, "void");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Bool, "bool");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Char, "char");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Schar, "signed char");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Uchar, "unsigned char");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Char8, "char8_t");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Char16, "char16_t");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Char32, "char32_t");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Short, "short");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Ushort, "unsigned short");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Int, "int");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Uint, "unsigned int");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Long, "long");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Ulong, "unsigned long");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Int64, "__int64");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Uint64, "unsigned __int64");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Wchar, "wchar_t");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Float, "float");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Double, "double");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Ldouble, "long double");
OUTPUT_ENUM_CLASS_VALUE(PrimitiveKind, Nullptr, "std::nullptr_t");
}
outputQualifiers(OS, Quals, true, false);
}
void NodeArrayNode::output(OutputStream &OS, OutputFlags Flags) const {
output(OS, Flags, ", ");
}
void NodeArrayNode::output(OutputStream &OS, OutputFlags Flags,
StringView Separator) const {
if (Count == 0)
return;
if (Nodes[0])
Nodes[0]->output(OS, Flags);
for (size_t I = 1; I < Count; ++I) {
OS << Separator;
Nodes[I]->output(OS, Flags);
}
}
void EncodedStringLiteralNode::output(OutputStream &OS,
OutputFlags Flags) const {
switch (Char) {
case CharKind::Wchar:
OS << "L\"";
break;
case CharKind::Char:
OS << "\"";
break;
case CharKind::Char16:
OS << "u\"";
break;
case CharKind::Char32:
OS << "U\"";
break;
}
OS << DecodedString << "\"";
if (IsTruncated)
OS << "...";
}
void IntegerLiteralNode::output(OutputStream &OS, OutputFlags Flags) const {
if (IsNegative)
OS << '-';
OS << Value;
}
void TemplateParameterReferenceNode::output(OutputStream &OS,
OutputFlags Flags) const {
if (ThunkOffsetCount > 0)
OS << "{";
else if (Affinity == PointerAffinity::Pointer)
OS << "&";
if (Symbol) {
Symbol->output(OS, Flags);
if (ThunkOffsetCount > 0)
OS << ", ";
}
if (ThunkOffsetCount > 0)
OS << ThunkOffsets[0];
for (int I = 1; I < ThunkOffsetCount; ++I) {
OS << ", " << ThunkOffsets[I];
}
if (ThunkOffsetCount > 0)
OS << "}";
}
void IdentifierNode::outputTemplateParameters(OutputStream &OS,
OutputFlags Flags) const {
if (!TemplateParams)
return;
OS << "<";
TemplateParams->output(OS, Flags);
OS << ">";
}
void DynamicStructorIdentifierNode::output(OutputStream &OS,
OutputFlags Flags) const {
if (IsDestructor)
OS << "`dynamic atexit destructor for ";
else
OS << "`dynamic initializer for ";
if (Variable) {
OS << "`";
Variable->output(OS, Flags);
OS << "''";
} else {
OS << "'";
Name->output(OS, Flags);
OS << "''";
}
}
void NamedIdentifierNode::output(OutputStream &OS, OutputFlags Flags) const {
OS << Name;
outputTemplateParameters(OS, Flags);
}
void IntrinsicFunctionIdentifierNode::output(OutputStream &OS,
OutputFlags Flags) const {
switch (Operator) {
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, New, "operator new");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Delete, "operator delete");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Assign, "operator=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, RightShift, "operator>>");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LeftShift, "operator<<");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LogicalNot, "operator!");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Equals, "operator==");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, NotEquals, "operator!=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ArraySubscript,
"operator[]");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Pointer, "operator->");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Increment, "operator++");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Decrement, "operator--");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Minus, "operator-");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Plus, "operator+");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Dereference, "operator*");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseAnd, "operator&");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, MemberPointer,
"operator->*");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Divide, "operator/");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Modulus, "operator%");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LessThan, "operator<");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LessThanEqual, "operator<=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, GreaterThan, "operator>");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, GreaterThanEqual,
"operator>=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Comma, "operator,");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Parens, "operator()");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseNot, "operator~");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseXor, "operator^");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseOr, "operator|");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LogicalAnd, "operator&&");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LogicalOr, "operator||");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, TimesEqual, "operator*=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, PlusEqual, "operator+=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, MinusEqual, "operator-=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, DivEqual, "operator/=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ModEqual, "operator%=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, RshEqual, "operator>>=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LshEqual, "operator<<=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseAndEqual,
"operator&=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseOrEqual,
"operator|=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, BitwiseXorEqual,
"operator^=");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VbaseDtor, "`vbase dtor'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VecDelDtor,
"`vector deleting dtor'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, DefaultCtorClosure,
"`default ctor closure'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ScalarDelDtor,
"`scalar deleting dtor'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VecCtorIter,
"`vector ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VecDtorIter,
"`vector dtor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VecVbaseCtorIter,
"`vector vbase ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VdispMap,
"`virtual displacement map'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, EHVecCtorIter,
"`eh vector ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, EHVecDtorIter,
"`eh vector dtor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, EHVecVbaseCtorIter,
"`eh vector vbase ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, CopyCtorClosure,
"`copy ctor closure'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, LocalVftableCtorClosure,
"`local vftable ctor closure'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ArrayNew, "operator new[]");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ArrayDelete,
"operator delete[]");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ManVectorCtorIter,
"`managed vector ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ManVectorDtorIter,
"`managed vector dtor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, EHVectorCopyCtorIter,
"`EH vector copy ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, EHVectorVbaseCopyCtorIter,
"`EH vector vbase copy ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VectorCopyCtorIter,
"`vector copy ctor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, VectorVbaseCopyCtorIter,
"`vector vbase copy constructor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, ManVectorVbaseCopyCtorIter,
"`managed vector vbase copy constructor iterator'");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, CoAwait,
"operator co_await");
OUTPUT_ENUM_CLASS_VALUE(IntrinsicFunctionKind, Spaceship, "operator<=>");
case IntrinsicFunctionKind::MaxIntrinsic:
case IntrinsicFunctionKind::None:
break;
}
outputTemplateParameters(OS, Flags);
}
void LocalStaticGuardIdentifierNode::output(OutputStream &OS,
OutputFlags Flags) const {
if (IsThread)
OS << "`local static thread guard'";
else
OS << "`local static guard'";
if (ScopeIndex > 0)
OS << "{" << ScopeIndex << "}";
}
void ConversionOperatorIdentifierNode::output(OutputStream &OS,
OutputFlags Flags) const {
OS << "operator";
outputTemplateParameters(OS, Flags);
OS << " ";
TargetType->output(OS, Flags);
}
void StructorIdentifierNode::output(OutputStream &OS, OutputFlags Flags) const {
if (IsDestructor)
OS << "~";
Class->output(OS, Flags);
outputTemplateParameters(OS, Flags);
}
void LiteralOperatorIdentifierNode::output(OutputStream &OS,
OutputFlags Flags) const {
OS << "operator \"\"" << Name;
outputTemplateParameters(OS, Flags);
}
void FunctionSignatureNode::outputPre(OutputStream &OS,
OutputFlags Flags) const {
if (!(Flags & OF_NoAccessSpecifier)) {
if (FunctionClass & FC_Public)
OS << "public: ";
if (FunctionClass & FC_Protected)
OS << "protected: ";
if (FunctionClass & FC_Private)
OS << "private: ";
}
if (!(Flags & OF_NoMemberType)) {
if (!(FunctionClass & FC_Global)) {
if (FunctionClass & FC_Static)
OS << "static ";
}
if (FunctionClass & FC_Virtual)
OS << "virtual ";
if (FunctionClass & FC_ExternC)
OS << "extern \"C\" ";
}
if (!(Flags & OF_NoReturnType) && ReturnType) {
ReturnType->outputPre(OS, Flags);
OS << " ";
}
if (!(Flags & OF_NoCallingConvention))
outputCallingConvention(OS, CallConvention);
}
void FunctionSignatureNode::outputPost(OutputStream &OS,
OutputFlags Flags) const {
if (!(FunctionClass & FC_NoParameterList)) {
OS << "(";
if (Params)
Params->output(OS, Flags);
else
OS << "void";
if (IsVariadic) {
if (OS.back() != '(')
OS << ", ";
OS << "...";
}
OS << ")";
}
if (Quals & Q_Const)
OS << " const";
if (Quals & Q_Volatile)
OS << " volatile";
if (Quals & Q_Restrict)
OS << " __restrict";
if (Quals & Q_Unaligned)
OS << " __unaligned";
if (IsNoexcept)
OS << " noexcept";
if (RefQualifier == FunctionRefQualifier::Reference)
OS << " &";
else if (RefQualifier == FunctionRefQualifier::RValueReference)
OS << " &&";
if (!(Flags & OF_NoReturnType) && ReturnType)
ReturnType->outputPost(OS, Flags);
}
void ThunkSignatureNode::outputPre(OutputStream &OS, OutputFlags Flags) const {
OS << "[thunk]: ";
FunctionSignatureNode::outputPre(OS, Flags);
}
void ThunkSignatureNode::outputPost(OutputStream &OS, OutputFlags Flags) const {
if (FunctionClass & FC_StaticThisAdjust) {
OS << "`adjustor{" << ThisAdjust.StaticOffset << "}'";
} else if (FunctionClass & FC_VirtualThisAdjust) {
if (FunctionClass & FC_VirtualThisAdjustEx) {
OS << "`vtordispex{" << ThisAdjust.VBPtrOffset << ", "
<< ThisAdjust.VBOffsetOffset << ", " << ThisAdjust.VtordispOffset
<< ", " << ThisAdjust.StaticOffset << "}'";
} else {
OS << "`vtordisp{" << ThisAdjust.VtordispOffset << ", "
<< ThisAdjust.StaticOffset << "}'";
}
}
FunctionSignatureNode::outputPost(OS, Flags);
}
void PointerTypeNode::outputPre(OutputStream &OS, OutputFlags Flags) const {
if (Pointee->kind() == NodeKind::FunctionSignature) {
// If this is a pointer to a function, don't output the calling convention.
// It needs to go inside the parentheses.
const FunctionSignatureNode *Sig =
static_cast<const FunctionSignatureNode *>(Pointee);
Sig->outputPre(OS, OF_NoCallingConvention);
} else
Pointee->outputPre(OS, Flags);
outputSpaceIfNecessary(OS);
if (Quals & Q_Unaligned)
OS << "__unaligned ";
if (Pointee->kind() == NodeKind::ArrayType) {
OS << "(";
} else if (Pointee->kind() == NodeKind::FunctionSignature) {
OS << "(";
const FunctionSignatureNode *Sig =
static_cast<const FunctionSignatureNode *>(Pointee);
outputCallingConvention(OS, Sig->CallConvention);
OS << " ";
}
if (ClassParent) {
ClassParent->output(OS, Flags);
OS << "::";
}
switch (Affinity) {
case PointerAffinity::Pointer:
OS << "*";
break;
case PointerAffinity::Reference:
OS << "&";
break;
case PointerAffinity::RValueReference:
OS << "&&";
break;
default:
assert(false);
}
outputQualifiers(OS, Quals, false, false);
}
void PointerTypeNode::outputPost(OutputStream &OS, OutputFlags Flags) const {
if (Pointee->kind() == NodeKind::ArrayType ||
Pointee->kind() == NodeKind::FunctionSignature)
OS << ")";
Pointee->outputPost(OS, Flags);
}
void TagTypeNode::outputPre(OutputStream &OS, OutputFlags Flags) const {
if (!(Flags & OF_NoTagSpecifier)) {
switch (Tag) {
OUTPUT_ENUM_CLASS_VALUE(TagKind, Class, "class");
OUTPUT_ENUM_CLASS_VALUE(TagKind, Struct, "struct");
OUTPUT_ENUM_CLASS_VALUE(TagKind, Union, "union");
OUTPUT_ENUM_CLASS_VALUE(TagKind, Enum, "enum");
}
OS << " ";
}
QualifiedName->output(OS, Flags);
outputQualifiers(OS, Quals, true, false);
}
void TagTypeNode::outputPost(OutputStream &OS, OutputFlags Flags) const {}
void ArrayTypeNode::outputPre(OutputStream &OS, OutputFlags Flags) const {
ElementType->outputPre(OS, Flags);
outputQualifiers(OS, Quals, true, false);
}
void ArrayTypeNode::outputOneDimension(OutputStream &OS, OutputFlags Flags,
Node *N) const {
assert(N->kind() == NodeKind::IntegerLiteral);
IntegerLiteralNode *ILN = static_cast<IntegerLiteralNode *>(N);
if (ILN->Value != 0)
ILN->output(OS, Flags);
}
void ArrayTypeNode::outputDimensionsImpl(OutputStream &OS,
OutputFlags Flags) const {
if (Dimensions->Count == 0)
return;
outputOneDimension(OS, Flags, Dimensions->Nodes[0]);
for (size_t I = 1; I < Dimensions->Count; ++I) {
OS << "][";
outputOneDimension(OS, Flags, Dimensions->Nodes[I]);
}
}
void ArrayTypeNode::outputPost(OutputStream &OS, OutputFlags Flags) const {
OS << "[";
outputDimensionsImpl(OS, Flags);
OS << "]";
ElementType->outputPost(OS, Flags);
}
void SymbolNode::output(OutputStream &OS, OutputFlags Flags) const {
Name->output(OS, Flags);
}
void FunctionSymbolNode::output(OutputStream &OS, OutputFlags Flags) const {
Signature->outputPre(OS, Flags);
outputSpaceIfNecessary(OS);
Name->output(OS, Flags);
Signature->outputPost(OS, Flags);
}
void VariableSymbolNode::output(OutputStream &OS, OutputFlags Flags) const {
const char *AccessSpec = nullptr;
bool IsStatic = true;
switch (SC) {
case StorageClass::PrivateStatic:
AccessSpec = "private";
break;
case StorageClass::PublicStatic:
AccessSpec = "public";
break;
case StorageClass::ProtectedStatic:
AccessSpec = "protected";
break;
default:
IsStatic = false;
break;
}
if (!(Flags & OF_NoAccessSpecifier) && AccessSpec)
OS << AccessSpec << ": ";
if (!(Flags & OF_NoMemberType) && IsStatic)
OS << "static ";
if (Type) {
Type->outputPre(OS, Flags);
outputSpaceIfNecessary(OS);
}
Name->output(OS, Flags);
if (Type)
Type->outputPost(OS, Flags);
}
void CustomTypeNode::outputPre(OutputStream &OS, OutputFlags Flags) const {
Identifier->output(OS, Flags);
}
void CustomTypeNode::outputPost(OutputStream &OS, OutputFlags Flags) const {}
void QualifiedNameNode::output(OutputStream &OS, OutputFlags Flags) const {
Components->output(OS, Flags, "::");
}
void RttiBaseClassDescriptorNode::output(OutputStream &OS,
OutputFlags Flags) const {
OS << "`RTTI Base Class Descriptor at (";
OS << NVOffset << ", " << VBPtrOffset << ", " << VBTableOffset << ", "
<< this->Flags;
OS << ")'";
}
void LocalStaticGuardVariableNode::output(OutputStream &OS,
OutputFlags Flags) const {
Name->output(OS, Flags);
}
void VcallThunkIdentifierNode::output(OutputStream &OS,
OutputFlags Flags) const {
OS << "`vcall'{" << OffsetInVTable << ", {flat}}";
}
void SpecialTableSymbolNode::output(OutputStream &OS, OutputFlags Flags) const {
outputQualifiers(OS, Quals, false, true);
Name->output(OS, Flags);
if (TargetName) {
OS << "{for `";
TargetName->output(OS, Flags);
OS << "'}";
}
return;
}

View File

@@ -0,0 +1,124 @@
//===--- Demangle.h ---------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_DEMANGLE_DEMANGLE_H
#define LLVM_DEMANGLE_DEMANGLE_H
#include <cstddef>
#include <string>
namespace llvm {
/// This is a llvm local version of __cxa_demangle. Other than the name and
/// being in the llvm namespace it is identical.
///
/// The mangled_name is demangled into buf and returned. If the buffer is not
/// large enough, realloc is used to expand it.
///
/// The *status will be set to a value from the following enumeration
enum : int {
demangle_unknown_error = -4,
demangle_invalid_args = -3,
demangle_invalid_mangled_name = -2,
demangle_memory_alloc_failure = -1,
demangle_success = 0,
};
char *itaniumDemangle(const char *mangled_name, char *buf, size_t *n,
int *status);
enum MSDemangleFlags {
MSDF_None = 0,
MSDF_DumpBackrefs = 1 << 0,
MSDF_NoAccessSpecifier = 1 << 1,
MSDF_NoCallingConvention = 1 << 2,
MSDF_NoReturnType = 1 << 3,
MSDF_NoMemberType = 1 << 4,
};
/// Demangles the Microsoft symbol pointed at by mangled_name and returns it.
/// Returns a pointer to the start of a null-terminated demangled string on
/// success, or nullptr on error.
/// If n_read is non-null and demangling was successful, it receives how many
/// bytes of the input string were consumed.
/// buf can point to a *n_buf bytes large buffer where the demangled name is
/// stored. If the buffer is too small, it is grown with realloc(). If buf is
/// nullptr, then this malloc()s memory for the result.
/// *n_buf stores the size of buf on input if buf is non-nullptr, and it
/// receives the size of the demangled string on output if n_buf is not nullptr.
/// status receives one of the demangle_ enum entries above if it's not nullptr.
/// Flags controls various details of the demangled representation.
char *microsoftDemangle(const char *mangled_name, size_t *n_read,
char *buf, size_t *n_buf,
int *status, MSDemangleFlags Flags = MSDF_None);
/// Attempt to demangle a string using different demangling schemes.
/// The function uses heuristics to determine which demangling scheme to use.
/// \param MangledName - reference to string to demangle.
/// \returns - the demangled string, or a copy of the input string if no
/// demangling occurred.
std::string demangle(const std::string &MangledName);
/// "Partial" demangler. This supports demangling a string into an AST
/// (typically an intermediate stage in itaniumDemangle) and querying certain
/// properties or partially printing the demangled name.
struct ItaniumPartialDemangler {
ItaniumPartialDemangler();
ItaniumPartialDemangler(ItaniumPartialDemangler &&Other);
ItaniumPartialDemangler &operator=(ItaniumPartialDemangler &&Other);
/// Demangle into an AST. Subsequent calls to the rest of the member functions
/// implicitly operate on the AST this produces.
/// \return true on error, false otherwise
bool partialDemangle(const char *MangledName);
/// Just print the entire mangled name into Buf. Buf and N behave like the
/// second and third parameters to itaniumDemangle.
char *finishDemangle(char *Buf, size_t *N) const;
/// Get the base name of a function. This doesn't include trailing template
/// arguments, ie for "a::b<int>" this function returns "b".
char *getFunctionBaseName(char *Buf, size_t *N) const;
/// Get the context name for a function. For "a::b::c", this function returns
/// "a::b".
char *getFunctionDeclContextName(char *Buf, size_t *N) const;
/// Get the entire name of this function.
char *getFunctionName(char *Buf, size_t *N) const;
/// Get the parameters for this function.
char *getFunctionParameters(char *Buf, size_t *N) const;
char *getFunctionReturnType(char *Buf, size_t *N) const;
/// If this function has any any cv or reference qualifiers. These imply that
/// the function is a non-static member function.
bool hasFunctionQualifiers() const;
/// If this symbol describes a constructor or destructor.
bool isCtorOrDtor() const;
/// If this symbol describes a function.
bool isFunction() const;
/// If this symbol describes a variable.
bool isData() const;
/// If this symbol is a <special-name>. These are generally implicitly
/// generated by the implementation, such as vtables and typeinfo names.
bool isSpecialName() const;
~ItaniumPartialDemangler();
private:
void *RootNode;
void *Context;
};
} // namespace llvm
#endif

View File

@@ -0,0 +1,92 @@
//===--- DemangleConfig.h ---------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains a variety of feature test macros copied from
// include/llvm/Support/Compiler.h so that LLVMDemangle does not need to take
// a dependency on LLVMSupport.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_DEMANGLE_COMPILER_H
#define LLVM_DEMANGLE_COMPILER_H
#ifndef __has_feature
#define __has_feature(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#ifndef DEMANGLE_GNUC_PREREQ
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__)
#define DEMANGLE_GNUC_PREREQ(maj, min, patch) \
((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) + __GNUC_PATCHLEVEL__ >= \
((maj) << 20) + ((min) << 10) + (patch))
#elif defined(__GNUC__) && defined(__GNUC_MINOR__)
#define DEMANGLE_GNUC_PREREQ(maj, min, patch) \
((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) >= ((maj) << 20) + ((min) << 10))
#else
#define DEMANGLE_GNUC_PREREQ(maj, min, patch) 0
#endif
#endif
#if __has_attribute(used) || DEMANGLE_GNUC_PREREQ(3, 1, 0)
#define DEMANGLE_ATTRIBUTE_USED __attribute__((__used__))
#else
#define DEMANGLE_ATTRIBUTE_USED
#endif
#if __has_builtin(__builtin_unreachable) || DEMANGLE_GNUC_PREREQ(4, 5, 0)
#define DEMANGLE_UNREACHABLE __builtin_unreachable()
#elif defined(_MSC_VER)
#define DEMANGLE_UNREACHABLE __assume(false)
#else
#define DEMANGLE_UNREACHABLE
#endif
#if __has_attribute(noinline) || DEMANGLE_GNUC_PREREQ(3, 4, 0)
#define DEMANGLE_ATTRIBUTE_NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER)
#define DEMANGLE_ATTRIBUTE_NOINLINE __declspec(noinline)
#else
#define DEMANGLE_ATTRIBUTE_NOINLINE
#endif
#if !defined(NDEBUG)
#define DEMANGLE_DUMP_METHOD DEMANGLE_ATTRIBUTE_NOINLINE DEMANGLE_ATTRIBUTE_USED
#else
#define DEMANGLE_DUMP_METHOD DEMANGLE_ATTRIBUTE_NOINLINE
#endif
#if __cplusplus > 201402L && __has_cpp_attribute(fallthrough)
#define DEMANGLE_FALLTHROUGH [[fallthrough]]
#elif __has_cpp_attribute(gnu::fallthrough)
#define DEMANGLE_FALLTHROUGH [[gnu::fallthrough]]
#elif !__cplusplus
// Workaround for llvm.org/PR23435, since clang 3.6 and below emit a spurious
// error when __has_cpp_attribute is given a scoped attribute in C mode.
#define DEMANGLE_FALLTHROUGH
#elif __has_cpp_attribute(clang::fallthrough)
#define DEMANGLE_FALLTHROUGH [[clang::fallthrough]]
#else
#define DEMANGLE_FALLTHROUGH
#endif
#define DEMANGLE_NAMESPACE_BEGIN namespace llvm { namespace itanium_demangle {
#define DEMANGLE_NAMESPACE_END } }
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,278 @@
//===------------------------- MicrosoftDemangle.h --------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_DEMANGLE_MICROSOFT_DEMANGLE_H
#define LLVM_DEMANGLE_MICROSOFT_DEMANGLE_H
#include "llvm/Demangle/DemangleConfig.h"
#include "llvm/Demangle/MicrosoftDemangleNodes.h"
#include "llvm/Demangle/StringView.h"
#include "llvm/Demangle/Utility.h"
#include <utility>
namespace llvm {
namespace ms_demangle {
// This memory allocator is extremely fast, but it doesn't call dtors
// for allocated objects. That means you can't use STL containers
// (such as std::vector) with this allocator. But it pays off --
// the demangler is 3x faster with this allocator compared to one with
// STL containers.
constexpr size_t AllocUnit = 4096;
class ArenaAllocator {
struct AllocatorNode {
uint8_t *Buf = nullptr;
size_t Used = 0;
size_t Capacity = 0;
AllocatorNode *Next = nullptr;
};
void addNode(size_t Capacity) {
AllocatorNode *NewHead = new AllocatorNode;
NewHead->Buf = new uint8_t[Capacity];
NewHead->Next = Head;
NewHead->Capacity = Capacity;
Head = NewHead;
NewHead->Used = 0;
}
public:
ArenaAllocator() { addNode(AllocUnit); }
~ArenaAllocator() {
while (Head) {
assert(Head->Buf);
delete[] Head->Buf;
AllocatorNode *Next = Head->Next;
delete Head;
Head = Next;
}
}
char *allocUnalignedBuffer(size_t Size) {
assert(Head && Head->Buf);
uint8_t *P = Head->Buf + Head->Used;
Head->Used += Size;
if (Head->Used <= Head->Capacity)
return reinterpret_cast<char *>(P);
addNode(std::max(AllocUnit, Size));
Head->Used = Size;
return reinterpret_cast<char *>(Head->Buf);
}
template <typename T, typename... Args> T *allocArray(size_t Count) {
size_t Size = Count * sizeof(T);
assert(Head && Head->Buf);
size_t P = (size_t)Head->Buf + Head->Used;
uintptr_t AlignedP =
(((size_t)P + alignof(T) - 1) & ~(size_t)(alignof(T) - 1));
uint8_t *PP = (uint8_t *)AlignedP;
size_t Adjustment = AlignedP - P;
Head->Used += Size + Adjustment;
if (Head->Used <= Head->Capacity)
return new (PP) T[Count]();
addNode(std::max(AllocUnit, Size));
Head->Used = Size;
return new (Head->Buf) T[Count]();
}
template <typename T, typename... Args> T *alloc(Args &&... ConstructorArgs) {
constexpr size_t Size = sizeof(T);
assert(Head && Head->Buf);
size_t P = (size_t)Head->Buf + Head->Used;
uintptr_t AlignedP =
(((size_t)P + alignof(T) - 1) & ~(size_t)(alignof(T) - 1));
uint8_t *PP = (uint8_t *)AlignedP;
size_t Adjustment = AlignedP - P;
Head->Used += Size + Adjustment;
if (Head->Used <= Head->Capacity)
return new (PP) T(std::forward<Args>(ConstructorArgs)...);
static_assert(Size < AllocUnit, "");
addNode(AllocUnit);
Head->Used = Size;
return new (Head->Buf) T(std::forward<Args>(ConstructorArgs)...);
}
private:
AllocatorNode *Head = nullptr;
};
struct BackrefContext {
static constexpr size_t Max = 10;
TypeNode *FunctionParams[Max];
size_t FunctionParamCount = 0;
// The first 10 BackReferences in a mangled name can be back-referenced by
// special name @[0-9]. This is a storage for the first 10 BackReferences.
NamedIdentifierNode *Names[Max];
size_t NamesCount = 0;
};
enum class QualifierMangleMode { Drop, Mangle, Result };
enum NameBackrefBehavior : uint8_t {
NBB_None = 0, // don't save any names as backrefs.
NBB_Template = 1 << 0, // save template instanations.
NBB_Simple = 1 << 1, // save simple names.
};
enum class FunctionIdentifierCodeGroup { Basic, Under, DoubleUnder };
// Demangler class takes the main role in demangling symbols.
// It has a set of functions to parse mangled symbols into Type instances.
// It also has a set of functions to convert Type instances to strings.
class Demangler {
public:
Demangler() = default;
virtual ~Demangler() = default;
// You are supposed to call parse() first and then check if error is true. If
// it is false, call output() to write the formatted name to the given stream.
SymbolNode *parse(StringView &MangledName);
TagTypeNode *parseTagUniqueName(StringView &MangledName);
// True if an error occurred.
bool Error = false;
void dumpBackReferences();
private:
SymbolNode *demangleEncodedSymbol(StringView &MangledName,
QualifiedNameNode *QN);
SymbolNode *demangleDeclarator(StringView &MangledName);
SymbolNode *demangleMD5Name(StringView &MangledName);
SymbolNode *demangleTypeinfoName(StringView &MangledName);
VariableSymbolNode *demangleVariableEncoding(StringView &MangledName,
StorageClass SC);
FunctionSymbolNode *demangleFunctionEncoding(StringView &MangledName);
Qualifiers demanglePointerExtQualifiers(StringView &MangledName);
// Parser functions. This is a recursive-descent parser.
TypeNode *demangleType(StringView &MangledName, QualifierMangleMode QMM);
PrimitiveTypeNode *demanglePrimitiveType(StringView &MangledName);
CustomTypeNode *demangleCustomType(StringView &MangledName);
TagTypeNode *demangleClassType(StringView &MangledName);
PointerTypeNode *demanglePointerType(StringView &MangledName);
PointerTypeNode *demangleMemberPointerType(StringView &MangledName);
FunctionSignatureNode *demangleFunctionType(StringView &MangledName,
bool HasThisQuals);
ArrayTypeNode *demangleArrayType(StringView &MangledName);
NodeArrayNode *demangleFunctionParameterList(StringView &MangledName,
bool &IsVariadic);
NodeArrayNode *demangleTemplateParameterList(StringView &MangledName);
std::pair<uint64_t, bool> demangleNumber(StringView &MangledName);
uint64_t demangleUnsigned(StringView &MangledName);
int64_t demangleSigned(StringView &MangledName);
void memorizeString(StringView s);
void memorizeIdentifier(IdentifierNode *Identifier);
/// Allocate a copy of \p Borrowed into memory that we own.
StringView copyString(StringView Borrowed);
QualifiedNameNode *demangleFullyQualifiedTypeName(StringView &MangledName);
QualifiedNameNode *demangleFullyQualifiedSymbolName(StringView &MangledName);
IdentifierNode *demangleUnqualifiedTypeName(StringView &MangledName,
bool Memorize);
IdentifierNode *demangleUnqualifiedSymbolName(StringView &MangledName,
NameBackrefBehavior NBB);
QualifiedNameNode *demangleNameScopeChain(StringView &MangledName,
IdentifierNode *UnqualifiedName);
IdentifierNode *demangleNameScopePiece(StringView &MangledName);
NamedIdentifierNode *demangleBackRefName(StringView &MangledName);
IdentifierNode *demangleTemplateInstantiationName(StringView &MangledName,
NameBackrefBehavior NBB);
IntrinsicFunctionKind
translateIntrinsicFunctionCode(char CH, FunctionIdentifierCodeGroup Group);
IdentifierNode *demangleFunctionIdentifierCode(StringView &MangledName);
IdentifierNode *
demangleFunctionIdentifierCode(StringView &MangledName,
FunctionIdentifierCodeGroup Group);
StructorIdentifierNode *demangleStructorIdentifier(StringView &MangledName,
bool IsDestructor);
ConversionOperatorIdentifierNode *
demangleConversionOperatorIdentifier(StringView &MangledName);
LiteralOperatorIdentifierNode *
demangleLiteralOperatorIdentifier(StringView &MangledName);
SymbolNode *demangleSpecialIntrinsic(StringView &MangledName);
SpecialTableSymbolNode *
demangleSpecialTableSymbolNode(StringView &MangledName,
SpecialIntrinsicKind SIK);
LocalStaticGuardVariableNode *
demangleLocalStaticGuard(StringView &MangledName, bool IsThread);
VariableSymbolNode *demangleUntypedVariable(ArenaAllocator &Arena,
StringView &MangledName,
StringView VariableName);
VariableSymbolNode *
demangleRttiBaseClassDescriptorNode(ArenaAllocator &Arena,
StringView &MangledName);
FunctionSymbolNode *demangleInitFiniStub(StringView &MangledName,
bool IsDestructor);
NamedIdentifierNode *demangleSimpleName(StringView &MangledName,
bool Memorize);
NamedIdentifierNode *demangleAnonymousNamespaceName(StringView &MangledName);
NamedIdentifierNode *demangleLocallyScopedNamePiece(StringView &MangledName);
EncodedStringLiteralNode *demangleStringLiteral(StringView &MangledName);
FunctionSymbolNode *demangleVcallThunkNode(StringView &MangledName);
StringView demangleSimpleString(StringView &MangledName, bool Memorize);
FuncClass demangleFunctionClass(StringView &MangledName);
CallingConv demangleCallingConvention(StringView &MangledName);
StorageClass demangleVariableStorageClass(StringView &MangledName);
bool demangleThrowSpecification(StringView &MangledName);
wchar_t demangleWcharLiteral(StringView &MangledName);
uint8_t demangleCharLiteral(StringView &MangledName);
std::pair<Qualifiers, bool> demangleQualifiers(StringView &MangledName);
// Memory allocator.
ArenaAllocator Arena;
// A single type uses one global back-ref table for all function params.
// This means back-refs can even go "into" other types. Examples:
//
// // Second int* is a back-ref to first.
// void foo(int *, int*);
//
// // Second int* is not a back-ref to first (first is not a function param).
// int* foo(int*);
//
// // Second int* is a back-ref to first (ALL function types share the same
// // back-ref map.
// using F = void(*)(int*);
// F G(int *);
BackrefContext Backrefs;
};
} // namespace ms_demangle
} // namespace llvm
#endif // LLVM_DEMANGLE_MICROSOFT_DEMANGLE_H

View File

@@ -0,0 +1,629 @@
//===- MicrosoftDemangleNodes.h ---------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the AST nodes used in the MSVC demangler.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_MICROSOFTDEMANGLENODES_H
#define LLVM_SUPPORT_MICROSOFTDEMANGLENODES_H
#include "llvm/Demangle/DemangleConfig.h"
#include "llvm/Demangle/StringView.h"
#include <array>
#include <cstdint>
#include <string>
namespace llvm {
namespace itanium_demangle {
class OutputStream;
}
}
using llvm::itanium_demangle::OutputStream;
using llvm::itanium_demangle::StringView;
namespace llvm {
namespace ms_demangle {
// Storage classes
enum Qualifiers : uint8_t {
Q_None = 0,
Q_Const = 1 << 0,
Q_Volatile = 1 << 1,
Q_Far = 1 << 2,
Q_Huge = 1 << 3,
Q_Unaligned = 1 << 4,
Q_Restrict = 1 << 5,
Q_Pointer64 = 1 << 6
};
enum class StorageClass : uint8_t {
None,
PrivateStatic,
ProtectedStatic,
PublicStatic,
Global,
FunctionLocalStatic,
};
enum class PointerAffinity { None, Pointer, Reference, RValueReference };
enum class FunctionRefQualifier { None, Reference, RValueReference };
// Calling conventions
enum class CallingConv : uint8_t {
None,
Cdecl,
Pascal,
Thiscall,
Stdcall,
Fastcall,
Clrcall,
Eabi,
Vectorcall,
Regcall,
};
enum class ReferenceKind : uint8_t { None, LValueRef, RValueRef };
enum OutputFlags {
OF_Default = 0,
OF_NoCallingConvention = 1,
OF_NoTagSpecifier = 2,
OF_NoAccessSpecifier = 4,
OF_NoMemberType = 8,
OF_NoReturnType = 16,
};
// Types
enum class PrimitiveKind {
Void,
Bool,
Char,
Schar,
Uchar,
Char8,
Char16,
Char32,
Short,
Ushort,
Int,
Uint,
Long,
Ulong,
Int64,
Uint64,
Wchar,
Float,
Double,
Ldouble,
Nullptr,
};
enum class CharKind {
Char,
Char16,
Char32,
Wchar,
};
enum class IntrinsicFunctionKind : uint8_t {
None,
New, // ?2 # operator new
Delete, // ?3 # operator delete
Assign, // ?4 # operator=
RightShift, // ?5 # operator>>
LeftShift, // ?6 # operator<<
LogicalNot, // ?7 # operator!
Equals, // ?8 # operator==
NotEquals, // ?9 # operator!=
ArraySubscript, // ?A # operator[]
Pointer, // ?C # operator->
Dereference, // ?D # operator*
Increment, // ?E # operator++
Decrement, // ?F # operator--
Minus, // ?G # operator-
Plus, // ?H # operator+
BitwiseAnd, // ?I # operator&
MemberPointer, // ?J # operator->*
Divide, // ?K # operator/
Modulus, // ?L # operator%
LessThan, // ?M operator<
LessThanEqual, // ?N operator<=
GreaterThan, // ?O operator>
GreaterThanEqual, // ?P operator>=
Comma, // ?Q operator,
Parens, // ?R operator()
BitwiseNot, // ?S operator~
BitwiseXor, // ?T operator^
BitwiseOr, // ?U operator|
LogicalAnd, // ?V operator&&
LogicalOr, // ?W operator||
TimesEqual, // ?X operator*=
PlusEqual, // ?Y operator+=
MinusEqual, // ?Z operator-=
DivEqual, // ?_0 operator/=
ModEqual, // ?_1 operator%=
RshEqual, // ?_2 operator>>=
LshEqual, // ?_3 operator<<=
BitwiseAndEqual, // ?_4 operator&=
BitwiseOrEqual, // ?_5 operator|=
BitwiseXorEqual, // ?_6 operator^=
VbaseDtor, // ?_D # vbase destructor
VecDelDtor, // ?_E # vector deleting destructor
DefaultCtorClosure, // ?_F # default constructor closure
ScalarDelDtor, // ?_G # scalar deleting destructor
VecCtorIter, // ?_H # vector constructor iterator
VecDtorIter, // ?_I # vector destructor iterator
VecVbaseCtorIter, // ?_J # vector vbase constructor iterator
VdispMap, // ?_K # virtual displacement map
EHVecCtorIter, // ?_L # eh vector constructor iterator
EHVecDtorIter, // ?_M # eh vector destructor iterator
EHVecVbaseCtorIter, // ?_N # eh vector vbase constructor iterator
CopyCtorClosure, // ?_O # copy constructor closure
LocalVftableCtorClosure, // ?_T # local vftable constructor closure
ArrayNew, // ?_U operator new[]
ArrayDelete, // ?_V operator delete[]
ManVectorCtorIter, // ?__A managed vector ctor iterator
ManVectorDtorIter, // ?__B managed vector dtor iterator
EHVectorCopyCtorIter, // ?__C EH vector copy ctor iterator
EHVectorVbaseCopyCtorIter, // ?__D EH vector vbase copy ctor iterator
VectorCopyCtorIter, // ?__G vector copy constructor iterator
VectorVbaseCopyCtorIter, // ?__H vector vbase copy constructor iterator
ManVectorVbaseCopyCtorIter, // ?__I managed vector vbase copy constructor
CoAwait, // ?__L operator co_await
Spaceship, // ?__M operator<=>
MaxIntrinsic
};
enum class SpecialIntrinsicKind {
None,
Vftable,
Vbtable,
Typeof,
VcallThunk,
LocalStaticGuard,
StringLiteralSymbol,
UdtReturning,
Unknown,
DynamicInitializer,
DynamicAtexitDestructor,
RttiTypeDescriptor,
RttiBaseClassDescriptor,
RttiBaseClassArray,
RttiClassHierarchyDescriptor,
RttiCompleteObjLocator,
LocalVftable,
LocalStaticThreadGuard,
};
// Function classes
enum FuncClass : uint16_t {
FC_None = 0,
FC_Public = 1 << 0,
FC_Protected = 1 << 1,
FC_Private = 1 << 2,
FC_Global = 1 << 3,
FC_Static = 1 << 4,
FC_Virtual = 1 << 5,
FC_Far = 1 << 6,
FC_ExternC = 1 << 7,
FC_NoParameterList = 1 << 8,
FC_VirtualThisAdjust = 1 << 9,
FC_VirtualThisAdjustEx = 1 << 10,
FC_StaticThisAdjust = 1 << 11,
};
enum class TagKind { Class, Struct, Union, Enum };
enum class NodeKind {
Unknown,
Md5Symbol,
PrimitiveType,
FunctionSignature,
Identifier,
NamedIdentifier,
VcallThunkIdentifier,
LocalStaticGuardIdentifier,
IntrinsicFunctionIdentifier,
ConversionOperatorIdentifier,
DynamicStructorIdentifier,
StructorIdentifier,
LiteralOperatorIdentifier,
ThunkSignature,
PointerType,
TagType,
ArrayType,
Custom,
IntrinsicType,
NodeArray,
QualifiedName,
TemplateParameterReference,
EncodedStringLiteral,
IntegerLiteral,
RttiBaseClassDescriptor,
LocalStaticGuardVariable,
FunctionSymbol,
VariableSymbol,
SpecialTableSymbol
};
struct Node {
explicit Node(NodeKind K) : Kind(K) {}
virtual ~Node() = default;
NodeKind kind() const { return Kind; }
virtual void output(OutputStream &OS, OutputFlags Flags) const = 0;
std::string toString(OutputFlags Flags = OF_Default) const;
private:
NodeKind Kind;
};
struct TypeNode;
struct PrimitiveTypeNode;
struct FunctionSignatureNode;
struct IdentifierNode;
struct NamedIdentifierNode;
struct VcallThunkIdentifierNode;
struct IntrinsicFunctionIdentifierNode;
struct LiteralOperatorIdentifierNode;
struct ConversionOperatorIdentifierNode;
struct StructorIdentifierNode;
struct ThunkSignatureNode;
struct PointerTypeNode;
struct ArrayTypeNode;
struct CustomNode;
struct TagTypeNode;
struct IntrinsicTypeNode;
struct NodeArrayNode;
struct QualifiedNameNode;
struct TemplateParameterReferenceNode;
struct EncodedStringLiteralNode;
struct IntegerLiteralNode;
struct RttiBaseClassDescriptorNode;
struct LocalStaticGuardVariableNode;
struct SymbolNode;
struct FunctionSymbolNode;
struct VariableSymbolNode;
struct SpecialTableSymbolNode;
struct TypeNode : public Node {
explicit TypeNode(NodeKind K) : Node(K) {}
virtual void outputPre(OutputStream &OS, OutputFlags Flags) const = 0;
virtual void outputPost(OutputStream &OS, OutputFlags Flags) const = 0;
void output(OutputStream &OS, OutputFlags Flags) const override {
outputPre(OS, Flags);
outputPost(OS, Flags);
}
Qualifiers Quals = Q_None;
};
struct PrimitiveTypeNode : public TypeNode {
explicit PrimitiveTypeNode(PrimitiveKind K)
: TypeNode(NodeKind::PrimitiveType), PrimKind(K) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override {}
PrimitiveKind PrimKind;
};
struct FunctionSignatureNode : public TypeNode {
explicit FunctionSignatureNode(NodeKind K) : TypeNode(K) {}
FunctionSignatureNode() : TypeNode(NodeKind::FunctionSignature) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override;
// Valid if this FunctionTypeNode is the Pointee of a PointerType or
// MemberPointerType.
PointerAffinity Affinity = PointerAffinity::None;
// The function's calling convention.
CallingConv CallConvention = CallingConv::None;
// Function flags (gloabl, public, etc)
FuncClass FunctionClass = FC_Global;
FunctionRefQualifier RefQualifier = FunctionRefQualifier::None;
// The return type of the function.
TypeNode *ReturnType = nullptr;
// True if this is a C-style ... varargs function.
bool IsVariadic = false;
// Function parameters
NodeArrayNode *Params = nullptr;
// True if the function type is noexcept.
bool IsNoexcept = false;
};
struct IdentifierNode : public Node {
explicit IdentifierNode(NodeKind K) : Node(K) {}
NodeArrayNode *TemplateParams = nullptr;
protected:
void outputTemplateParameters(OutputStream &OS, OutputFlags Flags) const;
};
struct VcallThunkIdentifierNode : public IdentifierNode {
VcallThunkIdentifierNode() : IdentifierNode(NodeKind::VcallThunkIdentifier) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
uint64_t OffsetInVTable = 0;
};
struct DynamicStructorIdentifierNode : public IdentifierNode {
DynamicStructorIdentifierNode()
: IdentifierNode(NodeKind::DynamicStructorIdentifier) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
VariableSymbolNode *Variable = nullptr;
QualifiedNameNode *Name = nullptr;
bool IsDestructor = false;
};
struct NamedIdentifierNode : public IdentifierNode {
NamedIdentifierNode() : IdentifierNode(NodeKind::NamedIdentifier) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
StringView Name;
};
struct IntrinsicFunctionIdentifierNode : public IdentifierNode {
explicit IntrinsicFunctionIdentifierNode(IntrinsicFunctionKind Operator)
: IdentifierNode(NodeKind::IntrinsicFunctionIdentifier),
Operator(Operator) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
IntrinsicFunctionKind Operator;
};
struct LiteralOperatorIdentifierNode : public IdentifierNode {
LiteralOperatorIdentifierNode()
: IdentifierNode(NodeKind::LiteralOperatorIdentifier) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
StringView Name;
};
struct LocalStaticGuardIdentifierNode : public IdentifierNode {
LocalStaticGuardIdentifierNode()
: IdentifierNode(NodeKind::LocalStaticGuardIdentifier) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
bool IsThread = false;
uint32_t ScopeIndex = 0;
};
struct ConversionOperatorIdentifierNode : public IdentifierNode {
ConversionOperatorIdentifierNode()
: IdentifierNode(NodeKind::ConversionOperatorIdentifier) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
// The type that this operator converts too.
TypeNode *TargetType = nullptr;
};
struct StructorIdentifierNode : public IdentifierNode {
StructorIdentifierNode() : IdentifierNode(NodeKind::StructorIdentifier) {}
explicit StructorIdentifierNode(bool IsDestructor)
: IdentifierNode(NodeKind::StructorIdentifier),
IsDestructor(IsDestructor) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
// The name of the class that this is a structor of.
IdentifierNode *Class = nullptr;
bool IsDestructor = false;
};
struct ThunkSignatureNode : public FunctionSignatureNode {
ThunkSignatureNode() : FunctionSignatureNode(NodeKind::ThunkSignature) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override;
struct ThisAdjustor {
uint32_t StaticOffset = 0;
int32_t VBPtrOffset = 0;
int32_t VBOffsetOffset = 0;
int32_t VtordispOffset = 0;
};
ThisAdjustor ThisAdjust;
};
struct PointerTypeNode : public TypeNode {
PointerTypeNode() : TypeNode(NodeKind::PointerType) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override;
// Is this a pointer, reference, or rvalue-reference?
PointerAffinity Affinity = PointerAffinity::None;
// If this is a member pointer, this is the class that the member is in.
QualifiedNameNode *ClassParent = nullptr;
// Represents a type X in "a pointer to X", "a reference to X", or
// "rvalue-reference to X"
TypeNode *Pointee = nullptr;
};
struct TagTypeNode : public TypeNode {
explicit TagTypeNode(TagKind Tag) : TypeNode(NodeKind::TagType), Tag(Tag) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override;
QualifiedNameNode *QualifiedName = nullptr;
TagKind Tag;
};
struct ArrayTypeNode : public TypeNode {
ArrayTypeNode() : TypeNode(NodeKind::ArrayType) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override;
void outputDimensionsImpl(OutputStream &OS, OutputFlags Flags) const;
void outputOneDimension(OutputStream &OS, OutputFlags Flags, Node *N) const;
// A list of array dimensions. e.g. [3,4,5] in `int Foo[3][4][5]`
NodeArrayNode *Dimensions = nullptr;
// The type of array element.
TypeNode *ElementType = nullptr;
};
struct IntrinsicNode : public TypeNode {
IntrinsicNode() : TypeNode(NodeKind::IntrinsicType) {}
void output(OutputStream &OS, OutputFlags Flags) const override {}
};
struct CustomTypeNode : public TypeNode {
CustomTypeNode() : TypeNode(NodeKind::Custom) {}
void outputPre(OutputStream &OS, OutputFlags Flags) const override;
void outputPost(OutputStream &OS, OutputFlags Flags) const override;
IdentifierNode *Identifier = nullptr;
};
struct NodeArrayNode : public Node {
NodeArrayNode() : Node(NodeKind::NodeArray) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
void output(OutputStream &OS, OutputFlags Flags, StringView Separator) const;
Node **Nodes = nullptr;
size_t Count = 0;
};
struct QualifiedNameNode : public Node {
QualifiedNameNode() : Node(NodeKind::QualifiedName) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
NodeArrayNode *Components = nullptr;
IdentifierNode *getUnqualifiedIdentifier() {
Node *LastComponent = Components->Nodes[Components->Count - 1];
return static_cast<IdentifierNode *>(LastComponent);
}
};
struct TemplateParameterReferenceNode : public Node {
TemplateParameterReferenceNode()
: Node(NodeKind::TemplateParameterReference) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
SymbolNode *Symbol = nullptr;
int ThunkOffsetCount = 0;
std::array<int64_t, 3> ThunkOffsets;
PointerAffinity Affinity = PointerAffinity::None;
bool IsMemberPointer = false;
};
struct IntegerLiteralNode : public Node {
IntegerLiteralNode() : Node(NodeKind::IntegerLiteral) {}
IntegerLiteralNode(uint64_t Value, bool IsNegative)
: Node(NodeKind::IntegerLiteral), Value(Value), IsNegative(IsNegative) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
uint64_t Value = 0;
bool IsNegative = false;
};
struct RttiBaseClassDescriptorNode : public IdentifierNode {
RttiBaseClassDescriptorNode()
: IdentifierNode(NodeKind::RttiBaseClassDescriptor) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
uint32_t NVOffset = 0;
int32_t VBPtrOffset = 0;
uint32_t VBTableOffset = 0;
uint32_t Flags = 0;
};
struct SymbolNode : public Node {
explicit SymbolNode(NodeKind K) : Node(K) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
QualifiedNameNode *Name = nullptr;
};
struct SpecialTableSymbolNode : public SymbolNode {
explicit SpecialTableSymbolNode()
: SymbolNode(NodeKind::SpecialTableSymbol) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
QualifiedNameNode *TargetName = nullptr;
Qualifiers Quals = Qualifiers::Q_None;
};
struct LocalStaticGuardVariableNode : public SymbolNode {
LocalStaticGuardVariableNode()
: SymbolNode(NodeKind::LocalStaticGuardVariable) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
bool IsVisible = false;
};
struct EncodedStringLiteralNode : public SymbolNode {
EncodedStringLiteralNode() : SymbolNode(NodeKind::EncodedStringLiteral) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
StringView DecodedString;
bool IsTruncated = false;
CharKind Char = CharKind::Char;
};
struct VariableSymbolNode : public SymbolNode {
VariableSymbolNode() : SymbolNode(NodeKind::VariableSymbol) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
StorageClass SC = StorageClass::None;
TypeNode *Type = nullptr;
};
struct FunctionSymbolNode : public SymbolNode {
FunctionSymbolNode() : SymbolNode(NodeKind::FunctionSymbol) {}
void output(OutputStream &OS, OutputFlags Flags) const override;
FunctionSignatureNode *Signature = nullptr;
};
} // namespace ms_demangle
} // namespace llvm
#endif

View File

@@ -0,0 +1,126 @@
//===--- StringView.h -------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// FIXME: Use std::string_view instead when we support C++17.
//
//===----------------------------------------------------------------------===//
#ifndef DEMANGLE_STRINGVIEW_H
#define DEMANGLE_STRINGVIEW_H
#include "DemangleConfig.h"
#include <algorithm>
#include <cassert>
#include <cstring>
DEMANGLE_NAMESPACE_BEGIN
class StringView {
const char *First;
const char *Last;
public:
static const size_t npos = ~size_t(0);
template <size_t N>
StringView(const char (&Str)[N]) : First(Str), Last(Str + N - 1) {}
StringView(const char *First_, const char *Last_)
: First(First_), Last(Last_) {}
StringView(const char *First_, size_t Len)
: First(First_), Last(First_ + Len) {}
StringView(const char *Str) : First(Str), Last(Str + std::strlen(Str)) {}
StringView() : First(nullptr), Last(nullptr) {}
StringView substr(size_t From) const {
return StringView(begin() + From, size() - From);
}
size_t find(char C, size_t From = 0) const {
size_t FindBegin = std::min(From, size());
// Avoid calling memchr with nullptr.
if (FindBegin < size()) {
// Just forward to memchr, which is faster than a hand-rolled loop.
if (const void *P = ::memchr(First + FindBegin, C, size() - FindBegin))
return size_t(static_cast<const char *>(P) - First);
}
return npos;
}
StringView substr(size_t From, size_t To) const {
if (To >= size())
To = size() - 1;
if (From >= size())
From = size() - 1;
return StringView(First + From, First + To);
}
StringView dropFront(size_t N = 1) const {
if (N >= size())
N = size();
return StringView(First + N, Last);
}
StringView dropBack(size_t N = 1) const {
if (N >= size())
N = size();
return StringView(First, Last - N);
}
char front() const {
assert(!empty());
return *begin();
}
char back() const {
assert(!empty());
return *(end() - 1);
}
char popFront() {
assert(!empty());
return *First++;
}
bool consumeFront(char C) {
if (!startsWith(C))
return false;
*this = dropFront(1);
return true;
}
bool consumeFront(StringView S) {
if (!startsWith(S))
return false;
*this = dropFront(S.size());
return true;
}
bool startsWith(char C) const { return !empty() && *begin() == C; }
bool startsWith(StringView Str) const {
if (Str.size() > size())
return false;
return std::equal(Str.begin(), Str.end(), begin());
}
const char &operator[](size_t Idx) const { return *(begin() + Idx); }
const char *begin() const { return First; }
const char *end() const { return Last; }
size_t size() const { return static_cast<size_t>(Last - First); }
bool empty() const { return First == Last; }
};
inline bool operator==(const StringView &LHS, const StringView &RHS) {
return LHS.size() == RHS.size() &&
std::equal(LHS.begin(), LHS.end(), RHS.begin());
}
DEMANGLE_NAMESPACE_END
#endif

View File

@@ -0,0 +1,191 @@
//===--- Utility.h ----------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Provide some utility classes for use in the demangler(s).
//
//===----------------------------------------------------------------------===//
#ifndef DEMANGLE_UTILITY_H
#define DEMANGLE_UTILITY_H
#include "StringView.h"
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <limits>
DEMANGLE_NAMESPACE_BEGIN
// Stream that AST nodes write their string representation into after the AST
// has been parsed.
class OutputStream {
char *Buffer = nullptr;
size_t CurrentPosition = 0;
size_t BufferCapacity = 0;
// Ensure there is at least n more positions in buffer.
void grow(size_t N) {
if (N + CurrentPosition >= BufferCapacity) {
BufferCapacity *= 2;
if (BufferCapacity < N + CurrentPosition)
BufferCapacity = N + CurrentPosition;
Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity));
if (Buffer == nullptr)
std::terminate();
}
}
void writeUnsigned(uint64_t N, bool isNeg = false) {
// Handle special case...
if (N == 0) {
*this << '0';
return;
}
char Temp[21];
char *TempPtr = std::end(Temp);
while (N) {
*--TempPtr = '0' + char(N % 10);
N /= 10;
}
// Add negative sign...
if (isNeg)
*--TempPtr = '-';
this->operator<<(StringView(TempPtr, std::end(Temp)));
}
public:
OutputStream(char *StartBuf, size_t Size)
: Buffer(StartBuf), CurrentPosition(0), BufferCapacity(Size) {}
OutputStream() = default;
void reset(char *Buffer_, size_t BufferCapacity_) {
CurrentPosition = 0;
Buffer = Buffer_;
BufferCapacity = BufferCapacity_;
}
/// If a ParameterPackExpansion (or similar type) is encountered, the offset
/// into the pack that we're currently printing.
unsigned CurrentPackIndex = std::numeric_limits<unsigned>::max();
unsigned CurrentPackMax = std::numeric_limits<unsigned>::max();
OutputStream &operator+=(StringView R) {
size_t Size = R.size();
if (Size == 0)
return *this;
grow(Size);
std::memmove(Buffer + CurrentPosition, R.begin(), Size);
CurrentPosition += Size;
return *this;
}
OutputStream &operator+=(char C) {
grow(1);
Buffer[CurrentPosition++] = C;
return *this;
}
OutputStream &operator<<(StringView R) { return (*this += R); }
OutputStream &operator<<(char C) { return (*this += C); }
OutputStream &operator<<(long long N) {
if (N < 0)
writeUnsigned(static_cast<unsigned long long>(-N), true);
else
writeUnsigned(static_cast<unsigned long long>(N));
return *this;
}
OutputStream &operator<<(unsigned long long N) {
writeUnsigned(N, false);
return *this;
}
OutputStream &operator<<(long N) {
return this->operator<<(static_cast<long long>(N));
}
OutputStream &operator<<(unsigned long N) {
return this->operator<<(static_cast<unsigned long long>(N));
}
OutputStream &operator<<(int N) {
return this->operator<<(static_cast<long long>(N));
}
OutputStream &operator<<(unsigned int N) {
return this->operator<<(static_cast<unsigned long long>(N));
}
size_t getCurrentPosition() const { return CurrentPosition; }
void setCurrentPosition(size_t NewPos) { CurrentPosition = NewPos; }
char back() const {
return CurrentPosition ? Buffer[CurrentPosition - 1] : '\0';
}
bool empty() const { return CurrentPosition == 0; }
char *getBuffer() { return Buffer; }
char *getBufferEnd() { return Buffer + CurrentPosition - 1; }
size_t getBufferCapacity() const { return BufferCapacity; }
};
template <class T> class SwapAndRestore {
T &Restore;
T OriginalValue;
bool ShouldRestore = true;
public:
SwapAndRestore(T &Restore_) : SwapAndRestore(Restore_, Restore_) {}
SwapAndRestore(T &Restore_, T NewVal)
: Restore(Restore_), OriginalValue(Restore) {
Restore = std::move(NewVal);
}
~SwapAndRestore() {
if (ShouldRestore)
Restore = std::move(OriginalValue);
}
void shouldRestore(bool ShouldRestore_) { ShouldRestore = ShouldRestore_; }
void restoreNow(bool Force) {
if (!Force && !ShouldRestore)
return;
Restore = std::move(OriginalValue);
ShouldRestore = false;
}
SwapAndRestore(const SwapAndRestore &) = delete;
SwapAndRestore &operator=(const SwapAndRestore &) = delete;
};
inline bool initializeOutputStream(char *Buf, size_t *N, OutputStream &S,
size_t InitSize) {
size_t BufferSize;
if (Buf == nullptr) {
Buf = static_cast<char *>(std::malloc(InitSize));
if (Buf == nullptr)
return false;
BufferSize = InitSize;
} else
BufferSize = *N;
S.reset(Buf, BufferSize);
return true;
}
DEMANGLE_NAMESPACE_END
#endif

View File

@@ -1,48 +0,0 @@
#pragma once
#include <vector>
#include <functional>
namespace hex {
enum class Events {
DataChanged,
PatternChanged,
FileDropped,
ByteSelected
};
struct EventHandler {
void *sender;
Events eventType;
std::function<void(const void*)> callback;
};
class EventManager {
public:
void post(Events eventType, const void *userData) {
for (auto &handler : this->m_eventHandlers)
if (eventType == handler.eventType)
handler.callback(userData);
}
void subscribe(Events eventType, void *sender, std::function<void(const void*)> callback) {
for (auto &handler : this->m_eventHandlers)
if (eventType == handler.eventType && sender == handler.sender)
return;
this->m_eventHandlers.push_back(EventHandler { sender, eventType, callback });
}
void unsubscribe(Events eventType, void *sender) {
std::erase_if(this->m_eventHandlers, [&eventType, &sender](EventHandler handler) {
return eventType == handler.eventType && sender == handler.sender;
});
}
private:
std::vector<EventHandler> m_eventHandlers;
};
}

View File

@@ -5,6 +5,7 @@
#include <array>
#include <optional>
#include <string>
#include <vector>
namespace hex {
@@ -21,4 +22,6 @@ namespace hex {
std::array<u32, 12> sha384(prv::Provider* &data, u64 offset, size_t size);
std::array<u32, 16> sha512(prv::Provider* &data, u64 offset, size_t size);
std::vector<u8> decode64(const std::vector<u8> &input);
std::vector<u8> encode64(const std::vector<u8> &input);
}

View File

@@ -0,0 +1,54 @@
#pragma once
#include <capstone/capstone.h>
#include <hex.hpp>
namespace hex {
enum class Architecture : s32 {
ARM,
ARM64,
MIPS,
X86,
PPC,
SPARC,
SYSZ,
XCORE,
M68K,
TMS320C64X,
M680X,
EVM,
MAX,
MIN = ARM
};
class Disassembler {
public:
static constexpr cs_arch toCapstoneArchictecture(Architecture architecture) {
return static_cast<cs_arch>(architecture);
}
static inline bool isSupported(Architecture architecture) {
return cs_support(toCapstoneArchictecture(architecture));
}
constexpr static const char * const ArchitectureNames[] = { "ARM32", "ARM64", "MIPS", "x86", "PowerPC", "Sparc", "SystemZ", "XCore", "68K", "TMS320C64x", "680X", "Ethereum" };
static inline s32 getArchitectureSupportedCount() {
static s32 supportedCount = -1;
if (supportedCount != -1) {
return supportedCount;
}
for (supportedCount = static_cast<s32>(Architecture::MIN); supportedCount < static_cast<s32>(Architecture::MAX); supportedCount++) {
if (!cs_support(supportedCount)) {
break;
}
}
return supportedCount;
}
};
}

View File

@@ -0,0 +1,33 @@
#pragma once
#include <string>
#include <string_view>
struct _object;
typedef struct _object PyObject;
namespace hex {
namespace prv { class Provider; }
class LoaderScript {
public:
LoaderScript() = delete;
static bool processFile(std::string_view scriptPath);
static void setFilePath(std::string_view filePath) { LoaderScript::s_filePath = filePath; }
static void setDataProvider(prv::Provider* provider) { LoaderScript::s_dataProvider = provider; }
private:
static inline std::string s_filePath;
static inline prv::Provider* s_dataProvider;
static PyObject* Py_getFilePath(PyObject *self, PyObject *args);
static PyObject* Py_addPatch(PyObject *self, PyObject *args);
static PyObject* Py_addBookmark(PyObject *self, PyObject *args);
static PyObject* Py_addStruct(PyObject *self, PyObject *args);
static PyObject* Py_addUnion(PyObject *self, PyObject *args);
};
}

View File

@@ -0,0 +1,88 @@
#pragma once
#include <hex.hpp>
#include <string>
#include <vector>
#include <queue>
#include <unordered_map>
#include <functional>
#include <optional>
namespace hex {
enum class TokenType {
Number,
Variable,
Function,
Operator,
Bracket
};
enum class Operator : u16 {
Invalid = 0x000,
Assign = 0x010,
Or = 0x020,
Xor = 0x030,
And = 0x040,
BitwiseOr = 0x050,
BitwiseXor = 0x060,
BitwiseAnd = 0x070,
Equals = 0x080,
NotEquals = 0x081,
GreaterThan = 0x090,
LessThan = 0x091,
GreaterThanOrEquals = 0x092,
LessThanOrEquals = 0x093,
ShiftLeft = 0x0A0,
ShiftRight = 0x0A1,
Addition = 0x0B0,
Subtraction = 0x0B1,
Multiplication = 0x0C0,
Division = 0x0C1,
Modulus = 0x0C2,
Exponentiation = 0x1D0,
Combine = 0x0E0,
BitwiseNot = 0x0F0,
Not = 0x0F1
};
enum class BracketType : std::uint8_t {
Left,
Right
};
struct Token {
TokenType type;
long double number;
Operator op;
BracketType bracketType;
std::string name;
std::vector<long double> arguments;
};
class MathEvaluator {
public:
MathEvaluator() = default;
std::optional<long double> evaluate(std::string input);
void registerStandardVariables();
void registerStandardFunctions();
void setVariable(std::string name, long double value);
void setFunction(std::string name, std::function<std::optional<long double>(std::vector<long double>)> function, size_t minNumArgs, size_t maxNumArgs);
std::unordered_map<std::string, long double>& getVariables() { return this->m_variables; }
private:
std::queue<Token> parseInput(const char *input);
std::queue<Token> toPostfix(std::queue<Token> inputQueue);
std::optional<long double> evaluate(std::queue<Token> postfixTokens);
std::unordered_map<std::string, long double> m_variables;
std::unordered_map<std::string, std::function<std::optional<long double>(std::vector<long double>)>> m_functions;
};
}

View File

@@ -0,0 +1,17 @@
#pragma once
#include <hex.hpp>
#include <map>
#include <vector>
namespace hex {
using Patches = std::map<u64, u8>;
std::vector<u8> generateIPSPatch(const Patches &patches);
std::vector<u8> generateIPS32Patch(const Patches &patches);
Patches loadIPSPatch(const std::vector<u8> &ipsPatch);
Patches loadIPS32Patch(const std::vector<u8> &ipsPatch);
}

View File

@@ -0,0 +1,51 @@
#pragma once
#include <hex.hpp>
#include "views/view.hpp"
#include "providers/provider.hpp"
#include <string_view>
namespace hex {
class Plugin {
public:
Plugin(std::string_view path);
~Plugin();
void initializePlugin(SharedData &sharedData) const;
View* createView() const;
void drawToolsEntry() const;
private:
using InitializePluginFunc = void(*)(SharedData &sharedData);
using CreateViewFunc = View*(*)();
using DrawToolsEntryFunc = void(*)();
void *m_handle = nullptr;
InitializePluginFunc m_initializePluginFunction = nullptr;
CreateViewFunc m_createViewFunction = nullptr;
DrawToolsEntryFunc m_drawToolsEntryFunction = nullptr;
};
class PluginHandler {
public:
PluginHandler() = delete;
static void load(std::string_view pluginFolder);
static void unload();
static void reload();
static const auto& getPlugins() {
return PluginHandler::s_plugins;
}
private:
static inline std::string s_pluginFolder;
static inline std::vector<Plugin> s_plugins;
};
}

View File

@@ -0,0 +1,46 @@
#pragma once
#include <list>
#include <string>
#include <string_view>
#include "patches.hpp"
#include "helpers/utils.hpp"
namespace hex {
class ProjectFile {
public:
ProjectFile() = delete;
static bool load(std::string_view filePath);
static bool store(std::string_view filePath = "");
[[nodiscard]] static bool hasUnsavedChanges() { return ProjectFile::s_hasUnsavedChanged; }
static void markDirty() { if (!ProjectFile::s_currProjectFilePath.empty()) ProjectFile::s_hasUnsavedChanged = true; }
[[nodiscard]] static std::string getProjectFilePath() { return ProjectFile::s_currProjectFilePath; }
[[nodiscard]] static std::string getFilePath() { return ProjectFile::s_filePath; }
static void setFilePath(std::string_view filePath) { ProjectFile::s_hasUnsavedChanged = true; ProjectFile::s_filePath = filePath; }
[[nodiscard]] static std::string getPattern() { return ProjectFile::s_pattern; }
static void setPattern(std::string_view pattern) { ProjectFile::s_hasUnsavedChanged = true; ProjectFile::s_pattern = pattern; }
[[nodiscard]] static const Patches& getPatches() { return ProjectFile::s_patches; }
static void setPatches(const Patches &patches) { ProjectFile::s_hasUnsavedChanged = true; ProjectFile::s_patches = patches; }
[[nodiscard]] static const std::list<Bookmark>& getBookmarks() { return ProjectFile::s_bookmarks; }
static void setBookmarks(const std::list<Bookmark> &bookmarks) { ProjectFile::s_hasUnsavedChanged = true; ProjectFile::s_bookmarks = bookmarks; }
private:
static inline std::string s_currProjectFilePath;
static inline bool s_hasUnsavedChanged = false;
static inline std::string s_filePath;
static inline std::string s_pattern;
static inline Patches s_patches;
static inline std::list<Bookmark> s_bookmarks;
};
}

View File

@@ -2,6 +2,7 @@
#include "token.hpp"
#include <bit>
#include <optional>
#include <unordered_map>
#include <vector>
@@ -10,119 +11,495 @@ namespace hex::lang {
class ASTNode {
public:
enum class Type {
VariableDecl,
TypeDecl,
Struct,
Union,
Enum,
Bitfield,
Scope,
};
constexpr ASTNode() = default;
constexpr virtual ~ASTNode() = default;
constexpr ASTNode(const ASTNode &) = default;
explicit ASTNode(Type type) : m_type(type) {}
virtual ~ASTNode() = default;
[[nodiscard]] constexpr u32 getLineNumber() const { return this->m_lineNumber; }
constexpr void setLineNumber(u32 lineNumber) { this->m_lineNumber = lineNumber; }
Type getType() { return this->m_type; }
virtual ASTNode* clone() const = 0;
private:
Type m_type;
u32 m_lineNumber = 1;
};
class ASTNodeVariableDecl : public ASTNode {
class ASTNodeIntegerLiteral : public ASTNode {
public:
explicit ASTNodeVariableDecl(const Token::TypeToken::Type &type, const std::string &name, const std::string& customTypeName = "", std::optional<u64> offset = { }, size_t arraySize = 1, std::optional<std::string> arraySizeVariable = { }, std::optional<u8> pointerSize = { })
: ASTNode(Type::VariableDecl), m_type(type), m_name(name), m_customTypeName(customTypeName), m_offset(offset), m_arraySize(arraySize), m_arraySizeVariable(arraySizeVariable), m_pointerSize(pointerSize) { }
ASTNodeIntegerLiteral(Token::IntegerLiteral literal) : ASTNode(), m_literal(literal) { }
const Token::TypeToken::Type& getVariableType() const { return this->m_type; }
const std::string& getCustomVariableTypeName() const { return this->m_customTypeName; }
const std::string& getVariableName() const { return this->m_name; };
std::optional<u64> getOffset() const { return this->m_offset; }
size_t getArraySize() const { return this->m_arraySize; }
std::optional<std::string> getArraySizeVariable() const { return this->m_arraySizeVariable; }
std::optional<u8> getPointerSize() const { return this->m_pointerSize; }
ASTNodeIntegerLiteral(const ASTNodeIntegerLiteral&) = default;
ASTNode* clone() const override {
return new ASTNodeIntegerLiteral(*this);
}
[[nodiscard]] const auto& getValue() const {
return this->m_literal.second;
}
[[nodiscard]] Token::ValueType getType() const {
return this->m_literal.first;
}
private:
Token::TypeToken::Type m_type;
std::string m_name, m_customTypeName;
std::optional<u64> m_offset;
size_t m_arraySize;
std::optional<std::string> m_arraySizeVariable;
std::optional<u8> m_pointerSize;
Token::IntegerLiteral m_literal;
};
class ASTNodeScope : public ASTNode {
class ASTNodeNumericExpression : public ASTNode {
public:
explicit ASTNodeScope(std::vector<ASTNode*> nodes) : ASTNode(Type::Scope), m_nodes(nodes) { }
ASTNodeNumericExpression(ASTNode *left, ASTNode *right, Token::Operator op)
: ASTNode(), m_left(left), m_right(right), m_operator(op) { }
~ASTNodeNumericExpression() override {
delete this->m_left;
delete this->m_right;
}
ASTNodeNumericExpression(const ASTNodeNumericExpression &other) : ASTNode(other) {
this->m_operator = other.m_operator;
this->m_left = other.m_left->clone();
this->m_right = other.m_right->clone();
}
ASTNode* clone() const override {
return new ASTNodeNumericExpression(*this);
}
ASTNode *getLeftOperand() { return this->m_left; }
ASTNode *getRightOperand() { return this->m_right; }
Token::Operator getOperator() { return this->m_operator; }
std::vector<ASTNode*> &getNodes() { return this->m_nodes; }
private:
std::vector<ASTNode*> m_nodes;
ASTNode *m_left, *m_right;
Token::Operator m_operator;
};
class ASTNodeStruct : public ASTNode {
class ASTNodeTernaryExpression : public ASTNode {
public:
explicit ASTNodeStruct(std::string name, std::vector<ASTNode*> nodes)
: ASTNode(Type::Struct), m_name(name), m_nodes(nodes) { }
ASTNodeTernaryExpression(ASTNode *first, ASTNode *second, ASTNode *third, Token::Operator op)
: ASTNode(), m_first(first), m_second(second), m_third(third), m_operator(op) { }
~ASTNodeTernaryExpression() override {
delete this->m_first;
delete this->m_second;
delete this->m_third;
}
ASTNodeTernaryExpression(const ASTNodeTernaryExpression &other) : ASTNode(other) {
this->m_operator = other.m_operator;
this->m_first = other.m_first->clone();
this->m_second = other.m_second->clone();
this->m_third = other.m_third->clone();
}
ASTNode* clone() const override {
return new ASTNodeTernaryExpression(*this);
}
ASTNode *getFirstOperand() { return this->m_first; }
ASTNode *getSecondOperand() { return this->m_second; }
ASTNode *getThirdOperand() { return this->m_third; }
Token::Operator getOperator() { return this->m_operator; }
const std::string& getName() const { return this->m_name; }
std::vector<ASTNode*> &getNodes() { return this->m_nodes; }
private:
std::string m_name;
std::vector<ASTNode*> m_nodes;
ASTNode *m_first, *m_second, *m_third;
Token::Operator m_operator;
};
class ASTNodeUnion : public ASTNode {
class ASTNodeBuiltinType : public ASTNode {
public:
explicit ASTNodeUnion(std::string name, std::vector<ASTNode*> nodes)
: ASTNode(Type::Union), m_name(name), m_nodes(nodes) { }
constexpr explicit ASTNodeBuiltinType(Token::ValueType type)
: ASTNode(), m_type(type) { }
[[nodiscard]] constexpr const auto& getType() const { return this->m_type; }
ASTNode* clone() const override {
return new ASTNodeBuiltinType(*this);
}
const std::string& getName() const { return this->m_name; }
std::vector<ASTNode*> &getNodes() { return this->m_nodes; }
private:
std::string m_name;
std::vector<ASTNode*> m_nodes;
};
class ASTNodeBitField : public ASTNode {
public:
explicit ASTNodeBitField(std::string name, std::vector<std::pair<std::string, size_t>> fields)
: ASTNode(Type::Bitfield), m_name(name), m_fields(fields) { }
const std::string& getName() const { return this->m_name; }
std::vector<std::pair<std::string, size_t>> &getFields() { return this->m_fields; }
private:
std::string m_name;
std::vector<std::pair<std::string, size_t>> m_fields;
const Token::ValueType m_type;
};
class ASTNodeTypeDecl : public ASTNode {
public:
explicit ASTNodeTypeDecl(const Token::TypeToken::Type &type, const std::string &name, const std::string& customTypeName = "")
: ASTNode(Type::TypeDecl), m_type(type), m_name(name), m_customTypeName(customTypeName) { }
ASTNodeTypeDecl(std::string_view name, ASTNode *type, std::optional<std::endian> endian = { })
: ASTNode(), m_name(name), m_type(type), m_endian(endian) { }
const std::string& getTypeName() const { return this->m_name; };
ASTNodeTypeDecl(const ASTNodeTypeDecl& other) : ASTNode(other) {
this->m_name = other.m_name;
this->m_type = other.m_type->clone();
this->m_endian = other.m_endian;
}
~ASTNodeTypeDecl() override {
delete this->m_type;
}
ASTNode* clone() const override {
return new ASTNodeTypeDecl(*this);
}
[[nodiscard]] std::string_view getName() const { return this->m_name; }
[[nodiscard]] ASTNode* getType() { return this->m_type; }
[[nodiscard]] std::optional<std::endian> getEndian() const { return this->m_endian; }
const Token::TypeToken::Type& getAssignedType() const { return this->m_type; }
const std::string& getAssignedCustomTypeName() const { return this->m_customTypeName; }
private:
Token::TypeToken::Type m_type;
std::string m_name, m_customTypeName;
std::string m_name;
ASTNode *m_type;
std::optional<std::endian> m_endian;
};
class ASTNodeVariableDecl : public ASTNode {
public:
ASTNodeVariableDecl(std::string_view name, ASTNode *type, ASTNode *placementOffset = nullptr)
: ASTNode(), m_name(name), m_type(type), m_placementOffset(placementOffset) { }
ASTNodeVariableDecl(const ASTNodeVariableDecl &other) : ASTNode(other) {
this->m_name = other.m_name;
this->m_type = other.m_type->clone();
if (other.m_placementOffset != nullptr)
this->m_placementOffset = other.m_placementOffset->clone();
else
this->m_placementOffset = nullptr;
}
~ASTNodeVariableDecl() override {
delete this->m_type;
}
ASTNode* clone() const override {
return new ASTNodeVariableDecl(*this);
}
[[nodiscard]] std::string_view getName() const { return this->m_name; }
[[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; }
[[nodiscard]] constexpr auto getPlacementOffset() const { return this->m_placementOffset; }
private:
std::string m_name;
ASTNode *m_type;
ASTNode *m_placementOffset;
};
class ASTNodeArrayVariableDecl : public ASTNode {
public:
ASTNodeArrayVariableDecl(std::string_view name, ASTNode *type, ASTNode *size, ASTNode *placementOffset = nullptr)
: ASTNode(), m_name(name), m_type(type), m_size(size), m_placementOffset(placementOffset) { }
ASTNodeArrayVariableDecl(const ASTNodeArrayVariableDecl &other) : ASTNode(other) {
this->m_name = other.m_name;
this->m_type = other.m_type->clone();
if (other.m_size != nullptr)
this->m_size = other.m_size->clone();
else
this->m_size = nullptr;
if (other.m_placementOffset != nullptr)
this->m_placementOffset = other.m_placementOffset->clone();
else
this->m_placementOffset = nullptr;
}
~ASTNodeArrayVariableDecl() override {
delete this->m_type;
delete this->m_size;
}
ASTNode* clone() const override {
return new ASTNodeArrayVariableDecl(*this);
}
[[nodiscard]] std::string_view getName() const { return this->m_name; }
[[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; }
[[nodiscard]] constexpr ASTNode* getSize() const { return this->m_size; }
[[nodiscard]] constexpr auto getPlacementOffset() const { return this->m_placementOffset; }
private:
std::string m_name;
ASTNode *m_type;
ASTNode *m_size;
ASTNode *m_placementOffset;
};
class ASTNodePointerVariableDecl : public ASTNode {
public:
ASTNodePointerVariableDecl(std::string_view name, ASTNode *type, ASTNode *sizeType, ASTNode *placementOffset = nullptr)
: ASTNode(), m_name(name), m_type(type), m_sizeType(sizeType), m_placementOffset(placementOffset) { }
ASTNodePointerVariableDecl(const ASTNodePointerVariableDecl &other) : ASTNode(other) {
this->m_name = other.m_name;
this->m_type = other.m_type->clone();
this->m_sizeType = other.m_sizeType->clone();
if (other.m_placementOffset != nullptr)
this->m_placementOffset = other.m_placementOffset->clone();
else
this->m_placementOffset = nullptr;
}
~ASTNodePointerVariableDecl() override {
delete this->m_type;
}
ASTNode* clone() const override {
return new ASTNodePointerVariableDecl(*this);
}
[[nodiscard]] std::string_view getName() const { return this->m_name; }
[[nodiscard]] constexpr ASTNode* getType() const { return this->m_type; }
[[nodiscard]] constexpr ASTNode* getSizeType() const { return this->m_sizeType; }
[[nodiscard]] constexpr auto getPlacementOffset() const { return this->m_placementOffset; }
private:
std::string m_name;
ASTNode *m_type;
ASTNode *m_sizeType;
ASTNode *m_placementOffset;
};
class ASTNodeStruct : public ASTNode {
public:
ASTNodeStruct() : ASTNode() { }
ASTNodeStruct(const ASTNodeStruct &other) : ASTNode(other) {
for (const auto &otherMember : other.getMembers())
this->m_members.push_back(otherMember->clone());
}
~ASTNodeStruct() override {
for (auto &member : this->m_members)
delete member;
}
ASTNode* clone() const override {
return new ASTNodeStruct(*this);
}
[[nodiscard]] const std::vector<ASTNode*>& getMembers() const { return this->m_members; }
void addMember(ASTNode *node) { this->m_members.push_back(node); }
private:
std::vector<ASTNode*> m_members;
};
class ASTNodeUnion : public ASTNode {
public:
ASTNodeUnion() : ASTNode() { }
ASTNodeUnion(const ASTNodeUnion &other) : ASTNode(other) {
for (const auto &otherMember : other.getMembers())
this->m_members.push_back(otherMember->clone());
}
~ASTNodeUnion() override {
for (auto &member : this->m_members)
delete member;
}
ASTNode* clone() const override {
return new ASTNodeUnion(*this);
}
[[nodiscard]] const std::vector<ASTNode*>& getMembers() const { return this->m_members; }
void addMember(ASTNode *node) { this->m_members.push_back(node); }
private:
std::vector<ASTNode*> m_members;
};
class ASTNodeEnum : public ASTNode {
public:
explicit ASTNodeEnum(const Token::TypeToken::Type &type, const std::string &name)
: ASTNode(Type::Enum), m_type(type), m_name(name) { }
explicit ASTNodeEnum(ASTNode *underlyingType) : ASTNode(), m_underlyingType(underlyingType) { }
const std::string& getName() const { return this->m_name; };
ASTNodeEnum(const ASTNodeEnum &other) : ASTNode(other) {
for (const auto &[name, entry] : other.getEntries())
this->m_entries.insert({ name, entry->clone() });
this->m_underlyingType = other.m_underlyingType->clone();
}
~ASTNodeEnum() override {
for (auto &[name, expr] : this->m_entries)
delete expr;
delete this->m_underlyingType;
}
ASTNode* clone() const override {
return new ASTNodeEnum(*this);
}
[[nodiscard]] const std::unordered_map<std::string, ASTNode*>& getEntries() const { return this->m_entries; }
void addEntry(const std::string &name, ASTNode* expression) { this->m_entries.insert({ name, expression }); }
[[nodiscard]] ASTNode *getUnderlyingType() { return this->m_underlyingType; }
const Token::TypeToken::Type& getUnderlyingType() const { return this->m_type; }
std::vector<std::pair<u64, std::string>>& getValues() { return this->m_values; }
private:
Token::TypeToken::Type m_type;
std::string m_name;
std::vector<std::pair<u64, std::string>> m_values;
std::unordered_map<std::string, ASTNode*> m_entries;
ASTNode *m_underlyingType;
};
class ASTNodeBitfield : public ASTNode {
public:
ASTNodeBitfield() : ASTNode() { }
ASTNodeBitfield(const ASTNodeBitfield &other) : ASTNode(other) {
for (const auto &[name, entry] : other.getEntries())
this->m_entries.emplace_back(name, entry->clone());
}
~ASTNodeBitfield() override {
for (auto &[name, expr] : this->m_entries)
delete expr;
}
ASTNode* clone() const override {
return new ASTNodeBitfield(*this);
}
[[nodiscard]] const std::vector<std::pair<std::string, ASTNode*>>& getEntries() const { return this->m_entries; }
void addEntry(const std::string &name, ASTNode* size) { this->m_entries.emplace_back(name, size); }
private:
std::vector<std::pair<std::string, ASTNode*>> m_entries;
};
class ASTNodeRValue : public ASTNode {
public:
explicit ASTNodeRValue(std::vector<std::string> path) : ASTNode(), m_path(std::move(path)) { }
ASTNodeRValue(const ASTNodeRValue&) = default;
ASTNode* clone() const override {
return new ASTNodeRValue(*this);
}
const std::vector<std::string>& getPath() {
return this->m_path;
}
private:
std::vector<std::string> m_path;
};
class ASTNodeScopeResolution : public ASTNode {
public:
explicit ASTNodeScopeResolution(std::vector<std::string> path) : ASTNode(), m_path(std::move(path)) { }
ASTNodeScopeResolution(const ASTNodeScopeResolution&) = default;
ASTNode* clone() const override {
return new ASTNodeScopeResolution(*this);
}
const std::vector<std::string>& getPath() {
return this->m_path;
}
private:
std::vector<std::string> m_path;
};
class ASTNodeConditionalStatement : public ASTNode {
public:
explicit ASTNodeConditionalStatement(ASTNode *condition, std::vector<ASTNode*> trueBody, std::vector<ASTNode*> falseBody)
: ASTNode(), m_condition(condition), m_trueBody(std::move(trueBody)), m_falseBody(std::move(falseBody)) { }
~ASTNodeConditionalStatement() override {
delete this->m_condition;
for (auto &statement : this->m_trueBody)
delete statement;
for (auto &statement : this->m_falseBody)
delete statement;
}
ASTNodeConditionalStatement(const ASTNodeConditionalStatement &other) : ASTNode(other) {
this->m_condition = other.m_condition->clone();
for (auto &statement : other.m_trueBody)
this->m_trueBody.push_back(statement->clone());
for (auto &statement : other.m_falseBody)
this->m_falseBody.push_back(statement->clone());
}
ASTNode* clone() const override {
return new ASTNodeConditionalStatement(*this);
}
[[nodiscard]] ASTNode* getCondition() {
return this->m_condition;
}
[[nodiscard]] const std::vector<ASTNode*>& getTrueBody() const {
return this->m_trueBody;
}
[[nodiscard]] const std::vector<ASTNode*>& getFalseBody() const {
return this->m_falseBody;
}
private:
ASTNode *m_condition;
std::vector<ASTNode*> m_trueBody, m_falseBody;
};
class ASTNodeFunctionCall : public ASTNode {
public:
explicit ASTNodeFunctionCall(std::string_view functionName, std::vector<ASTNode*> params)
: ASTNode(), m_functionName(functionName), m_params(std::move(params)) { }
~ASTNodeFunctionCall() override {
for (auto &param : this->m_params)
delete param;
}
ASTNodeFunctionCall(const ASTNodeFunctionCall &other) : ASTNode(other) {
this->m_functionName = other.m_functionName;
for (auto &param : other.m_params)
this->m_params.push_back(param->clone());
}
ASTNode* clone() const override {
return new ASTNodeFunctionCall(*this);
}
[[nodiscard]] std::string_view getFunctionName() {
return this->m_functionName;
}
[[nodiscard]] const std::vector<ASTNode*>& getParams() const {
return this->m_params;
}
private:
std::string m_functionName;
std::vector<ASTNode*> m_params;
};
class ASTNodeStringLiteral : public ASTNode {
public:
explicit ASTNodeStringLiteral(std::string_view string) : ASTNode(), m_string(string) { }
~ASTNodeStringLiteral() override { }
ASTNodeStringLiteral(const ASTNodeStringLiteral &other) : ASTNode(other) {
this->m_string = other.m_string;
}
ASTNode* clone() const override {
return new ASTNodeStringLiteral(*this);
}
[[nodiscard]] std::string_view getString() {
return this->m_string;
}
private:
std::string m_string;
};
}

View File

@@ -3,6 +3,7 @@
#include <hex.hpp>
#include "providers/provider.hpp"
#include "helpers/utils.hpp"
#include "lang/pattern_data.hpp"
#include "ast_node.hpp"
@@ -15,25 +16,110 @@ namespace hex::lang {
class Evaluator {
public:
Evaluator(prv::Provider* &provider, std::endian dataEndianess);
enum ConsoleLogLevel {
Debug,
Info,
Warning,
Error
};
std::pair<Result, std::vector<PatternData*>> evaluate(const std::vector<ASTNode*>& ast);
struct Function {
constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF;
constexpr static u32 MoreParametersThan = 0x8000'0000;
constexpr static u32 LessParametersThan = 0x4000'0000;
constexpr static u32 NoParameters = 0x0000'0000;
u32 parameterCount;
std::function<ASTNodeIntegerLiteral*(std::vector<ASTNode*>)> func;
};
Evaluator(prv::Provider* &provider, std::endian defaultDataEndian);
std::optional<std::vector<PatternData*>> evaluate(const std::vector<ASTNode*>& ast);
const auto& getConsoleLog() { return this->m_consoleLog; }
private:
std::unordered_map<std::string, ASTNode*> m_types;
std::map<std::string, ASTNode*> m_types;
prv::Provider* &m_provider;
std::endian m_dataEndianess;
std::endian m_defaultDataEndian;
u64 m_currOffset = 0;
std::vector<std::endian> m_endianStack;
std::vector<PatternData*> m_globalMembers;
std::vector<std::vector<PatternData*>*> m_currMembers;
std::map<std::string, Function> m_functions;
std::vector<std::pair<ConsoleLogLevel, std::string>> m_consoleLog;
using EvaluateError = std::string;
void emmitDebugInfo(std::string_view message) {
this->m_consoleLog.emplace_back(ConsoleLogLevel::Debug, "[-] " + std::string(message));
}
void emmitInfo(std::string_view message) {
this->m_consoleLog.emplace_back(ConsoleLogLevel::Info, "[i] " + std::string(message));
}
void emmitWaring(std::string_view message) {
this->m_consoleLog.emplace_back(ConsoleLogLevel::Warning, "[*] " + std::string(message));
}
[[noreturn]] static void throwEvaluateError(std::string_view message) {
throw EvaluateError("[!] " + std::string(message));
}
[[nodiscard]] std::endian getCurrentEndian() const {
return this->m_endianStack.back();
}
void addFunction(std::string_view name, u32 parameterCount, std::function<ASTNodeIntegerLiteral*(std::vector<ASTNode*>)> func) {
if (this->m_functions.contains(name.data()))
throwEvaluateError(hex::format("redefinition of function '%s'", name.data()));
this->m_functions[name.data()] = { parameterCount, func };
}
ASTNodeIntegerLiteral* evaluateScopeResolution(ASTNodeScopeResolution *node);
ASTNodeIntegerLiteral* evaluateRValue(ASTNodeRValue *node);
ASTNodeIntegerLiteral* evaluateFunctionCall(ASTNodeFunctionCall *node);
ASTNodeIntegerLiteral* evaluateOperator(ASTNodeIntegerLiteral *left, ASTNodeIntegerLiteral *right, Token::Operator op);
ASTNodeIntegerLiteral* evaluateOperand(ASTNode *node);
ASTNodeIntegerLiteral* evaluateTernaryExpression(ASTNodeTernaryExpression *node);
ASTNodeIntegerLiteral* evaluateMathematicalExpression(ASTNodeNumericExpression *node);
PatternData* evaluateBuiltinType(ASTNodeBuiltinType *node);
void evaluateMember(ASTNode *node, std::vector<PatternData*> &currMembers, bool increaseOffset);
PatternData* evaluateStruct(ASTNodeStruct *node);
PatternData* evaluateUnion(ASTNodeUnion *node);
PatternData* evaluateEnum(ASTNodeEnum *node);
PatternData* evaluateBitfield(ASTNodeBitfield *node);
PatternData* evaluateType(ASTNodeTypeDecl *node);
PatternData* evaluateVariable(ASTNodeVariableDecl *node);
PatternData* evaluateArray(ASTNodeArrayVariableDecl *node);
PatternData* evaluatePointer(ASTNodePointerVariableDecl *node);
std::pair<PatternData*, size_t> createStructPattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createUnionPattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createEnumPattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createBitfieldPattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createArrayPattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createStringPattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createCustomTypePattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
std::pair<PatternData*, size_t> createBuiltInTypePattern(ASTNodeVariableDecl *varDeclNode, u64 offset);
template<typename T>
T* asType(ASTNode *param) {
if (auto evaluatedParam = dynamic_cast<T*>(param); evaluatedParam != nullptr)
return evaluatedParam;
else
throwEvaluateError("function got wrong type of parameter");
}
#define BUILTIN_FUNCTION(name) ASTNodeIntegerLiteral* TOKEN_CONCAT(builtin_, name)(std::vector<ASTNode*> params)
BUILTIN_FUNCTION(findSequence);
BUILTIN_FUNCTION(readUnsigned);
BUILTIN_FUNCTION(readSigned);
BUILTIN_FUNCTION(assert);
BUILTIN_FUNCTION(warnAssert);
BUILTIN_FUNCTION(print);
#undef BUILTIN_FUNCTION
};
}

View File

@@ -4,6 +4,7 @@
#include "token.hpp"
#include <optional>
#include <string>
#include <vector>
@@ -11,9 +12,19 @@ namespace hex::lang {
class Lexer {
public:
using LexerError = std::pair<u32, std::string>;
Lexer();
std::pair<Result, std::vector<Token>> lex(const std::string& code);
std::optional<std::vector<Token>> lex(const std::string& code);
const LexerError& getError() { return this->m_error; }
private:
LexerError m_error;
[[noreturn]] void throwLexerError(std::string_view error, u32 lineNumber) const {
throw LexerError(lineNumber, "Lexer: " + std::string(error));
}
};
}

View File

@@ -1,18 +1,172 @@
#pragma once
#include <hex.hpp>
#include "token.hpp"
#include "ast_node.hpp"
#include "helpers/utils.hpp"
#include <unordered_map>
#include <stdexcept>
#include <utility>
#include <vector>
namespace hex::lang {
class Parser {
public:
Parser();
using TokenIter = std::vector<Token>::const_iterator;
using ParseError = std::pair<u32, std::string>;
std::pair<Result, std::vector<ASTNode*>> parse(const std::vector<Token> &tokens);
Parser() = default;
~Parser() = default;
std::optional<std::vector<ASTNode*>> parse(const std::vector<Token> &tokens);
const ParseError& getError() { return this->m_error; }
private:
ParseError m_error;
TokenIter m_curr;
TokenIter m_originalPosition;
std::unordered_map<std::string, ASTNode*> m_types;
std::vector<TokenIter> m_matchedOptionals;
u32 getLineNumber(s32 index) const {
return this->m_curr[index].lineNumber;
}
template<typename T>
const T& getValue(s32 index) const {
auto value = std::get_if<T>(&this->m_curr[index].value);
if (value == nullptr)
throwParseError("failed to decode token. Invalid type.", getLineNumber(index));
return *value;
}
Token::Type getType(s32 index) const {
return this->m_curr[index].type;
}
ASTNode* parseFunctionCall();
ASTNode* parseStringLiteral();
ASTNode* parseScopeResolution(std::vector<std::string> &path);
ASTNode* parseRValue(std::vector<std::string> &path);
ASTNode* parseFactor();
ASTNode* parseUnaryExpression();
ASTNode* parseMultiplicativeExpression();
ASTNode* parseAdditiveExpression();
ASTNode* parseShiftExpression();
ASTNode* parseRelationExpression();
ASTNode* parseEqualityExpression();
ASTNode* parseBinaryAndExpression();
ASTNode* parseBinaryXorExpression();
ASTNode* parseBinaryOrExpression();
ASTNode* parseBooleanAnd();
ASTNode* parseBooleanXor();
ASTNode* parseBooleanOr();
ASTNode* parseTernaryConditional();
ASTNode* parseMathematicalExpression();
ASTNode* parseConditional();
ASTNode* parseType(s32 startIndex);
ASTNode* parseUsingDeclaration();
ASTNode* parsePadding();
ASTNode* parseMemberVariable();
ASTNode* parseMemberArrayVariable();
ASTNode* parseMemberPointerVariable();
ASTNode* parseMember();
ASTNode* parseStruct();
ASTNode* parseUnion();
ASTNode* parseEnum();
ASTNode* parseBitfield();
ASTNode* parseVariablePlacement();
ASTNode* parseArrayVariablePlacement();
ASTNode* parsePointerVariablePlacement();
ASTNode* parseStatement();
std::vector<ASTNode*> parseTillToken(Token::Type endTokenType, const auto value) {
std::vector<ASTNode*> program;
ScopeExit guard([&]{ for (auto &node : program) delete node; });
while (this->m_curr->type != endTokenType || (*this->m_curr) != value) {
program.push_back(parseStatement());
}
this->m_curr++;
guard.release();
return program;
}
[[noreturn]] void throwParseError(std::string_view error, s32 token = -1) const {
throw ParseError(this->m_curr[token].lineNumber, "Parser: " + std::string(error));
}
/* Token consuming */
bool begin() {
this->m_originalPosition = this->m_curr;
this->m_matchedOptionals.clear();
return true;
}
bool sequence() {
return true;
}
bool sequence(Token::Type type, auto value, auto ... args) {
if (!peek(type, value)) {
this->m_curr = this->m_originalPosition;
return false;
}
this->m_curr++;
if (!sequence(args...)) {
this->m_curr = this->m_originalPosition;
return false;
}
return true;
}
bool variant(Token::Type type1, auto value1, Token::Type type2, auto value2) {
if (!peek(type1, value1)) {
if (!peek(type2, value2)) {
this->m_curr = this->m_originalPosition;
return false;
}
}
this->m_curr++;
return true;
}
bool optional(Token::Type type, auto value) {
if (peek(type, value)) {
this->m_matchedOptionals.push_back(this->m_curr);
this->m_curr++;
}
return true;
}
bool peek(Token::Type type, auto value, s32 index = 0) {
return this->m_curr[index].type == type && this->m_curr[index] == value;
}
bool peekOptional(Token::Type type, auto value, u32 index = 0) {
if (index >= this->m_matchedOptionals.size())
return false;
return peek(type, value, std::distance(this->m_curr, this->m_matchedOptionals[index]));
}
};

View File

@@ -1,18 +1,22 @@
#pragma once
#include <hex.hpp>
#include <string>
#include "imgui.h"
#include "imgui_memory_editor.h"
#include "providers/provider.hpp"
#include "utils.hpp"
#include "helpers/utils.hpp"
#include "lang/token.hpp"
#include <cstring>
#include <random>
#include <string>
namespace hex::lang {
using namespace ::std::literals::string_literals;
namespace {
std::string makeDisplayable(u8 *data, size_t size) {
@@ -24,6 +28,9 @@ namespace hex::lang {
result += *c;
}
if (*(data + size - 1) == '\x00')
result.pop_back();
return result;
}
@@ -31,11 +38,9 @@ namespace hex::lang {
class PatternData {
public:
enum class Type { Padding, Unsigned, Signed, Float, Character, String, Struct, Union, Array, Enum };
PatternData(Type type, u64 offset, size_t size, const std::string &name, u32 color = 0)
: m_type(type), m_offset(offset), m_size(size), m_color(color), m_name(name) {
constexpr u32 Palette[] = { 0x50b4771f, 0x500e7fff, 0x502ca02c, 0x502827d6, 0x50bd6794, 0x504b568c, 0x50c277e3, 0x507f7f7f, 0x5022bdbc, 0x50cfbe17 };
PatternData(u64 offset, size_t size, u32 color = 0)
: m_offset(offset), m_size(size), m_color(color) {
constexpr u32 Palette[] = { 0x70b4771f, 0x700e7fff, 0x702ca02c, 0x702827d6, 0x70bd6794, 0x704b568c, 0x70c277e3, 0x707f7f7f, 0x7022bdbc, 0x70cfbe17 };
if (color != 0)
return;
@@ -47,34 +52,51 @@ namespace hex::lang {
}
virtual ~PatternData() = default;
[[nodiscard]] Type getPatternType() const { return this->m_type; }
virtual PatternData* clone() = 0;
[[nodiscard]] u64 getOffset() const { return this->m_offset; }
[[nodiscard]] size_t getSize() const { return this->m_size; }
[[nodiscard]] const std::string& getName() const { return this->m_name; }
void setName(std::string name) { this->m_name = name; }
[[nodiscard]] const std::string& getVariableName() const { return this->m_variableName; }
void setVariableName(std::string name) { this->m_variableName = std::move(name); }
[[nodiscard]] const std::string& getTypeName() const { return this->m_typeName; }
void setTypeName(std::string name) { this->m_typeName = std::move(name); }
[[nodiscard]] u32 getColor() const { return this->m_color; }
void setColor(u32 color) { this->m_color = color; }
[[nodiscard]] std::endian getEndian() const { return this->m_endian; }
void setEndian(std::endian endian) { this->m_endian = endian; }
virtual void createEntry(prv::Provider* &provider) = 0;
virtual std::string getTypeName() = 0;
[[nodiscard]] virtual std::string getFormattedName() const = 0;
virtual std::optional<u32> highlightBytes(size_t offset) {
if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()))
auto currOffset = this->getOffset();
if (offset >= currOffset && offset < (currOffset + this->getSize()))
return this->getColor();
else
return { };
}
virtual std::map<u64, u32> getHighlightedAddresses() {
if (this->m_highlightedAddresses.empty()) {
for (u64 i = 0; i < this->getSize(); i++)
this->m_highlightedAddresses.insert({ this->getOffset() + i, this->getColor() });
}
return this->m_highlightedAddresses;
}
virtual void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) { }
static bool sortPatternDataTable(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider, lang::PatternData* left, lang::PatternData* right) {
if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("name")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left->getName() > right->getName();
return left->getVariableName() > right->getVariableName();
else
return left->getName() < right->getName();
return left->getVariableName() < right->getVariableName();
}
else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
@@ -95,10 +117,10 @@ namespace hex::lang {
provider->read(left->getOffset(), leftBuffer.data(), left->getSize());
provider->read(right->getOffset(), rightBuffer.data(), right->getSize());
if (PatternData::s_endianess != std::endian::native) {
if (left->m_endian != std::endian::native)
std::reverse(leftBuffer.begin(), leftBuffer.end());
if (right->m_endian != std::endian::native)
std::reverse(rightBuffer.begin(), rightBuffer.end());
}
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return leftBuffer > rightBuffer;
@@ -122,36 +144,41 @@ namespace hex::lang {
}
static void resetPalette() { PatternData::s_paletteOffset = 0; }
static void setEndianess(std::endian endianess) { PatternData::s_endianess = endianess; }
protected:
void createDefaultEntry(std::string value) {
void createDefaultEntry(std::string_view value) const {
ImGui::TableNextRow();
ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_AllowItemOverlap);
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip);
if (ImGui::Selectable(("##PatternDataLine"s + std::to_string(this->getOffset())).c_str(), false, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap)) {
Region selectRegion = { this->getOffset(), this->getSize() };
View::postEvent(Events::SelectionChangeRequest, &selectRegion);
}
ImGui::SameLine();
ImGui::Text("%s", this->getVariableName().c_str());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getName().c_str());
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn();
ImGui::Text("0x%04lx", this->getSize());
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->getFormattedName().c_str());
ImGui::TableNextColumn();
ImGui::Text("%s", value.c_str());
ImGui::Text("%s", value.data());
}
protected:
static inline std::endian s_endianess = std::endian::native;
std::endian m_endian = std::endian::native;
std::map<u64, u32> m_highlightedAddresses;
private:
Type m_type;
u64 m_offset;
size_t m_size;
u32 m_color;
std::string m_name;
std::string m_variableName;
std::string m_typeName;
static inline u8 s_paletteOffset = 0;
@@ -159,41 +186,49 @@ namespace hex::lang {
class PatternDataPadding : public PatternData {
public:
PatternDataPadding(u64 offset, size_t size) : PatternData(Type::Padding, offset, size, "", 0x00FFFFFF) { }
PatternDataPadding(u64 offset, size_t size) : PatternData(offset, size, 0x00FFFFFF) { }
PatternData* clone() override {
return new PatternDataPadding(*this);
}
void createEntry(prv::Provider* &provider) override {
}
std::string getTypeName() override {
[[nodiscard]] std::string getFormattedName() const override {
return "";
}
};
class PatternDataPointer : public PatternData {
public:
PatternDataPointer(u64 offset, size_t size, const std::string &name, PatternData *pointedAt, u32 color = 0)
: PatternData(Type::Unsigned, offset, size, name, color), m_pointedAt(pointedAt) {
this->m_pointedAt->setName("*" + this->m_pointedAt->getName());
PatternDataPointer(u64 offset, size_t size, PatternData *pointedAt, u32 color = 0)
: PatternData(offset, size, color), m_pointedAt(pointedAt) {
this->m_pointedAt->setVariableName("*" + this->m_pointedAt->getVariableName());
}
PatternData* clone() override {
return new PatternDataPointer(*this);
}
void createEntry(prv::Provider* &provider) override {
u64 data = 0;
provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), PatternData::s_endianess);
data = hex::changeEndianess(data, this->getSize(), this->getEndian());
ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip);
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
bool open = ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn();
ImGui::Text("0x%04lx", this->getSize());
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TextColored(ImColor(0xFF9BC64D), "%s*", this->m_pointedAt->getFormattedName().c_str());
ImGui::TableNextColumn();
ImGui::Text("*(0x%0*llx)", this->getSize() * 2, data);
ImGui::Text("*(0x%llX)", data);
if (open) {
this->m_pointedAt->createEntry(provider);
@@ -202,7 +237,7 @@ namespace hex::lang {
}
}
virtual std::optional<u32> highlightBytes(size_t offset) {
std::optional<u32> highlightBytes(size_t offset) override {
if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()))
return this->getColor();
else if (auto color = this->m_pointedAt->highlightBytes(offset); color.has_value())
@@ -211,27 +246,47 @@ namespace hex::lang {
return { };
}
std::string getTypeName() override {
std::map<u64, u32> getHighlightedAddresses() override {
if (this->m_highlightedAddresses.empty()) {
auto ownAddresses = PatternData::getHighlightedAddresses();
auto pointedToAddresses = this->m_pointedAt->getHighlightedAddresses();
ownAddresses.merge(pointedToAddresses);
this->m_highlightedAddresses = ownAddresses;
}
return this->m_highlightedAddresses;
}
[[nodiscard]] std::string getFormattedName() const override {
return "Pointer";
}
[[nodiscard]] PatternData* getPointedAtPattern() {
return this->m_pointedAt;
}
private:
PatternData *m_pointedAt;
};
class PatternDataUnsigned : public PatternData {
public:
PatternDataUnsigned(u64 offset, size_t size, const std::string &name, u32 color = 0) : PatternData(Type::Unsigned, offset, size, name, color) { }
PatternDataUnsigned(u64 offset, size_t size, u32 color = 0)
: PatternData(offset, size, color) { }
PatternData* clone() override {
return new PatternDataUnsigned(*this);
}
void createEntry(prv::Provider* &provider) override {
u64 data = 0;
provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), PatternData::s_endianess);
data = hex::changeEndianess(data, this->getSize(), this->getEndian());
this->createDefaultEntry(hex::format("%lu (0x%0*lx)", data, this->getSize() * 2, data));
this->createDefaultEntry(hex::format("%llu (0x%0*llX)", data, this->getSize() * 2, data));
}
std::string getTypeName() override {
[[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) {
case 1: return "u8";
case 2: return "u16";
@@ -245,19 +300,24 @@ namespace hex::lang {
class PatternDataSigned : public PatternData {
public:
PatternDataSigned(u64 offset, size_t size, const std::string &name, u32 color = 0) : PatternData(Type::Signed, offset, size, name, color) { }
PatternDataSigned(u64 offset, size_t size, u32 color = 0)
: PatternData(offset, size, color) { }
PatternData* clone() override {
return new PatternDataSigned(*this);
}
void createEntry(prv::Provider* &provider) override {
u64 data = 0;
provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), PatternData::s_endianess);
data = hex::changeEndianess(data, this->getSize(), this->getEndian());
s64 signedData = signedData = hex::signExtend(data, this->getSize(), 64);
s64 signedData = hex::signExtend(data, this->getSize(), 64);
this->createDefaultEntry(hex::format("%ld (0x%0*lx)", signedData, this->getSize() * 2, data));
this->createDefaultEntry(hex::format("%lld (0x%0*llX)", signedData, this->getSize() * 2, data));
}
std::string getTypeName() override {
[[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) {
case 1: return "s8";
case 2: return "s16";
@@ -271,28 +331,30 @@ namespace hex::lang {
class PatternDataFloat : public PatternData {
public:
PatternDataFloat(u64 offset, size_t size, const std::string &name, u32 color = 0) : PatternData(Type::Float, offset, size, name, color) { }
PatternDataFloat(u64 offset, size_t size, u32 color = 0)
: PatternData(offset, size, color) { }
void createEntry(prv::Provider* &provider) override {
double formatData = 0;
if (this->getSize() == 4) {
float data = 0;
provider->read(this->getOffset(), &data, 4);
data = hex::changeEndianess(data, 4, PatternData::s_endianess);
formatData = data;
} else if (this->getSize() == 8) {
double data = 0;
provider->read(this->getOffset(), &data, 8);
data = hex::changeEndianess(data, 8, PatternData::s_endianess);
formatData = data;
}
this->createDefaultEntry(hex::format("%f (0x%0*lx)", formatData, this->getSize() * 2, formatData));
PatternData* clone() override {
return new PatternDataFloat(*this);
}
std::string getTypeName() override {
void createEntry(prv::Provider* &provider) override {
if (this->getSize() == 4) {
u32 data = 0;
provider->read(this->getOffset(), &data, 4);
data = hex::changeEndianess(data, 4, this->getEndian());
this->createDefaultEntry(hex::format("%e (0x%0*lX)", *reinterpret_cast<float*>(&data), this->getSize() * 2, data));
} else if (this->getSize() == 8) {
u64 data = 0;
provider->read(this->getOffset(), &data, 8);
data = hex::changeEndianess(data, 8, this->getEndian());
this->createDefaultEntry(hex::format("%e (0x%0*llX)", *reinterpret_cast<double*>(&data), this->getSize() * 2, data));
}
}
[[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) {
case 4: return "float";
case 8: return "double";
@@ -301,9 +363,40 @@ namespace hex::lang {
}
};
class PatternDataBoolean : public PatternData {
public:
explicit PatternDataBoolean(u64 offset, u32 color = 0)
: PatternData(offset, 1, color) { }
PatternData* clone() override {
return new PatternDataBoolean(*this);
}
void createEntry(prv::Provider* &provider) override {
u8 boolean;
provider->read(this->getOffset(), &boolean, 1);
if (boolean == 0)
this->createDefaultEntry("false");
else if (boolean == 1)
this->createDefaultEntry("true");
else
this->createDefaultEntry("true*");
}
[[nodiscard]] std::string getFormattedName() const override {
return "bool";
}
};
class PatternDataCharacter : public PatternData {
public:
PatternDataCharacter(u64 offset, size_t size, const std::string &name, u32 color = 0) : PatternData(Type::Character, offset, size, name, color) { }
explicit PatternDataCharacter(u64 offset, u32 color = 0)
: PatternData(offset, 1, color) { }
PatternData* clone() override {
return new PatternDataCharacter(*this);
}
void createEntry(prv::Provider* &provider) override {
char character;
@@ -312,14 +405,19 @@ namespace hex::lang {
this->createDefaultEntry(hex::format("'%c'", character));
}
std::string getTypeName() override {
return "Character";
[[nodiscard]] std::string getFormattedName() const override {
return "char";
}
};
class PatternDataString : public PatternData {
public:
PatternDataString(u64 offset, size_t size, const std::string &name, u32 color = 0) : PatternData(Type::String, offset, size, name, color) { }
PatternDataString(u64 offset, size_t size, u32 color = 0)
: PatternData(offset, size, color) { }
PatternData* clone() override {
return new PatternDataString(*this);
}
void createEntry(prv::Provider* &provider) override {
std::vector<u8> buffer(this->getSize() + 1, 0x00);
@@ -329,28 +427,48 @@ namespace hex::lang {
this->createDefaultEntry(hex::format("\"%s\"", makeDisplayable(buffer.data(), this->getSize()).c_str()));
}
std::string getTypeName() override {
[[nodiscard]] std::string getFormattedName() const override {
return "String";
}
};
class PatternDataArray : public PatternData {
public:
PatternDataArray(u64 offset, size_t size, const std::string &name, const std::vector<PatternData*> & entries, u32 color = 0)
: PatternData(Type::Array, offset, size, name, color), m_entries(entries) { }
PatternDataArray(u64 offset, size_t size, std::vector<PatternData*> entries, u32 color = 0)
: PatternData(offset, size, color), m_entries(std::move(entries)) { }
PatternDataArray(const PatternDataArray &other) : PatternData(other.getOffset(), other.getSize(), other.getColor()) {
for (const auto &entry : other.m_entries)
this->m_entries.push_back(entry->clone());
}
PatternData* clone() override {
return new PatternDataArray(*this);
}
void createEntry(prv::Provider* &provider) override {
ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
if (this->m_entries.empty())
return;
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_AlphaPreview);
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
bool open = ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn();
ImGui::Text("0x%04lx", this->getSize());
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->m_entries[0]->getTypeName().c_str());
ImGui::SameLine(0, 0);
ImGui::TextUnformatted("[");
ImGui::SameLine(0, 0);
ImGui::TextColored(ImColor(0xFF00FF00), "%llu", this->m_entries.size());
ImGui::SameLine(0, 0);
ImGui::TextUnformatted("]");
ImGui::TableNextColumn();
ImGui::Text("%s", "{ ... }");
@@ -371,7 +489,16 @@ namespace hex::lang {
return { };
}
std::string getTypeName() override {
std::map<u64, u32> getHighlightedAddresses() override {
if (this->m_highlightedAddresses.empty()) {
for (auto &entry : this->m_entries) {
this->m_highlightedAddresses.merge(entry->getHighlightedAddresses());
}
}
return this->m_highlightedAddresses;
}
[[nodiscard]] std::string getFormattedName() const override {
return this->m_entries[0]->getTypeName() + "[" + std::to_string(this->m_entries.size()) + "]";
}
@@ -381,21 +508,29 @@ namespace hex::lang {
class PatternDataStruct : public PatternData {
public:
PatternDataStruct(u64 offset, size_t size, const std::string &name, const std::string &structName, const std::vector<PatternData*> & members, u32 color = 0)
: PatternData(Type::Struct, offset, size, name, color), m_structName(structName), m_members(members), m_sortedMembers(members) { }
PatternDataStruct(u64 offset, size_t size, const std::vector<PatternData*> & members, u32 color = 0)
: PatternData(offset, size, color), m_members(members), m_sortedMembers(members) { }
PatternDataStruct(const PatternDataStruct &other) : PatternData(other.getOffset(), other.getSize(), other.getColor()) {
for (const auto &member : other.m_members)
this->m_members.push_back(member->clone());
}
PatternData* clone() override {
return new PatternDataStruct(*this);
}
void createEntry(prv::Provider* &provider) override {
ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_AlphaPreview);
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
bool open = ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - (this->getSize() == 0 ? 0 : 1));
ImGui::TableNextColumn();
ImGui::Text("0x%04lx", this->getSize());
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TextColored(ImColor(0xFFD69C56), "struct"); ImGui::SameLine(); ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TableNextColumn();
ImGui::Text("%s", "{ ... }");
@@ -417,6 +552,16 @@ namespace hex::lang {
return { };
}
std::map<u64, u32> getHighlightedAddresses() override {
if (this->m_highlightedAddresses.empty()) {
for (auto &member : this->m_members) {
this->m_highlightedAddresses.merge(member->getHighlightedAddresses());
}
}
return this->m_highlightedAddresses;
}
void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) override {
this->m_sortedMembers = this->m_members;
@@ -428,33 +573,45 @@ namespace hex::lang {
member->sort(sortSpecs, provider);
}
std::string getTypeName() override {
return "struct " + this->m_structName;
[[nodiscard]] std::string getFormattedName() const override {
return "struct " + PatternData::getTypeName();
}
const auto& getMembers() const {
return this->m_members;
}
private:
std::string m_structName;
std::vector<PatternData*> m_members;
std::vector<PatternData*> m_sortedMembers;
};
class PatternDataUnion : public PatternData {
public:
PatternDataUnion(u64 offset, size_t size, const std::string &name, const std::string &unionName, const std::vector<PatternData*> & members, u32 color = 0)
: PatternData(Type::Union, offset, size, name, color), m_unionName(unionName), m_members(members), m_sortedMembers(members) { }
PatternDataUnion(u64 offset, size_t size, const std::vector<PatternData*> & members, u32 color = 0)
: PatternData(offset, size, color), m_members(members), m_sortedMembers(members) { }
PatternDataUnion(const PatternDataUnion &other) : PatternData(other.getOffset(), other.getSize(), other.getColor()) {
for (const auto &member : other.m_members)
this->m_members.push_back(member->clone());
}
PatternData* clone() override {
return new PatternDataUnion(*this);
}
void createEntry(prv::Provider* &provider) override {
ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_AlphaPreview);
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
bool open = ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), std::max(this->getOffset() + this->getSize() - (this->getSize() == 0 ? 0 : 1), u64(0)));
ImGui::TableNextColumn();
ImGui::Text("0x%04lx", this->getSize());
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TextColored(ImColor(0xFFD69C56), "union"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str());
ImGui::TableNextColumn();
ImGui::Text("%s", "{ ... }");
@@ -476,6 +633,16 @@ namespace hex::lang {
return { };
}
std::map<u64, u32> getHighlightedAddresses() override {
if (this->m_highlightedAddresses.empty()) {
for (auto &member : this->m_members) {
this->m_highlightedAddresses.merge(member->getHighlightedAddresses());
}
}
return this->m_highlightedAddresses;
}
void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) override {
this->m_sortedMembers = this->m_members;
@@ -487,96 +654,145 @@ namespace hex::lang {
member->sort(sortSpecs, provider);
}
std::string getTypeName() override {
return "union " + this->m_unionName;
[[nodiscard]] std::string getFormattedName() const override {
return "union " + PatternData::getTypeName();;
}
const auto& getMembers() const {
return this->m_members;
}
private:
std::string m_unionName;
std::vector<PatternData*> m_members;
std::vector<PatternData*> m_sortedMembers;
};
class PatternDataEnum : public PatternData {
public:
PatternDataEnum(u64 offset, size_t size, const std::string &name, const std::string &enumName, std::vector<std::pair<u64, std::string>> enumValues, u32 color = 0)
: PatternData(Type::Enum, offset, size, name, color), m_enumName(enumName), m_enumValues(enumValues) { }
PatternDataEnum(u64 offset, size_t size, std::vector<std::pair<Token::IntegerLiteral, std::string>> enumValues, u32 color = 0)
: PatternData(offset, size, color), m_enumValues(std::move(enumValues)) { }
PatternData* clone() override {
return new PatternDataEnum(*this);
}
void createEntry(prv::Provider* &provider) override {
u64 value = 0;
provider->read(this->getOffset(), &value, this->getSize());
value = hex::changeEndianess(value, this->getSize(), PatternData::s_endianess);
value = hex::changeEndianess(value, this->getSize(), this->getEndian());
std::string valueString = this->m_enumName + "::";
std::string valueString = PatternData::getTypeName() + "::";
bool foundValue = false;
for (auto &[entryValue, entryName] : this->m_enumValues) {
if (value == entryValue) {
valueString += entryName;
foundValue = true;
for (auto &[entryValueLiteral, entryName] : this->m_enumValues) {
bool matches = std::visit([&, name = entryName](auto &&entryValue) {
if (value == entryValue) {
valueString += name;
foundValue = true;
return true;
}
return false;
}, entryValueLiteral.second);
if (matches)
break;
}
}
if (!foundValue)
valueString += "???";
this->createDefaultEntry(hex::format("%s (0x%0*lx)", valueString.c_str(), this->getSize() * 2, value));
ImGui::TableNextRow();
ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
if (ImGui::Selectable(("##PatternDataLine"s + std::to_string(this->getOffset())).c_str(), false, ImGuiSelectableFlags_SpanAllColumns)) {
Region selectRegion = { this->getOffset(), this->getSize() };
View::postEvent(Events::SelectionChangeRequest, &selectRegion);
}
ImGui::SameLine();
ImGui::Text("%s", this->getVariableName().c_str());
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn();
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn();
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFFD69C56), "enum"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str());
ImGui::TableNextColumn();
ImGui::Text("%s", hex::format("%s (0x%0*llX)", valueString.c_str(), this->getSize() * 2, value).c_str());
}
std::string getTypeName() override {
return "enum " + this->m_enumName;
[[nodiscard]] std::string getFormattedName() const override {
return "enum " + PatternData::getTypeName();
}
const auto& getEnumValues() const {
return this->m_enumValues;
}
private:
std::string m_enumName;
std::vector<std::pair<u64, std::string>> m_enumValues;
std::vector<std::pair<Token::IntegerLiteral, std::string>> m_enumValues;
};
class PatternDataBitfield : public PatternData {
public:
PatternDataBitfield(u64 offset, size_t size, const std::string &name, const std::string &bitfieldName, std::vector<std::pair<std::string, size_t>> fields, u32 color = 0)
: PatternData(Type::Enum, offset, size, name, color), m_bitfieldName(bitfieldName), m_fields(fields) { }
PatternDataBitfield(u64 offset, size_t size, std::vector<std::pair<std::string, size_t>> fields, u32 color = 0)
: PatternData(offset, size, color), m_fields(std::move(fields)) { }
PatternData* clone() override {
return new PatternDataBitfield(*this);
}
void createEntry(prv::Provider* &provider) override {
u64 value = 0;
provider->read(this->getOffset(), &value, this->getSize());
value = hex::changeEndianess(value, this->getSize(), PatternData::s_endianess);
std::vector<u8> value(this->getSize(), 0);
provider->read(this->getOffset(), &value[0], value.size());
ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
if (this->m_endian == std::endian::big)
std::reverse(value.begin(), value.end());
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(0x00FFFFFF), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_AlphaPreview);
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
bool open = ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn();
ImGui::Text("0x%04lx", this->getSize());
ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn();
ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TextColored(ImColor(0xFFD69C56), "bitfield"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str());
ImGui::TableNextColumn();
ImGui::Text("{ %llx }", value);
std::string valueString = "{ ";
for (u64 i = 0; i < value.size(); i++)
valueString += hex::format("%02x ", value[i]);
valueString += "}";
ImGui::TextUnformatted(valueString.c_str());
if (open) {
u16 bitOffset = 0;
for (auto &[entryName, entrySize] : this->m_fields) {
ImGui::TableNextRow();
ImGui::TreeNodeEx(this->getName().c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip);
ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn();
ImGui::Text("%s", entryName.c_str());
ImGui::TableNextColumn();
ImGui::Text("0x%08lx : 0x%08lx", this->getOffset() + (bitOffset >> 3), this->getOffset() + ((bitOffset + entrySize) >> 3) - 1);
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn();
ImGui::Text("0x%08llX : 0x%08llX", this->getOffset() + (bitOffset >> 3), this->getOffset() + ((bitOffset + entrySize) >> 3));
ImGui::TableNextColumn();
if (entrySize == 1)
ImGui::Text("%llu bit", entrySize);
else
ImGui::Text("%llu bits", entrySize);
ImGui::TableNextColumn();
ImGui::Text("%s", entryName.c_str());
ImGui::TextColored(ImColor(0xFF9BC64D), "bits");
ImGui::TableNextColumn();
ImGui::Text("%llx", hex::extract((bitOffset + entrySize) - 1, bitOffset, value));
{
u128 fieldValue = 0;
std::memcpy(&fieldValue, value.data() + (bitOffset / 8), (entrySize / 8) + 1);
ImGui::Text("%llX", hex::extract((bitOffset + entrySize) - 1 - ((bitOffset / 8) * 8), bitOffset - ((bitOffset / 8) * 8), fieldValue));
}
bitOffset += entrySize;
}
@@ -585,12 +801,15 @@ namespace hex::lang {
}
std::string getTypeName() override {
return "bitfield " + this->m_bitfieldName;
[[nodiscard]] std::string getFormattedName() const override {
return "bitfield " + PatternData::getTypeName();
}
const auto& getFields() const {
return this->m_fields;
}
private:
std::string m_bitfieldName;
std::vector<std::pair<std::string, size_t>> m_fields;
};

View File

@@ -16,16 +16,26 @@ namespace hex::lang {
public:
Preprocessor();
std::pair<Result, std::string> preprocess(const std::string& code, bool initialRun = true);
std::optional<std::string> preprocess(const std::string& code, bool initialRun = true);
void addPragmaHandler(std::string pragmaType, std::function<bool(std::string)> function);
void addDefaultPragramHandlers();
void addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string&)> &function);
void addDefaultPragmaHandlers();
const std::pair<u32, std::string>& getError() { return this->m_error; }
private:
using PreprocessorError = std::pair<u32, std::string>;
[[noreturn]] void throwPreprocessorError(std::string_view error, u32 lineNumber) const {
throw PreprocessorError(lineNumber, "Preprocessor: " + std::string(error));
}
std::unordered_map<std::string, std::function<bool(std::string)>> m_pragmaHandlers;
std::set<std::pair<std::string, std::string>> m_defines;
std::set<std::pair<std::string, std::string>> m_pragmas;
std::pair<u32, std::string> m_error;
};
}

View File

@@ -1,21 +0,0 @@
#pragma once
#include <cstdint>
namespace hex::lang {
class Result {
public:
constexpr Result(const std::uint8_t module, const std::uint32_t desc) noexcept : m_result((module << 24) | (desc & 0x00FFFFFF)) { }
constexpr std::uint32_t getResult() const noexcept { return this->m_result; }
constexpr std::uint8_t getModule() const noexcept { return this->m_result >> 24; }
constexpr std::uint32_t getDescription() const noexcept { return this->m_result & 0x00FFFFFF; }
constexpr bool succeeded() const noexcept { return this->m_result == 0; }
constexpr bool failed() const noexcept { return !succeeded(); }
private:
const std::uint32_t m_result;
};
}

View File

@@ -1,14 +0,0 @@
#pragma once
#include "result.hpp"
namespace hex::lang {
constexpr Result ResultSuccess(0, 0);
constexpr Result ResultPreprocessingError(1, 1);
constexpr Result ResultLexicalError(2, 1);
constexpr Result ResultParseError(3, 1);
constexpr Result ResultEvaluatorError(4, 1);
}

View File

@@ -2,66 +2,244 @@
#include <hex.hpp>
#include "helpers/utils.hpp"
#include <utility>
#include <string>
#include <variant>
namespace hex::lang {
struct Token {
class Token {
public:
enum class Type : u64 {
Keyword,
Type,
ValueType,
Operator,
Integer,
String,
Identifier,
EndOfExpression,
ScopeOpen,
ScopeClose,
ArrayOpen,
ArrayClose,
Separator,
EndOfProgram
} type;
Separator
};
enum class Keyword {
Struct,
Union,
Using,
Enum,
Bitfield,
LittleEndian,
BigEndian,
If,
Else
};
enum class Operator {
AtDeclaration,
Assignment,
Inherit,
Plus,
Minus,
Star,
Slash,
ShiftLeft,
ShiftRight,
BitOr,
BitAnd,
BitXor,
BitNot,
BoolEquals,
BoolNotEquals,
BoolGreaterThan,
BoolLessThan,
BoolGreaterThanOrEquals,
BoolLessThanOrEquals,
BoolAnd,
BoolOr,
BoolXor,
BoolNot,
TernaryConditional
};
enum class ValueType {
Unsigned8Bit = 0x10,
Signed8Bit = 0x11,
Unsigned16Bit = 0x20,
Signed16Bit = 0x21,
Unsigned32Bit = 0x40,
Signed32Bit = 0x41,
Unsigned64Bit = 0x80,
Signed64Bit = 0x81,
Unsigned128Bit = 0x100,
Signed128Bit = 0x101,
Character = 0x13,
Boolean = 0x14,
Float = 0x42,
Double = 0x82,
CustomType = 0x00,
Padding = 0x1F,
Unsigned = 0xFF00,
Signed = 0xFF01,
FloatingPoint = 0xFF02,
Integer = 0xFF03,
Any = 0xFFFF
};
enum class Separator {
RoundBracketOpen,
RoundBracketClose,
CurlyBracketOpen,
CurlyBracketClose,
SquareBracketOpen,
SquareBracketClose,
Comma,
Dot,
ScopeResolution,
EndOfExpression,
EndOfProgram
};
using IntegerLiteral = std::pair<ValueType, std::variant<u8, s8, u16, s16, u32, s32, u64, s64, u128, s128, float, double>>;
using ValueTypes = std::variant<Keyword, std::string, Operator, IntegerLiteral, ValueType, Separator>;
Token(Type type, auto value, u32 lineNumber) : type(type), value(value), lineNumber(lineNumber) {
}
[[nodiscard]] constexpr static inline bool isUnsigned(const ValueType type) {
return (static_cast<u32>(type) & 0x0F) == 0x00;
}
[[nodiscard]] constexpr static inline bool isSigned(const ValueType type) {
return (static_cast<u32>(type) & 0x0F) == 0x01;
}
[[nodiscard]] constexpr static inline bool isFloatingPoint(const ValueType type) {
return (static_cast<u32>(type) & 0x0F) == 0x02;
}
[[nodiscard]] constexpr static inline u32 getTypeSize(const ValueType type) {
return static_cast<u32>(type) >> 4;
}
[[nodiscard]] constexpr static auto getTypeName(const lang::Token::ValueType type) {
switch (type) {
case ValueType::Signed8Bit: return "s8";
case ValueType::Signed16Bit: return "s16";
case ValueType::Signed32Bit: return "s32";
case ValueType::Signed64Bit: return "s64";
case ValueType::Signed128Bit: return "s128";
case ValueType::Unsigned8Bit: return "u8";
case ValueType::Unsigned16Bit: return "u16";
case ValueType::Unsigned32Bit: return "u32";
case ValueType::Unsigned64Bit: return "u64";
case ValueType::Unsigned128Bit: return "u128";
case ValueType::Float: return "float";
case ValueType::Double: return "double";
case ValueType::Character: return "char";
default: return "< ??? >";
}
}
bool operator==(const ValueTypes &other) const {
if (this->type == Type::Integer || this->type == Type::Identifier || this->type == Type::String)
return true;
else if (this->type == Type::ValueType) {
auto otherValueType = std::get_if<ValueType>(&other);
auto valueType = std::get_if<ValueType>(&this->value);
if (otherValueType == nullptr) return false;
if (valueType == nullptr) return false;
if (*otherValueType == *valueType)
return true;
else if (*otherValueType == ValueType::Any)
return *valueType != ValueType::CustomType && *valueType != ValueType::Padding;
else if (*otherValueType == ValueType::Unsigned)
return isUnsigned(*valueType);
else if (*otherValueType == ValueType::Signed)
return isSigned(*valueType);
else if (*otherValueType == ValueType::FloatingPoint)
return isFloatingPoint(*valueType);
else if (*otherValueType == ValueType::Integer)
return isUnsigned(*valueType) || isSigned(*valueType);
}
else
return other == this->value;
return false;
}
bool operator!=(const ValueTypes &other) const {
return !operator==(other);
}
Type type;
ValueTypes value;
u32 lineNumber;
struct KeywordToken {
enum class Keyword {
Struct,
Union,
Using,
Enum,
Bitfield
} keyword;
} keywordToken;
struct IdentifierToken {
std::string identifier;
} identifierToken;
struct OperatorToken {
enum class Operator {
AtDeclaration,
Assignment,
Inherit,
Star
} op;
} operatorToken;
struct IntegerToken {
s128 integer;
} integerToken;
struct TypeToken {
enum class Type {
Unsigned8Bit = 0x10,
Signed8Bit = 0x11,
Unsigned16Bit = 0x20,
Signed16Bit = 0x21,
Unsigned32Bit = 0x40,
Signed32Bit = 0x41,
Unsigned64Bit = 0x80,
Signed64Bit = 0x81,
Unsigned128Bit = 0x100,
Signed128Bit = 0x101,
Float = 0x42,
Double = 0x82,
CustomType = 0x00,
Padding = 0x1F
} type;
} typeToken;
};
}
}
#define COMPONENT(type, value) hex::lang::Token::Type::type, hex::lang::Token::type::value
#define KEYWORD_STRUCT COMPONENT(Keyword, Struct)
#define KEYWORD_UNION COMPONENT(Keyword, Union)
#define KEYWORD_USING COMPONENT(Keyword, Using)
#define KEYWORD_ENUM COMPONENT(Keyword, Enum)
#define KEYWORD_BITFIELD COMPONENT(Keyword, Bitfield)
#define KEYWORD_LE COMPONENT(Keyword, LittleEndian)
#define KEYWORD_BE COMPONENT(Keyword, BigEndian)
#define KEYWORD_IF COMPONENT(Keyword, If)
#define KEYWORD_ELSE COMPONENT(Keyword, Else)
#define INTEGER hex::lang::Token::Type::Integer, hex::lang::Token::IntegerLiteral(hex::lang::Token::ValueType::Any, u64(0))
#define IDENTIFIER hex::lang::Token::Type::Identifier, ""
#define STRING hex::lang::Token::Type::String, ""
#define OPERATOR_AT COMPONENT(Operator, AtDeclaration)
#define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment)
#define OPERATOR_INHERIT COMPONENT(Operator, Inherit)
#define OPERATOR_PLUS COMPONENT(Operator, Plus)
#define OPERATOR_MINUS COMPONENT(Operator, Minus)
#define OPERATOR_STAR COMPONENT(Operator, Star)
#define OPERATOR_SLASH COMPONENT(Operator, Slash)
#define OPERATOR_SHIFTLEFT COMPONENT(Operator, ShiftLeft)
#define OPERATOR_SHIFTRIGHT COMPONENT(Operator, ShiftRight)
#define OPERATOR_BITOR COMPONENT(Operator, BitOr)
#define OPERATOR_BITAND COMPONENT(Operator, BitAnd)
#define OPERATOR_BITXOR COMPONENT(Operator, BitXor)
#define OPERATOR_BITNOT COMPONENT(Operator, BitNot)
#define OPERATOR_BOOLEQUALS COMPONENT(Operator, BoolEquals)
#define OPERATOR_BOOLNOTEQUALS COMPONENT(Operator, BoolNotEquals)
#define OPERATOR_BOOLGREATERTHAN COMPONENT(Operator, BoolGreaterThan)
#define OPERATOR_BOOLLESSTHAN COMPONENT(Operator, BoolLessThan)
#define OPERATOR_BOOLGREATERTHANOREQUALS COMPONENT(Operator, BoolGreaterThanOrEquals)
#define OPERATOR_BOOLLESSTHANOREQUALS COMPONENT(Operator, BoolLessThanOrEquals)
#define OPERATOR_BOOLAND COMPONENT(Operator, BoolAnd)
#define OPERATOR_BOOLOR COMPONENT(Operator, BoolOr)
#define OPERATOR_BOOLXOR COMPONENT(Operator, BoolXor)
#define OPERATOR_BOOLNOT COMPONENT(Operator, BoolNot)
#define OPERATOR_TERNARYCONDITIONAL COMPONENT(Operator, TernaryConditional)
#define VALUETYPE_CUSTOMTYPE COMPONENT(ValueType, CustomType)
#define VALUETYPE_PADDING COMPONENT(ValueType, Padding)
#define VALUETYPE_UNSIGNED COMPONENT(ValueType, Unsigned)
#define VALUETYPE_SIGNED COMPONENT(ValueType, Signed)
#define VALUETYPE_FLOATINGPOINT COMPONENT(ValueType, FloatingPoint)
#define VALUETYPE_INTEGER COMPONENT(ValueType, Integer)
#define VALUETYPE_ANY COMPONENT(ValueType, Any)
#define SEPARATOR_ROUNDBRACKETOPEN COMPONENT(Separator, RoundBracketOpen)
#define SEPARATOR_ROUNDBRACKETCLOSE COMPONENT(Separator, RoundBracketClose)
#define SEPARATOR_CURLYBRACKETOPEN COMPONENT(Separator, CurlyBracketOpen)
#define SEPARATOR_CURLYBRACKETCLOSE COMPONENT(Separator, CurlyBracketClose)
#define SEPARATOR_SQUAREBRACKETOPEN COMPONENT(Separator, SquareBracketOpen)
#define SEPARATOR_SQUAREBRACKETCLOSE COMPONENT(Separator, SquareBracketClose)
#define SEPARATOR_COMMA COMPONENT(Separator, Comma)
#define SEPARATOR_DOT COMPONENT(Separator, Dot)
#define SEPARATOR_SCOPE_RESOLUTION COMPONENT(Separator, ScopeResolution)
#define SEPARATOR_ENDOFEXPRESSION COMPONENT(Separator, EndOfExpression)
#define SEPARATOR_ENDOFPROGRAM COMPONENT(Separator, EndOfProgram)

View File

@@ -15,6 +15,19 @@ namespace hex::lang {
Validator();
bool validate(const std::vector<ASTNode*>& ast);
void printAST(const std::vector<ASTNode*>& ast);
const std::pair<u32, std::string>& getError() { return this->m_error; }
private:
std::pair<u32, std::string> m_error;
using ValidatorError = std::pair<u32, std::string>;
[[noreturn]] void throwValidateError(std::string_view error, u32 lineNumber) const {
throw ValidatorError(lineNumber, error);
}
};
}

View File

@@ -6,6 +6,14 @@
#include <sys/stat.h>
#if defined(OS_WINDOWS)
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#include <sys/fcntl.h>
#endif
namespace hex::prv {
class FileProvider : public Provider {
@@ -18,14 +26,24 @@ namespace hex::prv {
bool isWritable() override;
void read(u64 offset, void *buffer, size_t size) override;
void write(u64 offset, void *buffer, size_t size) override;
void write(u64 offset, const void *buffer, size_t size) override;
void readRaw(u64 offset, void *buffer, size_t size) override;
void writeRaw(u64 offset, const void *buffer, size_t size) override;
size_t getActualSize() override;
std::vector<std::pair<std::string, std::string>> getDataInformation() override;
private:
FILE *m_file;
#if defined(OS_WINDOWS)
HANDLE m_file;
HANDLE m_mapping;
#else
int m_file;
#endif
std::string m_path;
void *m_mappedFile;
size_t m_fileSize;
bool m_fileStatsValid = false;
struct stat m_fileStats = { 0 };

View File

@@ -1,44 +0,0 @@
#pragma once
#include <hex.hpp>
#include <cmath>
#include <string>
#include <vector>
namespace hex::prv {
class Provider {
public:
constexpr static size_t PageSize = 0x1000'0000;
Provider() = default;
virtual ~Provider() = default;
virtual bool isAvailable() = 0;
virtual bool isReadable() = 0;
virtual bool isWritable() = 0;
virtual void read(u64 offset, void *buffer, size_t size) = 0;
virtual void write(u64 offset, void *buffer, size_t size) = 0;
virtual size_t getActualSize() = 0;
u32 getPageCount() { return std::ceil(this->getActualSize() / double(PageSize)); }
u32 getCurrentPage() const { return this->m_currPage; }
void setCurrentPage(u32 page) { if (page < getPageCount()) this->m_currPage = page; }
virtual size_t getBaseAddress() {
return PageSize * this->m_currPage;
}
virtual size_t getSize() {
return std::min(this->getActualSize() - PageSize * this->m_currPage, PageSize);
}
virtual std::vector<std::pair<std::string, std::string>> getDataInformation() = 0;
protected:
u32 m_currPage = 0;
};
}

View File

@@ -1,139 +0,0 @@
#pragma once
#include <hex.hpp>
#include <array>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#ifdef __MINGW32__
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif
#include "lang/token.hpp"
namespace hex {
template<typename ... Args>
inline std::string format(const std::string &format, Args ... args) {
ssize_t size = snprintf( nullptr, 0, format.c_str(), args ... );
if( size <= 0 )
return "";
std::vector<char> buffer(size + 1, 0x00);
snprintf(buffer.data(), size + 1, format.c_str(), args ...);
return std::string(buffer.data(), buffer.data() + size);
}
[[nodiscard]] constexpr inline u64 signExtend(u64 value, u8 currWidth, u8 targetWidth) {
u64 mask = 1LLU << (currWidth - 1);
return (((value ^ mask) - mask) << (64 - targetWidth)) >> (64 - targetWidth);
}
constexpr inline bool isUnsigned(const lang::Token::TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x00;
}
constexpr inline bool isSigned(const lang::Token::TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x01;
}
constexpr inline bool isFloatingPoint(const lang::Token::TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x02;
}
constexpr inline u32 getTypeSize(const lang::Token::TypeToken::Type type) {
return static_cast<u32>(type) >> 4;
}
inline std::string toByteString(u64 bytes) {
double value = bytes;
u8 unitIndex = 0;
while (value > 1024) {
value /= 1024;
unitIndex++;
if (unitIndex == 6)
break;
}
std::string result = hex::format("%.2f", value);
switch (unitIndex) {
case 0: result += " Bytes"; break;
case 1: result += " kB"; break;
case 2: result += " MB"; break;
case 3: result += " GB"; break;
case 4: result += " TB"; break;
case 5: result += " PB"; break;
case 6: result += " EB"; break;
default: result = "A lot!";
}
return result;
}
[[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const u64 &value) {
u64 mask = (std::numeric_limits<u64>::max() >> (63 - (from - to))) << to;
return (value & mask) >> to;
}
template<typename T>
struct always_false : std::false_type {};
template<typename T>
constexpr T changeEndianess(T value, std::endian endian) {
if (endian == std::endian::native)
return value;
if constexpr (sizeof(T) == 1)
return value;
else if constexpr (sizeof(T) == 2)
return __builtin_bswap16(value);
else if constexpr (sizeof(T) == 4)
return __builtin_bswap32(value);
else if constexpr (sizeof(T) == 8)
return __builtin_bswap64(value);
else
static_assert(always_false<T>::value, "Invalid type provided!");
}
template<typename T>
constexpr T changeEndianess(T value, size_t size, std::endian endian) {
if (endian == std::endian::native)
return value;
if (size == 1)
return value;
else if (size == 2)
return __builtin_bswap16(value);
else if (size == 4)
return __builtin_bswap32(value);
else if (size == 8)
return __builtin_bswap64(value);
else
throw std::invalid_argument("Invalid value size!");
}
class ScopeExit {
public:
ScopeExit(std::function<void()> func) : m_func(func) {}
~ScopeExit() { if (this->m_func != nullptr) this->m_func(); }
void release() {
this->m_func = nullptr;
}
private:
std::function<void()> m_func;
};
}

View File

@@ -1,50 +0,0 @@
#pragma once
#include <hex.hpp>
#include "imgui.h"
#include "event.hpp"
#include <functional>
#include <vector>
namespace hex {
class View {
public:
View() { }
virtual ~View() { }
virtual void createView() = 0;
virtual void createMenu() { }
virtual bool handleShortcut(int key, int mods) { return false; }
static std::vector<std::function<void()>>& getDeferedCalls() {
return View::s_deferedCalls;
}
static void postEvent(Events eventType, const void *userData = nullptr) {
View::s_eventManager.post(eventType, userData);
}
protected:
void subscribeEvent(Events eventType, std::function<void(const void*)> callback) {
View::s_eventManager.subscribe(eventType, this, callback);
}
void unsubscribeEvent(Events eventType) {
View::s_eventManager.unsubscribe(eventType, this);
}
void doLater(std::function<void()> &&function) {
View::s_deferedCalls.push_back(function);
}
private:
static inline EventManager s_eventManager;
static inline std::vector<std::function<void()>> s_deferedCalls;
};
}

View File

@@ -0,0 +1,26 @@
#pragma once
#include "views/view.hpp"
#include <vector>
#include <list>
#include "helpers/utils.hpp"
namespace hex {
namespace prv { class Provider; }
class ViewBookmarks : public View {
public:
explicit ViewBookmarks();
~ViewBookmarks() override;
void drawContent() override;
void drawMenu() override;
private:
std::list<Bookmark> m_bookmarks;
};
}

View File

@@ -0,0 +1,40 @@
#pragma once
#include <hex.hpp>
#include "imgui.h"
#include "views/view.hpp"
#include "lang/pattern_data.hpp"
#include <vector>
#include <tuple>
#include <cstdio>
namespace hex {
namespace prv { class Provider; }
class ViewCommandPalette : public View {
public:
ViewCommandPalette();
~ViewCommandPalette() override;
void drawContent() override;
void drawMenu() override;
bool handleShortcut(int key, int mods) override;
bool hasViewMenuItemEntry() override { return false; }
ImVec2 getMinSize() override { return ImVec2(400, 100); }
ImVec2 getMaxSize() override { return ImVec2(400, 100); }
private:
bool m_justOpened = false;
std::vector<char> m_commandBuffer;
std::vector<std::string> m_lastResults;
std::string m_exactResult;
std::vector<std::string> getCommandResults(std::string_view command);
};
}

View File

@@ -32,7 +32,7 @@ namespace hex {
u8 utf8Char[4];
float float32;
double float64;
#if defined(_WIN64)
#if defined(OS_WINDOWS) && defined(ARCH_64_BIT)
__time32_t time32;
__time64_t time64;
#else
@@ -41,24 +41,37 @@ namespace hex {
GUID guid;
};
struct CachedData {
CachedData(std::string name, std::string value, size_t size) : name(name), value(value), size(size) { }
std::string name;
std::string value;
size_t size;
};
enum class NumberDisplayStyle {
Decimal,
Hexadecimal,
Octal
};
class ViewDataInspector : public View {
public:
explicit ViewDataInspector(prv::Provider* &dataProvider);
explicit ViewDataInspector();
~ViewDataInspector() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
prv::Provider* &m_dataProvider;
bool m_windowOpen = true;
bool m_shouldInvalidate = true;
std::endian m_endianess = std::endian::native;
std::endian m_endian = std::endian::native;
NumberDisplayStyle m_numberDisplayStyle = NumberDisplayStyle::Decimal;
PreviewData m_previewData = { 0 };
size_t m_validBytes = 0;
std::vector<std::pair<std::string, std::string>> m_cachedData;
std::vector<CachedData> m_cachedData;
};
}

View File

@@ -1,5 +1,6 @@
#pragma once
#include "helpers/disassembler.hpp"
#include "views/view.hpp"
#include <capstone/capstone.h>
@@ -15,29 +16,28 @@ namespace hex {
struct Disassembly {
u64 address;
u64 offset;
size_t size;
std::string bytes;
std::string opcodeString;
std::string mnemonic;
std::string operators;
};
class ViewDisassembler : public View {
public:
explicit ViewDisassembler(prv::Provider* &dataProvider);
explicit ViewDisassembler();
~ViewDisassembler() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
prv::Provider* &m_dataProvider;
bool m_windowOpen = true;
bool m_shouldInvalidate = false;
u64 m_baseAddress = 0;
u64 m_codeOffset = 0;
u64 m_codeSize = 0;
u64 m_codeRegion[2] = { 0 };
bool m_shouldMatchSelection = false;
cs_arch m_architecture = CS_ARCH_ARM;
Architecture m_architecture = Architecture::ARM;
cs_mode m_modeBasicARM = cs_mode(0), m_modeExtraARM = cs_mode(0), m_modeBasicMIPS = cs_mode(0), m_modeBasicPPC = cs_mode(0), m_modeBasicX86 = cs_mode(0);
bool m_littleEndianMode = true, m_micoMode = false, m_sparcV9Mode = false;

View File

@@ -10,19 +10,18 @@ namespace hex {
class ViewHashes : public View {
public:
explicit ViewHashes(prv::Provider* &dataProvider);
explicit ViewHashes();
~ViewHashes() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
prv::Provider* &m_dataProvider;
bool m_windowOpen = true;
bool m_shouldInvalidate = true;
int m_currHashFunction = 0;
int m_hashStart = 0, m_hashEnd = 0;
u64 m_hashRegion[2] = { 0 };
bool m_shouldMatchSelection = false;
static constexpr const char* HashFunctionNames[] = { "CRC16", "CRC32", "MD4", "MD5", "SHA-1", "SHA-224", "SHA-256", "SHA-384", "SHA-512" };
};

View File

@@ -19,15 +19,19 @@ namespace hex {
ViewHelp();
~ViewHelp() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
bool hasViewMenuItemEntry() override { return false; }
private:
bool m_aboutWindowOpen = false;
bool m_patternHelpWindowOpen = false;
bool m_mathHelpWindowOpen = false;
void drawAboutPopup();
void drawPatternHelpPopup();
void drawMathEvaluatorHelp();
};
}

View File

@@ -1,6 +1,6 @@
#pragma once
#include "utils.hpp"
#include "helpers/utils.hpp"
#include "views/view.hpp"
#include "imgui_memory_editor.h"
@@ -20,19 +20,19 @@ namespace hex {
class ViewHexEditor : public View {
public:
ViewHexEditor(prv::Provider* &dataProvider, std::vector<lang::PatternData*> &patternData);
ViewHexEditor(std::vector<lang::PatternData*> &patternData);
~ViewHexEditor() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
bool handleShortcut(int key, int mods) override;
private:
MemoryEditor m_memoryEditor;
imgui_addons::ImGuiFileBrowser m_fileBrowser;
prv::Provider* &m_dataProvider;
std::vector<lang::PatternData*> &m_patternData;
std::map<u64, u32> m_highlightedBytes;
char m_searchStringBuffer[0xFFFF] = { 0 };
char m_searchHexBuffer[0xFFFF] = { 0 };
@@ -45,11 +45,18 @@ namespace hex {
s64 m_gotoAddress = 0;
std::vector<u8> m_dataToSave;
std::string m_loaderScriptScriptPath;
std::string m_loaderScriptFilePath;
void drawSearchPopup();
void drawGotoPopup();
void drawEditPopup();
void openFile(std::string path);
bool saveToFile(std::string path, const std::vector<u8>& data);
bool loadFromFile(std::string path, std::vector<u8>& data);
enum class Language { C, Cpp, CSharp, Rust, Python, Java, JavaScript };
void copyBytes();

View File

@@ -13,16 +13,13 @@ namespace hex {
class ViewInformation : public View {
public:
explicit ViewInformation(prv::Provider* &dataProvider);
explicit ViewInformation();
~ViewInformation() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
prv::Provider* &m_dataProvider;
bool m_windowOpen = true;
bool m_dataValid = false;
u32 m_blockSize = 0;
float m_averageEntropy = 0;

View File

@@ -0,0 +1,26 @@
#pragma once
#include <hex.hpp>
#include "imgui.h"
#include "views/view.hpp"
#include <optional>
namespace hex {
namespace prv { class Provider; }
class ViewPatches : public View {
public:
explicit ViewPatches();
~ViewPatches() override;
void drawContent() override;
void drawMenu() override;
private:
u64 m_selectedPatch;
};
}

View File

@@ -1,15 +1,14 @@
#pragma once
#include "lang/ast_node.hpp"
#include "views/view.hpp"
#include "lang/pattern_data.hpp"
#include "lang/evaluator.hpp"
#include "providers/provider.hpp"
#include <concepts>
#include <cstring>
#include <filesystem>
#include <thread>
#include "ImGuiFileBrowser.h"
#include "TextEditor.h"
@@ -18,19 +17,18 @@ namespace hex {
class ViewPattern : public View {
public:
explicit ViewPattern(prv::Provider* &dataProvider, std::vector<lang::PatternData*> &patternData);
explicit ViewPattern(std::vector<lang::PatternData*> &patternData);
~ViewPattern() override;
void createMenu() override;
void createView() override;
void drawMenu() override;
void drawContent() override;
private:
std::vector<lang::PatternData*> &m_patternData;
prv::Provider* &m_dataProvider;
std::filesystem::path m_possiblePatternFile;
bool m_windowOpen = true;
TextEditor m_textEditor;
std::vector<std::pair<lang::Evaluator::ConsoleLogLevel, std::string>> m_console;
imgui_addons::ImGuiFileBrowser m_fileBrowser;
void loadPatternFile(std::string path);

View File

@@ -16,17 +16,16 @@ namespace hex {
class ViewPatternData : public View {
public:
ViewPatternData(prv::Provider* &dataProvider, std::vector<lang::PatternData*> &patternData);
ViewPatternData(std::vector<lang::PatternData*> &patternData);
~ViewPatternData() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
prv::Provider* &m_dataProvider;
std::vector<lang::PatternData*> &m_patternData;
std::vector<lang::PatternData*> m_sortedPatternData;
bool m_windowOpen = true;
};
}

View File

@@ -17,20 +17,23 @@ namespace hex {
class ViewStrings : public View {
public:
explicit ViewStrings(prv::Provider* &dataProvider);
explicit ViewStrings();
~ViewStrings() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
prv::Provider* &m_dataProvider;
bool m_windowOpen = true;
bool m_shouldInvalidate = false;
std::vector<FoundString> m_foundStrings;
int m_minimumLength = 5;
char *m_filter;
std::string m_selectedString;
std::string m_demangledName;
void createStringContextMenu(const FoundString &foundString);
};
}

View File

@@ -4,6 +4,7 @@
#include "imgui.h"
#include "views/view.hpp"
#include "helpers/math_evaluator.hpp"
#include <array>
#include <string>
@@ -17,14 +18,12 @@ namespace hex {
ViewTools();
~ViewTools() override;
void createView() override;
void createMenu() override;
void drawContent() override;
void drawMenu() override;
private:
bool m_windowOpen = true;
char *m_mangledBuffer = nullptr;
char *m_demangledName = nullptr;
std::string m_demangledName;
bool m_asciiTableShowOctal = false;
@@ -35,10 +34,16 @@ namespace hex {
std::array<float, 4> m_pickedColor;
MathEvaluator m_mathEvaluator;
std::vector<long double> m_mathHistory;
std::string m_lastMathError;
char *m_mathInput = nullptr;
void drawDemangler();
void drawASCIITable();
void drawRegexReplacer();
void drawColorPicker();
void drawMathEvaluator();
};
}

View File

@@ -1,12 +1,14 @@
#pragma once
#include <concepts>
#include <filesystem>
#include <memory>
#include <vector>
#include "helpers/utils.hpp"
#include "views/view.hpp"
struct GLFWwindow;
struct ImGuiSettingsHandler;
namespace hex {
@@ -17,15 +19,19 @@ namespace hex {
void loop();
template<std::derived_from<View> T, typename ... Args>
template<derived_from<View> T, typename ... Args>
T* addView(Args&& ... args) {
this->m_views.emplace_back(new T(std::forward<Args>(args)...));
return static_cast<T*>(this->m_views.back());
}
public:
float m_globalScale = 1.0f, m_fontScale = 1.0f;
friend void *ImHexSettingsHandler_ReadOpenFn(ImGuiContext *ctx, ImGuiSettingsHandler *, const char *);
friend void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line);
friend void ImHexSettingsHandler_ApplyAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler);
friend void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf);
bool setFont(const std::filesystem::path &font_path);
private:
void frameBegin();
@@ -33,12 +39,18 @@ namespace hex {
void initGLFW();
void initImGui();
void initPlugins();
void deinitGLFW();
void deinitImGui();
void deinitPlugins();
GLFWwindow* m_window;
std::vector<View*> m_views;
std::vector<View*> m_pluginViews;
float m_globalScale = 1.0f, m_fontScale = 1.0f;
bool m_fpsVisible = false;
bool m_demoWindowOpen = false;
static inline std::tuple<int, int> s_currShortcut = { -1, -1 };
};

47
msys2/PKGBUILD Normal file
View File

@@ -0,0 +1,47 @@
_realname=ImHex
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=ci
pkgrel=1
pkgdesc="${_realname}: a Hex Editor for Reverse Engineers, Programmers and people that value their eye sight when working at 3 AM (mingw-w64)"
arch=('any')
url="https://github.com/WerWolv/ImHex"
license=('GPLv2')
depends=("${MINGW_PACKAGE_PREFIX}-python")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc"
"${MINGW_PACKAGE_PREFIX}-cmake"
"${MINGW_PACKAGE_PREFIX}-make"
"${MINGW_PACKAGE_PREFIX}-dlsym"
"${MINGW_PACKAGE_PREFIX}-capstone"
"${MINGW_PACKAGE_PREFIX}-glfw"
"${MINGW_PACKAGE_PREFIX}-glm"
"${MINGW_PACKAGE_PREFIX}-file"
"${MINGW_PACKAGE_PREFIX}-nlohmann-json"
"${MINGW_PACKAGE_PREFIX}-openssl"
"${MINGW_PACKAGE_PREFIX}-polly"
"${MINGW_PACKAGE_PREFIX}-python"
"${MINGW_PACKAGE_PREFIX}-freetype")
source=()
sha256sums=()
build() {
cd "${srcdir}"/../..
mkdir build
cd build
export BUILD_TYPE='Release'
MSYS2_ARG_CONV_EXCL=- cmake \
-G "MinGW Makefiles" \
-DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
../
mingw32-make
}
package() {
cd "${srcdir}"/../../build
mingw32-make DESTDIR="${pkgdir}" install
_licenses="${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}"
mkdir -p "${_licenses}"
install -m 644 ../LICENSE "${_licenses}"
}

View File

@@ -0,0 +1,15 @@
cmake_minimum_required(VERSION 3.16)
project(example)
set(CMAKE_CXX_STANDARD 20)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../libimhex ${CMAKE_CURRENT_BINARY_DIR}/plugins/libimhex)
set(CMAKE_SHARED_LIBRARY_PREFIX "plugin")
add_library(example SHARED
source/plugin_example.cpp
)
target_include_directories(example PRIVATE include)
target_link_libraries(example PRIVATE libimhex)

View File

@@ -0,0 +1,32 @@
#include <plugin.hpp>
#include <views/view.hpp>
class ViewExample : public hex::View {
public:
ViewExample() : hex::View("Example") {}
~ViewExample() override {}
void drawContent() override {
if (ImGui::Begin("Example")) {
ImGui::Text("Custom plugin window");
}
ImGui::End();
}
};
IMHEX_PLUGIN {
View* createView() {
return new ViewExample();
}
void drawToolsEntry() {
if (ImGui::CollapsingHeader("Example Tool")) {
ImGui::Text("Custom Plugin tool");
}
}
}

View File

@@ -0,0 +1,22 @@
cmake_minimum_required(VERSION 3.16)
project(libimhex)
set(CMAKE_CXX_STANDARD 20)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../../external/ImGui ${CMAKE_CURRENT_BINARY_DIR}/external/ImGui)
if (WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libstdc++ -static-libgcc -static")
endif()
add_library(libimhex STATIC
source/helpers/event.cpp
source/helpers/utils.cpp
source/providers/provider.cpp
source/views/view.cpp
)
target_include_directories(libimhex PUBLIC include)
target_link_libraries(libimhex PUBLIC imgui)

View File

@@ -0,0 +1,38 @@
#pragma once
#include <vector>
#include <functional>
namespace hex {
enum class Events {
FileLoaded,
DataChanged,
PatternChanged,
FileDropped,
WindowClosing,
RegionSelected,
SelectionChangeRequest,
AddBookmark,
AppendPatternLanguageCode,
ProjectFileStore,
ProjectFileLoad
};
struct EventHandler {
void *owner;
Events eventType;
std::function<void(const void*)> callback;
};
class EventManager {
public:
static void post(Events eventType, const void *userData);
static void subscribe(Events eventType, void *owner, std::function<void(const void*)> callback);
static void unsubscribe(Events eventType, void *sender);
};
}

View File

@@ -0,0 +1,71 @@
#pragma once
#include <functional>
#include <vector>
#include <helpers/event.hpp>
#include <imgui.h>
namespace hex { class SharedData; }
namespace hex::plugin::internal {
void initializePlugin(SharedData &sharedData);
}
namespace hex {
namespace prv { class Provider; }
class SharedData {
SharedData() = default;
public:
SharedData(const SharedData&) = delete;
SharedData(SharedData&&) = delete;
static auto& get() {
static SharedData instance;
return instance;
}
friend void hex::plugin::internal::initializePlugin(SharedData &sharedData);
friend class Window;
private:
void initializeData() {
static std::vector<EventHandler> eventHandlersStorage;
static std::vector<std::function<void()>> deferredCallsStorage;
static prv::Provider *currentProviderStorage;
static ImVec2 windowPosStorage, windowSizeStorage;
this->imguiContext = ImGui::GetCurrentContext();
this->eventHandlers = &eventHandlersStorage;
this->deferredCalls = &deferredCallsStorage;
this->currentProvider = &currentProviderStorage;
this->windowPos = &windowPosStorage;
this->windowSize = &windowSizeStorage;
}
void initializeData(const SharedData &other) {
this->imguiContext = other.imguiContext;
this->eventHandlers = other.eventHandlers;
this->deferredCalls = other.deferredCalls;
this->currentProvider = other.currentProvider;
this->windowPos = other.windowPos;
this->windowSize = other.windowSize;
}
public:
ImGuiContext *imguiContext;
std::vector<EventHandler> *eventHandlers;
std::vector<std::function<void()>> *deferredCalls;
prv::Provider **currentProvider;
ImVec2 *windowPos;
ImVec2 *windowSize;
};
}

View File

@@ -0,0 +1,206 @@
#pragma once
#include <hex.hpp>
#include <array>
#include <cstring>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <vector>
#ifdef __MINGW32__
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
#define off64_t off_t
#define fopen64 fopen
#define fseeko64 fseek
#define ftello64 ftell
#else
template<>
struct std::is_integral<u128> : public std::true_type { };
template<>
struct std::is_integral<s128> : public std::true_type { };
template<>
struct std::is_signed<s128> : public std::true_type { };
#endif
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000
#if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts>
#endif
// libcxx 12 still doesn't have many default concepts implemented, as a result we need to define it ourself using clang built-ins.
// [concept.derived] (patch from https://reviews.llvm.org/D74292)
namespace hex {
template<class _Dp, class _Bp>
concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*);
}
// [concepts.arithmetic]
namespace hex {
template<class _Tp>
concept integral = __is_integral(_Tp);
template<class _Tp>
concept signed_integral = integral<_Tp> && __is_signed(_Tp);
template<class _Tp>
concept unsigned_integral = integral<_Tp> && !signed_integral<_Tp>;
template<class _Tp>
concept floating_point = __is_floating_point(_Tp);
}
#else
// Assume supported
#include <concepts>
namespace hex {
using std::derived_from;
using std::integral;
using std::signed_integral;
using std::unsigned_integral;
using std::floating_point;
}
#endif
#define TOKEN_CONCAT_IMPL(x, y) x ## y
#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y)
namespace hex {
template<typename ... Args>
inline std::string format(const char *format, Args ... args) {
ssize_t size = snprintf( nullptr, 0, format, args ... );
if (size <= 0)
return "";
std::vector<char> buffer(size + 1, 0x00);
snprintf(buffer.data(), size + 1, format, args ...);
return std::string(buffer.data(), buffer.data() + size);
}
[[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const hex::unsigned_integral auto &value) {
std::remove_cvref_t<decltype(value)> mask = (std::numeric_limits<std::remove_cvref_t<decltype(value)>>::max() >> (((sizeof(value) * 8) - 1) - (from - to))) << to;
return (value & mask) >> to;
}
template<hex::integral T>
[[nodiscard]] constexpr inline T signExtend(T value, u8 currWidth, u8 targetWidth) {
T mask = 1LLU << (currWidth - 1);
return (((value ^ mask) - mask) << ((sizeof(T) * 8) - targetWidth)) >> ((sizeof(T) * 8) - targetWidth);
}
std::string toByteString(u64 bytes);
std::string makePrintable(char c);
template<typename T>
struct always_false : std::false_type {};
template<typename T>
constexpr T changeEndianess(T value, std::endian endian) {
if (endian == std::endian::native)
return value;
if constexpr (sizeof(T) == 1)
return value;
else if constexpr (sizeof(T) == 2)
return __builtin_bswap16(value);
else if constexpr (sizeof(T) == 4)
return __builtin_bswap32(value);
else if constexpr (sizeof(T) == 8)
return __builtin_bswap64(value);
else
static_assert(always_false<T>::value, "Invalid type provided!");
}
template<typename T>
constexpr T changeEndianess(T value, size_t size, std::endian endian) {
if (endian == std::endian::native)
return value;
if (size == 1)
return value;
else if (size == 2)
return __builtin_bswap16(value);
else if (size == 4)
return __builtin_bswap32(value);
else if (size == 8)
return __builtin_bswap64(value);
else if (size == 16) {
u64 parts[2];
std::memcpy(parts, &value, size);
return u128(parts[1]) << 64 | u128(parts[0]);
}
else
throw std::invalid_argument("Invalid value size!");
}
template< class T >
constexpr T bit_width(T x) noexcept {
return std::numeric_limits<T>::digits - std::countl_zero(x);
}
template<typename T>
constexpr T bit_ceil(T x) noexcept {
if (x <= 1u)
return T(1);
return T(1) << bit_width(T(x - 1));
}
inline std::string toEngineeringString(double value) {
constexpr std::array prefixes = { "a", "f", "p", "n", "u", "m", "", "k", "M", "G", "T", "P", "E" };
int8_t prefixIndex = 6;
while (prefixIndex != 0 && prefixIndex != 12 && (value >= 1000 || value < 1) && value != 0) {
if (value >= 1000) {
value /= 1000;
prefixIndex++;
} else if (value < 1) {
value *= 1000;
prefixIndex--;
}
}
return std::to_string(value).substr(0, 5) + prefixes[prefixIndex];
}
std::vector<u8> readFile(std::string_view path);
#define SCOPE_EXIT(func) ScopeExit TOKEN_CONCAT(scopeGuard, __COUNTER__)([&] { func })
class ScopeExit {
public:
ScopeExit(std::function<void()> func) : m_func(func) {}
~ScopeExit() { if (this->m_func != nullptr) this->m_func(); }
void release() {
this->m_func = nullptr;
}
private:
std::function<void()> m_func;
};
struct Region {
u64 address;
size_t size;
};
struct Bookmark {
Region region;
std::vector<char> name;
std::vector<char> comment;
};
}

View File

@@ -15,10 +15,10 @@ using s32 = std::int32_t;
using s64 = std::int64_t;
using s128 = __int128_t;
#include "lang/result.hpp"
#include "lang/results.hpp"
extern int mainArgc;
extern char **mainArgv;
#if defined(__EMX__) || defined (WIN32)
#ifdef OS_WINDOWS
#define MAGIC_PATH_SEPARATOR ";"
#else
#define MAGIC_PATH_SEPARATOR ":"

View File

@@ -0,0 +1,18 @@
#pragma once
#include <glad/glad.h>
#include <imgui.h>
#include <hex.hpp>
#include <views/view.hpp>
#include <providers/provider.hpp>
#include <helpers/shared_data.hpp>
#define IMHEX_PLUGIN namespace hex::plugin::internal { \
void initializePlugin(SharedData &sharedData) { \
if (glGetString == NULL) \
gladLoadGL(); \
SharedData::get().initializeData(sharedData); \
} \
} \
namespace hex::plugin

Some files were not shown because too many files have changed in this diff Show More