Compare commits

..

267 Commits

Author SHA1 Message Date
Nik
17c200a92e disassemblers/jvm: Added remaining instructions besides lookupswitch and tableswitch 2024-12-27 13:41:46 +01:00
Nik
384d4c7794 disassemblers: Added half of the JVM instructions 2024-12-27 01:07:36 +01:00
Nik
37a7e59c06 disassemblers: Added Intel 8051 architecture 2024-12-26 20:08:42 +01:00
Nik
e8cea09477 include/hex: Added definitions for new built-in types 2024-12-24 12:39:28 +01:00
Andrey Andreyevich Bienkowski
883433b260 includes/type: Fix parsing of signed leb128 (#333) 2024-12-18 21:49:16 +01:00
Nik
2db9993cb1 git: Fixed ninja package name 2024-12-18 21:45:45 +01:00
Nik
01ce565c9e git: Install ninja 2024-12-18 21:35:34 +01:00
Nik
b7b949ea27 git: Updated action runners 2024-12-18 20:53:54 +01:00
BobSmun
e026ff187e build: Improve build system (#327)
* *Add top level CMakeLists.txt, to make it easier to use both independently and from within other projects
* Add a unit_test target, to attach all unit tests to

* * Fix unit tests for windows
* Silence cmake warning regarding missing top project
* update .gitignore for vscode

---------

Co-authored-by: BobSmun <6492115+BobSmun@users.noreply.github.com>
2024-12-16 20:37:38 +01:00
Nik
63504f59a1 tests: Fixed fucked up include 2024-12-14 22:31:12 +01:00
Josef Šimánek
6113df643d git: Fix typo in readme (#332) 2024-12-14 16:35:25 +01:00
WerWolv
3f42dddd19 tests: Improve unit tests for includes and patterns 2024-12-14 16:34:27 +01:00
Luca Corbatto
2cc8868727 patterns: Added rar file pattern as requested in #258 (#324)
* Add rar file pattern as requested in #258

* Fix rar pattern

Removed some experimental (and apperantly broken) code.

* Break on EndOfArchive header instead of EOF

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-12-14 13:48:06 +01:00
Sabhya
7f02510762 patterns: Added dmp64.hexpat and test files (#331)
* [+] Added dmp64.hexpat && test files

* Fix encoding of pattern file

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-12-14 13:40:22 +01:00
Sewer.
13c4168af0 patterns/bzip3: Fixed Incorrect field on branch (#330) 2024-12-13 10:21:47 +01:00
Sewer.
1e69cd7fb2 patterns: Added BZip3 File Header Pattern (#329)
* Added: BZip3 Compression

* Fixed: Bound the SmallBlock data by parent's size

* Improved: Now uses the name 'Chunk' for block wrappers, such that the name 'block' matches with what the BZ3 API does

* Improved: Import rather than Include std::mem

* Added: Missing 'description' field in pragma
2024-12-12 21:56:13 +01:00
Sabhya
16a87df2ac patterns: Added DPAPI Blob, DPAPI MasterKey, CREDHIST patterns (#328)
* [+]Added DPAPI MasterKey & Updated README.md

* [+]Added DPAPI Blob Pattern & Updated README.md

* [+] Added CREDHIST Pattern &  Updated README.md

* [+] Test Files added for dpapimasterkey, dpapiblob & CREDHIST
2024-12-05 21:26:43 +01:00
kbugstar
b7598405b5 encodings: Added Chinese GBK encoding (#308)
Chinese Gbk encoding file
2024-12-01 17:19:14 +01:00
WerWolv
d14f8de459 includes/std: Added new palette control functions 2024-12-01 17:15:24 +01:00
WerWolv
4c96bfbeb3 patterns/fs: Fixed pattern and uploaded test data 2024-11-28 21:35:25 +01:00
Geky
500a3fe26e patterns: Added GBA ROM pattern (#323)
* add support for cartridge size type $54

Added support for cartridge size type $54, corresponding to 1.5 MiB (96 banks).

* add missing license

* Add GBA Cartridge Header

* Update README.md

Added GBA information to README.md and corrected a typo.
2024-11-28 17:59:45 +01:00
WerWolv
5ffc583640 pattern/tiff: Fixed function parameter types 2024-11-27 20:44:56 +01:00
Nik
b9f5f1668b includes/type: Fixed use of Reinterpreter type 2024-11-24 14:53:30 +01:00
Nik
4c22f28a67 pattern/rgbds: Fixed bad include 2024-11-24 14:53:02 +01:00
Bananchiki
6f9b05b853 themes: Added One Dark theme (#322)
* Added One Dark theme

* theme: fixed spacing
2024-11-24 14:51:06 +01:00
Mrmaxmeier
c533017d0b git: Various style fixes everywhere, removing whitespaces (#321)
* repo-wide: trim trailing spaces

Note: This doesn't touch the .tbl files in encodings/ since they include
meaningful trailing spaces (`20= `)

* patterns: clean up duplicate semicolons

* ELF: add header magic check

* glTF: use type::Magic for magic value

* glTF: check that the file size in the header matches

* xgstexture: fix generics syntax for magic value

* JPEG: define hex enum with 0x00 instead of 0X00

* CI: update deprecated actions

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-11-24 11:41:26 +01:00
Dexrn ZacAttack
221fa70a67 patterns: Added Miles Sound System Compressed Archive (MSSCMP) (#320)
* MSSCMP readme

* Add files via upload
2024-11-24 11:39:43 +01:00
Dexrn ZacAttack
661e5b7081 patterns: Added RAD Game Tools BINKA hexpat (#319)
* Binka readme

* Binka hexpat
2024-11-24 11:39:22 +01:00
Geky
7d0bbd1e24 patterns/GameBoy: Add support for cartridge size type $54 and missing licenses (#318)
* add support for cartridge size type $54

Added support for cartridge size type $54, corresponding to 1.5 MiB (96 banks).

* add missing license
2024-11-24 11:38:54 +01:00
Maxim Savenko
55aca93a18 patterns/mp4: Add 'stsz' box definition to MP4 pattern (#317) 2024-11-24 11:38:31 +01:00
otakuxtom
255116a587 patterns/pe: Fix error when ordinalTableRVA is zero (#315)
ordinalTableRVA is not always has value. it might be zero.
Whien this happened, it will failed.

Signed-off-by: Chunhao Hung <chunhao.hung@insyde.com>
Co-authored-by: Chunhao Hung <chunhao.hung@insyde.com>
2024-11-17 14:00:43 +01:00
Luca Corbatto
79e25fdb73 patterns/zip: Added parsing of general purpose bit flag (#314)
* Add parsing of general purpose bit flag

Add "GeneralPurposeBitFlags" bitfield definition. The names are based on
the official ZIP format specification although I chose to name the
fields closer to their purpose rather than their official name. This is
intended to make reading the pattern and its output easier. Example:
official name "Language encoding flag (EFS)" my name
"filenameAndCommentAreUtf8" because this immediately explains what it
does.

I chose not to implement the specifics of the "compressionOptions" as
their meanings are specific to the compression method used and it would
make the pattern much more complicated for (in my opinion) little gain.

I also chose to unify the names of the general purpose bit filed in the
LocalFileHeader and the CentralDirectoryFileHeader. Previously, they had
different names, suggesting they might have different meaning. According
to the official docs though, these fields have the exact same meaning.

Official docs: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

* Fix typo and remove redundant type declaration
2024-11-17 14:00:16 +01:00
Dexrn ZacAttack
c8d9a8deb7 patterns: Added Minecraft LCE LOC file pattern (#311)
* create LOC hexpat

* loc to list
2024-11-17 13:59:44 +01:00
Miku-666
1d680fbf5e patterns: Added Minecraft LCE .pck format pattern (#310) 2024-11-17 13:59:20 +01:00
Dexrn ZacAttack
bc5a55affe patterns/lcesave: Use Virtual Filesystem + ZLib support + auto endian detection (#309)
* use Virtual Filesystem + ZLib support + auto endian detection

* fix builtin

* smh how am I only noticing that I just duplicated a function for no reason

* ifdefs to fix actions moment
2024-11-17 13:58:56 +01:00
Dexrn ZacAttack
85f5541350 patterns: Added Minecraft LCE ARC file format (#307)
* Create arc.hexpat

* add test file

* mention arc

* abide by contributing.md

* use virtual filesystem

* brainfart

* ifdefs to fix github actions moment #2
2024-11-17 13:58:02 +01:00
bbbbbr
61d3e110fb patterns/gb: Add 16K and 32K arrays for ROM Banks (#305)
Having arrays for dividing the GB ROM up into ROM Banks makes it much easier to jump to and inspect data at the start and end of banks.

- 16K Banks are the typical standard
- 32K banks aren't very common but are used in a couple unlicensed Games such as those using the Wisdom Tree MBC controller
2024-11-17 13:57:45 +01:00
Hikodroid
af957389c2 patterns: Added pattern for LZNT1 compressed data (#304) 2024-11-17 13:57:23 +01:00
Hikodroid
e85645897e patterns: Added pattern for Blender project files (#303)
* patterns: Added pattern for Blender project files

* patterns/blend: Added pattern file and test data

* patterns/blend: Fix the thumbnail bugs by passing the source data by reference

* patterns/blend: Added ZSTD support and test data
2024-11-17 13:56:59 +01:00
Hikodroid
abc78d1644 patterns/fbx: Improved the FBX pattern (#302)
* patterns/fbx: Improved the FBX pattern
-Added pragma magic
-Fixed sizing of compressed contents array
-Added references
-Cleaned up whitespace

* Added missing ] bracket in README.md
2024-11-17 13:56:40 +01:00
Valentin Lenhart
46e41db0a8 patterns/pe: Use appropriate pointer for first section placement (#300) 2024-11-17 13:56:01 +01:00
Valentin Lenhart
c67dc84911 patterns/pe: Fixed off by one error in coff pattern (#299) 2024-11-17 13:55:30 +01:00
Guest257351
323898d083 patterns/lua5.1: Fixed a bug in the Lua 5.1 bytecode pattern (#298)
* Fixed a bug in the Lua 5.1 bytecode pattern

Lua 5.1 bytecode upvalue fields were incorrectly defined as a `Vector<u32>` instead of `Vector<LuaString>`.

* Fixed another bug in the lua 5.1 bytecode pattern

Lua 5.1 bytecode string sizes were incorrectly parsed as a 64-bit integer, instead of a 32-bit integer.

* Updated the Lua 5.1 bytecode pattern for 32-bit compilers.

Updated the pattern to allow for 32-bit and 64-bit integers for the size of the string length field.
2024-11-17 13:55:00 +01:00
Seth Hall
abbd25e7f6 patterns: Added Windows Notepad cache file pattern (#297)
* Added Windows Notepad Cache file parser.

* Fixed Notepad windowstate link in readme

* Added a test file for notepad-cache.hexpat
2024-11-17 13:54:29 +01:00
Martín Montané
c8ebb3eb8a includes/std: Added checks to ends_with and starts_with to prevent failure (#295)
Fixing cases where part is longer than string, this cases should both return false instead of failing.

Co-authored-by: Nik <werwolv98@gmail.com>
2024-11-17 13:54:03 +01:00
applecuckoo
bf94cb7243 patterns: Added new WebP and VGM patterns (#294)
* README: fix square bracket

* patterns: add WebP pattern

* patterns/dds: add x-dds mimetype

* patterns: add vgm pattern

* patterns/vgm: remove old pointer

* patterns/protobuf: fix field number handling

* patterns/protobuf: add .pb file extension

* patterns/uf2: updating the family IDs again

* patterns/png: add cHRM and tIME chunks

* patterns/png: whoops, old description snuck back in

* new quantized-mesh pattern

* add quantized-mesh to README, implement oct16 decoding
2024-11-17 13:53:18 +01:00
paxcut
6697fc23a4 themes: Updated the custom themes to the new text editor color palettes (#255)
* Updated the custom themes to the new text editor color palettes designed for full syntax highlighting, but the existing themes should look just like they did before.

* impr: renamed pattern-placed-variable to calculated-pointer and added view
fix: pe pattern could read past the end of file if symbol search option was turned on and input file had no symbols. In that case a StringTable array that has 1 element would be created and place at offset 0 where the size variable was set to a large number creating the error. The fix is to set the size of the array using numberOfSymbols>0

* Fix: that was a bad choice for the size of the stringTable array because  even if findSymbols is not on the file can contain symbols. This was causing the pe unit test to fail. To get the right array size use sizeof(symbolTable)>0 which will be 1 only if findSymbols is true and the file actually contains symbols
2024-11-17 13:52:30 +01:00
Nik
8a6bb6612b includes/std: Fixed standard library errors with latest nightly 2024-11-17 13:51:51 +01:00
endes0
1d66949375 patterns: Added ext4 filesystem pattern (#293)
* patterns: add ext4 volume layout pattern

* patterns: improve ext4 pattern

* patterns: remove debug pragma from ext4

* patterns: fix ext4 magic and padding

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-08-20 21:56:05 +02:00
SpaceManiac
7c65d51986 patterns/msgpack: Fixed endianess of lengths and fixint definition (#291)
* Fix endianness of msgpack ext datum lengths

* Fix formatting of negative fixints
2024-08-20 20:41:12 +02:00
BobSmun
d961271c5d includes/std: Fixed std::core::set_pattern_comment (#289) 2024-08-20 20:33:18 +02:00
applecuckoo
26d48df7dd patterns/uf2: Add new RP2xxx-related family IDs (#288)
* patterns/uf2: add family ID enum

* patterns/uf2: Fix enum spacing

* patterns: add missing description pragmas and README entries, etc.

* patterns/uf2: add reference for Family ID enum

* patterns/uf2: add new RP2xxx family IDs

* patterns/uf2: whoops (comma fix)
2024-08-09 12:39:28 +02:00
Nik
8f1f4911a0 includes/std: Fixed value display error with std::string::NullString 2024-08-07 22:12:25 +02:00
Eldred Habert
1d7cc537ed patterns: Added RGBDS object file format (#287) 2024-08-07 22:11:29 +02:00
qux-bbb
62ceaae09b patterns/lua54: Add a Lua 5.4 test file (#286) 2024-08-04 21:54:24 +02:00
Nik
4a8a6cba1b patterns/flipper_settings: Removed #pragma magic as they would give too many false positives 2024-08-03 20:14:27 +02:00
Nik
c3eb9e4126 patterns: Improved pattern descriptions 2024-08-03 17:44:37 +02:00
WerWolv
a263347414 tests: Added StuffIt5 archive 2024-08-03 15:16:48 +02:00
qux-bbb
204599a70b patterns: Added Lua 5.3 bytecode pattern (#285) 2024-08-03 14:47:07 +02:00
Jan Wiesemann
bf6ee6d02f patterns: Added pattern for Flipper Zero settings (#281)
* Added pattern for Flipper Zero settings

* Added readme entry

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-08-03 14:11:02 +02:00
qux-bbb
0125ec2c57 patterns: Added Lua 5.2 bytecode pattern (#284) 2024-08-03 14:07:50 +02:00
applecuckoo
c5aaac25dd patterns/uf2: Added Family ID enum to uf2.hexpat, Added missing description pragmas and other minor fixes (#282)
* patterns/uf2: add family ID enum

* patterns/uf2: Fix enum spacing

* patterns: add missing description pragmas and README entries, etc.

* patterns/uf2: add reference for Family ID enum
2024-08-03 10:47:40 +02:00
qux-bbb
196011ead9 patterns: Added Lua 5.1 bytecode pattern (#283) 2024-08-03 10:46:25 +02:00
xtex
5b15136ea4 patterns: Add HSDT pattern (#280)
Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-27 08:38:44 +02:00
qux-bbb
59c954ae28 patterns/lua54: Removed empty line (#278)
Remove an empty line.
2024-07-26 19:52:24 +02:00
Hikodroid
8a5cb1061b patterns/fbx: Simplified the fbx hexpat (#277) 2024-07-26 19:52:01 +02:00
Hikodroid
120bc84548 patterns/fbx: Fixed the fbx hexpat (#276)
* patterns: FBX - revised hexpat for fbx files but still broken

* patterns: FBX - implemented a workaround for the previously broken hexpat

* Disable ImHex-specific functions outside of ImHex

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-25 00:00:11 +02:00
WerWolv
0e17355db0 tests: Added more test files 2024-07-23 21:03:17 +02:00
WerWolv
6aee524d1a patterns: Fix various patterns, added more test files 2024-07-23 20:31:43 +02:00
WerWolv
b42c571d4d patterns: Fixed run problems with some patterns 2024-07-23 18:39:05 +02:00
xndcn
71e1ad8df7 patterns/jpeg: Simplify EOI marker search (#272)
Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-23 18:37:03 +02:00
WerWolv
5c7d77b50f patterns: Added Kaydara FBX Binary format
Credit to @Hikodroid
2024-07-23 18:29:02 +02:00
WerWolv
a746ecb164 tests: Moved/Renamed some test files 2024-07-23 18:24:05 +02:00
Dexrn ZacAttack
569e5c4c1a patterns: Added Minecraft LCE save format (#256)
* Add Minecraft LCE save format

* Add files to the pattern

took forever lol cuz weird syntax

* NBT parsing n stuff

* Minecraft Xbox 360 Edition saves, read description

TU033 is a pre-release version, which has a slightly different file format that I documented myself [here](https://github.com/Team-Lodestone/Documentation/blob/main/LCE/Pre-Release%20Save%20Format.md)

TU5 is a release version which uses the same file format used all the way up to latest TU (aka the last version released)

All of these saves have been decompressed from XMemCompress (iirc modified LZX)
Chunk data however is still compressed, because it's not meant to be uncompressed in the scope of reading the save.

https://github.com/Team-Lodestone/Documentation/blob/main/LCE/LCE%20File%20Versions.md

* Support Pre-Release files, JANKY file type detection, min and cur version.

* fix top comment

* LCE saves to readme
2024-07-23 18:17:02 +02:00
applecuckoo
0316f2b667 patterns: Add PKM pattern + add BCC checksum verification to ntag pattern (#274)
* patterns/ntag: add BCC checksum verification

* patterns: add PKM file pattern

* Add entry to README

* Added missing import

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-23 08:30:05 +02:00
WerWolv
196695e37b includes/std: Allow std::print() and std::format() to take any value as format argument again 2024-07-12 21:19:43 +02:00
WerWolv
bced518508 includes/std: Added std::mem::reached() for use with while-sized arrays 2024-07-10 21:32:55 +02:00
WerWolv
2f795fc23c includes/std: Added attrs library 2024-07-10 21:32:35 +02:00
C3pa
5ff783d571 includes: Fix various spelling errors (#270)
docs: fix some spelling errors

Related issue:
https://github.com/WerWolv/ImHex/issues/1139
2024-07-10 21:09:15 +02:00
WerWolv
4299243e95 includes/std: Added hex::dec::lz4_decompress() 2024-07-07 15:51:40 +02:00
Surasia
23b3c2b5d0 git: Fix hinf_tag and hinf_module links in readme (#268) 2024-07-07 13:44:04 +02:00
Surasia
da1c2687e8 patterns/hinf_*: Add Halo Infinite tag and module file patterns (#267)
* patterns/hinf: Add Halo Infinite Tag and Module patterns

* patterns/hinf_bitmap: remove pattern
2024-07-06 17:33:03 +02:00
WerWolv
18f968df5b includes/std: Drastically improved std::mem::MagicSearch, added find_string and find_string_in_range 2024-07-04 20:47:39 +02:00
WerWolv
f797c711ca includes/std: Optimize std::bit::popcount 2024-07-04 17:58:12 +02:00
WerWolv
5380877da4 tests: Added error message when no description is used 2024-07-04 08:28:20 +02:00
Marc Butler
bb46276bde patterns: Added Password Safe Version 3 pattern (#266)
* Add password safe V3

* Added description pragma

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-07-04 08:27:51 +02:00
Nik
4242869ac1 patterns/zlib: Cast bitfield enums to integers before doing math with them 2024-07-03 22:48:15 +02:00
WerWolv
8bdcd814a9 includes/std: Added std::unimplemented() 2024-07-02 18:00:52 +02:00
WerWolv
d7811ff5e9 patterns: Replaced old bitfield order attributes with new ones
Fixes #265
2024-07-02 18:00:41 +02:00
WerWolv
4d0b3e21bc includes/std: Added better documentation to std::mem::current_bit_offset() 2024-07-02 18:00:05 +02:00
WerWolv
acd6903b21 includes/std: Added crc8, crc16 and crc64 functions
Fixes #226
2024-07-02 17:59:40 +02:00
WerWolv
8d2a39f7d4 git: Added build folders to gitignore 2024-07-02 17:58:47 +02:00
Nik
65ef3a7783 includes/std: Removed cyclic dependency between std.mem and std.string 2024-07-01 23:47:09 +02:00
Nik
21a0b99eac includes/std: Added missing string include to std::mem 2024-06-29 23:25:58 +02:00
Rebuild
a33b68921d patterns: Added ttf/otf format (#263)
* Add ttf/otf format

* ttf: Put cff to preprocessing
2024-06-29 22:52:21 +02:00
Nik
a0bb71be58 includes/std: Added std::core::execute_function() 2024-06-29 11:53:43 +02:00
WerWolv
c7fc39ac19 git: Make sure test data is always treated as binaries 2024-06-26 20:59:41 +02:00
WerWolv
b540ead0ae includes/std: Added std::IIndexed as a nicer wrapper around std::core::array_index() 2024-06-25 22:52:57 +02:00
Nik
26878548f0 includes/std: Fixed NullString not including null terminator and not checking for string end correctly 2024-06-23 18:45:13 +02:00
C3pa
e4c9d86755 includes/std: Add some fixes from the WerWolv/Documentation repo (#262)
* Escape backslash in DOSPath docs

* Spelling correction for std\sys.pat

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-06-22 10:59:36 +02:00
WerWolv
2a3de1b705 includes: Tabs -> Spaces 2024-06-22 10:46:30 +02:00
WerWolv
e02280f9ee includes/type: Added arbitrarily formattable type 2024-06-20 21:21:42 +02:00
WerWolv
bbba68cef7 includes/std: Added null-terminated strings to the strings library 2024-06-20 21:21:30 +02:00
Joachim Schiele
28b281b403 patterns/pe: Added .didata section support (#257) 2024-06-16 15:23:01 +02:00
Kirill Gladkikh
c807959d75 patterns/jpeg: Support EOF in the middle of JPEG (#240)
* Support EOF in the middle of file

* Changed to eoi marker searching
2024-06-16 15:16:01 +02:00
Francisco J. Solis
3416d30f2b pattern/dds: Fix bitfield PixelFormatFlags (#259)
* Fix bitfield PixelFormatFlags

The padding names should not repeat
Comments should be added to each field for clarification
Padding should be corrected for luminance.

* Re-work of PixelFormatFlags

Add more information considering current GIMP repository structure
https://gitlab.gnome.org/GNOME/gimp/-/blame/master/plug-ins/file-dds/dds.h\#L145
2024-06-09 22:15:05 +02:00
iTrooz
10bf1c76cf chore: mention description pragma in PR template 2024-05-20 01:05:48 +02:00
iTrooz
5b7c212029 git: use ccache (#253) 2024-05-20 01:01:59 +02:00
iTrooz
1c2e948940 test: Make description pragma mandatory (#251) 2024-05-20 00:35:24 +02:00
iTrooz
7ea34e410a fix: add missing ; to core.pat 2024-05-20 00:13:52 +02:00
iTrooz
56950e44d8 fix: use renamed PatternRuntime::getEvalError() (#252) 2024-05-20 00:10:34 +02:00
iTrooz
ed42452fc1 chore: remove old coverage code 2024-05-20 00:01:36 +02:00
iTrooz
a68ecb8888 fix: run tests concurrently 2024-05-20 00:01:00 +02:00
WerWolv
8d4cf59497 patterns/ffx: Updated submodule 2024-05-19 17:05:56 +02:00
Benjamin Gilbert
3c2fed22e4 patterns: Add Windows animated cursor (#242)
* patterns: Add Windows animated cursor

* Added readme entry

* Added mime type to readme

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2024-05-19 16:58:03 +02:00
Christoph Koehler
ff550bd105 patterns: Add Digital Terrain Elevation Data (DTED) pattern file (#243)
Tested on DTED0 and DTED2, will likely work with DTED1 as well.
2024-05-19 16:55:30 +02:00
Rebuild
0ad6e3abde patterns/mp4: Use FixedPoint32 instead of u32 for width and height (#248)
Update mp4.hexpat

* Use FixedPoint32 instead of u32 for width and height
* Add formatting for displaying fixed point 16.16 and 8.8 numbers
2024-05-19 16:55:04 +02:00
Marijn Kneppers
891968db53 includes/std: Add create_directories to std (#250) 2024-05-19 16:46:05 +02:00
Marijn Kneppers
5799d1d7ea includes/std: Make std::file::flush not delete files (#246) 2024-05-12 23:39:49 +02:00
Marijn Kneppers
9c6bfeb50f includes/hex: Added hex::core::add_virtual_file (#247) 2024-05-12 23:38:57 +02:00
AdventureT
9f7cdded6a Crashlvl: Added support for version 0.95 (#245)
* Working on new Version

* Needs testing

* Updated CrashLvl script to support version 0.94c

* Update README.md

* Added TestData and author to script

* Delete tests/patterns/test_data/CrashLvl.hexpat.bin

* CrashLvl.hexpat: Added support for version 0.95
2024-05-12 23:38:25 +02:00
Claudius Coenen
03298b0b0c patterns: Added Wintec TES file pattern (#238) 2024-04-21 12:33:19 +02:00
LolHacksRule
5f2738872e patterns: Added XGSPak and XGSTexture patterns (#237)
* Add XGSPak and XGSTexture patterns

* Whoops forgot proper pointers

* Fix typo

* Whoops

* Proper start

* Update xgstexture.hexpat
2024-04-21 12:32:26 +02:00
nazDridoy
63585e6de7 patterns/7z: Added MIME type (#241) 2024-04-21 12:25:00 +02:00
Sabhya Raj Mehta
cb6caafa64 patterns/refs: Added Structure for MinStoreB+ node, missing GlobalRootNode Names & parses all Superblocks (#236)
[+] Added Structure for MinStoreB+ node, Missing GlobalRootNode Names
2024-03-29 11:55:01 +01:00
Leon Jacobs
236fadee47 patterns: Added gguf pattern (#235)
* (feat) add gguf parser

* (chore) cleanup empty struct

* (tests) add sample gguf for tests and update readme

* (feat) update type enum
2024-03-28 21:55:18 +01:00
GlorifiedPig
0549e62a14 patterns/tar: Fixed minor typo (#230)
changes "if" to "id"
2024-03-21 22:16:37 +01:00
Sabhya Raj Mehta
b4bf2b946f patterns/refs: Added filesystem Checking, comments, Renamed REFS_HEADER, and Fixed typo. (#231)
Added FileSystem Checking and comments && renamed struct ReFSHeader to VolumeBootRecord && Fixed Typo
2024-03-21 22:16:15 +01:00
Zwip-Zwap Zapony
5e82bfadac includes/std: Replace get_attribute_value with get_attribute_argument (#233)
Update get_attribute_argument/get_attribute_value

Replace std::core::get_attribute_value with std::core::get_attribute_argument
Mark optional arguments with square brackets in the documentation comments, and list their default values
2024-03-21 21:48:53 +01:00
Sabhya
a5c9f3b18a patterns: Added ReFS filesystem pattern (#229)
Added Pattern File For Parsing ReFS filesystem Header, SuperBlock and CheckPoint && updated README.md
2024-03-17 10:19:18 +01:00
Nik
38262e6bb9 tests/patterns: Moved xilinx bootgen test file to correct folder 2024-03-16 10:24:09 +01:00
Nik
0a37b60d70 git: Mark all test files as binary 2024-03-16 10:22:51 +01:00
Shadlock0133
345e264ff8 patterns: Add .bgcode file (#222)
Support for binary G-code files, used by 3d printers
2024-03-15 21:54:58 +01:00
syuuha
ba2c396534 patterns: Added pattern for ADTS files (#223) 2024-03-15 21:54:41 +01:00
paxcut
439f04e19b includes/std: Fixed "unknown function fm" error was shown in pattern data. (#225) 2024-03-15 21:54:03 +01:00
ogmini
eaeea8d093 patterns: Added pattern for Windows 11 Notepad Window State bin file (#228)
* Add files via upload

* Update README.md

* Update README.md

* Add files via upload

* Update Notepad-WindowState.hexpat

* Update and rename Notepad-WindowState.hexpat to notepadwindowstate.hexpat

* Rename Notepad-WindowState.hexpat.bin to notepad-windowstate.hexpat.bin

* Update README.md
2024-03-15 21:53:40 +01:00
Nik
9af8d7e693 includes/std: Added back #pragma once to mem library 2024-02-27 20:28:02 +01:00
WerWolv
dac2e0f786 patterns: Fixed a few errors 2024-02-25 22:59:32 +01:00
Nik
f70b7066b9 includes: Switch over to import statements (#224)
* Update includes and patterns to new import system

* Update namespaces to new syntax
2024-02-25 22:04:41 +01:00
WerWolv
3f44a743e8 yara: Added advanced analysis rules 2024-02-25 11:29:59 +01:00
WerWolv
834e5261b3 tests: Fixed tests not building 2024-02-18 13:07:04 +01:00
Nik
0e2966f10d includes/std: Added missing std::core::set_pattern_comment function 2024-02-09 13:23:51 +01:00
Nik
b2bc248447 includes/hex: SectionId -> Section 2024-01-31 08:24:03 +01:00
Nik
e6589ecba1 includes/std: Make std::mem::read_string take in a larger size 2024-01-31 08:22:25 +01:00
apewo
f75ba4b6ee patterns/pe: Add extra MIME Type (#220)
add pe mime

Co-authored-by: John Doe <bla@bla.bla>
2024-01-29 18:36:21 +01:00
Nik
cf18580960 includes/hex: Added decompress functions 2024-01-27 17:05:08 +01:00
lucia c
e7d1973957 patterns: Added SWF header pattern (#219)
* patterns: Added pattern for SWF files.

* Added test file for SWF header.

* Update README with SWF file type.
2024-01-27 15:53:16 +01:00
t1hq
35cc68544b encodings: Add custom encoding file for Big5 (#218)
* add big5 encoding table

* add notes for big5 encoding, and how to import custom encoding file
2024-01-27 11:18:47 +01:00
Nik
41d8967deb patterns/pyc: Remove unused function 2024-01-20 22:14:47 +01:00
pew
658ec20b37 patterns: Add .ras pattern (#216)
* Add simple .ras file pattern

* Update ras.hexpat

* Update README.md

* Add .ras test file

* Update ras.hexpat

* Update ras.hexpat

* Update ras.hexpat

* Update ras.hexpat
2024-01-10 00:38:18 +01:00
paxcut
fb5fcbafc1 includes/type: Changes to magic type to include address of failed asserts. (#217) 2024-01-10 00:36:17 +01:00
Brandon Maier
6f7988e96e patterns: Added Xilinx boot images (#210)
* Adds pattern for Xilinx's Zynq UltraScale+ Boot Image format.
* Boot images are generated by Xilinx's `bootgen` tool.
* Spec: Xilinx UG1283 https://docs.xilinx.com/r/en-US/ug1283-bootgen-user-guide/Zynq-UltraScale-MPSoC-Boot-and-Configuration
* Add test file generated as follows
  - Build bootgen tool from https://github.com/Xilinx/bootgen
  - Create dummy data with `dd if=/dev/zero of=image.bin count=1`
  - Create bif with `echo "img: {image.bin}" >image.bif`
  - Create test bin with
    `./bootgen -arch zynqmp -image image.bif -o xilinx_bootgen.hexpat.bin`
2023-12-28 18:32:13 +01:00
g4ngli0s
0a631f0c1f patterns/pe: Fix BaseRelocationBlock count inside BaseRelocationTable (#212) 2023-12-28 18:31:53 +01:00
EvelynTSMG
5942897c29 patterns/ffx: Pull in latest updates (#209)
* Add Final Fantasy X patterns

* Update README

* Fix: github dum

* Add Bastion patterns

* git: update submodules

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2023-12-22 14:02:37 +01:00
utkumaden
a7e6209791 patterns: Added gITF pattern(#205)
* Create gltf.hexpat

Added glTF binary file pattern.

* Add a test file for the glTF pattern.

* Renamed the test file to fit the pattern file name.

* Fixed typo in documentation.
2023-12-07 17:09:25 +01:00
EvelynTSMG
294f69fa36 patterns: Add Bastion patterns (#207)
* Add Final Fantasy X patterns

* Update README

* Fix: github dum

* Add Bastion patterns

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2023-12-07 16:38:32 +01:00
gmestanley
1ea12cd4bd patterns/pe: Bringing over the massively improved version of pe.hexpat (#204)
* Add files via upload

* Update README.md

Added nes.hexpat to list of hex patterns

* Fix indenting of hex patterns list

Moved nes.hexpat below NE.hexpat

* Update README.md

Fixed indenting of PP pattern file's description being wrong

* Added x-msdownload MIME type to PE description

* Made indenting & code of ips.hexpat better

* Improvements to gb.hexpat

* Urgent fix to ips.hexpat

* Urgent fix to gb.hexpat

* Massive pe.hexpat improvement

* Replaced virtualDifference with relativeVirtualDifference

* Fixing unnecessary pattern_limit
2023-12-07 16:36:50 +01:00
Surasia
8129504dcb patterns/hinf_luas: Added pattern for reading HavokScript 5.1 Bytecode from Halo Infinite (#203)
* patterns/hinf_luas: Added pattern for reading HavokScript 5.1 Bytecode from Halo Infinite

* Parses Header and Structures of the parent tag
* Reads Bytecode types and arguments
* Reads Constants and Debug Info
* Reads Referenced Tags in the File

* readme: fix relative link
2023-12-07 16:36:27 +01:00
klirktag
22e30cfef9 patterns/mp4: Add STBL-box children (#202)
add STBL-box children
2023-12-07 16:36:07 +01:00
EvelynTSMG
9b819cf392 patterns: Add Final Fantasy X patterns (#197)
* Add Final Fantasy X patterns

* Update README

* Fix: github dum
2023-11-20 11:54:56 +01:00
klirktag
3277821153 patterns/mp4: Support mp4a and avc1 codec boxes (#195)
add support for mp4a and avc1 codec boxes, and sample-time-to-sample box
2023-11-15 22:26:10 +01:00
paxcut
f23dbbb565 includes/std: Fixed std::string::replace not replacing sequences correctly (#198)
fix:  [Bug] std::string::replace("aa", "aa", "") returns "a" #1408
2023-11-15 22:25:34 +01:00
Surasia
52f7d9e77a patterns/hinf_bitmap: Added pattern for parsing Halo Infinite bitmap files (#194)
* patterns/hinf_bitmap: Added pattern for parsing Halo Infinite bitmap files

* Parses the header of all Halo Infinite files which includes related "dependencies", datablocks, structure references
* Read bitmap sequence data, including bitmap index, complete index, sprite info
* Find the width/height and DDS Format of the raw texture, which can then be parsed into usable DDS textures
* Locates raw DDS block info

* Nulled out the DDS section of the bitmap
2023-11-14 00:20:32 +01:00
klirktag
99df77baf2 patterns/mp4: Add childbox support for STBL boxes (#192)
* find childboxes in stbl

* add implementation for SampleDescriptionBox
2023-11-14 00:06:50 +01:00
klirktag
d7b0819ff0 patterns/mp4: Make handler_type into a char[4], which reflects how it is used (#193)
make handler_type into a char[4], which reflects how it is used
2023-11-14 00:06:31 +01:00
Nik
70f491d2fa includes/type: Fixed formatting of time_t values in big endian patterns 2023-11-12 22:18:46 +01:00
Hugo
08680a6544 patterns/bplist: Added pattern file for Apple’s binary property list format (bplist) (#190)
* Added pattern file for Apple’s binary property list format (bplist)

* renamed some stuff and improved error messages

* added error handling for object size special case (0x0F)
2023-11-12 01:02:50 +01:00
Ange Albertini
23bc36c4bd patterns/selinux: Detailed SELinux config bitfield (#188) 2023-11-06 16:30:53 +01:00
Ange Albertini
8ae778944d patterns/se: Increased array limit (#187)
Increased array limit
2023-11-01 20:19:10 +01:00
klirktag
7e6a5d3bfa patterns/mp4: Added stbl box (#185) 2023-10-29 19:54:23 +01:00
Hugo
27e55d2e6d patterns/zip: Added parsing of extra field (#182)
* zip pattern: Improved fallback method for finding eocd. Added test data to cover this edge case

* zip pattern: added parsing of extra field
2023-10-29 19:47:11 +01:00
Benjamin Gilbert
e0a602c10a patterns/jpeg: Small improvements (#184)
* patterns/jpeg: exclude EOI marker from SOS image data

* patterns/jpeg: use type::Magic for magic numbers

* patterns/jpeg: add RGB component IDs

* patterns/jpeg: add struct for APP14 marker

* patterns/jpeg: add definition for COM marker

* patterns/jpeg: add some format_read() for better legibility
2023-10-29 19:46:51 +01:00
AdventureT
8748646016 patterns/CrashLvl: Update Crash Back in Time level format (#186)
* Working on new Version

* Needs testing

* Updated CrashLvl script to support version 0.94c

* Update README.md

* Added TestData and author to script

* Delete tests/patterns/test_data/CrashLvl.hexpat.bin
2023-10-29 19:46:28 +01:00
iTrooz
4a52ee4cf8 patterns: add UEFI Boot Entry pattern (#183)
add uefi_boot_entry pattern
2023-10-24 23:04:49 +02:00
iTrooz
e517e3534b patterns: fix description pragmas (#181) 2023-10-24 17:25:43 +02:00
DmitriLeon2000
edd0aa9a2f patterns: Add .fas and .was pattern files (Oska DeskMates) (#176)
* Add .fas and .was pattern files (Oska DeskMates)

* Update .was pattern file

* Update .was/.wa3 pattern file

* Update README.md

* Update README.md

* Update .fas & .was pattern files

* Update README.md

* Update fas_oskasoftware_old.hexpat

* Added WAS test file

* Update WAS test file

* Update was_oskasoftware.hexpat
2023-10-24 07:35:38 +02:00
Hugo
a992d1ba92 patterns/zip: Improved fallback method for finding eocd (#177)
zip pattern: Improved fallback method for finding eocd. Added test data to cover this edge case
2023-10-24 07:35:02 +02:00
leen
6fbdcac556 patterns/ip: Fix payload size when ip header or tcp header has options in ip.hexpat (#178) 2023-10-24 07:34:35 +02:00
itsmeow
47fce1628f patterns: Add ARIA2 Control format (#179) 2023-10-24 07:33:56 +02:00
Nik
9b152ae560 includes/std: Fixed doc comment of std::math::atan2 2023-10-22 21:25:14 +02:00
Nik
6b136b7fc6 includes/std: Fixed std::math::atan2 not taking correct arguments 2023-10-22 21:23:51 +02:00
gmestanley
93494a19a4 patterns: Better code + credit given for ips.hexpat & better readme (#174)
* Add files via upload

* Update README.md

Added nes.hexpat to list of hex patterns

* Fix indenting of hex patterns list

Moved nes.hexpat below NE.hexpat

* Update README.md

Fixed indenting of PP pattern file's description being wrong

* Added x-msdownload MIME type to PE description

* Made indenting & code of ips.hexpat better

* Improvements to gb.hexpat

* Urgent fix to ips.hexpat

* Urgent fix to gb.hexpat
2023-10-15 21:21:19 +02:00
H0L0
4fd710e23e patterns/flac: Fix SEEKTABLE metadata block (#173)
Add SEEKTABLE to blocktype check
2023-10-15 21:19:34 +02:00
Nik
44842dc44b includes/std: Added std::mem::set_section_size (#175) 2023-10-15 21:15:12 +02:00
HalfInner
056035c540 patterns/zip: Add parsing local file header with minor adjustment (#172)
patterns/zip: add parsing local file header, and another adjustmenst

Add missing parsing for local file headers
Add compression method
Minor adjustments: removed black colors, marked magic ids
2023-10-06 12:20:30 +02:00
Diego
5ad8e15afc patterns/shp: Added ESRI patterns (#170)
* add .shp and .shx patterns

* add tests
2023-10-06 12:20:11 +02:00
Nik
39c4d11404 patterns/uefi: Remove invalid MIME pragma 2023-10-05 08:54:59 +02:00
Benjamin Gilbert
815bd5f7f3 git: Minor readme fixes (#168) 2023-09-26 16:51:31 +02:00
Benjamin Gilbert
917b05a9f2 patterns: Add DICOM (#162)
DICOM files specify a "transfer syntax" which defines the image
compression format, the encoding rules for the entire file, and any
special-case encoding rules for particular fields.  Many transfer syntaxes
have common design features, but a transfer syntax is allowed to use
completely custom encoding rules, and need not be publicly documented.

Explicitly reject transfer syntaxes we know we don't support: implicit VR
(uncommon), explicit VR big-endian (deprecated), deflate-compressed.
In all other cases, follow some general rules and hope it works out.

The large lookup functions were generated by a script, but I haven't
included the code here, since its input is hand-massaged data copied from
HTML tables.

Add a JPEG WSI test case from the WG26 2021 hackathon (CC0 license) and a
synthetic LE Explicit VLP case produced with img2dcm.
2023-09-26 16:51:02 +02:00
brliron
46a2cef993 patterns: Added Android VBMeta image pattern (#169) 2023-09-26 14:03:24 +02:00
Nik
bca25b1a78 includes/hex: Fixed duplicate variable name in hex::core::get_selection() function
Fixes #167
2023-09-25 07:22:06 +02:00
Benjamin Gilbert
7ecd6d87dd patterns/tiff: Support BigTIFF and tiled TIFF; bugfixes and cleanups (#159)
* patterns/tiff: show TIFF tag name/number in DirectoryEntry array

Don't require unfolding the array entry to see what tag it contains.

* patterns/tiff: show IFD number in IFD list

* patterns/tiff: add JPEGTables tag; correct name of ICC Profile tag

* patterns/tiff: add TIFFRational type

Rationals, uniquely, are primitives with two fields.  Add a struct to
represent this, rather than inlining them.

* patterns/tiff: use correct types for fields smaller than 4 bytes

Small fields are always left-aligned in the 4-byte Value Offset.  On
little-endian TIFFs we currently cheat this by declaring a 32-bit value
and letting little-endianness handle the semantics.  However, this adds
some extra conditionals, and misrepresents the resulting field as 32 bits.
Drop the cheat.

* patterns/tiff: add ValueOffset abstraction

We were using the field type to make assumptions about whether the Value
Offset is a Value or an Offset, which is incorrect.  If the Count
multiplied by the field size is larger than 4, the field is an Offset;
otherwise it's a Value.

Add display sugar for single-element arrays to avoid extra nesting.

* patterns/tiff: drop dead code

get_ifds_offsets() and BIG/LITTLE aren't used at all.  get_total_IFDs()
is only used for declaring the length of TIFFFile.IFDs, and isn't needed
because IFDs are structured as a linked list.

* patterns/tiff: drop set_endian()

The call in TIFFFile is redundant.  Drop both calls and open-code the
check at the top level, before executing any code.  The BigTIFF check
will eventually be added alongside this one.

Fail if we don't recognize the magic number.

* patterns/tiff: minor cleanups

* patterns/tiff: drop strip offset/byte count arrays from struct IFD

They're redundant with the fields in the DirectoryEntry array.  Also
they're buggy: they assume the field Value Offsets are always offsets,
which isn't true for single-strip IFDs, and they ignore a partial last
strip in multiple-strip IFDs.

* patterns/tiff: rewrite strip array generation

We're making extra work for ourselves by avoiding the type system.  Also,
by calculating the number of strips we expect rather than the number of
strips we actually have, we're miscounting and omitting any partial last
strip.

Instead, read the strip offsets and byte counts directly from the
IFDEntry array.

* patterns/tiff: add ImageData array for tiled IFDs

* patterns/tiff: increase variable widths for BigTIFF

Use 64-bit temporary variables for values that can be 64 bits in BigTIFF.

* patterns/tiff: support BigTIFF

* tests/patterns/test_data: add more TIFF tests
2023-09-24 20:04:20 +02:00
dn-ln
bf0d96db5f patterns/id3: Fix the error No variable named 'n' found. (#160) 2023-09-24 20:03:49 +02:00
paxcut
705900d38b includes/std: Fixed std::string::replace (#163)
The submitted fix may have been a work in progress version instead of the tested solution I intended to submit. Hopefully this time I'll get it right.
2023-09-24 19:58:04 +02:00
gmestanley
734afdf500 patterns: Added .nes pattern file (#166)
* Add files via upload

* Update README.md

Added nes.hexpat to list of hex patterns

* Fix indenting of hex patterns list

Moved nes.hexpat below NE.hexpat
2023-09-24 19:57:20 +02:00
Benjamin Gilbert
c0c117ac19 tests/patterns: support multiple test files for a pattern (#161)
Allow either a single test file in tests/patterns/${pattern}.hexpat.${ext},
as we do now, or multiple files in tests/patterns/${pattern}.hexpat/*.

Closes #158.
2023-09-10 09:56:25 +02:00
paxcut
7fba66a444 includes/std: Fixed std::string::replace truncating output incorrectly (#157) 2023-09-10 09:40:29 +02:00
Yury Ershov
8eed75d783 patterns/bson: Support for multiple documents per file (#156)
* BSON support multiple documents per file

BSON files can contain consecutive documents glued one after another. An example of these is MongoDB FTDC metrics export.

[`bsondump`](https://github.com/mongodb/mongo-tools/blob/master/bsondump/bsondump.go) can unpack this type of BSON documents.

* Add accidentally deleted lines
2023-09-10 09:39:32 +02:00
Kenichi Saita
81f4978656 patterns/vhdx: Various improvements (#154)
* Replaced right_to_left to bitfield_order

* Fixed type of ParentLocatorEntry (char -> char16)

* Fixed item address of MetadataTableEntry

* Improved RegionTableEntry# Please enter the commit message for your changes. Lines starting
2023-09-10 09:39:04 +02:00
iTrooz
b6e0557a1d patterns: put author and description inside each pattern (#155) 2023-08-28 12:32:23 +02:00
gmestanley
ba14dd0cb2 patterns: Adding IPS pattern and fixed PE magic file (#153)
* Update pe.hexpat

New improvement

* Add ips.hexpat via upload

* Add ips.hexpat.ips via upload

* Added IPS to README

* Mentioned Windows in portable_executable_magic
2023-08-27 00:38:30 +02:00
MatrixEditor
86f93dfdaf patterns: Added Ubiquiti firmware pattern (#145)
* Ubiquiti firmware pattern

* Added padding and crc32 fields

* Added unit test file

+ Renamed fields in partition struct
2023-08-16 23:28:01 +02:00
Justus Garbe
001900e3c2 patterns/pyc: Add a pattern for pyc files
Change name
2023-08-15 09:30:19 +02:00
Nik
6baae92553 includes/std: Added missing mem library include in ptr libary 2023-08-04 22:56:03 +02:00
Jason Shirk
520f9bcb22 patterns/pe: Fix DebugDirectory version field types (#146) 2023-08-04 01:14:49 +02:00
vikke1234
44b0392b78 patterns/fdt: Unflatten FDT (#144)
In order to have a better time viewing FDTs in the visualizer
scanner will now unflatten the FDT.

It could still be improved slightly by modifying FDTProps to
make their values be `u32`s and possibly detect whether they
should be u64s.
2023-08-04 01:11:20 +02:00
Nik
df2bd4e3f9 git: Run PatternLanguage webpage CI 2023-07-29 12:12:33 +02:00
Nik
7723cf55c6 patterns: Fixed wrong extensions for some patterns 2023-07-24 16:14:37 +02:00
Nik
caa2b6aaa6 patterns/fdt: Improved visualizing of data 2023-07-24 16:13:34 +02:00
lopqto
7344df7ff6 patterns/pyinstaller: Added PyInstaller pattern (#142) 2023-07-16 20:21:59 +02:00
Nik
df649d2e62 patterns/elf: Speed up section name querying 2023-07-14 21:52:47 +02:00
Nik
8710b9e66f scripts: Added basic Kaitai to ImHex Pattern converter 2023-07-14 17:08:49 +02:00
vikke1234
665c942329 patterns/fdt: Fixed typo (#141) 2023-07-14 12:18:27 +02:00
vikke1234
50f93d14ff patterns/fdt: Fix flattened device tree parsing (#140)
* Fix flattened device tree parsing

Fix parsing to support multiple FDTs in a file and
non-zero base addresses.

* Fix string parsing

Parent offset wasn't being taken into account
when looking for prop names.
2023-07-13 14:38:52 +02:00
Nik
ab43516517 includes/std: Allow std::mem::MagicSearch to work with non-zero base addresses 2023-07-13 12:10:54 +02:00
Nik
4587b465d4 includes/std: Fixed std::mem::eof() not working correctly with non-zero base addresses 2023-07-13 12:08:25 +02:00
Nik
75b2c7be7e includes/std: Fixed MagicSearch type 2023-07-13 12:06:02 +02:00
Ange Albertini
19dd39e7c0 patterns: Added SE Linux binary format pattern (#139)
* SE Linux policy binary

module, base, kernel and packages

* Updated README with SELinux patterns

* SELinux test files
2023-07-12 20:25:47 +02:00
Nik
ecd34d35b2 patterns/elf: Fixed p_data definition in Phdr structs 2023-07-12 14:10:01 +02:00
Nik
06366839aa includes/std: Added std::ByteSizedArray 2023-07-12 00:13:02 +02:00
Nik
e3c387d0cf patterns/3ds: Added 3DS Max pattern 2023-07-10 16:36:49 +02:00
brliron
5a7077412c patterns/bmp: Various improvements (#138)
- Add various version of the BitmapInfoHeader struct, and autodetect
  the correct one.
- Fix palette detection.
- Use BitmapInfoHeader::biSize to find the position of the palette / data.
2023-07-10 11:31:07 +02:00
WerWolv
d8a37b0579 tests: Added WAD test file 2023-07-09 10:05:47 +02:00
WerWolv
1f1b2b9c5b tests: Fixed name of afe2 test file 2023-07-09 10:05:40 +02:00
Nik
d1645d2dc2 patterns:/intel_hex: Allow Intel Hex pattern to support files with linux line endings 2023-07-09 00:39:23 +02:00
WerWolv
61ef68b12a tests: Added more test files 2023-07-09 00:31:48 +02:00
WerWolv
c52e5b959b patterns: Fixed intel hex pattern 2023-07-09 00:14:58 +02:00
WerWolv
4a62892411 tests: Added various new test files 2023-07-09 00:14:49 +02:00
Nemoumbra
fc9b4cdbc2 tests: Added ico test file (#137) 2023-07-08 23:33:20 +02:00
Nik
daa556db31 tests: Fixed name of jpeg test pattern 2023-07-08 23:15:42 +02:00
Nik
e01a832fab patterns/lua54: Fixed parameter named const 2023-07-08 23:07:05 +02:00
Nik
759708d446 patterns/png: Automatically name PNG chunks 2023-07-03 22:06:48 +02:00
Trevor Gross
82560e6d9d patterns: Add a pattern for zlib compression (#135)
Add a pattern for RFC 1950 zlib compression
2023-07-02 18:58:19 +02:00
Nik
1a2d785093 patterns/java_class: Added MIME type 2023-06-24 11:05:10 +02:00
Nik
addec74d91 type/leb128: Fixed type always displaying 0 2023-06-22 17:35:59 +02:00
jfsbrito
ce83eedf02 patterns/7z: Added CompressData length and other improvements (#134)
* Update 7z.hexpat - v1.01

v1.01
--Minor changes.
--CompressData lenght added
--Output optimization

* Update 7z.hexpat v1.02

-Minor Changes
-Added Bzip2 verification
2023-06-22 07:27:31 +02:00
Doriel Rivalet
463ddcc62e themes: Add Catppuccin themes (#132)
* docs(README): add catppuccin theme

* themes: add catppuccin flavors

* chore: rename catppuccin files

* docs(README): update catppuccin file names
2023-06-19 23:09:16 +02:00
jfsbrito
13b97fc976 patterns/7z: Added 7Zip pattern (#128)
* 7z.hexpat

This repository contains a custom pattern for the ImHex tool that enables the analysis of 7zip files. The pattern allows for a structured view of 7zip files within ImHex, providing insights into various aspects of the file structure.

- Identification of 7zip files: The custom pattern detects and identifies 7zip file types based on their signature.
- Extraction of key information: The pattern extracts important details from the 7zip file, such as the format version, CRC values, relative offset of the end header, and file size.
- Differentiation of compression methods: The pattern distinguishes between LZMA and LZMA2 compression methods used within the 7zip file.
- Visualization of start and end headers: The pattern helps in visualizing the start and end headers of the 7zip file, making it easier to navigate through its structure.

To use the custom pattern for analyzing 7zip files in ImHex, follow these steps:

1. Install ImHex: Ensure that you have ImHex installed on your system.
2. Open a 7zip file: Launch ImHex and open the 7zip file you want to analyze.
3. Apply the custom pattern: In the "Pattern" menu, select the custom pattern for 7zip file analysis and apply it.
4. Explore the file structure: ImHex will display the matched patterns, allowing you to explore the structure of the 7zip file with the extracted information.

Please note that this custom pattern is designed specifically for 7zip files and may not be suitable for other file formats.

Contributions to this custom pattern for 7zip file analysis are welcome. If you have any improvements, bug fixes, or suggestions, feel free to submit a pull request.

This custom pattern for ImHex is licensed under the [MIT License](LICENSE.md). You are free to modify and distribute this pattern as per the terms of the license.

We would like to acknowledge the developers of ImHex for providing an excellent tool for binary file analysis. The custom pattern for 7zip file analysis in this repository builds upon the capabilities of ImHex to enhance the understanding of 7zip file structures.

---

We hope you find this custom pattern useful for analyzing 7zip files using ImHex. If you encounter any issues or have any questions, please feel free to raise them in the "Issues" section of this repository.

Thanks!

* Added test file

---------
2023-06-19 23:08:42 +02:00
luisfilipe23lol
55e4283432 patterns/cda: Added CDA pattern (#133)
* Create cda.hexpat

pattern language created for .cda files

* added test file for cda pattern

* Delete cda.hexpat.cda.cda

* Add test file cda

test file for cda pattern

* Update README.md

Add cda file in read.me
2023-06-19 14:22:17 +02:00
Nik
ea225edf12 git: Disable coverage information for now 2023-06-17 15:20:01 +02:00
blondecake433
bb19cb43ee patterns:/mp4: Added mp4 pattern (#129) 2023-06-17 15:07:08 +02:00
Nik
8f8ad0e2d5 git: Try fix Coveralls heap out of memory 2023-06-17 15:02:53 +02:00
Nik
3ad1f3969f includes/std: Fixed documentation of copy_value_to_section function 2023-06-15 22:58:44 +02:00
cryptax
5451d45158 patterns/dex: Fix pattern to see data section of DEX files + Link_data (#127) 2023-06-15 18:48:47 +02:00
Nik
e6a731fa1d includes/type: Added Base64 type 2023-06-15 17:34:20 +02:00
Jackson Barreto
8a62001705 patterns: Added TIFF pattern (#126)
* Create tiff.hexpat

* Update README.md

Update readme to include tiff hexpat

* added file to test the pattern

---------

Co-authored-by: joelalves <joel.17.alves@gmail.com>
2023-06-15 08:08:39 +02:00
Nik
1f8710b586 patterns/ntag: Fixed Length type transform function 2023-06-13 13:36:53 +02:00
Nik
acd2d4abb8 includes/std: Fixed description of array library (#125) 2023-06-12 08:10:48 +02:00
qufb
032f3c7c01 pattern/midi: Support multiple tracks (#124)
* pattern/midi: Support multiple tracks

* pattern/midi: Replace custom type used to index array
2023-06-11 13:09:23 +02:00
无以铭川
3841ff51ef pattern/java_class: Format byte code instruction (#123) 2023-06-08 23:39:39 +02:00
Nik
622721403f patterns/flac: Fixed typo 2023-06-06 08:26:01 +02:00
Nik
11291d1ebb tests: Added JPG test file 2023-06-05 10:59:12 +02:00
Nik
92e61ccf5d tests: Fixed build with new pattern language changes 2023-06-05 10:03:55 +02:00
Nik
062edfe527 includes/std: Fixed std::fxpt::to_fixed conversion issue 2023-06-05 09:48:33 +02:00
paxcut
5b32941801 patterns: Added visualizers to image patterns (#117)
* Added image visualizers to image patterns that were supported

* missing include files

* Small style fixes

---------

Co-authored-by: Nik <werwolv98@gmail.com>
2023-06-04 22:38:25 +02:00
Nik
e99ab5b59b patterns/java_class: Fixed duplicate variables 2023-06-02 10:54:09 +02:00
Feitong Chen
775c836766 patterns/macho: Fix macho CpuType error and add CpuType::ARM64 and CpuType::ARM64_32 (#115) 2023-06-01 16:38:34 +02:00
blondecake433
43058b4c45 pattern/gif: Improved GIF pattern (#114) 2023-05-26 09:28:18 +02:00
Justus Garbe
0128ea87db patterns/java_class: Added Java SE 20 Attributes, added value displaying (#113)
greatly enchanced the java pattern
2023-05-19 17:59:15 +02:00
WerWolv
fe231436d9 patterns/gb: Added Gameboy ROM pattern (#89)
* Added gameboy format

* Add mime type

* Add test

* Avoid DMCA :sweating:
2023-05-19 16:09:14 +02:00
gmestanley
7a9ac44577 patterns/pe: Improved PE pattern (#112)
New improvement
2023-05-16 11:03:07 +02:00
Nick Bitounis
74e9d8f2e7 patterns: Added pattern file for M.A.X. v1.04 game files. (#111)
* Added pattern file for M.A.X. v1.04 game files.

* * Added MAX pattern in list of patterns.
* Added MAX sample game save file.
* Reordered the list of patterns to ascending name.

---------

Co-authored-by: n.bitounis <n.bitounis@xe.gr>
2023-05-08 16:17:19 +02:00
Nik
2f39a62d85 includes/std: Added support for writing patterns to files 2023-05-02 20:38:21 +02:00
AdventureT
e21063d58b patterns: Added Crash Bandicoot - Back in time level format (#110)
* Added Crash Bandicoot - Back in time level format

* Update README.md

* Fix README.md
2023-04-25 21:44:02 +02:00
paxcut
8f1a6bdd75 includes/std: Added std::math::exp(), fixed std::math::ln comment (#106)
Removed extraneous argument base to ln function and added the necessary definition in include file to access previously builtin function exp.
2023-04-17 22:19:47 +02:00
Nik
b9af43e08b patterns: Fixed WAV MIME type in readme 2023-04-16 21:37:40 +02:00
Nik
2ffa4e0161 patterns/wav: Fixed MIME type 2023-04-06 12:33:46 +02:00
319 changed files with 71218 additions and 5265 deletions

2
.gitattributes vendored
View File

@@ -1,2 +1,4 @@
*.pat linguist-language=Rust
*.hexpat linguist-language=Rust
tests/patterns/test_data/** binary

View File

@@ -5,7 +5,8 @@
## Checklist
- [ ] A pattern for this format doesn't exist yet (or this PR improves the existing one)
- [ ] The new pattern has been added to the relevant table in the Readme
- [ ] The new pattern has a description pragma (`#pragma description My pattern Description here`)
- [ ] The pattern was associated with all relevant MIME types (using `#pragma MIME mime-type` in the source code)
- Make sure to never use `application/octet-stream` here as that means "Unidentifiable binary data"
- [ ] A test file for this pattern has been added to [/tests/patterns/test_data](/tests/patterns/test_data)
- Try to keep this file below ~ 1 MB
- Try to keep this file below ~ 1 MB

View File

@@ -8,7 +8,7 @@ on:
repository_dispatch:
types: [run_tests]
workflow_dispatch:
inputs:
inputs:
generate_docs:
description: "Regenerate docs"
required: false
@@ -17,7 +17,7 @@ on:
jobs:
tests:
name: 🎯 Dispatch changes
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
env:
DISPATCH_TOKEN: ${{ secrets.DISPATCH_TOKEN }}
permissions:
@@ -27,13 +27,13 @@ jobs:
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
uses: actions/checkout@v4
with:
submodules: recursive
- name: 📄 Check changed include files
id: changed-includes
uses: tj-actions/changed-files@v35
uses: tj-actions/changed-files@v45
with:
files: includes/**/*.pat
@@ -45,3 +45,12 @@ jobs:
repo: Documentation
owner: WerWolv
event_type: update_pl_docs
- name: ✉️ Update PatternLanguage Website
if: ${{ env.DISPATCH_TOKEN != '' }}
uses: mvasigh/dispatch-action@main
with:
token: ${{ secrets.DISPATCH_TOKEN }}
repo: PatternLanguageWeb
owner: WerWolv
event_type: rebuild_wasm

View File

@@ -11,7 +11,7 @@ on:
jobs:
tests:
name: 🧪 Unit Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
permissions:
actions: read
contents: read
@@ -19,7 +19,7 @@ jobs:
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
uses: actions/checkout@v4
with:
submodules: recursive
@@ -28,54 +28,54 @@ jobs:
sudo apt update
sudo apt install -y \
build-essential \
gcc-12 \
g++-12 \
ccache \
gcc-14 \
g++-14 \
lld \
${PKGCONF:-} \
cmake \
make \
ninja-build \
python3 \
python3-pip \
libmagic-dev \
lcov
sudo pip install jsonschema
- name: 📜 Setup ccache
uses: hendrikmuhs/ccache-action@v1
with:
key: ${{ runner.os }}-ccache-${{ github.run_id }}
restore-keys: ${{ runner.os }}-ccache
max-size: 1G
- name: 🛠️ Build
run: |
cd tests
mkdir -p build
cd build
CC=gcc-12 CXX=g++-12 cmake \
CC=gcc-14 CXX=g++-14 cmake \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache \
-DCMAKE_C_FLAGS="-fuse-ld=lld --coverage" \
-DCMAKE_CXX_FLAGS="-fuse-ld=lld --coverage" \
-DIMHEX_PATTERNS_ENABLE_UNIT_TESTS=ON \
-DLIBPL_ENABLE_TESTS=OFF \
-DLIBPL_ENABLE_CLI=OFF \
-G Ninja \
..
make -j4
ninja unit_tests
- name: 🧪 Perform Unit Tests
run: |
cd tests/build
ctest --output-on-failure
- name: ⚗️ Generate Coverage Report
run: |
cd tests/build
lcov -d ./_deps/pattern_language-build/lib --gcov-tool /usr/bin/gcov-12 -c -o coverage.info
- name: ⬆️ Upload Coverage Report
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: tests/build/coverage.info
cd build
ctest --output-on-failure -j 4
- name: 📎 Validate JSON Files
run: |
cd constants
for file in ./[!_schema.json]*; do jsonschema -i $file _schema.json; done
cd ..
cd tips
for file in ./[!_schema.json]*; do jsonschema -i $file _schema.json; done
cd ..

11
.gitignore vendored
View File

@@ -1,5 +1,12 @@
tests/cmake-build-debug/
tests/cmake*/
tests/build*/
build/
.vscode/
.devcontainer/
.cache/
.idea/
.DS_Store
.DS_Store
compile_commands.json

8
.gitmodules vendored
View File

@@ -1,4 +1,10 @@
[submodule "rules"]
path = yara/official_rules
url = https://github.com/Yara-Rules/rules
branch = master
branch = master
[submodule "patterns/ffx"]
path = patterns/ffx
url = https://gitlab.com/EvelynTSMG/imhex-ffx-pats.git
[submodule "patterns/bastion"]
path = patterns/bastion
url = https://gitlab.com/EvelynTSMG/imhex-bastion-pats.git

30
CMakeLists.txt Normal file
View File

@@ -0,0 +1,30 @@
cmake_minimum_required(VERSION 3.16)
project(ImHex-Patterns)
option(IMHEX_PATTERNS_ENABLE_UNIT_TESTS "Enable building unit tests for ImHex-Patterns" OFF)
# if enabled, add a unit_test custom target for all the unit tests to be registered against
if(IMHEX_PATTERNS_ENABLE_UNIT_TESTS)
if(NOT TARGET unit_tests)
enable_testing()
add_custom_target(unit_tests)
endif()
endif()
# If this has been manually cloned into another project, libpl may already have been set up
if(NOT TARGET libpl)
include(FetchContent)
FetchContent_Declare(
pattern_language
GIT_REPOSITORY https://github.com/WerWolv/PatternLanguage
GIT_TAG master
)
FetchContent_MakeAvailable(pattern_language)
endif()
if(IMHEX_PATTERNS_ENABLE_UNIT_TESTS)
add_subdirectory(tests)
endif()

View File

@@ -8,5 +8,5 @@ Thanks a lot for any additions or improvements :)
## Adding new Patterns
When adding new patterns, if possible, please also add a test file named `<pattern_name>.hexpat.<extension>` to the `/tests/patterns/test_data` directory. This allows our Unit Tests to be run against your code so we can make sure it stays up-to-date and doesn't break when changes are made to the PatternLanguage.
Please try to keep these files as small as possible (~100kiB at most) so cloning stays fast.
Please try to keep these files as small as possible (~100kiB at most) so cloning stays fast.
Please also make sure to not submit any test files that are under copyright such as game files, ROMs or files extracted from other programs. We don't want a DMCA takedown on this repo.

218
README.md
View File

@@ -1,6 +1,7 @@
# ImHex Database
This repository serves as a database for files to use with the [ImHex Hex Editor](https://github.com/WerWolv/ImHex). It currently contains
- [Patterns](/patterns) - Binary Format definitions for the Pattern Language
- [Pattern Libraries](/includes) - Libraries that make using the Pattern Language easier
- [Magic Files](/magic) - Custom magic file definitions for the use with libmagic
@@ -22,75 +23,149 @@ Everything will immediately show up in ImHex's Content Store and gets bundled wi
| Name | MIME | Path | Description |
|------|------|------|-------------|
| 3DS | | [`patterns/3ds.hexpat`](patterns/3ds.hexpat) | Autodesk 3DS Max Model file |
| 7Z | | [`patterns/7z.hexpat`](patterns/7z.hexpat) | 7z File Format |
| ADTS | | [`patterns/adts.hexpat`](patterns/adts.hexpat) | ADTS/AAC audio files |
| AFE2 | | [`patterns/afe2.hexpat`](patterns/afe2.hexpat) | Nintendo Switch Atmosphère CFW Fatal Error log |
| ANI | `application/x-navi-animation` | [`patterns/ani.hexpat`](patterns/ani.hexpat) | Windows Animated Cursor file |
| AR | `application/x-archive` | [`patterns/ar.hexpat`](patterns/ar.hexpat) | Static library archive files |
| ARC | | [`patterns/arc.hexpat`](patterns/arc.hexpat) | Minecraft Legacy Console Edition ARC files |
| ARIA2 | | [`patterns/aria2.hexpat`](patterns/aria2.hexpat) | ARIA2 Download Manager Control files |
| ARM VTOR | | [`patterns/arm_cm_vtor.hexpat`](patterns/arm_cm_vtor.hexpat) | ARM Cortex M Vector Table Layout |
| Bastion | | [`patterns/bastion/*`](https://gitlab.com/EvelynTSMG/imhex-bastion-pats) | Various [Bastion](https://en.wikipedia.org/wiki/Bastion_(video_game)) files |
| Bencode | `application/x-bittorrent` | [`patterns/bencode.hexpat`](patterns/bencode.hexpat) | Bencode encoding, used by Torrent files |
| Prusa BGCODE | | [`patterns/bgcode.hexpat`](patterns/bgcode.hexpat) | PrusaSlicer Binary G-Code files |
| BLEND | | [`patterns/blend.hexpat`](patterns/blend.hexpat) | Blender Project file |
| BMP | `image/bmp` | [`patterns/bmp.hexpat`](patterns/bmp.hexpat) | OS2/Windows Bitmap files |
| ELF | `application/x-executable` | [`patterns/elf.hexpat`](patterns/elf.hexpat) | ELF header in elf binaries |
| PE | `application/x-dosexec` | [`patterns/pe.hexpat`](patterns/pe.hexpat) | PE header, COFF header, Standard COFF fields and Windows Specific fields |
| NE | | [`patterns/ne.hexpat`](patterns/ne.hexpat) | NE header and Standard NE fields |
| Intel HEX | | [`patterns/intel_hex.hexpat`](patterns/intel_hex.hexpat) | [Intel hexadecimal object file format definition]("https://en.wikipedia.org/wiki/Intel_HEX") |
| MIDI | `audio/midi` | [`patterns/midi.hexpat`](patterns/midi.hexpat) | MIDI header, event fields provided |
| WAV | `audio/wav` | [`patterns/wav.hexpat`](patterns/wav.hexpat) | RIFF header, WAVE header, PCM header |
| ZIP | `application/zip` | [`patterns/zip.hexpat`](patterns/zip.hexpat) | End of Central Directory Header, Central Directory File Headers |
| PCAP | `application/vnd.tcpdump.pcap` | [`patterns/pcap.hexpat`](patterns/pcap.hexpat) | pcap header and packets |
| SPIRV | | [`patterns/spirv.hexpat`](patterns/spirv.hexpat) | SPIR-V header and instructions |
| AFE2 | | [`patterns/afe2.hexpat`](patterns/afe2.hexpat) | Nintendo Switch Atmosphère CFW Fatal Error log |
| AR | `application/x-archive` | [`patterns/ar.hexpat`](patterns/ar.hexpat) | Static library archive files |
| NACP | | [`patterns/nacp.hexpat`](patterns/nacp.hexpat) | Nintendo Switch NACP files |
| NRO | | [`patterns/nro.hexpat`](patterns/nro.hexpat) | Nintendo Switch NRO files |
| PRODINFO | | [`patterns/prodinfo.hexpat`](patterns/prodinfo.hexpat) | Nintendo Switch PRODINFO |
| Java Class | `application/x-java-applet` | [`patterns/java_class.hexpat`](patterns/java_class.hexpat) | Java Class files |
| ARM VTOR | | [`patterns/arm_cm_vtor.hexpat`](patterns/arm_cm_vtor.hexpat) | ARM Cortex M Vector Table Layout |
| ICO | | [`patterns/ico.hexpat`](patterns/ico.hexpat) | Icon (.ico) or Cursor (.cur) files |
| PNG | `image/png` | [`patterns/png.hexpat`](patterns/png.hexpat) | PNG image files |
| QOI | `image/qoi` | [`patterns/qoi.hexpat`](patterns/qoi.hexpat) | QOI image files |
| DDS | `image/vnd-ms.dds` | [`patterns/dds.hexpat`](patterns/dds.hexpat) | DirectDraw Surface |
| TGA | `image/tga` | [`patterns/tga.hexpat`](patterns/tga.hexpat) | Truevision TGA/TARGA image |
| ISO | | [`patterns/iso.hexpat`](patterns/iso.hexpat) | ISO 9660 file system |
| VDF | | [`patterns/vdf.hexpat`](patterns/vdf.hexpat) | Binary Value Data Format (.vdf) files |
| IP | | [`patterns/ip.hexpat`](patterns/ip.hexpat) | Ethernet II Frames (IP Packets) |
| UF2 | | [`patterns/uf2.hexpat`](patterns/uf2.hexpat) | [USB Flashing Format](https://github.com/microsoft/uf2) |
| File System | | [`patterns/fs.hexpat`](patterns/fs.hexpat) | Drive File System |
| Bencode | `application/x-bittorrent` | [`patterns/bencode.hexpat`](patterns/bencode.hexpat) | Bencode encoding, used by Torrent files |
| Protobuf | | [`patterns/protobuf.hexpat`](patterns/protobuf.hexpat) | Google Protobuf encoding |
| OGG | `audio/ogg` | [`patterns/ogg.hexpat`](patterns/ogg.hexpat) | OGG Audio format |
| STL | `model/stl` | [`patterns/stl.hexpat`](patterns/stl.hexpat) | STL 3D Model format |
| VHDX | | [`patterns/vhdx.hexpat`](patterns/vhdx.hexpat) | Microsoft Hyper-V Virtual Hard Disk format |
| NTAG | | [`patterns/ntag.hexpat`](patterns/ntag.hexpat) | NTAG213/NTAG215/NTAG216, NFC Forum Type 2 Tag compliant IC |
| Shell Link | `application/x-ms-shortcut` | [`patterns/lnk.hexpat`](patterns/lnk.hexpat) | Windows Shell Link file format |
| Xilinx BIT | | [`patterns/xilinx_bit.hexpat`](patterns/xilinx_bit.hexpat) | Xilinx FPGA Bitstreams |
| FLAC | `audio/flac` | [`patterns/flac.hexpat`](patterns/flac.hexpat) | Free Lossless Audio Codec, FLAC Audio Format |
| BSON | `application/bson` | [`patterns/bson.hexpat`](patterns/bson.hexpat) | BSON (Binary JSON) format |
| msgpack | `application/x-msgpack` | [`patterns/msgpack.hexpat`](patterns/msgpack.hexpat) | MessagePack binary serialization format |
| MiniDump | `application/x-dmp` | [`patterns/minidump.hexpat`](patterns/minidump.hexpat) | Windows MiniDump files |
| ID3 | `audio/mpeg` | [`patterns/id3.hexpat`](patterns/id3.hexpat) | ID3 tags in MP3 files |
| TAR | `application/x-tar` | [`patterns/tar.hexpat`](patterns/tar.hexpat) | Tar file format |
| CPIO | `application/x-cpio` | [`patterns/cpio.hexpat`](patterns/cpio.hexpat) | Old Binary CPIO Format |
| FDT | | [`patterns/fdt.hexpat`](patterns/fdt.hexpat) | Flat Linux Device Tree blob |
| StuffItV5 | `application/x-stuffit` | [`patterns/sit5.hexpat`](patterns/sit5.hexpat) | StuffIt V5 archive |
| NBT | | [`patterns/nbt.hexpat`](patterns/nbt.hexpat) | Minecraft NBT format |
| PCX | `application/x-pcx` | [`patterns/pcx.hexpat`](patterns/pcx.hexpat) | PCX Image format |
| GZIP | `application/gzip` | [`patterns/gzip.hexpat`](patterns/gzip.hexpat) | GZip compressed data format |
| PFS0 | | [`patterns/pfs0.hexpat`](patterns/pfs0.hexpat) | Nintendo Switch PFS0 archive (NSP files) |
| XCI | | [`patterns/xci.hexpat`](patterns/xci.hexpat) | Nintendo Switch XCI cardridge ROM |
| WAD | | [`patterns/wad.hexpat`](patterns/wad.hexpat) | DOOM WAD Archive |
| GIF | `image/gif` | [`patterns/gif.hexpat`](patterns/gif.hexpat) | GIF image files |
| ZSTD | `application/zstd` | [`patterns/zstd.hexpat`](patterns/zstd.hexpat) | Zstandard compressed data format |
| COFF | `application/x-coff` | [`patterns/coff.hexpat`](patterns/coff.hexpat) | Common Object File Format (COFF) executable |
| Mach-O | `application/x-mach-binary` | [`patterns/macho.hexpat`](patterns/macho.hexpat) | Mach-O executable |
| CHM | | [`patterns/chm.hexpat`](patterns/chm.hexpat) | Windows HtmlHelp Data (ITSF / CHM) |
| DMG | | [`patterns/dmg.hexpat`](patterns/dmg.hexpat) | Apple Disk Image Trailer (DMG) |
| XBEH | `audio/x-xbox-executable` | [`patterns/xbeh.hexpat`](patterns/xbeh.hexpat) | Xbox executable |
| QBCL | | [`patterns/qbcl.hexpat`](patterns/qbcl.hexpat) | Qubicle voxel scene project file |
| BIN | | [`patterns/selinux.hexpat`](patterns/selinux.pat) | SE Linux modules |
| BINKA | | [`patterns/binka.hexpat`](patterns/binka.pat) | RAD Game Tools Bink Audio (BINKA) files |
| BSON | `application/bson` | [`patterns/bson.hexpat`](patterns/bson.hexpat) | BSON (Binary JSON) format |
| bplist | | [`patterns/bplist.hexpat`](patterns/bplist.hexpat) | Apple's binary property list format (bplist) |
| BSP | | [`patterns/bsp_goldsrc.hexpat`](patterns/bsp_goldsrc.hexpat) | GoldSrc engine maps format (used in Half-Life 1) |
| BZIP3 | | [`patterns/bzip3.hexpat`](patterns/bzip3.hexpat) | GoldSrc engine maps format (used in Half-Life 1) |
| CCHVA | | [`patterns/cchva.hexpat`](patterns/cchva.hexpat) | Command and Conquer Voxel Animation |
| CCVXL | | [`patterns/ccvxl.hexpat`](patterns/ccvxl.hexpat) | Command and Conquer Voxel Model |
| CCPAL | | [`patterns/ccpal.hexpat`](patterns/ccpal.hexpat) | Command and Conquer Voxel Palette |
| PIF | `image/pif` | [`patterns/pif.hexpat`](patterns/pif.hexpat) | PIF Image Format |
| JPEG | `image/jpeg` | [`patterns/jpeg.hexpat`](patterns/jpeg.hexpat) | JPEG Image Format |
| Lua 5.4 | | [`patterns/lua54.hexpat`](patterns/lua54.hexpat) | Lua 5.4 bytecode |
| CDA | | [`patterns/cda.hexpat`](patterns/cda.hexpat) | Compact Disc Audio track |
| CHM | | [`patterns/chm.hexpat`](patterns/chm.hexpat) | Windows HtmlHelp Data (ITSF / CHM) |
| COFF | `application/x-coff` | [`patterns/coff.hexpat`](patterns/coff.hexpat) | Common Object File Format (COFF) executable |
| CPIO | `application/x-cpio` | [`patterns/cpio.hexpat`](patterns/cpio.hexpat) | Old Binary CPIO Format |
| CrashLvl | | [`patterns/Crashlvl.hexpat`](patterns/Crashlvl.hexpat) | Crash Bandicoot - Back in Time (fan game) User created level format |
| CREDHIST | | [`patterns/credhist.hexpat`](patterns/credhist.hexpat) | CREDHIST Format |
| DDS | `image/vnd-ms.dds` | [`patterns/dds.hexpat`](patterns/dds.hexpat) | DirectDraw Surface |
| DEX | | [`patterns/dex.hexpat`](patterns/dex.hexpat) | Dalvik EXecutable Format |
| DS_Store | `application/octet-stream` | [`patterns/dsstore.hexpat`](patterns/dsstore.hexpat) | .DS_Store file format |
| UEFI | | [`patterns/uefi.hexpat`](patterns/uefi.hexpat)` | UEFI structs for parsing efivars |
| DICOM | `application/dicom` | [`patterns/dicom.hexpat`](patterns/dicom.hexpat) | DICOM image format |
| DMG | | [`patterns/dmg.hexpat`](patterns/dmg.hexpat) | Apple Disk Image Trailer (DMG) |
| DMP | | [`patterns/dmp64.hexpat`](patterns/dmp64.hexpat) | Windows Kernel Dump(DMP64) |
| DPAPI_Blob | | [`patterns/dpapblob.hexpat`](patterns/dpapiblob.hexpat) | Data protection API Blob File Format |
| DPAPI_MasterKey | | [`patterns/dpapimasterkey.hexpat`](patterns/dpapimasterkey.hexpat) | Data protection API MasterKey |
| DS_Store | | [`patterns/dsstore.hexpat`](patterns/dsstore.hexpat) | .DS_Store file format |
| DTA | | [`patterns/max_v104.hexpat`](patterns/max_v104.hexpat) | Mechanized Assault and Exploration v1.04 (strategy game) save file format |
| DTED | | [`patterns/dted.hexpat`](patterns/dted.hexpat) | Digital Terrain Elevation Data (DTED) |
| ELF | `application/x-executable` | [`patterns/elf.hexpat`](patterns/elf.hexpat) | ELF header in elf binaries |
| EVTX | | [`patterns/evtx.hexpat`](patterns/evtx.hexpat) | MS Windows Vista Event Log |
| BSP | | [`patterns/bsp_goldsrc.hexpat`](patterns/bsp_goldsrc.hexpat) | GoldSrc engine maps format (used in Half-Life 1) |
| EXT4 | | [`patterns/ext4.hexpat`](patterns/ext4.hexpat) | Ext4 filesystem |
| FAS | | [`patterns/fas_oskasoftware.hexpat`](patterns/fas_oskasoftware.hexpat) [`patterns/fas_oskasoftware_old.hexpat`](patterns/fas_oskasoftware_old.hexpat) (Old versions of Oska DeskMate) | Oska Software DeskMates FAS (Frames and Sequences) file |
| FBX | | [`patterns/fbx.hexpat`](patterns/fbx.hexpat) | Kaydara FBX Binary |
| FDT | | [`patterns/fdt.hexpat`](patterns/fdt.hexpat) | Flat Linux Device Tree blob |
| FFX | | [`patterns/ffx/*`](https://gitlab.com/EvelynTSMG/imhex-ffx-pats) | Various Final Fantasy X files |
| File System | | [`patterns/fs.hexpat`](patterns/fs.hexpat) | Drive File System |
| FLAC | `audio/flac` | [`patterns/flac.hexpat`](patterns/flac.hexpat) | Free Lossless Audio Codec, FLAC Audio Format |
| Flipper Zero Settings | | [`patterns/flipper_settings.hexpat`](patterns/flipper_settings.hexpat) | Flipper Zero Settings Files |
| GB | `application/x-gameboy-rom` | [`patterns/gb.hexpat`](patterns/gb.hexpat) | Game Boy ROM |
| GBA | `application/x-gameboy-advance-rom` | [`patterns/gba.hexpat`](patterns/gba.hexpat) | Game Boy Advance ROM header |
| GGUF | | [`patterns/gguf.hexpat`](patterns/gguf.hexpat) | GGML Inference Models |
| GIF | `image/gif` | [`patterns/gif.hexpat`](patterns/gif.hexpat) | GIF image files |
| GLTF | `model/gltf-binary` | [`patterns/gltf.hexpat`](patterns/gltf.hexpat) | GL Transmission Format binary 3D model file |
| GZIP | `application/gzip` | [`patterns/gzip.hexpat`](patterns/gzip.hexpat) | GZip compressed data format |
| Halo Tag || [`patterns/hinf_tag.hexpat`](patterns/hinf_tag.hexpat) | Halo Infinite Tag Files |
| Halo Module || [`patterns/hinf_module.hexpat`](patterns/hinf_module.hexpat) | Halo Infinite Module Archive Files |
| Halo HavokScript || [`patterns/hinf_luas.hexpat`](patterns/hinf_luas.hexpat) | Halo Infinite HavokScript 5.1 Bytecode |
| HSDT || [`patterns/hsdt.hexpat`](patterns/hsdt.hexpat) | HiSilicon device-tree table images |
| ICO | | [`patterns/ico.hexpat`](patterns/ico.hexpat) | Icon (.ico) or Cursor (.cur) files |
| ID3 | `audio/mpeg` | [`patterns/id3.hexpat`](patterns/id3.hexpat) | ID3 tags in MP3 files |
| Intel HEX | | [`patterns/intel_hex.hexpat`](patterns/intel_hex.hexpat) | [Intel hexadecimal object file format definition]("https://en.wikipedia.org/wiki/Intel_HEX") |
| IP | | [`patterns/ip.hexpat`](patterns/ip.hexpat) | Ethernet II Frames (IP Packets) |
| IPS | | [`patterns/ips.hexpat`](patterns/ips.hexpat) | IPS (International Patching System) files |
| ISO | | [`patterns/iso.hexpat`](patterns/iso.hexpat) | ISO 9660 file system |
| Java Class | `application/x-java-applet` | [`patterns/java_class.hexpat`](patterns/java_class.hexpat) | Java Class files |
| JPEG | `image/jpeg` | [`patterns/jpeg.hexpat`](patterns/jpeg.hexpat) | JPEG Image Format |
| LOC | | [`patterns/loc.hexpat`](patterns/loc.hexpat) | Minecraft Legacy Console Edition Language file |
| Lua 5.1 | | [`patterns/lua51.hexpat`](patterns/lua51.hexpat) | Lua 5.1 bytecode |
| Lua 5.2 | | [`patterns/lua52.hexpat`](patterns/lua52.hexpat) | Lua 5.2 bytecode |
| Lua 5.3 | | [`patterns/lua53.hexpat`](patterns/lua53.hexpat) | Lua 5.3 bytecode |
| Lua 5.4 | | [`patterns/lua54.hexpat`](patterns/lua54.hexpat) | Lua 5.4 bytecode |
| LCE Savefile | | [`patterns/lcesave.hexpat`](patterns/lcesave.hexpat) | Minecraft Legacy Console Edition save file |
| LZNT1 | | [`patterns/lznt1.hexpat`](patterns/lznt1.hexpat) | LZNT1 compressed data format |
| Mach-O | `application/x-mach-binary` | [`patterns/macho.hexpat`](patterns/macho.hexpat) | Mach-O executable |
| MIDI | `audio/midi` | [`patterns/midi.hexpat`](patterns/midi.hexpat) | MIDI header, event fields provided |
| MiniDump | `application/x-dmp` | [`patterns/minidump.hexpat`](patterns/minidump.hexpat) | Windows MiniDump files |
| mp4 | `video/mp4` | [`patterns/mp4.hexpat`](patterns/mp4.hexpat) | MPEG-4 Part 14 digital multimedia container format |
| msgpack | `application/x-msgpack` | [`patterns/msgpack.hexpat`](patterns/msgpack.hexpat) | MessagePack binary serialization format |
| MSSCMP | | [`patterns/msscmp.hexpat`](patterns/msscmp.hexpat) | Miles Sound System Compressed Archive |
| NACP | | [`patterns/nacp.hexpat`](patterns/nacp.hexpat) | Nintendo Switch NACP files |
| NBT | | [`patterns/nbt.hexpat`](patterns/nbt.hexpat) | Minecraft NBT format |
| NE | | [`patterns/ne.hexpat`](patterns/ne.hexpat) | NE header and Standard NE fields |
| nes | | [`patterns/nes.hexpat`](patterns/nes.hexpat) | .nes file format |
| NotepadCache | | [`patterns/notepad-cache.hexpat`](patterns/notepad-cache.hexpat) | Windows Notepad Cache |
| NotepadWindowState | | [`patterns/notepadwindowstate.hexpat`](patterns/notepadwindowstate.hexpat) | Windows 11 Notepad - Window State .bin file |
| NRO | | [`patterns/nro.hexpat`](patterns/nro.hexpat) | Nintendo Switch NRO files |
| NTAG | | [`patterns/ntag.hexpat`](patterns/ntag.hexpat) | NTAG213/NTAG215/NTAG216, NFC Forum Type 2 Tag compliant IC |
| OGG | `audio/ogg` | [`patterns/ogg.hexpat`](patterns/ogg.hexpat) | OGG Audio format |
| PAK | | [`patterns/xgspak.hexpat`](patterns/xgspak.hexpat) | Exient XGS Engine Pak files |
| PCAP | `application/vnd.tcpdump.pcap` | [`patterns/pcap.hexpat`](patterns/pcap.hexpat) | pcap header and packets |
| PCK | | [`patterns/pck.hexpat`](patterns/pck.hexpat) | Minecraft Legacy Console Edition .pck file |
| PCX | `application/x-pcx` | [`patterns/pcx.hexpat`](patterns/pcx.hexpat) | PCX Image format |
| PE | `application/x-dosexec` `application/x-msdownload` | [`patterns/pe.hexpat`](patterns/pe.hexpat) | PE header, COFF header, Standard COFF fields and Windows Specific fields |
| PP | | [`patterns/selinuxpp.hexpat`](patterns/selinuxpp.pat) | SE Linux package |
| PFS0 | | [`patterns/pfs0.hexpat`](patterns/pfs0.hexpat) | Nintendo Switch PFS0 archive (NSP files) |
| PIF | `image/pif` | [`patterns/pif.hexpat`](patterns/pif.hexpat) | PIF Image Format |
| PKM | | [`patterns/pkm.hexpat`](patterns/pkm.hexpat) | PKM texture format |
| PNG | `image/png` | [`patterns/png.hexpat`](patterns/png.hexpat) | PNG image files |
| PRODINFO | | [`patterns/prodinfo.hexpat`](patterns/prodinfo.hexpat) | Nintendo Switch PRODINFO |
| Protobuf | | [`patterns/protobuf.hexpat`](patterns/protobuf.hexpat) | Google Protobuf encoding |
| psafe3 | | [`patterns/psafe3.hexpat`](patterns/psafe3.hexpat`) | Password Safe V3 |
| PyInstaller | | [`patterns/pyinstaller.hexpat`](patterns/pyinstaller.hexpat) | PyInstaller binray files |
| PYC | | [`patterns/pyc.hexpat`](patterns/pyc.hexpat) | Python bytecode files |
| QBCL | | [`patterns/qbcl.hexpat`](patterns/qbcl.hexpat) | Qubicle voxel scene project file |
| QOI | `image/qoi` | [`patterns/qoi.hexpat`](patterns/qoi.hexpat) | QOI image files |
| quantized-mesh | | [`patterns/quantized-mesh.hexpat`](patterns/quantized-mesh.hexpat) | Cesium quantized-mesh terrain |
| RAR | `application/x-rar` | [`patterns/rar.hexpat`](patterns/rar.hexpat) | RAR archive file format |
| RAS | `image/x-sun-raster` | [`patterns/ras.hexpat`](patterns/ras.hexpat) | RAS image files |
| ReFS | | [`patterns/refs.hexpat`](patterns/refs.hexpat) | Microsoft Resilient File System |
| RGBDS | | [`patterns/rgbds.hexpat`](patterns/rgbds.hexpat) | [RGBDS](https://rgbds.gbdev.io) object file format |
| Shell Link | `application/x-ms-shortcut` | [`patterns/lnk.hexpat`](patterns/lnk.hexpat) | Windows Shell Link file format |
| shp | | [`patterns/shp.hexpat`](patterns/shp.hexpat) | ESRI shape file |
| shx | | [`patterns/shx.hexpat`](patterns/shx.hexpat) | ESRI index file |
| SPIRV | | [`patterns/spirv.hexpat`](patterns/spirv.hexpat) | SPIR-V header and instructions |
| STL | `model/stl` | [`patterns/stl.hexpat`](patterns/stl.hexpat) | STL 3D Model format |
| StuffItV5 | `application/x-stuffit` | [`patterns/sit5.hexpat`](patterns/sit5.hexpat) | StuffIt V5 archive |
| SWF | |[`patterns/swf.hexpat`](patterns/swf.hexpat) | Shockwave Flash file format |
| TAR | `application/x-tar` | [`patterns/tar.hexpat`](patterns/tar.hexpat) | Tar file format |
| TES | | [`patterns/wintec_tes.hexpat`](patterns/wintec_tes.hexpat) | Wintec TES GPS log |
| TIFF | `image/tiff` | [`patterns/tiff.hexpat`](patterns/tiff.hexpat) | Tag Image File Format |
| TGA | `image/tga` | [`patterns/tga.hexpat`](patterns/tga.hexpat) | Truevision TGA/TARGA image |
| TTF | `font/ttf`, `font/otf` | [`patterns/ttf.hexpat`](patterns/ttf.hexpat) | TrueType and OpenType font format |
| Ubiquiti | | [`patterns/ubiquiti.hexpat`](patterns/ubiquiti.hexpat) | Ubiquiti Firmware (update) image |
| UEFI | | [`patterns/uefi.hexpat`](patterns/uefi.hexpat)` | UEFI structs for parsing efivars |
| UEFI Boot Entry | | [`patterns/uefi_boot_entry.hexpat`](patterns/uefi_boot_entry.hexpat) | UEFI Boot Entry (Load option) |
| UF2 | | [`patterns/uf2.hexpat`](patterns/uf2.hexpat) | [USB Flashing Format](https://github.com/microsoft/uf2) |
| VBMeta | | [`patterns/vbmeta.hexpat`](patterns/vbmeta.hexpat) | Android VBMeta image |
| VDF | | [`patterns/vdf.hexpat`](patterns/vdf.hexpat) | Binary Value Data Format (.vdf) files |
| VGM | | [`patterns/vgm.hexpat`](patterns/vgm.hexpat) | VGM (Video Game Music) sound log |
| VHDX | | [`patterns/vhdx.hexpat`](patterns/vhdx.hexpat) | Microsoft Hyper-V Virtual Hard Disk format |
| WAV | `audio/x-wav` | [`patterns/wav.hexpat`](patterns/wav.hexpat) | RIFF header, WAVE header, PCM header |
| WAS | | [`patterns\was_oskasoftware.hexpat`](patterns\was_oskasoftware.hexpat) | Oska Software DeskMates WAS/WA3 (WAVE/MP3 Set) file
| WAD | | [`patterns/wad.hexpat`](patterns/wad.hexpat) | DOOM WAD Archive |
| WebP | `image/webp` | [`patterns/webp.hexpat`](patterns/webp.hexpat) | Google WebP image |
| XBEH | `audio/x-xbox-executable` | [`patterns/xbeh.hexpat`](patterns/xbeh.hexpat) | Xbox executable |
| XCI | | [`patterns/xci.hexpat`](patterns/xci.hexpat) | Nintendo Switch XCI cartridge ROM |
| XGT | | [`patterns/xgt.hexpat`](patterns/xgstexture.hexpat) | Exient XGS Engine Texture |
| Xilinx BIT | | [`patterns/xilinx_bit.hexpat`](patterns/xilinx_bit.hexpat) | Xilinx FPGA Bitstreams |
| Xilinx Bootgen | | [`patterns/xilinx_bootgen.hexpat`](patterns/xilinx_bootgen.hexpat) | Xilinx ZynqMP Boot Images |
| ZIP | `application/zip` | [`patterns/zip.hexpat`](patterns/zip.hexpat) | End of Central Directory Header, Central Directory File Headers |
| ZLIB | `application/zlib` | [`patterns/zlib.hexpat`](patterns/zlib.hexpat) | ZLIB compressed data format |
| ZSTD | `application/zstd` | [`patterns/zstd.hexpat`](patterns/zstd.hexpat) | Zstandard compressed data format |
### Scripts
@@ -103,9 +178,9 @@ Everything will immediately show up in ImHex's Content Store and gets bundled wi
| Name | Path | Description |
|------|------|-------------|
| libstd | [`includes/std/*`](includes/std) | Pattern Language Standard Libaray |
| libtype | [`includes/type/*`](includes/type) | Various custom types with special formatters |
| libhex | [`includes/hex/*`](includes/hex) | Functions to interact with ImHex |
| libstd | [`includes/std/*`](includes/std) | Pattern Language Standard Library |
| libtype | [`includes/type/*`](includes/type) | Various custom types with special formatters |
### Yara rules
@@ -140,6 +215,7 @@ Everything will immediately show up in ImHex's Content Store and gets bundled wi
| ASCII+OEM | [`encodings/ascii_oem.tbl`](encodings/ascii_oem.tbl) | ASCII encoding with Windows OEM characters |
| Baltic ISO | [`encodings/baltic_iso.tbl`](encodings/baltic_iso.tbl) | Baltic ISO encoding |
| Baltic Windows | [`encodings/baltic_windows.tbl`](encodings/baltic_windows.tbl) | Baltic Windows encoding |
| Big5 (Traditional Chinese) | [`encodings/big5.tbl`](encodings/big5.tbl) | Big5 encoding for Traditional Chinese |
| Cyrillic ISO | [`encodings/cyrillic_iso.tbl`](encodings/cyrillic_iso.tbl) | Cyrillic ISO encoding |
| Cyrillic Windows | [`encodings/cyrillic_windows.tbl`](encodings/cyrillic_windows.tbl) | Cyrillic Windows encoding |
| Cyrillic KOI8-R | [`encodings/cyrillic_koi8_r.tbl`](encodings/cyrillic_koi8_r.tbl) | Cyrillic KOI8-R encoding (Russian Characters) |
@@ -169,13 +245,25 @@ Everything will immediately show up in ImHex's Content Store and gets bundled wi
| Vietnamese | [`encodings/vietnamese.tbl`](encodings/vietnamese.tbl) | Vietnamese character encoding |
### Data Processor Nodes
| Name | Path | Description |
|------|------|-------------|
| Caesar Cipher | [`nodes/caesar.hexnode`](nodes/caesar.hexnode) | Simple adjustable per-byte Caecar Cipher (ROT) |
| XOR Cipher | [`nodes/xor.hexnode`](nodes/xor.hexnode) | XORs a input with a repeating XOR pad |
### Themes
| Name | Path | Description |
|------|------|-------------|
| Visual Studio Dark | [`themes/vs_dark.json`](themes/vs_dark.json) | Theme similar to Visual Studio's Dark theme |
| Solarized Dark | [`themes/solarized_dark.json`](themes/solarized_dark.json) | Solarized Dark Theme |
| Catppuccin Latte | [`themes/catppuccin-latte.json`](themes/catppuccin-latte.json) | Catppuccin Latte Flavor (Light Theme) |
| Catppuccin Frappe | [`themes/catppuccin-frappe.json`](themes/catppuccin-frappe.json) | Catppuccin Frappe Flavor (Dark Theme) |
| Catppuccin Macchiato | [`themes/catppuccin-macchiato.json`](themes/catppuccin-macchiato.json) | Catppuccin Macchiato Flavor (Dark Theme) |
| Catppuccin Mocha | [`themes/catppuccin-mocha.json`](themes/catppuccin-mocha.json) | Catppuccin Mocha Flavor (Dark Theme) |
### Disassemblers
| Name | Path | Description |
|------|------|-------------|
| 8051 | [`disassemblers/8051.json`](disassemblers/8051.json) | Intel 8051 Architecture |

View File

@@ -775,6 +775,6 @@
"name": "ENOTRECOVERABLE",
"desc": "State not recoverable"
}
]
}

730
disassemblers/8051.json Normal file
View File

@@ -0,0 +1,730 @@
{
"name": "Intel 8051",
"includes": [],
"options": [],
"opcodes": [
{
"mask": "0000'0000",
"mnemonic": "NOP",
"format": ""
},
{
"mask": "0000'0010 AAAA'AAAA AAAA'AAAA",
"mnemonic": "LJMP",
"format": "#0x{A:04X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "A"
}
}
]
},
{
"mask": "1000'0000 AAAA'AAAA",
"mnemonic": "SJMP",
"format": "#0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "A"
}
}
]
},
{
"mask": "0111'0011",
"mnemonic": "JMP",
"format": "@A+DPTR"
},
{
"mask": "0100'0000 AAAA'AAAA",
"mnemonic": "JC",
"format": "PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 2 + A"
}
}
]
},
{
"mask": "0011'0000 BBBB'BBBB AAAA'AAAA",
"mnemonic": "JNB",
"format": "BIT[0x{B:02X}], PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "0001'0000 BBBB'BBBB AAAA'AAAA",
"mnemonic": "JBC",
"format": "BIT[0x{B:02X}], PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "0010'0000 AAAA'AAAA RRRR'RRRR",
"mnemonic": "JB",
"format": "BIT[0x{A:02X}], PC + 0x{R:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "0001'0010 AAAA'AAAA AAAA'AAAA",
"mnemonic": "LCALL",
"format": "#0x{A:04X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "A"
}
}
]
},
{
"mask": "PPP1'0001 AAAA'AAAA",
"mnemonic": "ACALL",
"format": "page{P} #0x{A:04X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "P * 256 + A"
}
}
]
},
{
"mask": "PPP0'0001 AAAA'AAAA",
"mnemonic": "AJMP",
"format": "page{P} #0x{A:04X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "P * 256 + A"
}
}
]
},
{
"mask": "0000'0011",
"mnemonic": "RR",
"format": "A"
},
{
"mask": "0001'0011",
"mnemonic": "RRC",
"format": "A"
},
{
"mask": "0010'0011",
"mnemonic": "RL",
"format": "A"
},
{
"mask": "0011'0011",
"mnemonic": "RLC",
"format": "A"
},
{
"mask": "0000'0100",
"mnemonic": "INC",
"format": "A"
},
{
"mask": "0000'0101 AAAA'AAAA",
"mnemonic": "INC",
"format": "IRAM[0x{A:02X}]"
},
{
"mask": "0000'011R",
"mnemonic": "INC",
"format": "@R{R}"
},
{
"mask": "0000'1RRR",
"mnemonic": "INC",
"format": "R{R}"
},
{
"mask": "1010'0011",
"mnemonic": "INC",
"format": "DPTR"
},
{
"mask": "0001'0100",
"mnemonic": "DEC",
"format": "A"
},
{
"mask": "0001'0101 AAAA'AAAA",
"mnemonic": "DEC",
"format": "IRAM[0x{A:02X}]"
},
{
"mask": "0001'0110",
"mnemonic": "DEC",
"format": "@R0"
},
{
"mask": "0001'0111",
"mnemonic": "DEC",
"format": "@R1"
},
{
"mask": "0001'1RRR",
"mnemonic": "DEC",
"format": "R{R}"
},
{
"mask": "1110'0100",
"mnemonic": "CLR",
"format": "A"
},
{
"mask": "1100'0010 AAAA'AAAA",
"mnemonic": "CLR",
"format": "BIT[0x{A:02X}]"
},
{
"mask": "1100'0011",
"mnemonic": "CLR",
"format": "C"
},
{
"mask": "1111'0000",
"mnemonic": "MOVX",
"format": "@DPTR, A"
},
{
"mask": "1110'0000",
"mnemonic": "MOVX",
"format": "A, @DPTR"
},
{
"mask": "1111'001R",
"mnemonic": "MOVX",
"format": "@R{R}, A"
},
{
"mask": "1110'001R",
"mnemonic": "MOVX",
"format": "A, @R{R}"
},
{
"mask": "0111'011R AAAA'AAAA",
"mnemonic": "MOV",
"format": "@R{R}, #0x{A:02X}"
},
{
"mask": "0111'1RRR AAAA'AAAA",
"mnemonic": "MOV",
"format": "R{R}, #0x{A:02X}"
},
{
"mask": "1111'1RRR",
"mnemonic": "MOV",
"format": "R{R}, A"
},
{
"mask": "1110'011R",
"mnemonic": "MOV",
"format": "A, @R{R}"
},
{
"mask": "1111'011R",
"mnemonic": "MOV",
"format": "@R{R}, A"
},
{
"mask": "1110'1RRR",
"mnemonic": "MOV",
"format": "A, R{R}"
},
{
"mask": "1001'0010 AAAA'AAAA",
"mnemonic": "MOV",
"format": "BIT[0x{A:02X}], C"
},
{
"mask": "1010'0010 AAAA'AAAA",
"mnemonic": "MOV",
"format": "C, BIT[0x{A:02X}]"
},
{
"mask": "1001'0000 DDDD'DDDD DDDD'DDDD",
"mnemonic": "MOV",
"format": "DPTR, #0x{D:04X}"
},
{
"mask": "1110'0101 AAAA'AAAA",
"mnemonic": "MOV",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "1111'0101 AAAA'AAAA",
"mnemonic": "MOV",
"format": "IRAM[#0x{A:02X}], A"
},
{
"mask": "0111'0101 AAAA'AAAA DDDD'DDDD",
"mnemonic": "MOV",
"format": "IRAM[0x{A:02X}], #0x{D:02X}"
},
{
"mask": "1000'0101 AAAA'AAAA BBBB'BBBB",
"mnemonic": "MOV",
"format": "IRAM[0x{A:02X}], IRAM[0x{B:02X}]"
},
{
"mask": "0111'0100 DDDD'DDDD",
"mnemonic": "MOV",
"format": "A, #0x{D:02X}"
},
{
"mask": "1000'011R AAAA'AAAA",
"mnemonic": "MOV",
"format": "IRAM[0x{A:02X}], @R{R}"
},
{
"mask": "1000'1RRR AAAA'AAAA",
"mnemonic": "MOV",
"format": "IRAM[0x{A:02X}], R{R}"
},
{
"mask": "1010'011R AAAA'AAAA",
"mnemonic": "MOV",
"format": "@R{R}, IRAM[0x{A:02X}]"
},
{
"mask": "1010'1RRR AAAA'AAAA",
"mnemonic": "MOV",
"format": "R{R}, IRAM[0x{A:02X}]"
},
{
"mask": "0110'0000 AAAA'AAAA",
"mnemonic": "JZ",
"format": "PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 2 + A"
}
}
]
},
{
"mask": "0111'0000 AAAA'AAAA",
"mnemonic": "JNZ",
"format": "PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 2 + A"
}
}
]
},
{
"mask": "1001'0011",
"mnemonic": "MOVC",
"format": "A, @A+DPTR"
},
{
"mask": "1000'0011",
"mnemonic": "MOVC",
"format": "A, @A+PC"
},
{
"mask": "1101'011R",
"mnemonic": "XCHD",
"format": "A, @R{R}"
},
{
"mask": "1100'011R",
"mnemonic": "XCH",
"format": "A, @R{R}"
},
{
"mask": "1100'1RRR",
"mnemonic": "XCH",
"format": "A, R{R}"
},
{
"mask": "1100'0101 AAAA'AAAA",
"mnemonic": "XCH",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "0010'0010",
"mnemonic": "RET",
"format": ""
},
{
"mask": "0011'0010",
"mnemonic": "RETI",
"format": ""
},
{
"mask": "1101'0010 AAAA'AAAA",
"mnemonic": "SETB",
"format": "BIT[0x{A:02X}]"
},
{
"mask": "1101'0011",
"mnemonic": "SETB",
"format": "C"
},
{
"mask": "0101'0010 AAAA'AAAA",
"mnemonic": "ANL",
"format": "IRAM[0x{A:02X}], A"
},
{
"mask": "0101'0101 AAAA'AAAA",
"mnemonic": "ANL",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "0101'0011 AAAA'AAAA DDDD'DDDD",
"mnemonic": "ANL",
"format": "A, IRAM[0x{A:02X}], #0x{D:02X}"
},
{
"mask": "0101'0100 AAAA'AAAA",
"mnemonic": "ANL",
"format": "A, #0x{A:02X}"
},
{
"mask": "0101'011R",
"mnemonic": "ANL",
"format": "A, @R{R}"
},
{
"mask": "0101'1RRR",
"mnemonic": "ANL",
"format": "A, R{R}"
},
{
"mask": "1000'0010 AAAA'AAAA",
"mnemonic": "ANL",
"format": "C, BIT[0x{A:02X}]"
},
{
"mask": "1011'0000 AAAA'AAAA",
"mnemonic": "ANL",
"format": "C, /BIT[0x{A:02X}]"
},
{
"mask": "0100'0010 AAAA'AAAA",
"mnemonic": "ORL",
"format": "IRAM[0x{A:02X}], A"
},
{
"mask": "0100'0011 AAAA'AAAA DDDD'DDDD",
"mnemonic": "ORL",
"format": "IRAM[0x{A:02X}], #0x{D:02X}"
},
{
"mask": "0100'0100 DDDD'DDDD",
"mnemonic": "ORL",
"format": "A, #0x{D:02X}"
},
{
"mask": "0100'011R",
"mnemonic": "ORL",
"format": "A, @R{R}"
},
{
"mask": "0100'1RRR",
"mnemonic": "ORL",
"format": "A, R{R}"
},
{
"mask": "0100'0101 AAAA'AAAA",
"mnemonic": "ORL",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "0111'0010 AAAA'AAAA",
"mnemonic": "ORL",
"format": "C, BIT[0x{A:02X}]"
},
{
"mask": "1010'0000 AAAA'AAAA",
"mnemonic": "ORL",
"format": "C, /BIT[0x{A:02X}]"
},
{
"mask": "0110'0010 AAAA'AAAA",
"mnemonic": "XRL",
"format": "IRAM[0x{A:02X}], A"
},
{
"mask": "0110'0011 AAAA'AAAA DDDD'DDDD",
"mnemonic": "XRL",
"format": "IRAM[0x{A:02X}], #0x{D:02X}"
},
{
"mask": "0110'0100 DDDD'DDDD",
"mnemonic": "XRL",
"format": "A, #0x{D:02X}"
},
{
"mask": "0110'011R",
"mnemonic": "XRL",
"format": "A, @R{R}"
},
{
"mask": "0110'1RRR",
"mnemonic": "XRL",
"format": "A, R{R}"
},
{
"mask": "0110'0101 AAAA'AAAA",
"mnemonic": "XRL",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "0010'0100 DDDD'DDDD",
"mnemonic": "ADD",
"format": "A, #0x{D:02X}"
},
{
"mask": "0010'011R",
"mnemonic": "ADD",
"format": "A, @R{R}"
},
{
"mask": "0010'0101 AAAA'AAAA",
"mnemonic": "ADD",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "0011'0100 DDDD'DDDD",
"mnemonic": "ADDC",
"format": "A, #0x{D:02X}"
},
{
"mask": "0011'011R",
"mnemonic": "ADDC",
"format": "A, @R{R}"
},
{
"mask": "0011'0101 AAAA'AAAA",
"mnemonic": "ADDC",
"format": "A, IRAM[0x{A:02X}]"
},
{
"mask": "0011'1RRR",
"mnemonic": "ADDC",
"format": "A, R{R}"
},
{
"mask": "1001'0100 DDDD'DDDD",
"mnemonic": "SUBB",
"format": "A, #0x{D:02X}"
},
{
"mask": "1001'0101 IIII'IIII",
"mnemonic": "SUBB",
"format": "A, IRAM[0x{I:02X}]"
},
{
"mask": "1001'011R",
"mnemonic": "SUBB",
"format": "A, @R{R}"
},
{
"mask": "1001'1RRR",
"mnemonic": "SUBB",
"format": "A, R{R}"
},
{
"mask": "1010'0100",
"mnemonic": "MUL",
"format": "AB"
},
{
"mask": "1000'0100",
"mnemonic": "DIV",
"format": "AB"
},
{
"mask": "0010'1RRR",
"mnemonic": "ORL",
"format": "A, R{R}"
},
{
"mask": "1011'0101 IIII'IIII AAAA'AAAA",
"mnemonic": "CJNE",
"format": "A, IRAM[0x{I:02X}], PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "1011'0100 DDDD'DDDD AAAA'AAAA",
"mnemonic": "CJNE",
"format": "A, #0x{D:02X}, PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "1011'011R DDDD'DDDD AAAA'AAAA",
"mnemonic": "CJNE",
"format": "@R{R}, #0x{D:02X}, PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "1011'1RRR DDDD'DDDD AAAA'AAAA",
"mnemonic": "CJNE",
"format": "R{R}, #0x{D:02X}, PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "1101'0101 IIII'IIII AAAA'AAAA",
"mnemonic": "DJNZ",
"format": "IRAM[0x{I:02X}], PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 3 + A"
}
}
]
},
{
"mask": "1101'1RRR AAAA'AAAA",
"mnemonic": "DJNZ",
"format": "R{R}, PC + 0x{R:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 2 + A"
}
}
]
},
{
"mask": "0101'0000 AAAA'AAAA",
"mnemonic": "JNC",
"format": "PC + 0x{A:02X}",
"metadata": [
{
"type": "jump",
"data": {
"destination": "offset + 2 + A"
}
}
]
},
{
"mask": "1101'0000 AAAA'AAAA",
"mnemonic": "POP",
"format": "IRAM[0x{A:02X}]"
},
{
"mask": "1100'0000 AAAA'AAAA",
"mnemonic": "PUSH",
"format": "IRAM[0x{A:02X}]"
},
{
"mask": "1101'0100",
"mnemonic": "DA",
"format": ""
},
{
"mask": "1100'0100",
"mnemonic": "SWAP",
"format": "A"
},
{
"mask": "1111'0100",
"mnemonic": "CPL",
"format": "A"
},
{
"mask": "1011'0011",
"mnemonic": "CPL",
"format": "C"
},
{
"mask": "1011'0010 BBBB'BBBB",
"mnemonic": "CPL",
"format": "BIT[0x{B:02X}]"
},
{
"mask": "1010'0101",
"mnemonic": "INVALID",
"format": ""
},
{
"mask": "XXXX'XXXX",
"mnemonic": "DB",
"format": "#0x{X:02X}",
"metadata": [
{
"type": "data",
"data": {
"value": "X"
}
}
]
}
]
}

1045
disassemblers/jvm.json Normal file

File diff suppressed because it is too large Load Diff

18594
encodings/big5.tbl Normal file

File diff suppressed because it is too large Load Diff

21921
encodings/gbk.tbl Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,12 @@
#pragma once
#include <hex/impl/imhex_check.pat>
import hex.impl.imhex_check;
/*!
Core intrinsic functions to interact with the ImHex Hex Editor
*/
namespace hex::core {
namespace auto hex::core {
/**
A type representing a selection in the hex editor
@@ -21,20 +21,30 @@ namespace hex::core {
@return The current selection
*/
fn get_selection() {
u128 result = builtin::hex::core::get_selection();
u128 selection = builtin::hex::core::get_selection();
Selection result;
if (result == u128(-1)) {
if (selection == u128(-1)) {
result.valid = false;
result.address = 0x00;
result.size = 0x00;
} else {
result.valid = true;
result.address = result >> 64;
result.size = result & u64(-1);
result.address = selection >> 64;
result.size = selection & u64(-1);
}
return result;
};
}
/**
Add a file to the Virtual Filesystem
@param path The name of the file
@param pattern The pattern associated with the file
*/
fn add_virtual_file(str path, auto pattern)
{
builtin::hex::core::add_virtual_file(path, pattern);
};
}

View File

@@ -1,12 +1,14 @@
#pragma once
#include <hex/impl/imhex_check.pat>
import hex.impl.imhex_check;
import std.mem;
/*!
Library to allow decoding of more complex values
*/
namespace hex::dec {
namespace auto hex::dec {
/**
Demangles a mangled name into a human readable name
@@ -17,4 +19,57 @@ namespace hex::dec {
return builtin::hex::dec::demangle(mangled_name);
};
/**
Decompresses the bytes of a pattern into a section using the zlib algorithm
@param pattern The pattern whose bytes should be decompressed
@param section The section to decompress the data into
@param window_size The window size passed to zlib
@return true if successful, false otherwise
*/
fn zlib_decompress(ref auto pattern, std::mem::Section section, u64 window_size = 0) {
return builtin::hex::dec::zlib_decompress(pattern, section, window_size);
};
/**
Decompresses the bytes of a pattern into a section using the bzip algorithm
@param pattern The pattern whose bytes should be decompressed
@param section The section to decompress the data into
@return true if successful, false otherwise
*/
fn bzip_decompress(ref auto pattern, std::mem::Section section) {
return builtin::hex::dec::bzip_decompress(pattern, section);
};
/**
Decompresses the bytes of a pattern into a section using the LZMA algorithm
@param pattern The pattern whose bytes should be decompressed
@param section The section to decompress the data into
@return true if successful, false otherwise
*/
fn lzma_decompress(ref auto pattern, std::mem::Section section) {
return builtin::hex::dec::lzma_decompress(pattern, section);
};
/**
Decompresses the bytes of a pattern into a section using the zstd algorithm
@param pattern The pattern whose bytes should be decompressed
@param section The section to decompress the data into
@return true if successful, false otherwise
*/
fn zstd_decompress(ref auto pattern, std::mem::Section section) {
return builtin::hex::dec::zstd_decompress(pattern, section);
};
/**
Decompresses the bytes of a pattern into a section using the lz4 algorithm
@param pattern The pattern whose bytes should be decompressed
@param section The section to decompress the data into
@param frame Whether the data is framed or not
@return true if successful, false otherwise
*/
fn lz4_decompress(ref auto pattern, std::mem::Section section, bool frame = true) {
return builtin::hex::dec::lz4_decompress(pattern, section, frame);
};
}

View File

@@ -1,12 +1,12 @@
#pragma once
#include <hex/impl/imhex_check.pat>
import hex.impl.imhex_check;
/*!
Library to do HTTP requests
*/
namespace hex::http {
namespace auto hex::http {
/**
Performs a HTTP GET request to the given URL and returns the response body

View File

@@ -1,17 +1,17 @@
#pragma once
#include <hex/impl/imhex_check.pat>
import hex.impl.imhex_check;
/*!
Library to interact with the currently loaded provider.
*/
namespace hex::prv {
namespace auto hex::prv {
/**
Queries information from the currently loaded provider. The kind of information that's available depends on the provider that's loaded
> **Available information**
> - File Provider
> - `file_path() -> str`
@@ -32,12 +32,12 @@ namespace hex::prv {
> - `region_size(regionName) -> u64`
> - `process_id() -> u32`
> - `process_name() -> str`
@param category Information category
@param argument Extra argument to pass along
*/
fn get_information(str category, str argument = "") {
return builtin::hex::prv::get_information(category, argument);
};
}

View File

@@ -0,0 +1,28 @@
#pragma once
import hex.impl.imhex_check;
/*!
Types to work with custom encoded strings using Thiny encoding definitions
*/
namespace auto hex::type {
/**
A string that was encoded using a custom encoding
@tparam Data Pattern whose bytes are used in the decoding process
@tparam EncodingDefinition A string containing a Thingy encoding definition as used by ImHex's custom encoding feature
*/
struct EncodedString<auto Data, auto EncodingDefinition> {
builtin::hex::dec::EncodedString<Data, EncodingDefinition> string;
} [[sealed, format("hex::type::impl::format_encoded_string")]];
namespace impl {
fn format_encoded_string(ref auto string) {
return string.string;
};
}
}

View File

@@ -0,0 +1,143 @@
#pragma once
import hex.impl.imhex_check;
/*!
Types to work with machine code
*/
namespace auto hex::type {
/**
A machine code instruction which will get disassembled
@tparam DisassemblerSetting A string containing the config for the disassembler in the form of "architecture; setting1, setting2, no-setting3"
@tparam SyntaxType Syntax used in the disassembly. Possible values are "intel", "at&t", "masm" and "motorola"
@tparam ImageBaseAddress Start address of the instruction region in the data
@tparam ImageLoadAddress Address where the instructions will be loaded into memory
Possible Values for DisassemblerSetting:
- Architecture, all may be suffixed with le or be to specify endianess (e.g armbe or mipsle)
- arm
- thumb
- aarch64
- arm64
- mips
- x86
- x86_64
- x64
- ppc
- powerpc
- sparc
- sysz
- xcore
- m68k
- m680x
- tms320c64x
- evm
- wasm
- riscv
- mos65xx
- bpf
- sh
- tricore
- Settings, not all settings make sense for each architecture. Prefixing settings with no- will remove them instead
- 16bit
- 32bit
- 64bit
- cortex-m
- armv8
- micromips
- mips2
- mips3
- mips32r6
- sparcv9
- qpx
- spe
- ps
- 68000
- 68010
- 68020
- 68030
- 68040
- 68060
- 6301
- 6309
- 6800
- 6801
- 6805
- 6808
- 6809
- 6811
- cpu12
- hcs08
- bpfe
- rv32g
- rv64g
- riscvc
- 6502
- 65c02
- w65c02
- 65816
- long-m
- long-x
- sh2
- sh2a
- sh3
- sh4
- sh4a
- shfpu
- shdsp
- 1.1
- 1.2
- 1.3
- 1.3.1
- 1.6
- 1.6.1
- 1.6.2
*/
struct Instruction<auto DisassemblerSetting, auto SyntaxType, auto ImageBaseAddress, auto ImageLoadAddress> {
builtin::hex::dec::Instruction<DisassemblerSetting, SyntaxType, ImageBaseAddress, ImageLoadAddress> instruction;
} [[sealed, format("hex::type::impl::format_instruction")]];
/**
A machine code instruction which will get disassembled using Intel syntax
@tparam DisassemblerSetting A string containing the config for the disassembler in the form of "architecture; setting1, setting2, no-setting3"
@tparam ImageBaseAddress Start address of the instruction region in the data
@tparam ImageLoadAddress Address where the instructions will be loaded into memory
*/
using InstructionIntel<auto DisassemblerSetting, auto ImageBaseAddress, auto ImageLoadAddress> = Instruction<DisassemblerSetting, "intel", ImageBaseAddress, ImageLoadAddress>;
/**
A machine code instruction which will get disassembled using AT&T syntax
@tparam DisassemblerSetting A string containing the config for the disassembler in the form of "architecture; setting1, setting2, no-setting3"
@tparam ImageBaseAddress Start address of the instruction region in the data
@tparam ImageLoadAddress Address where the instructions will be loaded into memory
*/
using InstructionATNT<auto DisassemblerSetting, auto ImageBaseAddress, auto ImageLoadAddress> = Instruction<DisassemblerSetting, "at&t", ImageBaseAddress, ImageLoadAddress>;
/**
A machine code instruction which will get disassembled using MASM syntax
@tparam DisassemblerSetting A string containing the config for the disassembler in the form of "architecture; setting1, setting2, no-setting3"
@tparam ImageBaseAddress Start address of the instruction region in the data
@tparam ImageLoadAddress Address where the instructions will be loaded into memory
*/
using InstructionMASM<auto DisassemblerSetting, auto ImageBaseAddress, auto ImageLoadAddress> = Instruction<DisassemblerSetting, "masm", ImageBaseAddress, ImageLoadAddress>;
/**
A machine code instruction which will get disassembled using Motorola syntax
@tparam DisassemblerSetting A string containing the config for the disassembler in the form of "architecture; setting1, setting2, no-setting3"
@tparam ImageBaseAddress Start address of the instruction region in the data
@tparam ImageLoadAddress Address where the instructions will be loaded into memory
*/
using InstructionMotorola<auto DisassemblerSetting, auto ImageBaseAddress, auto ImageLoadAddress> = Instruction<DisassemblerSetting, "motorola", ImageBaseAddress, ImageLoadAddress>;
namespace impl {
fn format_instruction(ref auto instruction) {
return instruction.instruction;
};
}
}

View File

@@ -0,0 +1,66 @@
#pragma once
import hex.impl.imhex_check;
/*!
Types to decode JSON and JSON-like file formats into a pattern tree
*/
namespace auto hex::type {
/**
Type representing a JSON string
@tparam Size size of the string
*/
struct Json<auto Size> {
char __data[Size];
builtin::hex::dec::Json<__data> json [[merge]];
};
/**
Type representing Bson data
@tparam Size size of the data
*/
struct Bson<auto Size> {
u8 __data[Size];
builtin::hex::dec::Bson<__data> bson [[merge]];
};
/**
Type representing Cbor data
@tparam Size size of the data
*/
struct Cbor<auto Size> {
u8 __data[Size];
builtin::hex::dec::Cbor<__data> cbor [[merge]];
};
/**
Type representing Bjdata data
@tparam Size size of the data
*/
struct Bjdata<auto Size> {
u8 __data[Size];
builtin::hex::dec::Bjdata<__data> bjdata [[merge]];
};
/**
Type representing Msgpack data
@tparam Size size of the data
*/
struct Msgpack<auto Size> {
u8 __data[Size];
builtin::hex::dec::Msgpack<__data> msgpack [[merge]];
};
/**
Type representing Ubjson data
@tparam Size size of the data
*/
struct Ubjson<auto Size> {
u8 __data[Size];
builtin::hex::dec::Ubjson<__data> ubjson [[merge]];
};
}

View File

@@ -1,30 +1,30 @@
#pragma once
#include <std/io.pat>
#include <std/mem.pat>
import std.io;
import std.mem;
#include <hex/impl/imhex_check.pat>
#include <hex/dec.pat>
import hex.impl.imhex_check;
import hex.dec;
/*!
Types to automatically decode mangled names
*/
namespace hex::type {
namespace auto hex::type {
/**
A mangled name string that gets demangled when displayed
*/
struct MangledName {
char value[];
} [[sealed, format("hex::type::impl::format_mangled_name")]];
namespace impl {
fn format_mangled_name(ref MangledName name) {
return hex::dec::demangle(name.value);
};
}
}

View File

@@ -1,19 +1,52 @@
#pragma once
import std.sys;
import std.core;
/*!
The array library contains various helper functions and types to make
it easier to work with Arrays.
The array library contains a helper type to make it easier to create multi-dimensional arrays
and pass arrays to functions as parameters.
*/
namespace std {
namespace auto std {
/**
Simple one dimensional array wrapper
@tparam T The array types
@tparam Size Size of the array
@tparam Size Number of entries in the array
*/
struct Array<T, auto Size> {
T data[Size] [[inline]];
} [[format("std::impl::format_array")]];
/**
Simple array wrapper for an array with a size in bytes
@tparam T The array types
@tparam NumBytes Number of bytes the array contains
*/
struct ByteSizedArray<T, auto NumBytes> {
u64 startAddress = $;
T array[while($ - startAddress < NumBytes)] [[inline]];
std::assert($ - startAddress == NumBytes, "Not enough bytes available to fit a whole number of types");
} [[format("std::impl::format_array")]];
/**
An interface type for getting the index of the currently processed element in an array. This is a nice wrapper around `std::core::array_index()`
To use it, inherit from it and use the `this.index` field to get the index of the current element
*/
struct IIndexed {
const u64 index = std::core::array_index();
};
}
namespace impl {
fn format_array(ref auto array) {
return "[ ... ]";
};
}
}

70
includes/std/attrs.pat Normal file
View File

@@ -0,0 +1,70 @@
import std.io;
import std.core;
/*!
The attributes library contains a set of attributes that can be used to annotate types with certain properties.
To use an attribute, simply make your custom type inherit from the attribute type you want to use.
For example, to make a type hidden, you can use the `Hidden` attribute like this:
```rust
struct MyType : std::attr::Hidden {
// ...
};
```
*/
namespace auto std::attr {
/**
Attribute that marks a type as a literal type.
This means the type behaves like a built-in type in the sense that it doesn't show its internal state and its display value is determined by a format function.
It can also be transformed into a different built-in literal when used in an expression.
@tparam FormatFunction The format function to use. The return value of this function is used to display the value of the literal and also determines the value returned when the literal is used in an expression.
*/
struct Literal<auto FormatFunction> { }
[[sealed, format_read(FormatFunction), transform(FormatFunction)]];
/**
Attribute that changes the name of the variable created from a type.
@tparam Name The name of the variable created
*/
struct Named<auto Name> { }
[[name(Name)]];
/**
Attribute that adds a comment to the variable created from a type.
@tparam Comment The comment to add
*/
struct Commented<auto Comment> {}
[[comment(Comment)]];
/**
Attribute that marks a type as hidden.
This means variables of this type are not displayed in the UI.
*/
struct Hidden {}
[[hidden]];
/**
Attribute that marks a type as hidden and also hides it from the highlighter.
This means variables of this type are don't display any highlighting in the UI but are still visible.
*/
struct HighlightHidden {}
[[highlight_hidden]];
/**
Attribute that marks a type as inline.
Creating a variable of this type will not create a new layer but instead dump the contents of the type directly into the current layer.
*/
struct Inlined {}
[[inline]];
/**
Attribute that marks a type as sealed.
Sealed types don't display their internal state in the UI.
*/
struct Sealed {}
[[sealed]];
}

View File

@@ -1,63 +1,67 @@
#pragma once
#include <std/limits.pat>
import std.limits;
/*!
This library contains various helper functions for common bit operations.
This library contains various helper functions for common bit operations.
*/
namespace std::bit {
namespace auto std::bit {
/**
Calculates the number of 1 bits in a given number
@param x The number
@return The number of bits set to 1 in `x`
*/
fn popcount(u128 x) {
x = (x & (std::limits::u128_max() / 3)) + ((x >> 1) & (std::limits::u128_max() / 3));
x = (x & (std::limits::u128_max() / 5)) + ((x >> 2) & (std::limits::u128_max() / 5));
x = (x & (std::limits::u128_max() / 17)) + ((x >> 4) & (std::limits::u128_max() / 17));
return x % 0xFF;
};
/**
Calculates the number of 1 bits in a given number
@param x The number
@return The number of bits set to 1 in `x`
*/
fn popcount(u128 x) {
const u128 a = 0x55555555555555555555555555555555;
const u128 b = 0x33333333333333333333333333333333;
const u128 c = 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F;
/**
Checks if only a single bit is set to 1 in a given number
@param x The number
@return True if there's a single bit set to 1 in `x`, false otherwise
*/
fn has_single_bit(u128 x) {
return x != 0 && (x & (x - 1)) == 0;
};
/**
Rounds the given number up to the next bigger power of two
@param x The number
@return Next bigger power of two that can fit `x`
*/
fn bit_ceil(u128 x) {
if (x == 0) return 0;
u8 i;
while ((1 << i) < x)
i = i + 1;
return 1 << i;
};
x = (x & a) + ((x >> 1) & a);
x = (x & b) + ((x >> 2) & b);
x = (x & c) + ((x >> 4) & c);
/**
Rounds the given number down to the next bigger power of two
@param x The number
@return Next smaller power of two
*/
fn bit_floor(u128 x) {
if (x == 0) return 0;
u8 i;
while ((x >> i) > 0)
i = i + 1;
return 1 << (i - 1);
};
return x % 0xFF;
};
/**
Checks if only a single bit is set to 1 in a given number
@param x The number
@return True if there's a single bit set to 1 in `x`, false otherwise
*/
fn has_single_bit(u128 x) {
return x != 0 && (x & (x - 1)) == 0;
};
/**
Rounds the given number up to the next bigger power of two
@param x The number
@return Next bigger power of two that can fit `x`
*/
fn bit_ceil(u128 x) {
if (x == 0) return 0;
u8 i;
while ((1 << i) < x)
i = i + 1;
return 1 << i;
};
/**
Rounds the given number down to the next bigger power of two
@param x The number
@return Next smaller power of two
*/
fn bit_floor(u128 x) {
if (x == 0) return 0;
u8 i;
while ((x >> i) > 0)
i = i + 1;
return 1 << (i - 1);
};
}

View File

@@ -1,13 +1,13 @@
#pragma once
#include <std/mem.pat>
import std.mem;
/*!
The core library contains intrinsics and "compiler magic" functions that
get extra help from the runtime to fulfill their purpose.
*/
namespace std::core {
namespace auto std::core {
/**
The layout order of each field after byte-endianness has been handled.
@@ -38,27 +38,35 @@ namespace std::core {
};
/**
Returns the first parameter of the attribute of a pattern if it has one
Returns the nth parameter of the attribute of a pattern if it has one
@param pattern The pattern to check
@param attribute The attribute's name to query
@param [index] The parameter index of the attribute to return. Defaults to 0
*/
fn get_attribute_argument(ref auto pattern, str attribute, u32 index = 0) {
return builtin::std::core::get_attribute_argument(pattern, attribute, index);
};
/**
@warning Removed in 1.27.0
*/
fn get_attribute_value(ref auto pattern, str attribute) {
return builtin::std::core::get_attribute_value(pattern, attribute);
builtin::std::error("`std::core::get_attribute_value(pattern, attribute)` has been removed.\nUse `std::core::get_attribute_argument(pattern, attribute, [index])` instead.");
};
/**
Sets the current default endianess.
Any patterns created following this attribute will be created using the set endianess.
@param endian The new default endianess
Sets the current default endianness.
Any patterns created following this attribute will be created using the set endianness.
@param endian The new default endianness
*/
fn set_endian(std::mem::Endian endian) {
builtin::std::core::set_endian(u32(endian));
};
/**
Gets the current default endianess.
@return The currently set default endianess
Gets the current default endianness.
@return The currently set default endianness
*/
fn get_endian() {
return builtin::std::core::get_endian();
@@ -146,4 +154,39 @@ namespace std::core {
fn set_display_name(ref auto pattern, str name) {
builtin::std::core::set_display_name(pattern, name);
};
/**
Changes the comment attached to a pattern
@param pattern The pattern to modify
@param comment The new comment of the pattern
*/
fn set_pattern_comment(ref auto pattern, str comment) {
builtin::std::core::set_pattern_comment(pattern, comment);
};
/**
Executes the function with the given name, passing in all given arguments
@param function_name The namespace-prefixed name of the function
@param args Arguments to pass to the function
*/
fn execute_function(str function_name, auto ... args) {
builtin::std::core::execute_function(function_name, args);
};
/**
Sets the pattern color palette for all future created patterns
@param args RGBA8 colors as 32 bit integers (0xAABBGGRR)
*/
fn set_pattern_palette_colors(auto ... colors) {
builtin::std::core::set_pattern_palette_colors(colors);
};
/**
Resets the current pattern palette progress back to zero.
This can be useful to force all instances of a type to have the same coloring for its members
*/
fn reset_pattern_palette() {
builtin::std::core::reset_pattern_palette();
};
}

View File

@@ -5,7 +5,7 @@
of ASCII characters.
*/
namespace std::ctype {
namespace auto std::ctype {
/**
Checks if the given character `c` is a digit between '0' and '9'

View File

@@ -1,112 +1,120 @@
#pragma once
/*!
The File library allows reading and writing from/to external files using
a C-like File IO API.
The File library allows reading and writing from/to external files using
a C-like File IO API.
**These functions are considered dangerous and require the user to manually permit them**
**These functions are considered dangerous and require the user to manually permit them**
*/
namespace std::file {
namespace auto std::file {
/**
/**
A handle representing a file that has been opened
*/
using Handle = s32;
/**
using Handle = s32;
/**
The mode to open a file in.
Read opens the file in read-only mode
Write opens the file in read and write mode
Create creates a new file if it doesn't exist and overwrites an existing file
Read opens the file in read-only mode
Write opens the file in read and write mode
Create creates a new file if it doesn't exist and overwrites an existing file
*/
enum Mode : u8 {
Read = 1,
Write = 2,
Create = 3
};
enum Mode : u8 {
Read = 1,
Write = 2,
Create = 3
};
/**
/**
Opens a file
@param path The path to the file to open
@param mode File open mode
@return Handle to the newly opened file
@param path The path to the file to open
@param mode File open mode
@return Handle to the newly opened file
*/
fn open(str path, Mode mode) {
return builtin::std::file::open(path, u32(mode));
};
fn open(str path, Mode mode) {
return builtin::std::file::open(path, u32(mode));
};
/**
/**
Closes a file handle that has been opened previously
@param handle The handle to close
@param handle The handle to close
*/
fn close(Handle handle) {
builtin::std::file::close(handle);
};
fn close(Handle handle) {
builtin::std::file::close(handle);
};
/**
/**
Reads the content of a file into a string
@param handle The file handle to read from
@param size Number of bytes to read
@return String containing the read data
@param handle The file handle to read from
@param size Number of bytes to read
@return String containing the read data
*/
fn read(Handle handle, u64 size) {
return builtin::std::file::read(handle, size);
};
fn read(Handle handle, u64 size) {
return builtin::std::file::read(handle, size);
};
/**
/**
Writes the content of a string into a file
@param handle The file handle to write to
@param data String to write to the file
@param handle The file handle to write to
@param data String or Pattern to write to the file
*/
fn write(Handle handle, str data) {
builtin::std::file::write(handle, data);
};
fn write(Handle handle, auto data) {
builtin::std::file::write(handle, data);
};
/**
/**
Sets the current cursor position in the given file handle
@param handle The file handle to set the cursor position in
@param offset The offset to move the cursor to
@param handle The file handle to set the cursor position in
@param offset The offset to move the cursor to
*/
fn seek(Handle handle, u64 offset) {
builtin::std::file::seek(handle, offset);
};
fn seek(Handle handle, u64 offset) {
builtin::std::file::seek(handle, offset);
};
/**
Queries the size of a file
@param handle The handle of the file to get the size of
@return The file's size
*/
fn size(Handle handle) {
return builtin::std::file::size(handle);
};
/**
Queries the size of a file
@param handle The handle of the file to get the size of
@return The file's size
*/
fn size(Handle handle) {
return builtin::std::file::size(handle);
};
/**
Resizes a file
@param handle The handle of the file to resize
*/
fn resize(Handle handle, u64 size) {
builtin::std::file::resize(handle, size);
};
/**
Resizes a file
@param handle The handle of the file to resize
*/
fn resize(Handle handle, u64 size) {
builtin::std::file::resize(handle, size);
};
/**
Flushes changes made to a file to disk
@param handle The handle of the file to flush
*/
fn flush(Handle handle) {
builtin::std::file::remove(handle);
};
/**
Flushes changes made to a file to disk
@param handle The handle of the file to flush
*/
fn flush(Handle handle) {
builtin::std::file::flush(handle);
};
/**
Deletes a file from disk. This will also automatically close this file
@param handle The handle of the file to delete
*/
fn remove(Handle handle) {
builtin::std::file::remove(handle);
};
/**
Deletes a file from disk. This will also automatically close this file
@param handle The handle of the file to delete
*/
fn remove(Handle handle) {
builtin::std::file::remove(handle);
};
/**
Create all directories for the provided path
@param path The path for which all directories should be created
*/
fn create_directories(str path) {
builtin::std::file::create_directories(path);
};
}

View File

@@ -1,89 +1,89 @@
#pragma once
/*!
Library for doing arithmetic with fixed point numbers and converting them from/to floating point numbers.
Library for doing arithmetic with fixed point numbers and converting them from/to floating point numbers.
*/
namespace std::fxpt {
namespace auto std::fxpt {
/**
A fixed point value
*/
using fixed = s128;
/**
A fixed point value
*/
using fixed = s128;
/**
Converts a fixed point value into a floating point value
@param fxt The fixed point value to convert
@param precision The bits of precision the new value should have
@return The floating point representation of fxt
*/
fn to_float(fixed fxt, u32 precision) {
return double(fxt) / double((1 << precision));
};
/**
Converts a floating point value into a fixed point value
@param flt The floating point value to convert
@param precision The bits of precision the new value should have
@return The fixed point representation of flt
*/
fn to_fixed(double flt, u32 precision) {
return fixed((flt * (1 << precision)));
};
/**
Converts a fixed point value into a floating point value
@param fxt The fixed point value to convert
@param precision The bits of precision the new value should have
@return The floating point representation of fxt
*/
fn to_float(fixed fxt, u32 precision) {
return double(fxt) / double((1 << precision));
};
/**
Changes the number of bits used to represent the decimal part of the given fixed point number
@param value The fixed point value to convert
@param start_precision The current number of bits used
@param end_precision The new number of bits used
@return `value` as a new fixed point number with `end_precision` bits of precision
*/
fn change_precision(fixed value, u32 start_precision, u32 end_precision) {
return std::fxpt::to_fixed(std::fxpt::to_float(value, start_precision), end_precision);
};
/**
Adds two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the addition of `a` and `b`
*/
fn add(fixed a, fixed b, u32 precision) {
return a + b;
};
/**
Subtracts two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the subtraction of `a` and `b`
*/
fn subtract(fixed a, fixed b, u32 precision) {
return a - b;
};
/**
Multiplies two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the multiplication of `a` and `b`
*/
fn multiply(fixed a, fixed b, u32 precision) {
return (a * b) / (1 << precision);
};
/**
Divides two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the division of `a` and `b`
*/
fn divide(fixed a, fixed b, u32 precision) {
return (a << precision) / b;
};
/**
Converts a floating point value into a fixed point value
@param flt The floating point value to convert
@param precision The bits of precision the new value should have
@return The fixed point representation of flt
*/
fn to_fixed(double flt, u32 precision) {
return s128((flt * (1 << precision)));
};
/**
Changes the number of bits used to represent the decimal part of the given fixed point number
@param value The fixed point value to convert
@param start_precision The current number of bits used
@param end_precision The new number of bits used
@return `value` as a new fixed point number with `end_precision` bits of precision
*/
fn change_precision(fixed value, u32 start_precision, u32 end_precision) {
return std::fxpt::to_fixed(std::fxpt::to_float(value, start_precision), end_precision);
};
/**
Adds two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the addition of `a` and `b`
*/
fn add(fixed a, fixed b, u32 precision) {
return a + b;
};
/**
Subtracts two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the subtraction of `a` and `b`
*/
fn subtract(fixed a, fixed b, u32 precision) {
return a - b;
};
/**
Multiplies two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the multiplication of `a` and `b`
*/
fn multiply(fixed a, fixed b, u32 precision) {
return (a * b) / (1 << precision);
};
/**
Divides two fixed point numbers with a given precision together
@param a First fixed point number
@param b Second fixed point number
@param precision The precision of `a` and `b`
@return Result of the division of `a` and `b`
*/
fn divide(fixed a, fixed b, u32 precision) {
return (a << precision) / b;
};
}

View File

@@ -4,20 +4,62 @@
The hash library contains various data hash functions
*/
namespace std::hash {
namespace auto std::hash {
/**
Calculates the CRC8 hash of the bytes inside of a given pattern
@param pattern The pattern to calculate the CRC8 hash of
@param init The CRC8 init value
@param poly The CRC8 polynomial
@param xorout The CRC8 XOR-Out value
@param reflect_in Whether or not the input bytes should be reflected
@param reflect_out Whether or not the output should be reflected
@return Calculated CRC8 hash
*/
fn crc8(ref auto pattern, u8 init, u8 poly, u8 xorout, bool reflect_in, bool reflect_out) {
return builtin::std::hash::crc8(pattern, init, poly, xorout, reflect_in, reflect_out);
};
/**
Calculates the CRC16 hash of the bytes inside of a given pattern
@param pattern The pattern to calculate the CRC16 hash of
@param init The CRC16 init value
@param poly The CRC16 polynomial
@param xorout The CRC16 XOR-Out value
@param reflect_in Whether or not the input bytes should be reflected
@param reflect_out Whether or not the output should be reflected
@return Calculated CRC16 hash
*/
fn crc16(ref auto pattern, u16 init, u16 poly, u16 xorout, bool reflect_in, bool reflect_out) {
return builtin::std::hash::crc16(pattern, init, poly, xorout, reflect_in, reflect_out);
};
/**
Calculates the CRC32 hash of the bytes inside of a given pattern
@param pattern The pattern to calculate the crc32 hash of
@param pattern The pattern to calculate the CRC32 hash of
@param init The CRC32 init value
@param poly The CRC32 polynomial
@param xorout The CRC32 XOR-Out value
@param reflect_in Whether or not the input bytes should be reflected
@param reflect_out Whether or not the output should be reflected
@return Calculated CRC32 hash
@return Calculated CRC32 hash
*/
fn crc32(ref auto pattern, u32 init, u32 poly, u32 xorout, bool reflect_in, bool reflect_out) {
return builtin::std::hash::crc32(pattern, init, poly, xorout, reflect_in, reflect_out);
};
/**
Calculates the CRC64 hash of the bytes inside of a given pattern
@param pattern The pattern to calculate the CRC64 hash of
@param init The CRC64 init value
@param poly The CRC64 polynomial
@param xorout The CRC64 XOR-Out value
@param reflect_in Whether or not the input bytes should be reflected
@param reflect_out Whether or not the output should be reflected
@return Calculated CRC64 hash
*/
fn crc64(ref auto pattern, u64 init, u64 poly, u64 xorout, bool reflect_in, bool reflect_out) {
return builtin::std::hash::crc64(pattern, init, poly, xorout, reflect_in, reflect_out);
};
}

View File

@@ -4,26 +4,26 @@
The IO library allows formatting strings and outputting text to the console
*/
namespace std {
namespace auto std {
/**
Formats the given arguments using the format string and prints the result to the console
This function uses the C++20 `std::format` or libfmt's `fmt::format` syntax.
@param fmt Format string
@param fmt Format string or any other value that can be converted to a string
@param args Values to use in the formatting
*/
fn print(str fmt, auto ... args) {
fn print(auto fmt, auto ... args) {
builtin::std::print(fmt, args);
};
/**
Formats the given arguments using the format string and returns the result as a string
This function uses the C++20 `std::format` or libfmt's `fmt::format` syntax.
@param fmt Format string
@param fmt Format string or any other value that can be converted to a string
@param args Values to use in the formatting
@return The formatted string
*/
fn format(str fmt, auto ... args) {
fn format(auto fmt, auto ... args) {
return builtin::std::format(fmt, args);
};

View File

@@ -1,169 +1,169 @@
#pragma once
/*!
Library to calculate the minimum and maximum values that fit into a given data type
Library to calculate the minimum and maximum values that fit into a given data type
*/
namespace std::limits {
/**
Returns the minimum value that can be stored in a `u8`.
@return Minimum value
*/
fn u8_min() {
return u8(0);
};
/**
Returns the maximum value that can be stored in a `u8`.
@return Maximum value
*/
fn u8_max() {
return u8(-1);
};
namespace auto std::limits {
/**
Returns the minimum value that can be stored in a `s8`.
@return Minimum value
*/
/**
Returns the minimum value that can be stored in a `u8`.
@return Minimum value
*/
fn u8_min() {
return u8(0);
};
/**
Returns the maximum value that can be stored in a `u8`.
@return Maximum value
*/
fn u8_max() {
return u8(-1);
};
/**
Returns the minimum value that can be stored in a `s8`.
@return Minimum value
*/
fn s8_min() {
return -s8((std::limits::u8_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s8`.
@return Maximum value
*/
fn s8_max() {
return s8((std::limits::u8_max() / 2));
};
return -s8((std::limits::u8_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s8`.
@return Maximum value
*/
fn s8_max() {
return s8((std::limits::u8_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u16`.
@return Minimum value
*/
fn u16_min() {
return u16(0);
};
/**
Returns the maximum value that can be stored in a `u16`.
@return Maximum value
*/
fn u16_max() {
return u16(-1);
};
/**
Returns the minimum value that can be stored in a `s16`.
@return Minimum value
*/
fn s16_min() {
return -s16((std::limits::u16_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s16`.
@return Maximum value
*/
fn s16_max() {
return s16((std::limits::u16_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u32`.
@return Minimum value
*/
fn u32_min() {
return u32(0);
};
/**
Returns the maximum value that can be stored in a `u32`.
@return Maximum value
*/
fn u32_max() {
return u32(-1);
};
/**
Returns the minimum value that can be stored in a `s32`.
@return Minimum value
*/
fn s32_min() {
return -s32((std::limits::u32_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s32`.
@return Maximum value
*/
fn s32_max() {
return s32((std::limits::u32_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u64`.
@return Minimum value
*/
fn u64_min() {
return u64(0);
};
/**
Returns the maximum value that can be stored in a `u64`.
@return Maximum value
*/
fn u64_max() {
return u64(-1);
};
/**
Returns the minimum value that can be stored in a `s64`.
@return Minimum value
*/
fn s64_min() {
return -s64((std::limits::u64_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s64`.
@return Maximum value
*/
fn s64_max() {
return s64((std::limits::u64_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u128`.
@return Minimum value
*/
fn u128_min() {
return u128(0);
};
/**
Returns the maximum value that can be stored in a `u128`.
@return Maximum value
*/
fn u128_max() {
return u128(-1);
};
/**
Returns the minimum value that can be stored in a `s128`.
@return Minimum value
*/
fn s128_min() {
return -s128((std::limits::u128_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s128`.
@return Maximum value
*/
fn s128_max() {
return s128((std::limits::u128_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u16`.
@return Minimum value
*/
fn u16_min() {
return u16(0);
};
/**
Returns the maximum value that can be stored in a `u16`.
@return Maximum value
*/
fn u16_max() {
return u16(-1);
};
/**
Returns the minimum value that can be stored in a `s16`.
@return Minimum value
*/
fn s16_min() {
return -s16((std::limits::u16_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s16`.
@return Maximum value
*/
fn s16_max() {
return s16((std::limits::u16_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u32`.
@return Minimum value
*/
fn u32_min() {
return u32(0);
};
/**
Returns the maximum value that can be stored in a `u32`.
@return Maximum value
*/
fn u32_max() {
return u32(-1);
};
/**
Returns the minimum value that can be stored in a `s32`.
@return Minimum value
*/
fn s32_min() {
return -s32((std::limits::u32_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s32`.
@return Maximum value
*/
fn s32_max() {
return s32((std::limits::u32_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u64`.
@return Minimum value
*/
fn u64_min() {
return u64(0);
};
/**
Returns the maximum value that can be stored in a `u64`.
@return Maximum value
*/
fn u64_max() {
return u64(-1);
};
/**
Returns the minimum value that can be stored in a `s64`.
@return Minimum value
*/
fn s64_min() {
return -s64((std::limits::u64_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s64`.
@return Maximum value
*/
fn s64_max() {
return s64((std::limits::u64_max() / 2));
};
/**
Returns the minimum value that can be stored in a `u128`.
@return Minimum value
*/
fn u128_min() {
return u128(0);
};
/**
Returns the maximum value that can be stored in a `u128`.
@return Maximum value
*/
fn u128_max() {
return u128(-1);
};
/**
Returns the minimum value that can be stored in a `s128`.
@return Minimum value
*/
fn s128_min() {
return -s128((std::limits::u128_max() / 2)) - 1;
};
/**
Returns the maximum value that can be stored in a `s128`.
@return Maximum value
*/
fn s128_max() {
return s128((std::limits::u128_max() / 2));
};
}

View File

@@ -1,333 +1,340 @@
#pragma once
#include <std/mem.pat>
import std.mem;
/*!
Library containing more advanced mathematical operations.
Library containing more advanced mathematical operations.
*/
namespace std::math {
namespace auto std::math {
/**
Compares the values `a` and `b` with each other and returns the smaller of the two
@param a First value
@param b Second value
@return `a` if `a` is smaller than `b`, otherwise `b`
*/
fn min(auto a, auto b) {
if (a < b)
return a;
else
return b;
};
/**
Compares the values `a` and `b` with each other and returns the bigger of the two
@param a First value
@param b Second value
@return `a` if `a` is bigger than `b`, otherwise `b`
*/
fn max(auto a, auto b) {
if (a > b)
return a;
else
return b;
};
/**
Compares the values `a` and `b` with each other and returns the smaller of the two
@param a First value
@param b Second value
@return `a` if `a` is smaller than `b`, otherwise `b`
*/
fn min(auto a, auto b) {
if (a < b)
return a;
else
return b;
};
/**
Clamps the value of `x` between `min` and `max`.
@param x Value
@param min Minimum value
@param max Maximum value
@return `min` if `x` is smaller than `min`, `max` if `x` is bigger than `max`, `x` otherwise
*/
fn clamp(auto x, auto min, auto max) {
if (x < min)
return min;
else if (x > max)
return max;
else
return x;
};
/**
Compares the values `a` and `b` with each other and returns the bigger of the two
@param a First value
@param b Second value
@return `a` if `a` is bigger than `b`, otherwise `b`
*/
fn max(auto a, auto b) {
if (a > b)
return a;
else
return b;
};
/**
Returns the absolute value of `x`.
@param x Value
@return `x` if `x` is positive, `-x` otherwise
*/
fn abs(auto x) {
if (x < 0)
return -x;
else
return x;
};
/**
Clamps the value of `x` between `min` and `max`.
@param x Value
@param min Minimum value
@param max Maximum value
@return `min` if `x` is smaller than `min`, `max` if `x` is bigger than `max`, `x` otherwise
*/
fn clamp(auto x, auto min, auto max) {
if (x < min)
return min;
else if (x > max)
return max;
else
return x;
};
/**
Returns the sign of `x`.
@param x Value
@return `1` if `x` is positive, `-1` if `x` is negative, `0` if `x` is zero
*/
fn sign(auto x) {
if (x > 0)
return 1;
else if (x < 0)
return -1;
else
return 0;
};
/**
Returns the absolute value of `x`.
@param x Value
@return `x` if `x` is positive, `-x` otherwise
*/
fn abs(auto x) {
if (x < 0)
return -x;
else
return x;
};
/**
Copies the sign of `y` to `x`.
@param x Value
@param y Value
@return `x` if `y` is positive, `-x` if `y` is negative
*/
fn copy_sign(auto x, auto y) {
if (y >= 0)
return std::math::abs(x);
else
return -std::math::abs(x);
};
/**
Returns the sign of `x`.
@param x Value
@return `1` if `x` is positive, `-1` if `x` is negative, `0` if `x` is zero
*/
fn sign(auto x) {
if (x > 0)
return 1;
else if (x < 0)
return -1;
else
return 0;
};
/**
Calculates the factorial of `x`.
@param x Value
@return Factorial of `x`
*/
fn factorial(u128 x) {
u128 result;
result = x;
while (x > 1) {
x = x - 1;
result = result * x;
}
return result;
};
/**
Copies the sign of `y` to `x`.
@param x Value
@param y Value
@return `x` if `y` is positive, `-x` if `y` is negative
*/
fn copy_sign(auto x, auto y) {
if (y >= 0)
return std::math::abs(x);
else
return -std::math::abs(x);
};
/**
Calculates the binomial coefficient of `n` and `k`.
@param n Value
@param k Value
@return Binomial coefficient of `n` and `k`
*/
fn comb(u128 n, u128 k) {
if (k > n)
return 0;
else
return std::math::factorial(n) / (std::math::factorial(k) * std::math::factorial(n - k));
};
/**
Calculates the factorial of `x`.
@param x Value
@return Factorial of `x`
*/
fn factorial(u128 x) {
u128 result;
/**
Calculates the permutation of `n` and `k`.
@param n Value
@param k Value
@return Permutation of `n` and `k`
*/
fn perm(u128 n, u128 k) {
if (k > n)
return 0;
else
return std::math::factorial(n) / std::math::factorial(n - k);
};
result = x;
while (x > 1) {
x = x - 1;
result = result * x;
}
/**
Floors the value of `value`.
@param value Value
@return `value` floored
*/
fn floor(auto value) { return builtin::std::math::floor(value); };
return result;
};
/**
Ceils the value of `value`.
@param value Value
@return `value` ceiled
*/
fn ceil(auto value) { return builtin::std::math::ceil(value); };
/**
Calculates the binomial coefficient of `n` and `k`.
@param n Value
@param k Value
@return Binomial coefficient of `n` and `k`
*/
fn comb(u128 n, u128 k) {
if (k > n)
return 0;
else
return std::math::factorial(n) / (std::math::factorial(k) * std::math::factorial(n - k));
};
/**
Rounds the value of `value`.
@param value Value
@return `value` rounded
*/
fn round(auto value) { return builtin::std::math::round(value); };
/**
Calculates the permutation of `n` and `k`.
@param n Value
@param k Value
@return Permutation of `n` and `k`
*/
fn perm(u128 n, u128 k) {
if (k > n)
return 0;
else
return std::math::factorial(n) / std::math::factorial(n - k);
};
/**
Truncates the value of `value`.
@param value Value
@return `value` truncated
*/
fn trunc(auto value) { return builtin::std::math::trunc(value); };
/**
Floors the value of `value`.
@param value Value
@return `value` floored
*/
fn floor(auto value) { return builtin::std::math::floor(value); };
/**
Ceils the value of `value`.
@param value Value
@return `value` ceiled
*/
fn ceil(auto value) { return builtin::std::math::ceil(value); };
/**
Rounds the value of `value`.
@param value Value
@return `value` rounded
*/
fn round(auto value) { return builtin::std::math::round(value); };
/**
Truncates the value of `value`.
@param value Value
@return `value` truncated
*/
fn trunc(auto value) { return builtin::std::math::trunc(value); };
/**
Calculates the logarithm of `value` with base 10.
@param value Value
@return Logarithm of `value` with base 10
*/
fn log10(auto value) { return builtin::std::math::log10(value); };
/**
Calculates the logarithm of `value` with base 10.
@param value Value
@return Logarithm of `value` with base 10
*/
fn log10(auto value) { return builtin::std::math::log10(value); };
/**
Calculates the logarithm of `value` with base 2.
@param value Value
@return Logarithm of `value` with base 2
*/
fn log2(auto value) { return builtin::std::math::log2(value); };
/**
Calculates the logarithm of `value` with base 2.
@param value Value
@return Logarithm of `value` with base 2
*/
fn log2(auto value) { return builtin::std::math::log2(value); };
/**
Calculates the natural logarithm of `value`.
@param value Value
@param base Base
@return Logarithm of `value` with base `e`
*/
fn ln(auto value) { return builtin::std::math::ln(value); };
/**
Calculates the natural logarithm of `value`.
@param value Value
@return Logarithm of `value` with base `e`
*/
fn ln(auto value) { return builtin::std::math::ln(value); };
/**
Calculates the floating point modulus of `value`.
@param value Value
@return Floating point modulus of `value`
*/
fn fmod(auto value) { return builtin::std::math::fmod(value); };
/**
Calculates the floating point modulus of `value`.
@param value Value
@return Floating point modulus of `value`
*/
fn fmod(auto value) { return builtin::std::math::fmod(value); };
/**
Calculates the value of `base` raised to the power of `exp`.
@param base Base
@param exp Exponent
@return `base` raised to the power of `exp`
*/
fn pow(auto base, auto exp) { return builtin::std::math::pow(base, exp); };
/**
Calculates the value of `base` raised to the power of `exp`.
@param base Base
@param exp Exponent
@return `base` raised to the power of `exp`
*/
fn pow(auto base, auto exp) { return builtin::std::math::pow(base, exp); };
/**
Calculates the square root of `value`.
@param value Value
@return Square root of `value`
*/
fn sqrt(auto value) { return builtin::std::math::sqrt(value); };
/**
Calculates the value of the natural number `e` raised to the power of `value`.
@param value Exponent
@return `e` raised to the power of `value`
*/
fn exp(auto value) { return builtin::std::math::exp(value); };
/**
Calculates the cubic root of `value`.
@param value Value
@return Cubic root of `value`
*/
fn cbrt(auto value) { return builtin::std::math::cbrt(value); };
/**
Calculates the square root of `value`.
@param value Value
@return Square root of `value`
*/
fn sqrt(auto value) { return builtin::std::math::sqrt(value); };
/**
Calculates the sine of `value`.
@param value Angle value in radians
@return Sine of `value`
*/
fn sin(auto value) { return builtin::std::math::sin(value); };
/**
Calculates the cubic root of `value`.
@param value Value
@return Cubic root of `value`
*/
fn cbrt(auto value) { return builtin::std::math::cbrt(value); };
/**
Calculates the cosine of `value`.
@param value Angle value in radians
@return Cosine of `value`
*/
fn cos(auto value) { return builtin::std::math::cos(value); };
/**
Calculates the sine of `value`.
@param value Angle value in radians
@return Sine of `value`
*/
fn sin(auto value) { return builtin::std::math::sin(value); };
/**
Calculates the tangent of `value`.
@param value Angle value in radians
@return Tangent of `value`
*/
fn tan(auto value) { return builtin::std::math::tan(value); };
/**
Calculates the cosine of `value`.
@param value Angle value in radians
@return Cosine of `value`
*/
fn cos(auto value) { return builtin::std::math::cos(value); };
/**
Calculates the arc sine of `value`.
@param value Angle value in radians
@return Arc sine of `value`
*/
fn asin(auto value) { return builtin::std::math::asin(value); };
/**
Calculates the tangent of `value`.
@param value Angle value in radians
@return Tangent of `value`
*/
fn tan(auto value) { return builtin::std::math::tan(value); };
/**
Calculates the arc cosine of `value`.
@param value Value
@return Arc cosine of `value` in radians
*/
fn acos(auto value) { return builtin::std::math::acos(value); };
/**
Calculates the arc sine of `value`.
@param value Angle value in radians
@return Arc sine of `value`
*/
fn asin(auto value) { return builtin::std::math::asin(value); };
/**
Calculates the arc tangent of `value`.
@param value Value
@return Arc tangent of `value` in radians between `-pi/2` and `pi/2`
*/
fn atan(auto value) { return builtin::std::math::atan(value); };
/**
Calculates the arc cosine of `value`.
@param value Value
@return Arc cosine of `value` in radians
*/
fn acos(auto value) { return builtin::std::math::acos(value); };
/**
Calculates the arc tangent of `value`.
@param value Value
@return Arc tangent of `value` in radians between `-pi` and `pi`
*/
fn atan2(auto value) { return builtin::std::math::atan2(value); };
/**
Calculates the arc tangent of `value`.
@param value Value
@return Arc tangent of `value` in radians between `-pi/2` and `pi/2`
*/
fn atan(auto value) { return builtin::std::math::atan(value); };
/**
Calculates the hyperbolic sine of `value`.
@param value Angle value in radians
@return Hyperbolic sine of `value`
*/
fn sinh(auto value) { return builtin::std::math::sinh(value); };
/**
Calculates the arc tangent of `value`.
@param y Value representing the proportion of the y-coordinate
@param x Value representing the proportion of the x-coordinate.
@return Arc tangent of `value` in radians between `-pi` and `pi`
*/
fn atan2(auto y, auto x) { return builtin::std::math::atan2(y, x); };
/**
Calculates the hyperbolic cosine of `value`.
@param value Angle value in radians
@return Hyperbolic cosine of `value`
*/
fn cosh(auto value) { return builtin::std::math::cosh(value); };
/**
Calculates the hyperbolic sine of `value`.
@param value Angle value in radians
@return Hyperbolic sine of `value`
*/
fn sinh(auto value) { return builtin::std::math::sinh(value); };
/**
Calculates the hyperbolic tangent of `value`.
@param value Angle value in radians
@return Hyperbolic tangent of `value`
*/
fn tanh(auto value) { return builtin::std::math::tanh(value); };
/**
Calculates the hyperbolic cosine of `value`.
@param value Angle value in radians
@return Hyperbolic cosine of `value`
*/
fn cosh(auto value) { return builtin::std::math::cosh(value); };
/**
Calculates the hyperbolic tangent of `value`.
@param value Angle value in radians
@return Hyperbolic tangent of `value`
*/
fn tanh(auto value) { return builtin::std::math::tanh(value); };
/**
Calculates the arc hyperbolic sine of `value`.
@param value Value
@return Arc hyperbolic sine of `value`
*/
fn asinh(auto value) { return builtin::std::math::asinh(value); };
/**
Calculates the arc hyperbolic sine of `value`.
@param value Value
@return Arc hyperbolic sine of `value`
*/
fn asinh(auto value) { return builtin::std::math::asinh(value); };
/**
Calculates the arc hyperbolic cosine of `value`.
@param value Value
@return Arc hyperbolic cosine of `value`
*/
fn acosh(auto value) { return builtin::std::math::acosh(value); };
/**
Calculates the arc hyperbolic cosine of `value`.
@param value Value
@return Arc hyperbolic cosine of `value`
*/
fn acosh(auto value) { return builtin::std::math::acosh(value); };
/**
Calculates the arc hyperbolic tangent of `value`.
@param value Value
@return Arc hyperbolic tangent of `value`
*/
fn atanh(auto value) { return builtin::std::math::atanh(value); };
/**
Calculates the arc hyperbolic tangent of `value`.
@param value Value
@return Arc hyperbolic tangent of `value`
*/
fn atanh(auto value) { return builtin::std::math::atanh(value); };
/**
Options to use with the `std::math::accumulate` function.
*/
enum AccumulateOperation : u8 {
Add = 0,
Multiply = 1,
Modulo = 2,
Min = 3,
Max = 4
};
/**
Options to use with the `std::math::accumulate` function.
*/
enum AccumulateOperation : u8 {
Add = 0,
Multiply = 1,
Modulo = 2,
Min = 3,
Max = 4
};
/**
Calculates the sum of all values in the specified memory range.
@param start Start address
@param end End address
@param valueSize Size of each value in bytes
@param [section] Section to use
@param [operation] Operation to use. Defaults to addition
@param [endian] Endianness to use. Defaults to native
@return Sum of all values in the specified memory range
*/
fn accumulate(u128 start, u128 end, u128 valueSize, std::mem::Section section = 0, AccumulateOperation operation = AccumulateOperation::Add, std::mem::Endian endian = std::mem::Endian::Native) {
return builtin::std::math::accumulate(start, end, valueSize, section, u128(operation), u128(endian));
};
/**
Calculates the sum of all values in the specified memory range.
@param start Start address
@param end End address
@param valueSize Size of each value in bytes
@param section Section to use
@param operation Operation to use
@param endian Endianness to use
@return Sum of all values in the specified memory range
*/
fn accumulate(u128 start, u128 end, u128 valueSize, std::mem::Section section = 0, AccumulateOperation operation = AccumulateOperation::Add, std::mem::Endian endian = std::mem::Endian::Native) {
return builtin::std::math::accumulate(start, end, valueSize, section, u128(operation), u128(endian));
};
}

View File

@@ -4,15 +4,32 @@
Library for doing raw memory accesses and other low-level operations.
*/
namespace std::mem {
namespace auto std::mem {
namespace impl {
struct MagicSearchImpl<auto Magic, T> {
s128 address = builtin::std::mem::find_string_in_range(0, $, builtin::std::mem::size(), Magic);
if (address < 0)
break;
$ = address;
try {
T data [[inline]];
} catch {
T data;
}
};
}
/**
A Handle for a custom Section
*/
using Section = u128;
/**
The Endianess of a value
The endianness of a value
*/
enum Endian : u8 {
Native = 0,
@@ -26,7 +43,16 @@ namespace std::mem {
@return True if the cursor is at the end of the memory
*/
fn eof() {
return $ >= std::mem::size();
return $ >= (std::mem::base_address() + std::mem::size());
};
/**
Function that returns true if the cursor position is at or beyond the given address
@param address The address to compare against
@return True if the cursor is at or beyond the given address
*/
fn reached(u128 address) {
return $ >= address;
};
/**
@@ -40,10 +66,10 @@ namespace std::mem {
return remainder != 0 ? value + (alignment - remainder) : value;
};
/**
Gets the base address of the memory
Gets the base address of the data
@return The base address of the memory
*/
fn base_address() {
@@ -51,7 +77,7 @@ namespace std::mem {
};
/**
Gets the size of the memory
Gets the size of the data
@return The size of the memory
*/
fn size() {
@@ -59,17 +85,18 @@ namespace std::mem {
};
/**
Finds a sequence of bytes in the memory
Finds a sequence of bytes in the data
@param occurrence_index The index of the occurrence to find
@param bytes The bytes to find
@return The address of the sequence
*/
fn find_sequence(u128 occurrence_index, auto ... bytes) {
return builtin::std::mem::find_sequence_in_range(occurrence_index, builtin::std::mem::base_address(), builtin::std::mem::size(), bytes);
const u128 address = builtin::std::mem::base_address();
return builtin::std::mem::find_sequence_in_range(occurrence_index, address, address + builtin::std::mem::size(), bytes);
};
/**
Finds a sequence of bytes in a specific region of the memory
Finds a sequence of bytes in a specific region of the data
@param occurrence_index The index of the occurrence to find
@param offsetFrom The offset from which to start searching
@param offsetTo The offset to which to search
@@ -80,11 +107,35 @@ namespace std::mem {
return builtin::std::mem::find_sequence_in_range(occurrence_index, offsetFrom, offsetTo, bytes);
};
/**
Finds a string in the data
@param occurrence_index The index of the occurrence to find
@param string The string to find
@return The address of the sequence
*/
fn find_string(u128 occurrence_index, str string) {
const u128 address = builtin::std::mem::base_address();
return builtin::std::mem::find_string_in_range(occurrence_index, address, address + builtin::std::mem::size(), string);
};
/**
Finds a string in a specific region of the data
@param occurrence_index The index of the occurrence to find
@param offsetFrom The offset from which to start searching
@param offsetTo The offset to which to search
@param string The string to find
@return The address of the sequence
*/
fn find_string_in_range(u128 occurrence_index, u128 offsetFrom, u128 offsetTo, str string) {
return builtin::std::mem::find_string_in_range(occurrence_index, offsetFrom, offsetTo, string);
};
/**
Reads a unsigned value from the memory
@param address The address to read from
@param size The size of the value to read
@param endian The endianess of the value to read
@param [endian] The endianness of the value to read. Defaults to native
@return The value read
*/
fn read_unsigned(u128 address, u8 size, Endian endian = Endian::Native) {
@@ -95,7 +146,7 @@ namespace std::mem {
Reads a signed value from the memory
@param address The address to read from
@param size The size of the value to read
@param endian The endianess of the value to read
@param [endian] The endianness of the value to read. Defaults to native
@return The value read
*/
fn read_signed(u128 address, u8 size, Endian endian = Endian::Native) {
@@ -108,18 +159,10 @@ namespace std::mem {
@param size The size of the value to read
@return The value read
*/
fn read_string(u128 address, u8 size) {
fn read_string(u128 address, u128 size) {
return builtin::std::mem::read_string(address, size);
};
/**
Gets the current bit offset within the current byte that a bitfield will read.
*/
fn current_bit_offset() {
return builtin::std::mem::current_bit_offset();
};
/**
Reads a number of bits from the specified bit offset within the specified byte
@param byteOffset The byte offset within the data
@@ -160,6 +203,15 @@ namespace std::mem {
return builtin::std::mem::get_section_size(section);
};
/**
Changes the size of a custom section
@param section The handle to the section
@param size The new size of the section
*/
fn set_section_size(Section section, u128 size) {
builtin::std::mem::set_section_size(section, size);
};
/**
Copies a range of bytes from one section into another
@param from_section The section to copy from
@@ -174,15 +226,22 @@ namespace std::mem {
/**
Copies a range of bytes from the main section into a custom section
@param from_section The section to copy from
@param from_address The address to copy from
@param value The pattern whose bytes should be copied
@param to_section The section to copy to
@param to_address The address to copy to
@param size The size of the range to copy
*/
fn copy_value_to_section(ref auto value, Section to_section, u64 to_address) {
builtin::std::mem::copy_value_to_section(value, to_section, to_address);
};
/**
Returns the current bit offset when inside of a bitfield.
@return The current bit offset between 0 and 7
*/
fn current_bit_offset() {
return builtin::std::mem::current_bit_offset();
};
/**
Searches for a sequence of bytes and places the given type at that address
@@ -190,19 +249,7 @@ namespace std::mem {
@tparam T The type to place at the address
*/
struct MagicSearch<auto Magic, T> {
if ($ < (std::mem::size() - std::string::length(Magic) - 1)) {
char __potentialMagic__[std::string::length(Magic)] [[hidden, no_unique_address]];
if (__potentialMagic__ == Magic) {
T data [[inline]];
} else {
padding[1];
continue;
}
} else {
padding[1];
continue;
}
std::mem::impl::MagicSearchImpl<Magic, T> impl[while(!std::mem::eof())] [[inline]];
};
/**
@@ -211,10 +258,10 @@ namespace std::mem {
@tparam To The type to reinterpret to
*/
union Reinterpreter<From, To> {
From from;
To to;
From from_value;
To to_value;
};
/**
Aligns the cursor to the given alignment
@@ -233,11 +280,11 @@ namespace std::mem {
} [[sealed, format("std::mem::impl::format_bytes")]];
namespace impl {
fn format_bytes(auto bytes) {
return "";
};
}
}

View File

@@ -1,11 +1,13 @@
#pragma once
import std.mem;
/*!
The Pointer library contains helper functions to deal with pointer types.
The `relative_to` functions are meant to be used with the `[[pointer_base]]` attribute
*/
namespace std::ptr {
namespace auto std::ptr {
/**
Use the offset of the current pointer as start address
@@ -55,7 +57,7 @@ namespace std::ptr {
// `pointerValue` is `no_unique_address` because we don't want to advance
// the current memory location after reading the value of the pointer itself;
// we want to examine the value at this address to determine what should be
// displayed. It's also `hidden` so the editor only displays either thee
// displayed. It's also `hidden` so the editor only displays either thee
// padding or the populated pointer/pointee field.
PointerTy pointerValue [[no_unique_address, hidden]];
if (pointerValue == 0x0) {
@@ -64,4 +66,4 @@ namespace std::ptr {
PointeeTy *data : PointerTy;
}
};
}
}

View File

@@ -1,13 +1,13 @@
#pragma once
#include <std/limits.pat>
import std.limits;
/*!
Library to generate random numbers. Supports various different distribution types.
*/
namespace std::random {
namespace auto std::random {
/**
Represents the type of distribution to use to generate a random number
*/
@@ -61,21 +61,21 @@ namespace std::random {
> - `Poisson(mean) -> i128`
@param distribution Distribution to use
@param param1 This parameter depends on the type of distribution used.
@param param2 This parameter depends on the type of distribution used.
@param [param1] This parameter depends on the type of distribution used. Defaults to 0
@param [param2] This parameter depends on the type of distribution used. Defaults to 0
*/
fn generate_using(Distribution distribution, auto param1 = 0, auto param2 = 0) {
return builtin::std::random::generate(u32(distribution), param1, param2);
};
/**
Generates a uniformly distributed random number between `min` and `max`
@param min Minimum number
@param max Maximum number
@param [min] Minimum number. Defaults to 0
@param [max] Maximum number. Defaults to `u64_max`
*/
fn generate(u64 min = std::limits::u64_min(), u64 max = std::limits::u64_max()) {
return std::random::generate_using(Distribution::Uniform, min, max);
};
}

View File

@@ -1,129 +1,153 @@
#pragma once
#include <std/io.pat>
import std.io;
import std.mem;
/*!
Libray to interact with strings.
Library to interact with strings.
*/
namespace std::string {
namespace auto std::string {
/**
Base type for sized strings. Represents a string with its size preceeding it.
@tparam SizeType The type of the size field.
@tparam DataType The type of the characters.
*/
struct SizedStringBase<SizeType, DataType> {
SizeType size;
DataType data[size];
} [[sealed, format("std::string::impl::format_sized_string"), transform("std::string::impl::format_sized_string")]];
/**
Base type for sized strings. Represents a string with its size preceding it.
@tparam SizeType The type of the size field.
@tparam DataType The type of the characters.
*/
struct SizedStringBase<SizeType, DataType> {
SizeType size;
DataType data[size];
} [[sealed, format("std::string::impl::format_string"), transform("std::string::impl::format_string")]];
/**
A ASCII string with a prefixed size.
@tparam SizeType The type of the size field.
*/
using SizedString<SizeType> = SizedStringBase<SizeType, char>;
/**
A ASCII string with a prefixed size.
@tparam SizeType The type of the size field.
*/
using SizedString<SizeType> = SizedStringBase<SizeType, char>;
/**
A UTF-16 string with a prefixed size.
@tparam SizeType The type of the size field.
*/
using SizedString16<SizeType> = SizedStringBase<SizeType, char16>;
/**
A UTF-16 string with a prefixed size.
@tparam SizeType The type of the size field.
*/
using SizedString16<SizeType> = SizedStringBase<SizeType, char16>;
namespace impl {
/**
Base type for null-terminated strings. Represents a string with its size determined by the first 0x00 byte found.
@tparam DataType The type of the characters.
*/
struct NullStringBase<DataType> {
DataType data[while(std::mem::read_unsigned($, sizeof(DataType)) != 0x00)];
DataType null_terminator;
} [[sealed, format("std::string::impl::format_string"), transform("std::string::impl::format_string")]];
fn format_sized_string(ref auto string) {
return string.data;
};
/**
A null-terminated ASCII string.
*/
using NullString = NullStringBase<char>;
}
/**
A null-terminated UTF-16 string.
*/
using NullString16 = NullStringBase<char16>;
/**
Gets the length of a string.
@param string The string to get the length of.
@return The length of the string.
*/
fn length(str string) {
return builtin::std::string::length(string);
};
namespace impl {
/**
Gets the character at a given index.
@param string The string to get the character from.
@param index The index of the character to get.
@return The character at the given index.
*/
fn at(str string, u32 index) {
return builtin::std::string::at(string, index);
};
fn format_string(ref auto string) {
return string.data;
};
/**
Gets a substring of a string.
@param string The string to get the substring from.
@param pos The position of the first character of the substring.
@param count The number of characters to get.
@return The substring.
*/
fn substr(str string, u32 pos, u32 count) {
return builtin::std::string::substr(string, pos, count);
};
}
/**
Gets the length of a string.
@param string The string to get the length of.
@return The length of the string.
*/
fn length(str string) {
return builtin::std::string::length(string);
};
/**
Gets the character at a given index.
@param string The string to get the character from.
@param index The index of the character to get.
@return The character at the given index.
*/
fn at(str string, u32 index) {
return builtin::std::string::at(string, index);
};
/**
Gets a substring of a string.
@param string The string to get the substring from.
@param pos The position of the first character of the substring.
@param count The number of characters to get.
@return The substring.
*/
fn substr(str string, u32 pos, u32 count) {
return builtin::std::string::substr(string, pos, count);
};
/**
Converts a string to an integer.
@param string The string to convert.
@param base The base of the number.
@return The integer.
*/
fn parse_int(str string, u8 base) {
return builtin::std::string::parse_int(string, base);
};
/**
Converts a string to an integer.
@param string The string to convert.
@param base The base of the number.
@return The integer.
*/
fn parse_int(str string, u8 base) {
return builtin::std::string::parse_int(string, base);
};
/**
Converts a string to a float.
@param string The string to convert.
@return The float.
*/
fn parse_float(str string) {
return builtin::std::string::parse_float(string);
};
/**
Converts a string to a float.
@param string The string to convert.
@return The float.
*/
fn parse_float(str string) {
return builtin::std::string::parse_float(string);
};
/**
Converts any type to a string.
@param x The value to convert.
@return The string.
*/
/**
Converts any type to a string.
@param x The value to convert.
@return The string.
*/
fn to_string(auto x) {
return std::format("{}", x);
};
/**
Checks if a string starts with a given substring.
@param string The string to check.
@param part The substring to check for.
@return True if the string starts with the substring, false otherwise.
*/
/**
Checks if a string starts with a given substring.
@param string The string to check.
@param part The substring to check for.
@return True if the string starts with the substring, false otherwise.
*/
fn starts_with(str string, str part) {
if (std::string::length(string) < std::string::length(part))
return false;
return std::string::substr(string, 0, std::string::length(part)) == part;
};
/**
Checks if a string ends with a given substring.
@param string The string to check.
@param part The substring to check for.
@return True if the string ends with the substring, false otherwise.
*/
/**
Checks if a string ends with a given substring.
@param string The string to check.
@param part The substring to check for.
@return True if the string ends with the substring, false otherwise.
*/
fn ends_with(str string, str part) {
if (std::string::length(string) < std::string::length(part))
return false;
return std::string::substr(string, std::string::length(string) - std::string::length(part), std::string::length(part)) == part;
};
/**
Checks if a string contains a given substring.
@param string The string to check.
@param part The substring to check for.
@return True if the string contains the substring, false otherwise.
*/
/**
Checks if a string contains a given substring.
@param string The string to check.
@param part The substring to check for.
@return True if the string contains the substring, false otherwise.
*/
fn contains(str string, str part) {
s32 string_len = std::string::length(string);
s32 part_len = std::string::length(part);
@@ -136,103 +160,100 @@ namespace std::string {
return false;
};
/**
Reverses a string.
@param string The string to reverse.
@return The reversed string.
*/
fn reverse(str string) {
/**
Reverses a string.
@param string The string to reverse.
@return The reversed string.
*/
fn reverse(str string) {
str result;
s32 i;
i = std::string::length(string);
while (i > 0) {
i = i - 1;
result = result + std::string::at(string, i);
}
return result;
};
/**
Converts a string to upper case.
@param string The string to convert.
@return The converted string.
*/
/**
Converts a string to upper case.
@param string The string to convert.
@return The converted string.
*/
fn to_upper(str string) {
str result;
u32 i;
char c;
while (i < std::string::length(string)) {
c = std::string::at(string, i);
if (c >= 'a' && c <= 'z')
result = result + char(c - 0x20);
else
result = result + c;
i = i + 1;
}
return result;
};
/**
Converts a string to lower case.
@param string The string to convert.
@return The converted string.
*/
fn to_lower(str string) {
str result;
u32 i;
char c;
while (i < std::string::length(string)) {
c = std::string::at(string, i);
if (c >= 'A' && c <= 'Z')
result = result + char(c + 0x20);
else
result = result + c;
i = i + 1;
}
return result;
};
str result;
/**
Replaces all occurrences of a substring with another substring.
@param string The string to replace in.
@param pattern The substring to replace.
@param replace The substring to replace with.
@return The string with the replacements.
*/
u32 i;
char c;
while (i < std::string::length(string)) {
c = std::string::at(string, i);
if (c >= 'a' && c <= 'z')
result = result + char(c - 0x20);
else
result = result + c;
i = i + 1;
}
return result;
};
/**
Converts a string to lower case.
@param string The string to convert.
@return The converted string.
*/
fn to_lower(str string) {
str result;
u32 i;
char c;
while (i < std::string::length(string)) {
c = std::string::at(string, i);
if (c >= 'A' && c <= 'Z')
result = result + char(c + 0x20);
else
result = result + c;
i = i + 1;
}
return result;
};
/**
Replaces all occurrences of a substring with another substring.
@param string The string to replace in.
@param pattern The substring to replace.
@param replace The substring to replace with.
@return The string with the replacements.
*/
fn replace(str string, str pattern, str replace) {
u32 string_len, pattern_len, replace_len;
string_len = std::string::length(string);
pattern_len = std::string::length(pattern);
replace_len = std::string::length(replace);
if (pattern_len > string_len)
return string;
str result;
u32 i;
while (i <= (string_len - pattern_len)) {
if (std::string::substr(string, i, pattern_len) == pattern) {
result = result + replace;
i = i + pattern_len;
} else {
result = result + std::string::at(string, i);
i = i + 1;
}
}
return result;
};
s32 string_len = std::string::length(string);
s32 pattern_len = std::string::length(pattern);
if (pattern_len > string_len || pattern_len * string_len == 0 )
return string;
str result;
s32 string_index;
s32 remaining_len = string_len;
while (pattern_len <= remaining_len) {
if (std::string::substr(string, string_index, pattern_len) == pattern) {
result += replace;
string_index += pattern_len;
} else {
result += std::string::at(string, string_index);
string_index += 1;
}
remaining_len = string_len - string_index;
}
result += std::string::substr(string, string_index, remaining_len );
return result;
};
}

View File

@@ -1,16 +1,16 @@
#pragma once
#include <std/io.pat>
import std.io;
/*!
Basic helper functions
*/
namespace std {
namespace auto std {
/**
Asserts that a given value is true. If it's not, abort evaluation and print the given message to the console
@param conditoon The condition that is required to be true
@param condition The condition that is required to be true
@param message The message to print in case the assertion doesn't hold
*/
fn assert(bool condition, str message) {
@@ -21,7 +21,7 @@ namespace std {
/**
Asserts that a given value is true. If it's not, print the given message to the console as a warning
@param conditoon The condition that is required to be true
@param condition The condition that is required to be true
@param message The message to print in case the assertion doesn't hold
*/
fn assert_warn(bool condition, str message) {
@@ -49,4 +49,11 @@ namespace std {
return builtin::std::sizeof_pack(pack);
};
/**
Throws an error notifying the developer that the current code path is not implemented currently.
*/
fn unimplemented() {
std::error("Unimplemented code path reached!");
};
}

View File

@@ -1,191 +1,200 @@
#pragma once
#include <std/io.pat>
import std.io;
/*!
Library to handle time and date related operations.
Library to handle time and date related operations.
*/
namespace std::time {
namespace auto std::time {
/**
A structured representation of a time and date.
*/
struct Time {
u8 sec;
u8 min;
u8 hour;
u8 mday;
u8 mon;
u16 year;
u8 wday;
u16 yday;
bool isdst;
} [[sealed]];
/**
A structured representation of a time and date.
*/
struct Time {
u8 sec;
u8 min;
u8 hour;
u8 mday;
u8 mon;
u16 year;
u8 wday;
u16 yday;
bool isdst;
} [[sealed]];
/**
A helper type to convert between Time and u128.
*/
union TimeConverter {
Time time;
u128 value;
};
/**
A helper type to convert between Time and u128.
*/
union TimeConverter {
Time time;
u128 value;
};
/**
A type to represent a time in seconds since the epoch.
*/
using EpochTime = u128;
/**
A type to represent a time in seconds since the epoch.
*/
using EpochTime = u32;
/**
A type to represent a time zone.
*/
enum TimeZone : u8 {
Local,
UTC
};
/**
A type to represent a time zone.
*/
enum TimeZone : u8 {
Local,
UTC
};
/**
A type to represent a DOS date.
*/
bitfield DOSDate {
day: 5;
month: 4;
year: 7;
} [[sealed]];
/**
A type to represent a DOS date.
*/
bitfield DOSDate {
day: 5;
month: 4;
year: 7;
} [[sealed]];
/**
A type to represent a DOS time.
*/
bitfield DOSTime {
seconds: 5;
minutes: 6;
hours: 5;
} [[sealed]];
/**
A type to represent a DOS time.
*/
bitfield DOSTime {
seconds: 5;
minutes: 6;
hours: 5;
} [[sealed]];
namespace impl {
namespace impl {
union DOSDateConverter {
DOSDate date;
u16 value;
};
union DOSDateConverter {
DOSDate date;
u16 value;
};
union DOSTimeConverter {
DOSTime time;
u16 value;
};
union DOSTimeConverter {
DOSTime time;
u16 value;
};
}
}
/**
Returns the current time in seconds since the epoch.
@return The current time in seconds since the epoch.
*/
fn epoch() {
return builtin::std::time::epoch();
};
/**
Returns the current time in seconds since the epoch.
@return The current time in seconds since the epoch.
*/
fn epoch() {
return builtin::std::time::epoch();
};
/**
Converts a time in seconds since the epoch to a local time.
@param epoch_time The time in seconds since the epoch.
@return The local time.
*/
fn to_local(EpochTime epoch_time) {
TimeConverter converter;
/**
Converts a time in seconds since the epoch to a local time.
@param epoch_time The time in seconds since the epoch.
@return The local time.
*/
fn to_local(EpochTime epoch_time) {
le TimeConverter converter;
converter.value = builtin::std::time::to_local(epoch_time);
converter.value = builtin::std::time::to_local(epoch_time);
return converter.time;
};
return converter.time;
};
/**
Converts a time in seconds since the epoch to a UTC time.
@param epoch_time The time in seconds since the epoch.
@return The UTC time.
*/
fn to_utc(EpochTime epoch_time) {
TimeConverter converter;
/**
Converts a time in seconds since the epoch to a UTC time.
@param epoch_time The time in seconds since the epoch.
@return The UTC time.
*/
fn to_utc(EpochTime epoch_time) {
le TimeConverter converter;
converter.value = builtin::std::time::to_utc(epoch_time);
converter.value = builtin::std::time::to_utc(epoch_time);
return converter.time;
};
return converter.time;
};
/**
Queries the current time in the specified time zone.
@param time_zone The time zone to query.
@return The current time in the specified time zone.
*/
fn now(TimeZone time_zone = TimeZone::Local) {
TimeConverter converter;
/**
Queries the current time in the specified time zone.
@param [time_zone] The time zone to query. Defaults to local.
@return The current time in the specified time zone.
*/
fn now(TimeZone time_zone = TimeZone::Local) {
le TimeConverter converter;
if (time_zone == TimeZone::Local)
converter.value = builtin::std::time::to_local(std::time::epoch());
else if (time_zone == TimeZone::UTC)
converter.value = builtin::std::time::to_utc(std::time::epoch());
else
converter.value = 0x00;
if (time_zone == TimeZone::Local)
converter.value = builtin::std::time::to_local(std::time::epoch());
else if (time_zone == TimeZone::UTC)
converter.value = builtin::std::time::to_utc(std::time::epoch());
else
converter.value = 0x00;
return converter.time;
};
return converter.time;
};
/**
Converts a value to a DOS date.
@param value The value to convert.
@return The DOS date.
*/
fn to_dos_date(u16 value) {
impl::DOSDateConverter converter;
/**
Converts a value to a DOS date.
@param value The value to convert.
@return The DOS date.
*/
fn to_dos_date(u16 value) {
le impl::DOSDateConverter converter;
converter.value = value;
converter.value = value;
return converter.date;
};
return converter.date;
};
/**
Converts a value to a DOS time.
@param value The value to convert.
@return The DOS time.
*/
fn to_dos_time(u16 value) {
impl::DOSTimeConverter converter;
/**
Converts a value to a DOS time.
@param value The value to convert.
@return The DOS time.
*/
fn to_dos_time(u16 value) {
le impl::DOSTimeConverter converter;
converter.value = value;
converter.value = value;
return converter.time;
};
return converter.time;
};
/**
Formats a time according to the specified format string.
@param time The time to format.
@param format_string The format string to use.
@return The formatted time.
*/
fn format(Time time, str format_string = "%c") {
TimeConverter converter;
converter.time = time;
/**
Converts a FILETIME to unix time.
@param value The value to convert.
@return Timestamp formatted as unix time.
*/
fn filetime_to_unix(u64 value) {
return value / 10000000 - 11644473600;
};
return builtin::std::time::format(format_string, converter.value);
};
/**
Formats a time according to the specified format string.
@param time The time to format.
@param [format_string] The format string to use. Defaults to "%c".
@return The formatted time.
*/
fn format(Time time, str format_string = "%c") {
le TimeConverter converter;
converter.time = time;
/**
Formats a DOS date according to the specified format string.
@param date The DOS date to format.
@param format_string The format string to use.
@return The formatted DOS date.
*/
fn format_dos_date(DOSDate date, str format_string = "{}/{}/{}") {
return std::format(format_string, date.day, date.month, date.year + 1980);
};
return builtin::std::time::format(format_string, converter.value);
};
/**
Formats a DOS time according to the specified format string.
@param time The DOS time to format.
@param format_string The format string to use.
@return The formatted DOS time.
*/
fn format_dos_time(DOSTime time, str format_string = "{:02}:{:02}:{:02}") {
return std::format(format_string, time.hours, time.minutes, time.seconds * 2);
};
/**
Formats a DOS date according to the specified format string.
@param date The DOS date to format.
@param [format_string] The format string to use. Defaults to "{}/{}/{}".
@return The formatted DOS date.
*/
fn format_dos_date(DOSDate date, str format_string = "{}/{}/{}") {
return std::format(format_string, date.day, date.month, date.year + 1980);
};
/**
Formats a DOS time according to the specified format string.
@param time The DOS time to format.
@param [format_string] The format string to use. Defaults to "{:02}:{:02}:{:02}".
@return The formatted DOS time.
*/
fn format_dos_time(DOSTime time, str format_string = "{:02}:{:02}:{:02}") {
return std::format(format_string, time.hours, time.minutes, time.seconds * 2);
};
}

View File

@@ -1,14 +1,14 @@
#pragma once
#include <std/io.pat>
#include <std/math.pat>
import std.io;
import std.math;
/*!
Types used to change the base of the displayed integer value.
Used like `type::Hex<u32> hexNumber;`, `type::Oct<u16> octalNumber;`
*/
namespace type {
namespace auto type {
/**
Integer type representing a Hexadecimal value. Displays its value in hexadecimal format.
@@ -34,7 +34,7 @@ namespace type {
*/
using Bin<T> = T [[format("type::impl::format_bin")]];
namespace impl {
namespace impl {
fn format_number(auto value, str fmt) {
bool negative = value < 0;
@@ -50,6 +50,6 @@ namespace type {
fn format_dec(auto value) { return type::impl::format_number(value, "{}"); };
fn format_bin(auto value) { return type::impl::format_number(value, "0b{:08b}"); };
}
}
}

63
includes/type/base64.pat Normal file
View File

@@ -0,0 +1,63 @@
import std.io;
import std.string;
import std.mem;
/*!
Type representing a Base64 encoded string
*/
namespace auto type {
/**
Type representing a Base64 encoded string
@tparam T String type
*/
struct Base64<T> {
T string;
} [[sealed, format("type::impl::transform_base64")]];
namespace impl {
fn get_decoded_value(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1; // Invalid character
};
fn decode_base64(str input) {
u64 inputLength = std::string::length(input);
str result;
s32 val = 0;
s32 bits = -8;
for (u32 i = 0, i < inputLength, i += 1) {
char c = input[i];
if (c == '=')
break;
s32 index = type::impl::get_decoded_value(c);
if (index == -1)
continue;
val = (val << 6) + index;
bits += 6;
if (bits >= 0) {
result += char((val >> bits) & 0xFF);
bits -= 8;
}
}
return result;
};
fn transform_base64(ref auto base64) {
return type::impl::decode_base64(base64.string);
};
}
}

View File

@@ -1,12 +1,12 @@
#pragma once
#include <std/io.pat>
import std.io;
/*!
Type to decode a BCD (Binary Coded Decimal) number
*/
namespace type {
namespace auto type {
/**
Decodes a BCD value where one byte represents a single digit

View File

@@ -1,13 +1,14 @@
#pragma once
#include <std/io.pat>
import std.io;
import std.core;
/*!
Types to display single bytes using various different representations
*/
namespace type {
namespace auto type {
/**
Type visualizing the value of each individual bit
*/
@@ -20,8 +21,8 @@ namespace type {
bit5 : 1;
bit6 : 1;
bit7 : 1;
} [[format("type::impl::format_bits"), right_to_left]];
} [[format("type::impl::format_bits"), bitfield_order(std::core::BitfieldOrder::LeastToMostSignificant, 8)]];
/**
Type visualizing the value of the two nibbles
*/
@@ -29,9 +30,9 @@ namespace type {
low : 4;
high : 4;
} [[format("type::impl::format_nibbles")]];
/**
Type representing a single Byte. Decodes the byte as it's hexadeicmal value, individual bits and nibbles
Type representing a single Byte. Decodes the byte as it's hexadecimal value, individual bits and nibbles
*/
union Byte {
u8 value;
@@ -40,7 +41,7 @@ namespace type {
} [[format("type::impl::format_byte"), single_color]];
namespace impl {
namespace impl {
fn format_byte(Byte byte) {
return std::format("0x{0:02X} (0b{1:08b}) LSB:{2}, MSB:{3}",
@@ -49,9 +50,9 @@ namespace type {
byte.bits.bit0,
byte.bits.bit7);
};
fn format_bits(Bits bits) {
return std::format("0b{}{}{}{}{}{}{}{}",
return std::format("0b{}{}{}{}{}{}{}{}",
bits.bit7,
bits.bit6,
bits.bit5,
@@ -61,11 +62,11 @@ namespace type {
bits.bit1,
bits.bit0);
};
fn format_nibbles(Nibbles nibbles) {
return std::format("{{ {0:0X}, {1:0X} }}", nibbles.high, nibbles.low);
};
}
}
}

View File

@@ -1,20 +1,20 @@
#pragma once
#include <std/io.pat>
#include <std/core.pat>
import std.io;
import std.core;
/*!
Types representing RGB or RGBA colors. The decoded color will be displayed in their color field
*/
namespace type {
namespace auto type {
/**
Type representing a generic RGBA color with a variable number of bits for each color
@tparam R Number of bits used for the red component
@tparam G Number of bits used for the green component
@tparam B Number of bits used for the blue component
@tparam A Number of bits used for the alpha component
@tparam A Number of bits used for the alpha component
*/
bitfield RGBA<auto R, auto G, auto B, auto A> {
r : R;
@@ -22,7 +22,7 @@ namespace type {
b : B;
if (A > 0) a : A;
} [[sealed, format("type::impl::format_color"), color(std::format("{0:02X}{1:02X}{2:02X}FF", r, g, b))]];
/**
Type representing a generic RGB color with a variable number of bits for each color
@tparam R Number of bits used for the red component
@@ -30,7 +30,7 @@ namespace type {
@tparam B Number of bits used for the blue component
*/
using RGB<auto R, auto G, auto B> = RGBA<R,G,B,0>;
/**
Type representing a RGBA color with 8 bits for the red component, 8 bits for green, 8 bits for blue and 8 bits for alpha
@@ -56,7 +56,7 @@ namespace type {
Type representing a RGBA color with 5 bits for the red component, 5 bits for green, 5 bits for blue and 1 bits for alpha
*/
using RGBA5551 = RGBA<5,5,5,1>;
namespace impl {
@@ -76,5 +76,5 @@ namespace type {
};
}
}

View File

@@ -1,45 +1,45 @@
#pragma once
#include <std/io.pat>
#include <std/math.pat>
#include <std/mem.pat>
import std.io;
import std.math;
import std.mem;
/*!
Type representing a 16 bit half precision floating point number
*/
namespace type {
namespace auto type {
/**
Type representing a 16 bit half precision floating point number
*/
using float16 = u16 [[format("type::impl::format_float16")]];
namespace impl {
union U32ToFloatConverter {
u32 intValue;
float floatValue;
};
fn format_float16(float16 value) {
fn format_float16(float16 value) {
u32 sign = value >> 15;
u32 exponent = (value >> 10) & 0x1F;
u32 mantissa = value & 0x3FF;
u32 result = 0x00;
if (exponent == 0) {
if (mantissa == 0) {
result = sign << 31;
} else {
exponent = 0x7F - 14;
while ((mantissa & (1 << 10)) == 0) {
exponent -= 1;
mantissa <<= 1;
}
mantissa &= 0x3FF;
result = (sign << 31) | (exponent << 23) | (mantissa << 13);
}
@@ -48,10 +48,10 @@ namespace type {
} else {
result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13);
}
std::mem::Reinterpreter<u32, float> converter;
converter.from = result;
converter.from_value = result;
return std::format("{}", converter.to);
};

42
includes/type/fmt.pat Normal file
View File

@@ -0,0 +1,42 @@
#pragma once
import std.io;
/*!
Type that allows specifying its format value using a format string.
## Usage
The following code reads a u32 from the data and formats it as an upper case hexadecimal value with
a minimum of 8 digits which is prefixed by 0x.
The format string is the same as passed to `std::format()` and follows the libfmt specification.
```rust
type::Formatted<u32, "0x{:08X}"> hex_formatted_integer @ 0x00;
```
*/
namespace auto type {
/**
Arbitrarily formatted type
@tparam T Type to format
@tparam FormatString libfmt format string to format the value
*/
struct Formatted<T, auto FormatString> {
T value;
} [[sealed, format("type::impl::format_formatted"), transform("type::impl::transform_formatted")]];
namespace impl {
fn format_formatted(ref auto formatted) {
return std::format(std::format("{{0:{}}}", formatted.FormatString), formatted.value);
};
fn transform_formatted(ref auto formatted) {
return formatted.value;
};
}
}

View File

@@ -1,17 +1,17 @@
#pragma once
#include <std/io.pat>
import std.io;
/*!
Types to deal with UUIDs (Universally Unique Identifiers) / GUIDs (Globally Unique Identifiers) as described in RFC 4122
Types to deal with UUIDs (Universally Unique Identifiers) / GUIDs (Globally Unique Identifiers) as described in RFC 4122
*/
namespace type {
namespace auto type {
/**
Type representing a GUID value
*/
struct GUID {
/**
Type representing a GUID value
*/
struct GUID {
u32 time_low;
u16 time_mid;
u16 time_high_and_version;
@@ -20,31 +20,31 @@ namespace type {
u8 node[6];
} [[sealed, format("type::impl::format_guid")]];
/**
Alias name for GUID
*/
using UUID = GUID;
/**
Alias name for GUID
*/
using UUID = GUID;
namespace impl {
namespace impl {
fn format_guid(GUID guid) {
bool valid = ((le u16(guid.time_high_and_version) >> 12) <= 5) && (((guid.clock_seq_and_reserved >> 4) >= 8) || ((guid.clock_seq_and_reserved >> 4) == 0));
return std::format("{}{{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}",
valid ? "" : "Invalid ",
le u32(guid.time_low),
le u16(guid.time_mid),
le u16(guid.time_high_and_version),
guid.clock_seq_and_reserved,
guid.clock_seq_low,
guid.node[0],
guid.node[1],
guid.node[2],
guid.node[3],
guid.node[4],
guid.node[5]);
};
fn format_guid(GUID guid) {
bool valid = ((le u16(guid.time_high_and_version) >> 12) <= 5) && (((guid.clock_seq_and_reserved >> 4) >= 8) || ((guid.clock_seq_and_reserved >> 4) == 0));
}
return std::format("{}{{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}",
valid ? "" : "Invalid ",
le u32(guid.time_low),
le u16(guid.time_mid),
le u16(guid.time_high_and_version),
guid.clock_seq_and_reserved,
guid.clock_seq_low,
guid.node[0],
guid.node[1],
guid.node[2],
guid.node[3],
guid.node[4],
guid.node[5]);
};
}
}

View File

@@ -1,13 +1,13 @@
#pragma once
#include <std/io.pat>
#include <std/string.pat>
import std.io;
import std.string;
/*!
Types used to decode IP addresses
*/
namespace type {
namespace auto type {
/**
A 4 byte IPv4 Address as described in RFC 791

View File

@@ -1,72 +1,72 @@
#pragma once
#include <std/io.pat>
#include <std/mem.pat>
import std.io;
import std.mem;
/*!
Types used to decode Little Endian Base 128 numbers used to store large numbers as space efficiently as possible
Types used to decode Little Endian Base 128 numbers used to store large numbers as space efficiently as possible
*/
namespace type {
/**
Base LEB128 type. Use `uLEB128` and `sLEB128` instead.
*/
struct LEB128Base {
u8 array[while($ == addressof(this) || std::mem::read_unsigned($-1, 1) & 0x80 != 0)] [[hidden]];
} [[sealed]];
namespace auto type {
/**
A unsigned variant of a LEB128 number
*/
using uLEB128 = LEB128Base [[format("type::impl::format_uleb128"), transform("type::impl::transform_uleb128")]];
/**
Base LEB128 type. Use `uLEB128` and `sLEB128` instead.
*/
struct LEB128Base {
u8 array[while($ == addressof(this) || std::mem::read_unsigned($-1, 1) & 0x80 != 0)] [[hidden]];
} [[sealed]];
/**
A signed variant of a LEB128 number
*/
using sLEB128 = LEB128Base [[format("type::impl::format_sleb128"), transform("type::impl::transform_sleb128")]];
/**
A unsigned variant of a LEB128 number
*/
using uLEB128 = LEB128Base [[format("type::impl::format_uleb128"), transform("type::impl::transform_uleb128")]];
/**
Legacy alias for uLEB128
*/
using LEB128 = uLEB128;
namespace impl {
fn transform_uleb128_array(auto array) {
u128 res = array[0] & 0x7f;
for(u8 i = 1, array[i-1] & 0x80 != 0, i+=1) {
res |= u128(array[i] & 0x7f) << 7 * i;
}
return res;
};
/**
A signed variant of a LEB128 number
*/
using sLEB128 = LEB128Base [[format("type::impl::format_sleb128"), transform("type::impl::transform_sleb128")]];
fn transform_sleb128_array(auto array) {
s128 res = type::impl::transform_uleb128_array(array);
if (res & 0x40 != 0) {
res |= ~0 << (sizeof(array) / sizeof(u8)) * 7;
}
return res;
};
fn format_uleb128(auto leb128) {
u128 res = type::impl::transform_uleb128_array(leb128.array);
return std::format("{} ({:#x})", res, res);
};
fn transform_uleb128(auto leb128) {
return type::impl::transform_uleb128_array(leb128.array);
};
/**
Legacy alias for uLEB128
*/
using LEB128 = uLEB128;
fn format_sleb128(auto leb128) {
s128 res = type::impl::transform_sleb128_array(leb128.array);
return std::format("{} ({:#x})", res, res);
};
fn transform_sleb128(auto leb128) {
return type::impl::transform_sleb128_array(leb128.array);
};
namespace impl {
fn transform_uleb128_array(ref auto array) {
u128 res = array[0] & 0x7f;
for(u8 i = 1, array[i-1] & 0x80 != 0, i+=1) {
res |= u128(array[i] & 0x7f) << 7 * i;
}
return res;
};
fn transform_sleb128_array(ref auto array) {
s128 res = type::impl::transform_uleb128_array(array);
if (res & 1 << ((sizeof(array) / sizeof(u8)) * 7 - 1) != 0) {
res |= ~0 << (sizeof(array) / sizeof(u8)) * 7;
}
return res;
};
fn format_uleb128(ref auto leb128) {
u128 res = type::impl::transform_uleb128_array(leb128.array);
return std::format("{} ({:#x})", res, res);
};
fn transform_uleb128(ref auto leb128) {
return type::impl::transform_uleb128_array(leb128.array);
};
fn format_sleb128(ref auto leb128) {
s128 res = type::impl::transform_sleb128_array(leb128.array);
return std::format("{} ({:#x})", res, res);
};
fn transform_sleb128(ref auto leb128) {
return type::impl::transform_sleb128_array(leb128.array);
};
}
}
}

View File

@@ -1,32 +1,32 @@
#pragma once
#include <std/io.pat>
import std.io;
/*!
Types used to decode MAC Addresses
Types used to decode MAC Addresses
*/
namespace type {
namespace auto type {
/**
A MAC Address as used in the Internet Protocol
*/
struct MACAddress {
u8 bytes[6];
} [[sealed, format("type::impl::format_mac_address")]];
/**
A MAC Address as used in the Internet Protocol
*/
struct MACAddress {
u8 bytes[6];
} [[sealed, format("type::impl::format_mac_address")]];
namespace impl {
namespace impl {
fn format_mac_address(MACAddress address) {
return std::format("{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
address.bytes[0],
address.bytes[1],
address.bytes[2],
address.bytes[3],
address.bytes[4],
address.bytes[5]);
};
return std::format("{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
address.bytes[0],
address.bytes[1],
address.bytes[2],
address.bytes[3],
address.bytes[4],
address.bytes[5]);
};
}
}
}

View File

@@ -1,13 +1,33 @@
#include <std/string.pat>
#include <std/sys.pat>
#include <std/io.pat>
#include <std/ctype.pat>
import std.string;
import std.sys;
import std.io;
import std.ctype;
/*!
Types used to parse and enforce specific magic numbers
*/
namespace type {
namespace auto type
{
/**
Escapes all bytes in a string to only contain printable characters. All non-printable bytes will be transformed to sequences in the form form \xFF
@param value Byte array to escape
@return Escaped string
*/
fn escape_bytes(ref auto value) {
str result;
for (u32 i = 0, i < sizeof(value), i += 1)
{
char c = value[i];
if (std::ctype::isprint(c))
result += c;
else
result += std::format("\\x{:02X}", u8(c));
}
return result;
};
/**
A Magic number. Throws an error if the magic number does not match the expected value
@@ -15,24 +35,11 @@ namespace type {
*/
struct Magic<auto ExpectedValue> {
char value[std::string::length(ExpectedValue)];
std::assert(value == ExpectedValue, std::format("Invalid magic value! Expected \"{}\", got \"{}\".", ExpectedValue, value));
std::assert(value == ExpectedValue, std::format("Invalid magic value! Expected \"{}\", got \"{}\" at position 0x{:X}", type::escape_bytes(ExpectedValue), type::escape_bytes(value), $ - std::string::length(ExpectedValue)));
} [[sealed, format("type::impl::format_magic")]];
namespace impl {
fn format_magic(ref auto magic) {
str result;
for (u32 i = 0, i < sizeof(magic.value), i += 1) {
char c = magic.value[i];
if (std::ctype::isprint(c))
result += c;
else
result += std::format("\\x{:02X}", u8(c));
}
return std::format("\"{}\"", result);
return std::format("\"{}\"", type::escape_bytes(magic.value));
};
}
}

View File

@@ -1,53 +1,53 @@
#include <std/mem.pat>
import std.mem;
/*!
Types dealing with various kinds of resource paths
Types dealing with various kinds of resource paths
*/
namespace type {
namespace auto type {
/**
Type representing a single path segment. Use the `Path` type instead of using this on its own
@tparam Delimeter The delimeter sequence used to separate two path segments
*/
struct PathSegment<auto Delimeter> {
char string[while(std::mem::read_string($, std::string::length(Delimeter)) != Delimeter && std::mem::read_unsigned($, 1) != 0x00)];
char separator [[hidden]];
if (separator == 0x00) {
$ -= 1;
break;
}
} [[sealed, format("type::impl::format_path_segment")]];
/**
A generic type representing a path with an arbitrary delimeter
@tparam Delimeter The delimeter sequence used to separate two path segments
*/
struct Path<auto Delimeter> {
PathSegment<Delimeter> segments[while(true)];
} [[format("type::impl::format_path")]];
/**
A type representing a Unix path using a '/' forwardslash as delimeter
*/
using UnixPath = Path<"/">;
/**
Type representing a single path segment. Use the `Path` type instead of using this on its own
@tparam Delimiter The delimiter sequence used to separate two path segments
*/
struct PathSegment<auto Delimiter> {
char string[while(std::mem::read_string($, std::string::length(Delimiter)) != Delimiter && std::mem::read_unsigned($, 1) != 0x00)];
char separator [[hidden]];
if (separator == 0x00) {
$ -= 1;
break;
}
} [[sealed, format("type::impl::format_path_segment")]];
/**
A generic type representing a path with an arbitrary delimiter
@tparam Delimiter The delimiter sequence used to separate two path segments
*/
struct Path<auto Delimiter> {
PathSegment<Delimiter> segments[while(true)];
} [[format("type::impl::format_path")]];
/**
A type representing a Unix path using a '/' forward slash as delimiter
*/
using UnixPath = Path<"/">;
/**
A type representing a DOS path using a '\' backslash as delimeter
*/
using DOSPath = Path<"\\">;
namespace impl {
fn format_path_segment(ref auto segment) {
return segment.string;
};
fn format_path(ref auto path) {
return std::mem::read_string($, sizeof(path));
};
}
/**
A type representing a DOS path using a '\\' backslash as delimiter
*/
using DOSPath = Path<"\\">;
namespace impl {
fn format_path_segment(ref auto segment) {
return segment.string;
};
fn format_path(ref auto path) {
return std::mem::read_string($, sizeof(path));
};
}
}

View File

@@ -1,10 +1,10 @@
#include <std/io.pat>
import std.io;
/*!
Types used to pretty print size values
*/
namespace type {
namespace auto type {
/**
A generic size type which displays its value in Bytes (or kiB, MiB, GiB, TiB, PiB, EiB if larger)

View File

@@ -1,21 +1,21 @@
#pragma once
#include <std/io.pat>
#include <std/time.pat>
import std.io;
import std.time;
/*!
Types used to decode various different time formats
*/
namespace type {
namespace auto type {
/**
A 32 bit Unix time value
*/
using time32_t = u32 [[format("type::impl::format_time_t")]];
/**
Alias name for `time32_t`
Alias name for `time32_t`
*/
using time_t = time32_t;
@@ -34,6 +34,11 @@ namespace type {
*/
using DOSTime = u16 [[format("type::impl::format_dostime")]];
/**
A 64bit FILETIME value
*/
using FILETIME = u64 [[format("type::impl::format_filetime_as_unix")]];
namespace impl {
fn format_time_t(u128 value) {
@@ -48,6 +53,10 @@ namespace type {
return std::time::format_dos_time(std::time::to_dos_time(value));
};
fn format_filetime_as_unix(u64 value) {
return std::time::filetime_to_unix(value);
};
}
}

View File

@@ -5,7 +5,7 @@
*/
// Explicitly don't add these types to the `type` namespace for usability
// namespace type {
// namespace auto type {
// using char = s8;
using byte = s8;

View File

@@ -5,7 +5,7 @@
*/
// Explicitly don't add these types to the `type` namespace for usability
// namespace type {
// namespace auto type {
using uint8_t = u8;
using uint16_t = u16;

View File

@@ -5,7 +5,7 @@
*/
// Explicitly don't add these types to the `type` namespace for usability
// namespace type {
// namespace auto type {
using le16 = le u16;
using be16 = be u16;

View File

@@ -5,7 +5,7 @@
*/
// Explicitly don't add these types to the `type` namespace for usability
// namespace type {
// namespace auto type {
// using u8 = u8;
// using u16 = u16;

View File

@@ -5,7 +5,7 @@
*/
// Explicitly don't add these types to the `type` namespace for usability
// namespace type {
// namespace auto type {
using BYTE = u8;
using WORD = u16;

View File

@@ -1,4 +1,4 @@
# A libmagic database containing definition for PE files used by MS-DOS based systems
# A libmagic database containing definition for PE files used by MS-DOS/Windows based systems
# MS-DOS Portable Executable
0x0 string/b MZ MS-DOS Binary

1141
patterns/3ds.hexpat Normal file

File diff suppressed because it is too large Load Diff

102
patterns/7z.hexpat Normal file
View File

@@ -0,0 +1,102 @@
#pragma description 7z Archive
#pragma MIME application/x-7z-compressed
import std.io;
import std.mem;
import std.math;
enum Type:u8{
startPosition = 0x00, // Start position
sizeStartHeader = 0x20, // Size of start Header
};
enum TypeB:u48{
sevenZipSignature = 0x1C27AFBC7A37, // Defining 7z signature
};
struct StartHeader {
// File signature
u48 signature [[color("FF0000")] ];
// Version format
u16 formatVersion [[color("00FF00")]];
// CRC start header
u32 crcOfTheFollowing20Bytes [[color("0000FF")]];
// Relative offset of End Header
u64 relativeOffsetEndHeader [[color("FFFF00")]];
// Length of End Header
u64 theLengthOfEndHeader [[color("00FFFF")]];
// CRC of End Ender
u32 crcOftheEndHeader [[color("FF00FF")]];
// File size calculation
u64 fileSize = relativeOffsetEndHeader + theLengthOfEndHeader + Type::sizeStartHeader;
// Absolute offset calculation End Header
u64 startEndHeader = relativeOffsetEndHeader + Type::sizeStartHeader;
};
StartHeader startheader @ Type::startPosition;
struct CompressedData {
// Start of compressed data
u8 startOfCompressedData[4] [[color("C0C0C0")]];
};
CompressedData compresseddata @ Type::sizeStartHeader;
struct EndHeader {
// Set padding to place End Header in right position
padding[startheader.relativeOffsetEndHeader];
// Mark link to meta block
u8 linkToMetaBlock [[color("FF0000")]];
// Mark all End Header
char fullEndHeader[startheader.theLengthOfEndHeader] [[color("63954A")]];
// Detect LZMA signature
u64 lzmaSignaturePosition = std::mem::find_sequence_in_range(0, addressof(fullEndHeader), addressof(fullEndHeader) + sizeof(fullEndHeader), 0x23, 0x03, 0x01, 0x01, 0x05, 0x5D);
// Mark positions if LZMA signature was detected
if(lzmaSignaturePosition != 0xFFFFFFFFFFFFFFFF){
u48 lzmaSignature @ lzmaSignaturePosition [[color("0000FF")]];
}
};
EndHeader endheader @ Type::sizeStartHeader;
// Check 7z type
if(startheader.signature == TypeB::sevenZipSignature){
std::print("It is a 7z File Type");
}else{
std::print("The file is not 7z type");
}
std::print("Format Version {} ",startheader.formatVersion);
// Version verification
if(startheader.formatVersion == 0x0400){
std::print("Major Version 0x00 || 0 - Minor Version 0x04 || 4");
}
// Verification of the compressed method is LZMA, Bzip2 or LZMA2
if(compresseddata.startOfCompressedData[0] == Type::startPosition){
std::print("Compressed Method LZMA");
}else if(compresseddata.startOfCompressedData[0] == 0x42){
std::print("Compressed Method Bzip2");
}else{
std::print("Compressed Method LZMA2");
}
std::print("CRC Start Header 0x{:X}",startheader.crcOfTheFollowing20Bytes);
std::print("CRC End Header 0x{:X} ", startheader.crcOftheEndHeader);
std::print("CompressedData length 0x{:X} || {} bytes ",startheader.relativeOffsetEndHeader, startheader.relativeOffsetEndHeader);
std::print("Relative Offset of End Header 0x{:X} || {} bytes",startheader.relativeOffsetEndHeader, startheader.relativeOffsetEndHeader);
std::print("Offset to start End Header 0x{:X} || {} bytes",startheader.startEndHeader,startheader.startEndHeader);
std::print("End Header length 0x{:X} || {} bytes",startheader.theLengthOfEndHeader,startheader.theLengthOfEndHeader);
std::print("File size 0x{:X} || {} bytes",startheader.fileSize, startheader.fileSize);

370
patterns/Crashlvl.hexpat Normal file
View File

@@ -0,0 +1,370 @@
#pragma author AdventureT
#pragma description Crash Bandicoot - Back in Time (fan game) User created level
#pragma history
#pragma 0.3 2024-05-15 Added support for version 0.95
#pragma 0.2 2023-10-29 Added support for version 0.94c
#pragma 0.1 2023-04-25 Initial support
// Supports all versions till 0.95, newer versions might be compatible!
import type.magic;
import std.string;
import std.array;
struct Header {
type::Magic<"CRASHLVL"> magic;
u8 version;
if (version >= 4) {
std::string::SizedString<u8> gameVersion;
}
std::string::SizedString<u8> levelName;
std::string::SizedString<u8> author;
};
// Background Music
enum BGM : u32 {
None,
BonusBGM,
CrashCreatorBGM,
MainMenuBGM,
WarpRoomBGM,
Level01BGM,
Level02BGM,
Level03BGM,
Level04BGM,
Level05BGM,
SewerBGM,
EgyptBGM,
NBrioBGM
};
enum BGMV2 : u32 {
None,
N_TropyBGM,
CrashCreatorBGM,
MainMenuBGM,
WarpRoomBGM,
Jungle01BGM,
SnowBGM,
RiverBGM,
FutureBGM,
LabBGM,
SewerBGM,
EgyptBGM,
NBrioBGM,
AdventureBGM,
SpyBGM,
ChaseBGM,
TrialsBGM,
SpaceBGM,
Jungle02BGM,
RipperBGM,
TheGreatWallBGM,
RoadToSomewhereBGM,
LavaKoalaBGM,
CortexBGM,
CyberCortexBGM,
ArabicBGM,
N_Tropy2BGM,
JazzBGM,
Space2BGM,
TawnaBonusBGM,
CortexPowerBGM,
ArabicBonusBGM,
EgyptBonusBGM,
FutureBonusBGM,
LostCityBGM,
PolarBGM,
RiverBonusBGM,
RuinsBonusBGM,
SewerBonusBGM,
SnowBonusBGM,
RoadToRuinBGM,
NGinBGM,
Arabia01BGM,
Arabia02BGM,
BashBGM,
Cortex02BGM
};
// v0.95
enum BGMV3 : BGMV2 {
None,
N_TropyBGM,
CrashCreatorBGM,
MainMenuBGM,
WarpRoomBGM,
Jungle01BGM,
SnowBGM,
RiverBGM,
FutureBGM,
LabBGM,
SewerBGM,
EgyptBGM,
NBrioBGM,
AdventureBGM,
SpyBGM,
ChaseBGM,
TrialsBGM,
SpaceBGM,
Jungle02BGM,
RipperBGM,
TheGreatWallBGM,
RoadToSomewhereBGM,
LavaKoalaBGM,
CortexBGM,
CyberCortexBGM,
ArabicBGM,
N_Tropy2BGM,
JazzBGM,
Space2BGM,
TawnaBonusBGM,
CortexPowerBGM,
ArabicBonusBGM,
EgyptBonusBGM,
FutureBonusBGM,
LostCityBGM,
PolarBGM,
RiverBonusBGM,
RuinsBonusBGM,
SewerBonusBGM,
SnowBonusBGM,
RoadToRuinBGM,
NGinBGM,
Arabia01BGM,
Arabia02BGM,
BashBGM,
Cortex02BGM,
MedievalBGM,
PreHistoricBGM,
UnderWaterBGM,
BrioRevisitedBGM,
EgyptChaseBGM,
RuinsLoopBGM,
DingoSynthBGM
};
enum Type : u32 {
Unset,
Flashback,
Trial
};
enum TypeV2 : u32 {
Practice,
Flashback,
Trial,
Adventure
};
enum Skybox : u32 {
Night,
Day,
Storm,
Dawn
};
enum SkyboxV2 : u32 {
Default = 1,
Briolab,
Fort,
Moon,
Toxic,
AboutRight,
Crash1Island,
Arabia,
RoadToRuin,
Black
};
// 0.95
enum SkyboxV3 : u32 {
Default = 1,
Briolab,
Fort,
Moon,
Toxic,
AboutRight,
Crash1Island,
Arabia,
RoadToRuin,
MotorcycleDay,
MotorcycleNoon,
MotorcycleMoon,
MotorcycleNight,
Black
};
enum Scenery : u32 {
None,
FutureTense,
Forest,
Waterfall,
Snow,
Fortress
};
enum SceneryV2 : u32 {
None,
FutureTense,
Forest,
Waterfall,
None2,
Fortress,
None3,
Lava,
TheGreatGate,
Mountain,
KoalaKong,
SunsetVista,
HangemHigh,
Sphynxinator,
Tunnel,
Pipes
};
enum SceneryV4 : u32 {
None,
FutureTense,
Forest,
Waterfall,
Snow,
Fortress,
None2,
Lava,
TheGreatGate,
Mountain,
KoalaKong,
SunsetVista,
HangemHigh,
Sphynxinator,
Tunnel,
Pipes
};
// 0.95
enum SceneryV5 : u32 {
None,
FutureTense,
Forest,
Waterfall,
Snow,
Fortress,
None2,
Lava,
TheGreatGate,
Mountain,
KoalaKong,
SunsetVista,
HangemHigh,
Sphynxinator,
Tunnel,
Pipes,
Medieval,
FutureCity,
TinyArena,
HeavyMachinery,
CrystalCave,
MedievalWithHouses,
CortexBonusChamber
};
enum Weather : u32 {
Default,
Snow,
Rain
};
// 0.95
enum WeatherV2 : u32 {
Default,
Snow,
Rain,
Night,
UnderWater
};
struct Options {
// Type
if (header.version > 1) {
TypeV2 type;
}
else {
Type type;
}
// Skybox
if (header.version > 1) {
if (header.gameVersion == "0.95") {
SkyboxV3 skybox;
}
else {
SkyboxV2 skybox;
}
}
else {
Skybox skybox;
}
// Scenery
if (header.version == 1) {
Scenery scenery;
}
else if (header.version > 1 && header.version < 4) {
SceneryV2 scenery;
}
else {
if (header.gameVersion == "0.95") {
SceneryV5 skybox;
}
else {
SceneryV4 skybox;
}
}
// Weather
if (header.version > 2) {
if (header.gameVersion == "0.95") {
WeatherV2 weather;
}
else {
Weather weather;
}
}
// Background music
if (header.version > 1) {
BGMV2 bgm;
}
else {
BGM bgm;
}
// Time Trial
if (type == Type::Trial) {
u32 timeTrialTicksBronze;
u32 timeTrialTicksSilver;
u32 timeTrialTicksGold;
}
};
struct Object {
std::string::SizedString<u8> objName;
if (header.version > 1) {
u16 x;
u16 y;
bool hasMetafields;
if (hasMetafields) {
u16 numOfMetafields;
u8 metafields[numOfMetafields];
}
}
else {
u32 x;
u32 y;
}
};
struct Objects{
u32 objCount;
std::Array<Object, objCount> objArray;
};
Header header @ $;
Options options @ $;
Objects objects @ $;

197
patterns/adts.hexpat Normal file
View File

@@ -0,0 +1,197 @@
#pragma author zhoubo
#pragma description AAC ADTSn (Audio Data Transport Stream) Audio
#pragma magic [ FF F? ] @ 0x00
#pragma pattern_limit 0xFFFFFF
// History
// 0.4 2024-02-12 zhoubo: Porting from 010 Editor Templates.
// 0.3 2024-02-09 zhoubo: use BitfieldDisablePadding(Unpadded Bitfields) for odd header bytes(7,9 bytes) color, and remove FSeek.
// 0.2 2024-02-05 zhoubo: fix some comment & color.
// 0.1 2022-06-13 zhoubo: Init release. only ADTS, not support ADIF,LATM.
// More information available at:
// 1. https://wiki.multimedia.cx/index.php?title=ADTS
// 2. https://en.wikipedia.org/wiki/Advanced_Audio_Coding
// 3. https://en.wikipedia.org/wiki/AAC
// 4. https://juejin.cn/post/7032170229732442148
#pragma endian big
#include <std/sys.pat>
#include <std/core.pat>
fn GetMPEGVersionComment(auto MPEG_Version)
{
str comment = "";
match (MPEG_Version)
{
(0): comment = "MPEG-4";
(1): comment = "MPEG-2";
}
return comment;
};
fn GetProtectionAbsentComment(auto Protection_absence)
{
str comment = "";
match (Protection_absence)
{
(0): comment = "ADTS has 9 bytes with CRC";
(1): comment = "ADTS has 7 bytes without CRC";
}
return comment;
};
fn GetProfileComment(auto Profile)
{
str comment = "";
match (Profile)
{
(0x00): comment = "AAC Main";
(0x01): comment = "AAC LC (Low Complexity)";
(0x10): comment = "AAC SSR (Scalable Sample Rate)";
(0x11): comment = "AAC LTP (Long Term Prediction)";
}
return comment;
};
fn GetSamplingFrequencyIndexComment(auto Sampling_frequency_index)
{
str comment = "";
match (Sampling_frequency_index)
{
(0x0): comment = "96000Hz";
(0x1): comment = "88200Hz";
(0x2): comment = "64000Hz";
(0x3): comment = "48000Hz";
(0x4): comment = "44100Hz";
(0x5): comment = "32000Hz";
(0x6): comment = "24000Hz";
(0x7): comment = "22050Hz";
(0x8): comment = "16000Hz";
(0x9): comment = "12000Hz";
(0xa): comment = "11025Hz";
(0xb): comment = "8000Hz";
(0xc): comment = "7350Hz";
(0xd): comment = "Reserved";
(0xe): comment = "Reserved";
(0xf): comment = "FORBIDDEN (malformed)";
}
return comment;
};
fn GetChannelConfigurationComment(auto Channel_configuration)
{
str comment = "";
match (Channel_configuration)
{
(0): comment = "Defined in AOT Specifc Config";
(1): comment = "1 channel: front-center";
(2): comment = "2 channels: front-left, front-right";
(3): comment = "3 channels: front-center, front-left, front-right";
(4): comment = "4 channels: front-center, front-left, front-right, back-center";
(5): comment = "5 channels: front-center, front-left, front-right, back-left, back-right";
(6): comment = "6 channels: front-center, front-left, front-right, back-left, back-right, LFE-channel";
(7): comment = "8 channels: front-center, front-left, front-right, side-left, side-right, back-left, back-right, LFE-channel";
}
return comment;
};
fn GetBufferFullnessComment(auto ADTS_buffer_fullness)
{
str comment = "";
match (ADTS_buffer_fullness)
{
(0x7FF): comment = "VBR (most software ignore this field)";
(_): comment = "rate..?? (most software ignore this field)";
}
return comment;
};
fn GetRawDataBlockComment(auto Number_of_AAC_frames_minus_1)
{
str comment = "";
match (Number_of_AAC_frames_minus_1)
{
(0x0): comment = "has 1 AAC data block";
(_): comment = "data block number + 1";
}
return comment;
};
//-----------------------------------
// Define structures used in AAC files
//
// [1.adts_fixed_header information]
// Syncword: 12bits, sync header, always 0xFFF。
// MPEG_Version: 1bit, 0 means MPGE-4, 1 means MPGE-2
// Layer: 2bits, alwayas ”00”
// Protection_absence: 1bit, 0 means ADTS Header 9 bytes; 1 means ADTS Header 7 bytes
// Profile: 2bit, AAC level : Main,LC,SSR,LTP
// Sampling_frequency_index: 4bits, Sampling Frequencies
// Private_bit: 1bit
// Channel_configuration: 3bits, channel number...
// Originality: 1bit
// Home: 1bit
//
// [2.adts_variable_header information]
// Copyright_id_bit: 1bit
// Copyright_id_start: 1bit
// AAC_frame_length: 13bits, AAC frame length : ADTS Header(7 or 9 bytes) + sizeof(AAC Frame)
// ADTS_buffer_fullness: 11bits, 0x7FF means VBR
// Number_of_AAC_frames_minus_1: 2bits, ADTS Frame numbers : Number_of_AAC_frames_minus_1 + 1
//
// [3.CRC information]
// CRC16: 16bits, when Protection_absence=0
bitfield ADTS_HEADER
{
// ADTS_FIXED_HEADER
Syncword : 12 [[color("00FF00"), comment("always 0xFFF")]];
MPEG_Version : 1 [[color("00FF00"), comment(GetMPEGVersionComment(this))]];
Layer : 2 [[color("00FF00"), comment("always 0")]];
Protection_absence : 1 [[color("00FF00"), comment(GetProtectionAbsentComment(this))]];
Profile : 2 [[color("0000FF"), comment(GetProfileComment(this))]];
Sampling_frequency_index : 4 [[color("0000FF"), comment(GetSamplingFrequencyIndexComment(this))]];
Private_bit : 1 [[color("0000FF")]];
Channel_configuration : 3 [[color("0000FF"), comment(GetChannelConfigurationComment(this))]];
Originality : 1 [[color("0000FF")]];
Home : 1 [[color("0000FF")]];
// ADTS_VARIABLE_HEADER
Copyright_id_bit : 1 [[color("0000FF")]];
Copyright_id_start : 1 [[color("0000FF")]];
AAC_frame_length : 13 [[color("0000FF")]];
ADTS_buffer_fullness : 11 [[color("0000FF"), comment(GetBufferFullnessComment(this))]];
Number_of_AAC_frames_minus_1 : 2 [[color("0000FF"), comment(GetRawDataBlockComment(this))]];
// ADTS_CRC_HEADER
if (0 == Protection_absence) // Header with CRC
{
u16 CRC16 [[color("FFFF00")]];
}
else // Header without CRC
{
}
};
struct ADTS_FRAME
{
ADTS_HEADER Header;
if (0 == Header.Protection_absence) // Header with CRC 2 bytes
{
u8 Data[Header.AAC_frame_length - 9] [[color("000000")]];
}
else // Header without CRC
{
u8 Data[Header.AAC_frame_length - 7] [[color("000000")]];
}
};
//---------------------------------------------
ADTS_FRAME adtsFrame[while(!std::mem::eof())] @ 0x00;

View File

@@ -1,7 +1,10 @@
#pragma author WerWolv
#pragma description Nintendo Switch Atmosphère CFW Fatal Error log
#pragma endian little
#include <std/io.pat>
#include <std/sys.pat>
import std.io;
import std.sys;
#define ATMOSPHERE_REBOOT_TO_FATAL_MAGIC "AFE2"
#define ATMOSPHERE_REBOOT_TO_FATAL_MAGIC_1 "AFE1"
@@ -49,8 +52,8 @@ std::assert(ctx.magic == ATMOSPHERE_REBOOT_TO_FATAL_MAGIC ||
ctx.magic == ATMOSPHERE_REBOOT_TO_FATAL_MAGIC_1 ||
ctx.magic == ATMOSPHERE_REBOOT_TO_FATAL_MAGIC_0,
"File is not a valid Atmosphere fatal error binary!");
std::assert_warn(ctx.magic == ATMOSPHERE_REBOOT_TO_FATAL_MAGIC,
std::assert_warn(ctx.magic == ATMOSPHERE_REBOOT_TO_FATAL_MAGIC,
"Atmosphere fatal error binary is for an older version!");

66
patterns/ani.hexpat Normal file
View File

@@ -0,0 +1,66 @@
#pragma description Windows animated cursor
#pragma MIME application/x-navi-animation
#pragma endian little
import std.io;
import std.mem;
bitfield HeaderFlags {
icon : 1;
sequence : 1;
padding: 30;
};
struct anih {
u32 struct_size;
u32 stored_frames;
u32 animation_steps;
u32 w;
u32 h;
u32 bits;
u32 planes;
u32 default_jiffies;
HeaderFlags flags;
};
struct rate {
u32 jiffies[parent.size / 4];
};
struct seq {
u32 index[parent.size / 4];
};
struct RiffChunk {
char signature[4];
u32 size;
if (signature == "RIFF" || signature == "LIST") {
char type[4];
RiffChunk chunks[while($ - addressof(type) < size)];
} else if (signature[0] == 'I' && parent.type == "INFO") {
char info[size];
} else if (signature == "anih") {
anih anih [[inline]];
} else if (signature == "rate") {
rate rate [[inline]];
} else if (signature == "seq ") {
seq seq [[inline]];
} else {
std::mem::Bytes<size> data;
}
padding[size % 2];
} [[format_read("read_chunk")]];
fn read_chunk(RiffChunk chunk) {
if (chunk.signature == "RIFF" || chunk.signature == "LIST") {
return std::format("{}<{}> ({})", chunk.signature, chunk.type, chunk.size);
} else {
str ret = std::format("{} ({})", chunk.signature, chunk.size);
try {
ret += std::format(" \"{}\"", chunk.info);
} catch {}
return ret;
}
};
RiffChunk riff @ 0;

View File

@@ -1,8 +1,11 @@
#pragma author WerWolv
#pragma description GNU Static library archive
#pragma MIME application/x-archive
#include <std/string.pat>
#include <std/mem.pat>
#include <std/sys.pat>
import std.string;
import std.mem;
import std.sys;
struct ARFile {
char file_name[16];
@@ -12,7 +15,7 @@ struct ARFile {
char file_mode[8];
char file_size[10];
u16 end_marker;
if (end_marker == 0x0A60) {
u8 data[std::string::parse_int(this.file_size, 10)];
padding[sizeof(data) & 1];
@@ -20,6 +23,9 @@ struct ARFile {
};
char signature[8] @ 0x00;
if (signature == "!<arch>\r") {
std::error("Archive file got corrupted due to CRLF line ending conversion!");
}
std::assert(signature == "!<arch>\n", "File is not a valid archive!");
ARFile files[while($ < std::mem::size())] @ $;

26
patterns/arc.hexpat Normal file
View File

@@ -0,0 +1,26 @@
#pragma author DexrnZacAttack
#pragma description Minecraft LCE ARC File
#pragma endian big
import std.string;
#ifdef __IMHEX__
import hex.core;
#endif
struct Table {
u16 nameSize;
char fileName[nameSize];
u32 offset;
u32 size;
u8 file[size] @ offset;
#ifdef __IMHEX__
hex::core::add_virtual_file(fileName, file);
#endif
} [[name(std::string::to_string(fileName))]];
struct ARC {
u32 count;
Table table[count];
};
ARC arc @ 0x00;

36
patterns/aria2.hexpat Normal file
View File

@@ -0,0 +1,36 @@
#pragma author itsmeow
#pragma description aria2 Control File
#pragma endian big
/*
Format sourced from:
https://aria2.github.io/manual/en/html/technical-notes.html#control-file-aria2-format
Version 0 files are not supported by default
However parsing one is as simple as changing to #pragma endian ittle
and resolving any errors resulting from that by adding be prefixes to struct fields.
*/
struct AriaInFlight {
u32 index;
u32 length;
u32 bitfield_piece_length;
u8 bitfield_p[bitfield_piece_length];
};
struct AriaHeader {
u16 version;
u32 extension;
u32 infohash_length;
u8 infohash[infohash_length];
u32 piece_length;
u64 total_length;
u64 upload_length;
u32 bitfield_length;
u8 bitfield_d[bitfield_length];
u32 inflight_count;
AriaInFlight inflights[inflight_count];
};
AriaHeader aria_header @ 0x00;

View File

@@ -1,7 +1,10 @@
#pragma author WerWolv
#pragma description ARM Cortex M Vector Table Layout
#pragma endian little
#include <std/io.pat>
#include <std/mem.pat>
import std.io;
import std.mem;
#define VTOR 0x00000000
#define EXTERNAL_INTERRUPT_COUNT 64
@@ -37,21 +40,21 @@ VectorTable vector_table @ VTOR;
fn main() {
u32 table_size = sizeof(vector_table);
u32 default_handler_address = 0x00;
for (u32 i = 4, i < table_size, i = i + 4) {
u32 occurrences = 0;
for (u32 j = 4, j < table_size, j = j + 4) {
if (std::mem::read_unsigned(i, 4) == std::mem::read_unsigned(j, 4)) {
occurrences = occurrences + 1;
if (occurrences > 1)
default_handler_address = std::mem::read_unsigned(i, 4);
}
}
}
if (default_handler_address != 0x00)
std::print("Default Handler implementation at 0x{:08X}", default_handler_address);
};

1
patterns/bastion Submodule

Submodule patterns/bastion added at e6deed433c

View File

@@ -1,73 +1,76 @@
#pragma MIME application/x-bittorrent
#include <std/ctype.pat>
#include <std/mem.pat>
#include <std/string.pat>
namespace bencode {
struct ASCIIDecimal {
char value[while(std::ctype::isdigit(std::mem::read_unsigned($, 1)))];
} [[sealed, format("bencode::format_ascii_decimal"), transform("bencode::format_ascii_decimal")]];
fn format_ascii_decimal(ASCIIDecimal adsasd) {
return std::string::parse_int(adsasd.value, 10);
};
enum Type : u8 {
Integer = 'i',
Dictionary = 'd',
List = 'l',
String0 = '0',
String1 = '1',
String2 = '2',
String3 = '3',
String4 = '4',
String5 = '5',
String6 = '6',
String7 = '7',
String8 = '8',
String9 = '9'
};
struct String {
ASCIIDecimal length;
char separator [[hidden]];
char value[length];
} [[sealed, format("bencode::format_string"), transform("bencode::format_string")]];
fn format_string(String string) {
return string.value;
};
using Bencode;
using Value;
struct DictionaryEntry {
String key;
Value value;
};
struct Value {
Type type;
if (type == Type::Dictionary) {
DictionaryEntry entry[while(std::mem::read_unsigned($, 1) != 'e')];
} else if (type == Type::Integer) {
ASCIIDecimal value;
char end;
} else {
$ -= 1;
String value;
}
};
struct Bencode {
Value value[while(!std::mem::eof())] [[inline]];
char end;
};
}
bencode::Bencode bencode @ 0x00;
#pragma author WerWolv
#pragma description Torrent data (Bencode)
#pragma MIME application/x-bittorrent
import std.ctype;
import std.mem;
import std.string;
namespace bencode {
struct ASCIIDecimal {
char value[while(std::ctype::isdigit(std::mem::read_unsigned($, 1)))];
} [[sealed, format("bencode::format_ascii_decimal"), transform("bencode::format_ascii_decimal")]];
fn format_ascii_decimal(ASCIIDecimal adsasd) {
return std::string::parse_int(adsasd.value, 10);
};
enum Type : u8 {
Integer = 'i',
Dictionary = 'd',
List = 'l',
String0 = '0',
String1 = '1',
String2 = '2',
String3 = '3',
String4 = '4',
String5 = '5',
String6 = '6',
String7 = '7',
String8 = '8',
String9 = '9'
};
struct String {
ASCIIDecimal length;
char separator [[hidden]];
char value[length];
} [[sealed, format("bencode::format_string"), transform("bencode::format_string")]];
fn format_string(String string) {
return string.value;
};
using Bencode;
using Value;
struct DictionaryEntry {
String key;
Value value;
};
struct Value {
Type type;
if (type == Type::Dictionary) {
DictionaryEntry entry[while(std::mem::read_unsigned($, 1) != 'e')];
} else if (type == Type::Integer) {
ASCIIDecimal value;
char end;
} else {
$ -= 1;
String value;
}
};
struct Bencode {
Value value[while(!std::mem::eof())] [[inline]];
char end;
};
}
bencode::Bencode bencode @ 0x00;

80
patterns/bgcode.hexpat Normal file
View File

@@ -0,0 +1,80 @@
#pragma author Shadlock0133 (aka Aurora)
#pragma description Prusa Binary G-Code
import type.magic;
import std.mem;
enum ChecksumType : u16 {
None,
CRC32,
};
enum BlockType : u16 {
FileMetadata,
GCode,
SlicerMetadata,
PrinterMetadata,
PrintMetadata,
Thumbnail,
};
enum Compression : u16 {
None,
Deflate,
Heatshrink11_4,
Heatshrink12_4,
};
enum Encoding : u16 {
Ini,
};
enum ImageFormat : u16 {
Png,
Jpg,
Qoi,
};
struct Header {
type::Magic<"GCDE"> magic;
u32 version;
ChecksumType checksum_type;
};
Header header @ 0;
std::assert(header.version == 1, "only version 1 supported");
struct Block {
BlockType type;
Compression compression;
u32 uncompressed_size;
auto size = uncompressed_size;
if (compression != Compression::None) {
u32 compressed_size;
size = compressed_size;
}
match (type) {
(BlockType::FileMetadata
| BlockType::PrinterMetadata
| BlockType::PrintMetadata
| BlockType::SlicerMetadata): {
Encoding encoding;
}
(BlockType::Thumbnail): {
ImageFormat image_format;
u16 width;
u16 height;
}
(BlockType::GCode): {
u16;
}
(_): { std::assert(false, "unknown type"); }
}
u8 data[size];
match (header.checksum_type) {
(ChecksumType::None): {}
(ChecksumType::CRC32): { u32 checksum; }
}
};
Block blocks[while(!std::mem::eof())] @ $;

24
patterns/binka.hexpat Normal file
View File

@@ -0,0 +1,24 @@
#pragma author DexrnZacAttack
#pragma description RAD Game Tools BINKA (Bink Audio)
#pragma magic [31 46 43 42] @ 0x00
import std.string;
import std.math;
import type.magic;
fn getDuration(u32 duration_ts, u32 sample_rate) {
return float(duration_ts) / float(sample_rate);
};
struct Binka {
type::Magic<"1FCB"> magic;
u8; // can't get this to change anything when using ffprobe
u8 channel_count [[name(std::format("Channel Count: {}", this))]];
u16 sample_rate [[name(std::format("Sample Rate: {}", this))]];
u32 duration_ts [[name(std::format("Duration: {}s", std::math::floor(getDuration(this, sample_rate))))]];
u32;
u32 size [[name(std::format("File Size: {} bytes", this))]];
u8 data[size - 20];
};
Binka binka @ 0x00;

196
patterns/blend.hexpat Normal file
View File

@@ -0,0 +1,196 @@
#pragma description Blender file
#pragma magic [42 4C 45 4E 44 45 52] @ 0x00
/*
* References:
* https://projects.blender.org/blender/blender
* https://github.com/facebook/zstd/blob/master/contrib/seekable_format/zstd_seekable_compression_format.md
*
* Refer to the following files/structs:
* source/blender/blenloader/intern/writefile.cc
* source/blender/blenkernel/BKE_main.hh BlendThumbnail
* source/blender/makesdna/DNA_sdna_types.h BHead
*/
// Increased the pattern limit to be able to evaluate all pixels of the embedded thumbnail.
#pragma pattern_limit 1000000
#ifdef __IMHEX__
import hex.dec;
#endif
import std.core;
import std.io;
import std.mem;
import std.string;
import std.sys;
import type.color;
import type.magic;
// Useful for extracting the thumbnail if the rest of the blend file is corrupted or truncated.
bool quitAfterThumbnailIsParsed in;
// Allow the pattern evaluator to skip the thumbnail e.g. if evaluation takes too long.
bool skipThumbnail in;
struct BHead<Ptr> {
char code[4];
s32 len;
Ptr old;
s32 SDNAnr;
s32 nr;
// ENDB marks the last data block in the file.
if (code == "ENDB") {
break;
}
};
struct ThumbnailLine<auto width> {
type::RGBA8 pixels[width];
};
fn copyThumbnail(u32 height, ref auto lines, std::mem::Section target) {
for (s64 l = (height - 1), l >= 0, l = l - 1) {
u64 currentSectionSize = std::mem::get_section_size(target);
// Append the current line to section.
std::mem::copy_value_to_section(lines[l], target, currentSectionSize);
}
};
struct Thumbnail {
u32 width;
u32 height;
u128 size = width * height;
ThumbnailLine<width> lines[height];
// Generate the thumbnail section.
std::mem::Section thumbnailFlipped = std::mem::create_section("thumbnail");
copyThumbnail(height, lines, thumbnailFlipped);
type::RGBA8 image[size] @ 0x00 in thumbnailFlipped;
}
#ifdef __IMHEX__
[[hex::visualize("bitmap", image, width, height)]]
#endif
;
struct DataBlock<Ptr> {
BHead<Ptr> bHead;
if (bHead.SDNAnr == 0 && bHead.code == "TEST") {
if (skipThumbnail) {
u8 thumbnail[bHead.len]; // Interpret as raw binary data.
} else {
Thumbnail thumbnail;
auto thumbnailSize = sizeof(thumbnail);
std::assert(thumbnailSize == bHead.len,
std::format("The thumbnail (size={:#x}) does not fit exactly into its DataBlock (len={:#x})!",
thumbnailSize, bHead.len));
}
if (quitAfterThumbnailIsParsed) {
break;
}
} else {
u8 data[bHead.len]; // Unknown. Interpret as raw binary data.
}
};
enum PointerSize : char {
POINTER_4BYTE = '_',
POINTER_8BYTE = '-'
};
enum Endianness : char {
BIG_ENDIAN = 'V',
LITTLE_ENDIAN = 'v'
};
struct Blend<auto inputSize> {
type::Magic<"BLENDER"> magic;
PointerSize pointerSize;
Endianness endianness;
char version[3];
match (endianness) {
(Endianness::LITTLE_ENDIAN): std::core::set_endian(std::mem::Endian::Little);
(Endianness::BIG_ENDIAN): std::core::set_endian(std::mem::Endian::Big);
(_): std::error("Invalid value for endianness!");
}
match (pointerSize) {
(PointerSize::POINTER_4BYTE): DataBlock<u32> dataBlock[while($ < inputSize)];
(PointerSize::POINTER_8BYTE): DataBlock<u64> dataBlock[while($ < inputSize)];
(_): std::error("Invalid pointer size!");
}
};
struct BlendWrapper {
u128 currentPos = $;
char magic[4] @ currentPos [[hidden]];
if (magic != "\x28\xB5\x2F\xFD") { // ZSTD magic
// Assume the blend file is uncompressed.
Blend<sizeof($)> blend @ currentPos;
return;
}
} [[inline]];
BlendWrapper blendWrapper @ 0x00;
// Assume the blend file is ZSTD compressed.
struct SeekTableFooter {
u32 numFrames;
char flag;
type::Magic<"\xB1\xEA\x92\x8F"> footerMagic;
};
u128 seekTableFooterSize = 9;
SeekTableFooter seekTableFooter @ (sizeof($) - seekTableFooterSize);
struct SeekTableEntry {
u32 compressedSize;
u32 uncompressedSize;
};
u128 seekTableEntrySize = 8;
SeekTableEntry seekTableEntries[seekTableFooter.numFrames]
@ (addressof(seekTableFooter) - seekTableFooter.numFrames * seekTableEntrySize);
struct SeekTableHeader {
type::Magic<"\x5E\x2A\x4D\x18"> magic;
u32 frameSize;
};
u128 seekTableHeaderSize = 8;
std::assert(seekTableFooter.numFrames > 0, "The seek table must contain entries!");
SeekTableHeader seekTableHeader @ (addressof(seekTableEntries[0]) - seekTableHeaderSize);
u32 frameIndex = 0;
struct ZSTDFrame {
u8 data[seekTableEntries[frameIndex].compressedSize];
frameIndex = frameIndex + 1;
};
ZSTDFrame zstdFrames[seekTableFooter.numFrames] @ 0x00;
#ifdef __IMHEX__
std::mem::Section decompressedSection = std::mem::create_section("decompressedBlend");
u128 previousSectionSize = 0;
for (u32 i = 0, i < seekTableFooter.numFrames, i = i + 1) {
std::assert(hex::dec::zstd_decompress(zstdFrames[i].data, decompressedSection),
"Decompression failed!");
u32 uncompressedSize = seekTableEntries[i].uncompressedSize;
u128 currentSectionSize = std::mem::get_section_size(decompressedSection)
- previousSectionSize;
std::assert_warn(uncompressedSize == currentSectionSize,
std::format("The uncompressedSize {} for ZSTDFrame #{} "
+ "must be equal to its actual decompressed size{}!",
uncompressedSize, i, currentSectionSize));
previousSectionSize += currentSectionSize;
};
Blend<previousSectionSize> blend @ 0x00 in decompressedSection;
#endif

View File

@@ -1,5 +1,8 @@
#pragma description OS2/Windows Bitmap
#pragma MIME image/bmp
#pragma endian little
import std.mem;
struct BitmapFileHeader {
u8 bfType[2];
@@ -9,13 +12,38 @@ struct BitmapFileHeader {
u32 bfOffBits;
};
struct BitmapInfoHeader {
enum Compression : u32 {
BI_RGB,
BI_RLE8,
BI_RLE4,
BI_BITFIELDS,
BI_JPEG,
BI_PNG,
BI_ALPHABITFIELDS,
BI_CMYK,
BI_CMYKRLE8,
BI_CMYKRLE4,
};
struct CIEXYZ {
u32 ciexyzX;
u32 ciexyzY;
u32 ciexyzZ;
};
struct CIEXYZTRIPLE {
CIEXYZ ciexyzRed;
CIEXYZ ciexyzGreen;
CIEXYZ ciexyzBlue;
};
struct BitmapInfoHeaderV1 {
u32 biSize;
s32 biWidth;
s32 biHeight;
u16 biPlanes;
u16 biBitCount;
u32 biCompression;
Compression biCompression;
u32 biSizeImage;
s32 biXPelsPerMeter;
s32 biYPelsPerMeter;
@@ -23,6 +51,31 @@ struct BitmapInfoHeader {
u32 biClrImportant;
};
struct BitmapInfoHeaderV2 : BitmapInfoHeaderV1 {
u32 biRedMask;
u32 biGreenMask;
u32 biBlueMask;
};
struct BitmapInfoHeaderV3 : BitmapInfoHeaderV2 {
u32 biAlphaMask;
};
struct BitmapInfoHeaderV4 : BitmapInfoHeaderV3 {
u32 biCSType;
CIEXYZTRIPLE biEndpoints;
u32 biGammaRed;
u32 biGammaGreen;
u32 biGammaBlue;
};
struct BitmapInfoHeaderV5 : BitmapInfoHeaderV4 {
u32 biIntent;
u32 biProfileData;
u32 biProfileSize;
u32 biReserved;
};
struct Colors {
u8 blue;
u8 green;
@@ -31,21 +84,32 @@ struct Colors {
};
struct Bitmap {
u8 data[std::mem::size()] [[no_unique_address, hidden]];
BitmapFileHeader bmfh;
BitmapInfoHeader bmih;
if ((bmih.biBitCount != 24) && (bmih.biBitCount != 32))
// Deduce the header version from its size
u32 bmInfoHeaderSize [[hidden, no_unique_address]];
match (bmInfoHeaderSize) {
(40): BitmapInfoHeaderV1 bmih;
(52): BitmapInfoHeaderV2 bmih;
(56): BitmapInfoHeaderV3 bmih;
(108): BitmapInfoHeaderV4 bmih;
(124): BitmapInfoHeaderV5 bmih;
(_): BitmapInfoHeaderV1 bmih;
}
padding[bmih.biSize - sizeof(bmih)];
if (bmih.biBitCount <= 8)
{
if (bmih.biClrUsed > 0 )
Colors rgbq[bmih.biClrUsed];
else
Colors rgbq[1 << bmih.biBitCount];
}
if (bmih.biSizeImage > 0 )
u8 lineData[bmih.biSizeImage];
else
u8 lineData[bmfh.bfSize - $];
};
} [[hex::visualize("image", this.data)]];
Bitmap bitmap @ 0x00;

273
patterns/bplist.hexpat Normal file
View File

@@ -0,0 +1,273 @@
#pragma description Apple binary property list
import std.math;
import std.core;
import type.magic;
import type.time;
using CFBinaryPlistObject;
enum Marker : u8 {
Null = 0x00,
False = 0x08,
True = 0x09,
Fill = 0x0F,
Int = 0x10,
Real = 0x20,
Date = 0x30,
Data = 0x40,
ASCIIString = 0x50,
Unicode16String = 0x60,
UNK_0x70 = 0x70,
UID = 0x80,
UNK_0x90 = 0x90,
Array = 0xA0,
UNK_0xB0 = 0xB0,
Set = 0xC0,
Dict = 0xD0,
UNK_0xE0 = 0xE0,
UNK_0xF0 = 0xF0
};
fn get_marker_name(u8 marker) {
if (marker == Marker::Null){// null 0000 0000
return "Null ";
}else if (marker == Marker::False){ //bool 0000 1000 // false
return "False";
}else if (marker == Marker::True){//bool 0000 1001 // true
return "True";
}else if (marker == Marker::Fill){ //fill 0000 1111 // fill byte
return "Fill";
}else if (marker & 0xF0 == Marker::Int){ //int 0001 nnnn ... // # of bytes is 2^nnnn, big-endian bytes
return "Int";
}else if (marker & 0xF0 == Marker:: Real){ //real 0010 nnnn ... // # of bytes is 2^nnnn, big-endian bytes
return "Real";
}else if (marker == Marker::Date){ //date 0011 0011 ... // 8 byte float follows, big-endian bytes
return "Date";
}else if (marker & 0xF0 == Marker::Data){ //data 0100 nnnn [int] ... // nnnn is number of bytes unless 1111 then int count follows, followed by bytes
return "Data";
}else if (marker & 0xF0 == Marker::ASCIIString){ //string 0101 nnnn [int] ... // ASCII string, nnnn is # of chars, else 1111 then int count, then bytes
return "ASCIIString";
}else if (marker & 0xF0 == Marker::Unicode16String){ //string 0110 nnnn [int] ... // Unicode string, nnnn is # of chars, else 1111 then int count, then big-endian 2-byte
return "Unicode16String";
}else if (marker & 0xF0 == Marker::UNK_0x70){ //0111 xxxx // unused
return "UNK_0x70";
}else if (marker & 0xF0 == Marker::UID){ //uid 1000 nnnn ... // nnnn+1 is # of bytes
return "UID";
}else if (marker & 0xF0 == Marker::UNK_0x90){ // 1001 xxxx // unused
return "UNK_0x90";
}else if (marker & 0xF0 == Marker::Array){ //array 1010 nnnn [int] objref* // nnnn is count, unless '1111', then int count follows
return "Array";
}else if (marker & 0xF0 == Marker::UNK_0xB0){ //1011 xxxx // unused
return "UNK_0xB0";
}else if (marker & 0xF0 == Marker::Set){ //set 1100 nnnn [int] objref* // nnnn is count, unless '1111', then int count follows
return "Set";
}else if (marker & 0xF0 == Marker::Dict){ //dict 1101 nnnn [int] keyref* objref* // nnnn is count, unless '1111', then int count follows
return "Dict";
}else if (marker & 0xF0 == Marker::UNK_0xE0){ // 1110 xxxx // unused
return "UNK_0xE0";
}else if (marker & 0xF0 == Marker::UNK_0xF0){ //1111 xxxx // unused
return "UNK_0xF0";
}
};
fn format_tag(u8 marker) {
return std::format("{}", get_marker(marker));
};
fn coredata_to_date (double val){
return type::impl::format_time_t(978307200 + val);
};
struct DictElement {
CFBinaryPlistObject key @ offsetTable[parent.objReference.key_refs[std::core::array_index()]].offset;
CFBinaryPlistObject value @ offsetTable[parent.objReference.value_refs[std::core::array_index()]].offset;
};
struct ArrayElement {
CFBinaryPlistObject value @ offsetTable[parent.objReference.value_refs[std::core::array_index()]].offset;
};
struct ObjectReference{
match(trailer.objectRefSize){
(1): {
be u8 key_refs[parent.ObjectLen.size];
be u8 value_refs[parent.ObjectLen.size];
}
(2): {
be u16 key_refs[parent.ObjectLen.size];
be u16 value_refs[parent.ObjectLen.size];
}
(4): {
be u32 key_refs[parent.ObjectLen.size];
be u32 value_refs[parent.ObjectLen.size];
}
(8): {
be u64 key_refs[parent.ObjectLen.size];
be u64 value_refs[parent.ObjectLen.size];
}
}
};
struct ObjectReferenceArray{
match(trailer.objectRefSize){
(1): be u8 value_refs[parent.ObjectLen.size];
(2): be u16 value_refs[parent.ObjectLen.size];
(4): be u32 value_refs[parent.ObjectLen.size];
(8): be u64 value_refs[parent.ObjectLen.size];
}
};
struct ObjectLen{
if (parent.marker_lsb != 0x0F){
u8 size = parent.marker_lsb [[export]];
}else{
CFBinaryPlistObject obj;
if (obj.marker & 0xF0 != Marker::Int){
std::error(std::format("Expects a 'Int' marker. Got 0x{:x} marker, with value {}", obj.marker, obj.value));
}
u128 size = obj.value [[export]];
}
};
struct CFBinaryPlistOffset{
match (trailer.offsetIntSize){
(1): be u8 offset;
(2): be u16 offset;
(4): be u32 offset;
(8): be u64 offset;
}
};
struct CFBinaryPlistObject{
u8 marker [[format("get_marker_name")]];
u8 marker_msb = marker & 0xF0;
u8 marker_lsb = marker & 0x0F;
match (marker_msb){
(0x0): {
match (marker_lsb){
(Marker::Null): {
u8 value = 0x00 [[export]];
}
(Marker::False): {
bool value = false [[export]];
}
(Marker::True): {
bool value = true [[export]];
}
(Marker::Fill): {
//I think the correct implementation is to do nothing here. The marker will be used as padding (Fill) ???
}
(_): {
std::error("Detected unknown marker {}.", marker_msb);
}
}
}
(Marker::Int): {
be u8 size = std::math::pow(2, marker_lsb);
// in format version '00', 1, 2, and 4-byte integers have to be interpreted as unsigned,
// whereas 8-byte integers are signed (and 16-byte when available)
// negative 1, 2, 4-byte integers are always emitted as 8 bytes in format '00'
// integers are not required to be in the most compact possible representation, but only the last 64 bits are significant currently
// Source: https://opensource.apple.com/source/CF/CF-550/CFBinaryPList.c
match (size) {
(1): be u8 value;
(2): be u16 value;
(4): be u32 value;
(8): be s64 value;
(16): be s128 value;
(_): std::error(std::format("Invalid size detected for 'Int' marker. Got size: {}.", size));
}
}
(Marker::Real): {
be u8 size = std::math::pow(2, marker_lsb);
match (size){
(4): be float value;
(8): be double value;
(_): std::error(std::format("Invalid size detected for 'Real' marker. Got size: {}.", size));
}
}
(Marker::Date): {
be double value [[format("coredata_to_date")]];
}
(Marker::Data): {
ObjectLen ObjectLen;
u8 value[ObjectLen.size];
}
(Marker::ASCIIString): {
ObjectLen ObjectLen;
char value[ObjectLen.size];
}
(Marker::Unicode16String): {
ObjectLen ObjectLen;
be char16 value[ObjectLen.size];
}
(Marker::UID): {
//Not 100% sure if this is correct for UID. Need more testing
u8 size = marker_lsb+1;
match (size) {
(1): be u8 value;
(2): be u16 value;
(4): be u32 value;
(8): be u64 value;
(16): be u128 value;
(_): std::error(std::format("Invalid size detected for 'UID' marker. Got size: {}.", size));
}
}
(Marker::Set | Marker::Array): {
ObjectLen ObjectLen;
ObjectReferenceArray objReference;
ArrayElement value[ObjectLen.size];
}
(Marker::Dict): {
ObjectLen ObjectLen;
ObjectReference objReference;
DictElement value[ObjectLen.size];
}
(Marker::UNK_0x70 | Marker::UNK_0x90 | Marker::UNK_0xB0 | Marker::UNK_0xE0 | Marker::UNK_0xF0): {
std::error(std::format("Got unused marker 0x{:x}", marker));
}
(_): {
std::error(std::format("Got unknown marker 0x{:x}", marker));
}
}
};
struct CFBinaryPlistHeader{
type::Magic<"bplist"> magic;
u16 version;
if (version != 0x3030){
std::error("Unsupported version detected. Only version 00 is supported (bplist00).");
}
};
struct CFBinaryPlistTrailer {
u8 unused[5];
u8 sortVersion;
be u8 offsetIntSize;
match (offsetIntSize){
(1|2|4|8): {}
(_): {std::error("Invalid offsetIntSize.");}
}
be u8 objectRefSize;
match (objectRefSize){
(1|2|4|8): {}
(_): {std::error("Invalid objectRefSize.");}
}
be u64 numObjects;
be u64 topObject;
be u64 offsetTableOffset;
};
CFBinaryPlistHeader header @ 0x00;
CFBinaryPlistTrailer trailer @ std::mem::size()-32;
CFBinaryPlistOffset offsetTable[trailer.numObjects] @ trailer.offsetTableOffset;
CFBinaryPlistObject objectTable @ offsetTable[trailer.topObject].offset;

View File

@@ -1,128 +1,132 @@
#pragma MIME application/bson
#include <type/time.pat>
enum Type : u8 {
Double = 0x01,
String = 0x02,
EmbeddedDocument = 0x03,
Array = 0x04,
Binary = 0x05,
Undefined = 0x06,
ObjectId = 0x07,
Boolean = 0x08,
UTCDatetime = 0x09,
Null = 0x0A,
Regex = 0x0B,
DBPointer = 0x0C,
JavaScript = 0x0D,
Symbol = 0x0E,
JavaScriptWithScope = 0x0F,
Int32 = 0x10,
Timestamp = 0x11,
Int64 = 0x12,
Decimal128 = 0x13,
MinKey = 0xFF,
MaxKey = 0x7F
};
enum Subtype : u8 {
GenericBinarySubtype = 0x00,
Function = 0x01,
BinaryOld = 0x02,
UUIDOld = 0x03,
UUID = 0x04,
MD5 = 0x05,
EncryptedBSONValue = 0x06,
CompressedBSONColumn = 0x07,
UserDefined = 0x80
};
struct Binary {
s32 length;
Subtype subtype;
u8 data[length];
};
struct String {
u32 length [[hidden]];
char value[length];
} [[sealed, format("format_string")]];
struct CString {
char value[];
} [[sealed, format("format_string")]];
fn format_string(auto string) {
return string.value;
};
struct ObjectId {
type::time32_t timestamp;
u8 randomValue[5];
u24 counter;
};
struct DBPointer {
String name;
ObjectId value;
};
using Document;
struct Element {
Type type;
CString name;
if (type == Type::Double) {
double value;
} else if (type == Type::String) {
String value;
} else if (type == Type::EmbeddedDocument) {
Document value;
} else if (type == Type::Array) {
Document value;
} else if (type == Type::Binary) {
Binary value;
} else if (type == Type::Undefined) {
/* undefined */
} else if (type == Type::ObjectId) {
ObjectId value;
} else if (type == Type::Boolean) {
bool value;
} else if (type == Type::UTCDatetime) {
type::time64_t value;
} else if (type == Type::Null) {
/* null */
} else if (type == Type::Regex) {
CString regexPattern;
CString regexOptions;
} else if (type == Type::DBPointer) {
DBPointer value;
} else if (type == Type::JavaScript) {
String value;
} else if (type == Type::Symbol) {
String value;
} else if (type == Type::JavaScriptWithScope) {
String value;
} else if (type == Type::Int32) {
s32 value;
} else if (type == Type::Timestamp) {
u64 value;
} else if (type == Type::Int64) {
s64 value;
} else if (type == Type::Decimal128) {
u128 value;
}
};
struct Document {
s32 listLength;
Element elements[while($ < ((addressof(this) + listLength) - 1))];
padding[1];
};
Document document @ 0x00;
#pragma author WerWolv
#pragma description BSON (Binary JSON)
#pragma MIME application/bson
import std.mem;
import type.time;
enum Type : u8 {
Double = 0x01,
String = 0x02,
EmbeddedDocument = 0x03,
Array = 0x04,
Binary = 0x05,
Undefined = 0x06,
ObjectId = 0x07,
Boolean = 0x08,
UTCDatetime = 0x09,
Null = 0x0A,
Regex = 0x0B,
DBPointer = 0x0C,
JavaScript = 0x0D,
Symbol = 0x0E,
JavaScriptWithScope = 0x0F,
Int32 = 0x10,
Timestamp = 0x11,
Int64 = 0x12,
Decimal128 = 0x13,
MinKey = 0xFF,
MaxKey = 0x7F
};
enum Subtype : u8 {
GenericBinarySubtype = 0x00,
Function = 0x01,
BinaryOld = 0x02,
UUIDOld = 0x03,
UUID = 0x04,
MD5 = 0x05,
EncryptedBSONValue = 0x06,
CompressedBSONColumn = 0x07,
UserDefined = 0x80
};
struct Binary {
s32 length;
Subtype subtype;
u8 data[length];
};
struct String {
u32 length [[hidden]];
char value[length];
} [[sealed, format("format_string")]];
struct CString {
char value[];
} [[sealed, format("format_string")]];
fn format_string(auto string) {
return string.value;
};
struct ObjectId {
type::time32_t timestamp;
u8 randomValue[5];
u24 counter;
};
struct DBPointer {
String name;
ObjectId value;
};
using Document;
struct Element {
Type type;
CString name;
if (type == Type::Double) {
double value;
} else if (type == Type::String) {
String value;
} else if (type == Type::EmbeddedDocument) {
Document value;
} else if (type == Type::Array) {
Document value;
} else if (type == Type::Binary) {
Binary value;
} else if (type == Type::Undefined) {
/* undefined */
} else if (type == Type::ObjectId) {
ObjectId value;
} else if (type == Type::Boolean) {
bool value;
} else if (type == Type::UTCDatetime) {
type::time64_t value;
} else if (type == Type::Null) {
/* null */
} else if (type == Type::Regex) {
CString regexPattern;
CString regexOptions;
} else if (type == Type::DBPointer) {
DBPointer value;
} else if (type == Type::JavaScript) {
String value;
} else if (type == Type::Symbol) {
String value;
} else if (type == Type::JavaScriptWithScope) {
String value;
} else if (type == Type::Int32) {
s32 value;
} else if (type == Type::Timestamp) {
u64 value;
} else if (type == Type::Int64) {
s64 value;
} else if (type == Type::Decimal128) {
u128 value;
}
};
struct Document {
s32 listLength;
Element elements[while($ < ((addressof(this) + listLength) - 1))];
padding[1];
};
Document documents[while(!std::mem::eof())] @ 0x00 [[inline]];

View File

@@ -1,6 +1,8 @@
#include <std/ptr.pat>
#include <std/mem.pat>
#include <std/sys.pat>
#pragma description GoldSrc engine map (Half-Life 1)
import std.ptr;
import std.mem;
import std.sys;
#pragma endian little
@@ -161,7 +163,7 @@ struct dmiptexlump_t
MiptexPointer dataofs[nummiptex];
};
struct VisibilityData
struct VisibilityData
{
u8 data[file_header.lumps[LumpIndex::Visibility].filelen];
u8 pad[std::mem::align_to(4, sizeof(this)) - sizeof(this)];

64
patterns/bzip3.hexpat Normal file
View File

@@ -0,0 +1,64 @@
#pragma author Sewer56
#pragma description Parses BZip3 compression (file format) by Kamila Szewczyk
#pragma MIME application/x-bzip3
#pragma endian little
#pragma magic [42 5A 33 76 31] @ 0x00
import std.mem;
// Helper function for bit counting
fn popcount(u8 b) {
u32 count = 0;
while (b != 0) {
count = count + (b & 1);
b = b >> 1;
}
return count;
};
// Frame header structure
struct FrameHeader {
char magic[5]; // "BZ3v1"
u32 blockSize; // Maximum block size
};
// Small block header (for blocks < 64 bytes)
struct SmallBlock {
u32 crc32; // CRC32 checksum
u32 literal; // Always 0xFFFFFFFF for small blocks
u8 data[parent.compressedSize - 8]; // Uncompressed data
};
// Regular block (blocks > 64 bytes)
struct Block {
u32 crc32; // CRC32 checksum of uncompressed data
u32 bwtIndex; // Burrows-Wheeler transform index
u8 model; // Compression model flags
if ((model & 0x02) != 0)
u32 lzpSize; // Size after LZP compression
if ((model & 0x04) != 0)
u32 rleSize; // Size after RLE compression
u8 data[parent.compressedSize - (popcount(model) * 4 + 9)];
};
// Main block structure
struct Chunk {
u32 compressedSize; // Size of compressed block
u32 origSize; // Original uncompressed size
if (origSize < 64) {
SmallBlock block;
} else {
Block block;
}
};
// Main parsing structure
struct BZip3File {
FrameHeader header;
// Read blocks until end of file
Chunk chunks[while(!std::mem::eof())];
};
BZip3File file @ 0x0;

View File

@@ -1,3 +1,5 @@
#pragma description Command and Conquer Voxel Animation
// Command and conquer voxel animation format
struct vec4_s {

View File

@@ -1,3 +1,5 @@
#pragma description Command and Conquer Voxel Palette
// Command and conquer palette format
struct Color {

View File

@@ -1,3 +1,5 @@
#pragma description Command and Conquer Voxel Model
// Command and Conquer voxel model format
struct vec4_s {

31
patterns/cda.hexpat Normal file
View File

@@ -0,0 +1,31 @@
#pragma description Compact Disc Audio track
struct Header {
u32 RIFF;
s32 size;
u32 CDDA;
u32 fmt;
u32 lenghtofthechunck;
u16 versionofcdformat;
u16 numberofrange;
u32 identifier;
};
struct DataInfo {
u32 range;
u32 duration;
u8 rangepositionframes;
u8 rangepositionseconds;
u8 rangepositionminutes;
u8 nullbyte;
u8 durationtrackframes;
u8 durationtrackseconds;
u8 durationtrackminutes;
u8 nullbytee;
};
Header header @ 0;
DataInfo data @ 0x1C;

View File

@@ -1,395 +1,398 @@
#include <type/magic.pat>
#include <type/size.pat>
#include <type/guid.pat>
#include <type/leb128.pat>
#include <std/sys.pat>
enum WindowsLanguageId : u32 {
Arabic_SaudiArabia = 0x401,
Arabic_Iraq = 0x801,
Arabic_Egypt = 0xc01,
Arabic_Libya = 0x1001,
Arabic_Algeria = 0x1401,
Arabic_Morocco = 0x1801,
Arabic_Tunisia = 0x1c01,
Arabic_Oman = 0x2001,
Arabic_Yemen = 0x2401,
Arabic_Syria = 0x2801,
Arabic_Jordan = 0x2c01,
Arabic_Lebanon = 0x3001,
Arabic_Kuwait = 0x3401,
Arabic_UAE = 0x3801,
Arabic_Bahrain = 0x3c01,
Arabic_Qatar = 0x4001,
Bulgarian = 0x402,
Catalan = 0x403,
Valencian = 0x803,
Chinese_Taiwan = 0x404,
Chinese_PRC = 0x804,
Chinese_HongKongSAR = 0xc04,
Chinese_Singapore = 0x1004,
Chinese_MacaoSAR = 0x1404,
Czech = 0x405,
Danish = 0x406,
German_Germany = 0x407,
German_Switzerland = 0x807,
German_Austria = 0xc07,
German_Luxembourg = 0x1007,
German_Liechtenstein = 0x1407,
Greek = 0x408,
English_UnitedStates = 0x409,
English_UnitedKingdom = 0x809,
English_Australia = 0xc09,
English_Canada = 0x1009,
English_NewZealand = 0x1409,
English_Ireland = 0x1809,
English_SouthAfrica = 0x1c09,
English_Jamaica = 0x2009,
English_Caribbean = 0x2409,
English_Belize = 0x2809,
English_TrinidadandTobago = 0x2c09,
English_Zimbabwe = 0x3009,
English_Philippines = 0x3409,
English_Indonesia = 0x3809,
English_HongKongSAR = 0x3c09,
English_India = 0x4009,
English_Malaysia = 0x4409,
English_Singapore = 0x4809,
Spanish_SpainTraditionalSort = 0x40a,
Spanish_Mexico = 0x80a,
Spanish_Spain = 0xc0a,
Spanish_Guatemala = 0x100a,
Spanish_CostaRica = 0x140a,
Spanish_Panama = 0x180a,
Spanish_DominicanRepublic = 0x1c0a,
Spanish_Venezuela = 0x200a,
Spanish_Colombia = 0x240a,
Spanish_Peru = 0x280a,
Spanish_Argentina = 0x2c0a,
Spanish_Ecuador = 0x300a,
Spanish_Chile = 0x340a,
Spanish_Uruguay = 0x380a,
Spanish_Paraguay = 0x3c0a,
Spanish_Bolivia = 0x400a,
Spanish_ElSalvador = 0x440a,
Spanish_Honduras = 0x480a,
Spanish_Nicaragua = 0x4c0a,
Spanish_PuertoRico = 0x500a,
Spanish_UnitedStates = 0x540a,
Spanish_LatinAmerica = 0x580a,
Finnish = 0x40b,
French_France = 0x40c,
French_Belgium = 0x80c,
French_Canada = 0xc0c,
French_Switzerland = 0x100c,
French_Luxembourg = 0x140c,
French_Monaco = 0x180c,
French_Caribbean = 0x1c0c,
French_Reunion = 0x200c,
French_CongoDRC = 0x240c,
French_Senegal = 0x280c,
French_Cameroon = 0x2c0c,
French_CoteDIvoire = 0x300c,
French_Mali = 0x340c,
French_Morocco = 0x380c,
French_Haiti = 0x3c0c,
Hebrew = 0x40d,
Hungarian = 0x40e,
Icelandic = 0x40f,
Italian_Italy = 0x410,
Italian_Switzerland = 0x810,
Japanese = 0x411,
Korean = 0x412,
Dutch_Netherlands = 0x413,
Dutch_Belgium = 0x813,
Norwegian_Bokmal = 0x414,
Norwegian_Nynorsk = 0x814,
Polish = 0x415,
Portuguese_Brazil = 0x416,
Portuguese_Portugal = 0x816,
Romansh = 0x417,
Romanian = 0x418,
Romanian_Moldova = 0x818,
Russian = 0x419,
Russian_Moldova = 0x819,
Croatian_Croatia = 0x41a,
Serbian_LatinSerbiaandMontenegroFormer = 0x81a,
Serbian_CyrillicSerbiaAndMontenegroFormer = 0xc1a,
Croatian_BosniaAndHerzegovina = 0x101a,
Bosnian_Latin = 0x141a,
Serbian_LatinBosniaAndHerzegovina = 0x181a,
Serbian_CyrillicBosniaAndHerzegovina = 0x1c1a,
Bosnian_Cyrillic = 0x201a,
Serbian_LatinSerbia = 0x241a,
Serbian_CyrillicSerbia = 0x281a,
Serbian_LatinMontenegro = 0x2c1a,
Serbian_CyrillicMontenegro = 0x301a,
Slovak = 0x41b,
Albanian = 0x41c,
Swedish_Sweden = 0x41d,
Swedish_Finland = 0x81d,
Thai = 0x41e,
Turkish = 0x41f,
Urdu_Pakistan = 0x420,
Urdu_India = 0x820,
Indonesian = 0x421,
Ukrainian = 0x422,
Belarusian = 0x423,
Slovenian = 0x424,
Estonian = 0x425,
Latvian = 0x426,
Lithuanian = 0x427,
Tajik = 0x428,
Persian = 0x429,
Vietnamese = 0x42a,
Armenian = 0x42b,
Azerbaijani_Latin = 0x42c,
Azerbaijani_Cyrillic = 0x82c,
Basque = 0x42d,
UpperSorbian = 0x42e,
LowerSorbian = 0x82e,
Macedonian = 0x42f,
Sesotho_SouthAfrica = 0x430,
Xitsonga = 0x431,
Setswana_SouthAfrica = 0x432,
Setswana_Botswana = 0x832,
Venda = 0x433,
isiXhosa = 0x434,
isiZulu = 0x435,
Afrikaans = 0x436,
Georgian = 0x437,
Faroese = 0x438,
Hindi = 0x439,
Maltese = 0x43a,
NorthernSami_Norway = 0x43b,
NorthernSami_Sweden = 0x83b,
NorthernSami_Finland = 0xc3b,
LuleSami_Norway = 0x103b,
LuleSami_Sweden = 0x143b,
SouthernSami_Norway = 0x183b,
SouthernSami_Sweden = 0x1c3b,
SkoltSami_Finland = 0x203b,
InariSami_Finland = 0x243b,
Irish = 0x83c,
Yiddish = 0x43d,
Malay_Malaysia = 0x43e,
Malay_BruneiDarussalam = 0x83e,
Kazakh = 0x43f,
Kyrgyz = 0x440,
Kiswahili = 0x441,
Turkmen = 0x442,
Uzbek_Latin = 0x443,
Uzbek_Cyrillic = 0x843,
Tatar = 0x444,
Bangla_India = 0x445,
Bangla_Bangladesh = 0x845,
Punjabi_India = 0x446,
Punjabi_Pakistan = 0x846,
Gujarati = 0x447,
Odia = 0x448,
Tamil_India = 0x449,
Tamil_SriLanka = 0x849,
Telugu = 0x44a,
Kannada = 0x44b,
Malayalam = 0x44c,
Assamese = 0x44d,
Marathi = 0x44e,
Sanskrit = 0x44f,
Mongolian_Cyrillic = 0x450,
Mongolian_TraditionalMongolianPRC = 0x850,
Mongolian_TraditionalMongolianMongolia = 0xc50,
Tibetan_PRC = 0x451,
Welsh = 0x452,
Khmer = 0x453,
Lao = 0x454,
Burmese = 0x455,
Galician = 0x456,
Konkani = 0x457,
Manipuri = 0x458,
Sindhi_Devanagari = 0x459,
Sindhi_Arabic = 0x859,
Syriac = 0x45a,
Sinhala = 0x45b,
Cherokee_Cherokee = 0x45c,
Inuktitut_Syllabics = 0x45d,
Inuktitut_Latin = 0x85d,
Amharic = 0x45e,
Tamazight_ArabicMorocco = 0x45f,
Tamazight_LatinAlgeria = 0x85f,
Tamazight_TifinaghMorocco = 0x105f,
Kashmiri_Arabic = 0x460,
Kashmiri = 0x860,
Nepali = 0x461,
Nepali_India = 0x861,
Frisian = 0x462,
Pashto = 0x463,
Filipino = 0x464,
Divehi = 0x465,
Edo = 0x466,
Fulah_Nigeria = 0x467,
Fulah_LatinSenegal = 0x867,
Hausa = 0x468,
Ibibio_Nigeria = 0x469,
Yoruba = 0x46a,
Quechua_Bolivia = 0x46b,
Quechua_Ecuador = 0x86b,
Quechua_Peru = 0xc6b,
SesothoSaLeboa = 0x46c,
Bashkir = 0x46d,
Luxembourgish = 0x46e,
Greenlandic = 0x46f,
Igbo = 0x470,
Kanuri = 0x471,
Oromo = 0x472,
Tigrinya_Ethiopia = 0x473,
Tigrinya_Eritrea = 0x873,
Guarani = 0x474,
Hawaiian = 0x475,
Latin = 0x476,
Somali = 0x477,
Yi_PRC = 0x478,
Papiamentu = 0x479,
Mapudungun = 0x47a,
Mohawk = 0x47c,
Breton = 0x47e,
Uyghur_PRC = 0x480,
Maori = 0x481,
Occitan = 0x482,
Corsican = 0x483,
Alsatian = 0x484,
Sakha = 0x485,
Kiche = 0x486,
Kinyarwanda = 0x487,
Wolof = 0x488,
Dari = 0x48c,
ScottishGaelic_UnitedKingdom = 0x491,
CentralKurdish_Iraq = 0x492
};
struct DirectoryListingEntry {
type::LEB128 nameLength;
char name[nameLength];
type::LEB128 contentSection;
type::LEB128 offset;
type::LEB128 length;
};
struct DirectoryIndexEntry {
type::LEB128 nameLength;
char name[nameLength];
type::LEB128 directoryListingChunk;
};
struct ListingChunk {
char magic[4];
if (magic == "PMGL") {
type::Size<u32> freeSpaceLength;
u32;
u32 prevChunkNumber, nextChunkNumber;
u16 directoryListingEntryCount @ addressof(this) + parent.directoryChunkSize - 2;
u16 offsets[(freeSpaceLength - 2) / 2] @ addressof(directoryListingEntryCount) - (freeSpaceLength - 2);
DirectoryListingEntry directories[directoryListingEntryCount];
$ = addressof(directoryListingEntryCount) + sizeof(directoryListingEntryCount);
} else if (magic == "PMGI") {
type::Size<u32> freeSpaceLength;
u16 directoryIndexEntryCount @ addressof(this) + parent.directoryChunkSize - 2;
u16 offsets[(freeSpaceLength - 2) / 2] @ addressof(directoryIndexEntryCount) - (freeSpaceLength - 2);
DirectoryIndexEntry indexes[directoryIndexEntryCount];
$ = addressof(directoryIndexEntryCount) + sizeof(directoryIndexEntryCount);
} else {
std::error("Invalid chunk magic!");
}
};
struct HeaderSection {
char magic[4];
if (magic == "\xFE\x01\x00\x00") {
u32;
type::Size<u64> fileSize;
u32;
u32;
} else if (magic == "ITSP") {
u32 version;
type::Size<u32> directoryHeaderLength1;
u32;
u32 directoryChunkSize;
u32 quickRefSectionDensity;
u32 indexTreeDepth;
u32 rootIndexChunkNumber;
u32 firstPMGLChunkNumber;
u32 lastPMGLChunkNumber;
u32;
u32 directoryChunkCount;
WindowsLanguageId languageId;
type::GUID guid;
type::Size<u32> directoryHeaderLength2;
u32;
u32;
u32;
ListingChunk chunk[directoryChunkCount];
} else {
std::error("Invalid header section magic!");
}
};
struct HeaderSectionTableEntry {
u64 offset;
type::Size<u64> size;
HeaderSection headerSection @ offset;
};
struct NameListEntry {
type::Size<u16> nameLength;
char16 name[nameLength];
padding[2];
};
struct NameListFile {
u16 fileLengthWords;
u16 entriesInFile;
NameListEntry nameList[entriesInFile];
padding[0x2E];
};
struct SectionData {
u32 fileLengthWords;
type::Magic<"LZXC"> magic;
u32 version;
u32 lzxResetInterval;
type::Size<u32> windowSize;
type::Size<u32> cacheSize;
u32;
};
struct Content {
NameListFile nameListFile;
SectionData sectionData;
};
struct CHM {
type::Magic<"ITSF"> magic;
u32 version;
type::Size<u32> headerSize;
u32;
be u32 timeStamp;
WindowsLanguageId languageId;
type::GUID guids[2];
HeaderSectionTableEntry headerSectionTable[2];
Content *dataOffset : u64;
};
CHM chm @ 0x00;
#pragma author WerWolv
#pragma description Windows HtmlHelp Data (ITSF / CHM)
import type.magic;
import type.size;
import type.guid;
import type.leb128;
import std.sys;
enum WindowsLanguageId : u32 {
Arabic_SaudiArabia = 0x401,
Arabic_Iraq = 0x801,
Arabic_Egypt = 0xc01,
Arabic_Libya = 0x1001,
Arabic_Algeria = 0x1401,
Arabic_Morocco = 0x1801,
Arabic_Tunisia = 0x1c01,
Arabic_Oman = 0x2001,
Arabic_Yemen = 0x2401,
Arabic_Syria = 0x2801,
Arabic_Jordan = 0x2c01,
Arabic_Lebanon = 0x3001,
Arabic_Kuwait = 0x3401,
Arabic_UAE = 0x3801,
Arabic_Bahrain = 0x3c01,
Arabic_Qatar = 0x4001,
Bulgarian = 0x402,
Catalan = 0x403,
Valencian = 0x803,
Chinese_Taiwan = 0x404,
Chinese_PRC = 0x804,
Chinese_HongKongSAR = 0xc04,
Chinese_Singapore = 0x1004,
Chinese_MacaoSAR = 0x1404,
Czech = 0x405,
Danish = 0x406,
German_Germany = 0x407,
German_Switzerland = 0x807,
German_Austria = 0xc07,
German_Luxembourg = 0x1007,
German_Liechtenstein = 0x1407,
Greek = 0x408,
English_UnitedStates = 0x409,
English_UnitedKingdom = 0x809,
English_Australia = 0xc09,
English_Canada = 0x1009,
English_NewZealand = 0x1409,
English_Ireland = 0x1809,
English_SouthAfrica = 0x1c09,
English_Jamaica = 0x2009,
English_Caribbean = 0x2409,
English_Belize = 0x2809,
English_TrinidadandTobago = 0x2c09,
English_Zimbabwe = 0x3009,
English_Philippines = 0x3409,
English_Indonesia = 0x3809,
English_HongKongSAR = 0x3c09,
English_India = 0x4009,
English_Malaysia = 0x4409,
English_Singapore = 0x4809,
Spanish_SpainTraditionalSort = 0x40a,
Spanish_Mexico = 0x80a,
Spanish_Spain = 0xc0a,
Spanish_Guatemala = 0x100a,
Spanish_CostaRica = 0x140a,
Spanish_Panama = 0x180a,
Spanish_DominicanRepublic = 0x1c0a,
Spanish_Venezuela = 0x200a,
Spanish_Colombia = 0x240a,
Spanish_Peru = 0x280a,
Spanish_Argentina = 0x2c0a,
Spanish_Ecuador = 0x300a,
Spanish_Chile = 0x340a,
Spanish_Uruguay = 0x380a,
Spanish_Paraguay = 0x3c0a,
Spanish_Bolivia = 0x400a,
Spanish_ElSalvador = 0x440a,
Spanish_Honduras = 0x480a,
Spanish_Nicaragua = 0x4c0a,
Spanish_PuertoRico = 0x500a,
Spanish_UnitedStates = 0x540a,
Spanish_LatinAmerica = 0x580a,
Finnish = 0x40b,
French_France = 0x40c,
French_Belgium = 0x80c,
French_Canada = 0xc0c,
French_Switzerland = 0x100c,
French_Luxembourg = 0x140c,
French_Monaco = 0x180c,
French_Caribbean = 0x1c0c,
French_Reunion = 0x200c,
French_CongoDRC = 0x240c,
French_Senegal = 0x280c,
French_Cameroon = 0x2c0c,
French_CoteDIvoire = 0x300c,
French_Mali = 0x340c,
French_Morocco = 0x380c,
French_Haiti = 0x3c0c,
Hebrew = 0x40d,
Hungarian = 0x40e,
Icelandic = 0x40f,
Italian_Italy = 0x410,
Italian_Switzerland = 0x810,
Japanese = 0x411,
Korean = 0x412,
Dutch_Netherlands = 0x413,
Dutch_Belgium = 0x813,
Norwegian_Bokmal = 0x414,
Norwegian_Nynorsk = 0x814,
Polish = 0x415,
Portuguese_Brazil = 0x416,
Portuguese_Portugal = 0x816,
Romansh = 0x417,
Romanian = 0x418,
Romanian_Moldova = 0x818,
Russian = 0x419,
Russian_Moldova = 0x819,
Croatian_Croatia = 0x41a,
Serbian_LatinSerbiaandMontenegroFormer = 0x81a,
Serbian_CyrillicSerbiaAndMontenegroFormer = 0xc1a,
Croatian_BosniaAndHerzegovina = 0x101a,
Bosnian_Latin = 0x141a,
Serbian_LatinBosniaAndHerzegovina = 0x181a,
Serbian_CyrillicBosniaAndHerzegovina = 0x1c1a,
Bosnian_Cyrillic = 0x201a,
Serbian_LatinSerbia = 0x241a,
Serbian_CyrillicSerbia = 0x281a,
Serbian_LatinMontenegro = 0x2c1a,
Serbian_CyrillicMontenegro = 0x301a,
Slovak = 0x41b,
Albanian = 0x41c,
Swedish_Sweden = 0x41d,
Swedish_Finland = 0x81d,
Thai = 0x41e,
Turkish = 0x41f,
Urdu_Pakistan = 0x420,
Urdu_India = 0x820,
Indonesian = 0x421,
Ukrainian = 0x422,
Belarusian = 0x423,
Slovenian = 0x424,
Estonian = 0x425,
Latvian = 0x426,
Lithuanian = 0x427,
Tajik = 0x428,
Persian = 0x429,
Vietnamese = 0x42a,
Armenian = 0x42b,
Azerbaijani_Latin = 0x42c,
Azerbaijani_Cyrillic = 0x82c,
Basque = 0x42d,
UpperSorbian = 0x42e,
LowerSorbian = 0x82e,
Macedonian = 0x42f,
Sesotho_SouthAfrica = 0x430,
Xitsonga = 0x431,
Setswana_SouthAfrica = 0x432,
Setswana_Botswana = 0x832,
Venda = 0x433,
isiXhosa = 0x434,
isiZulu = 0x435,
Afrikaans = 0x436,
Georgian = 0x437,
Faroese = 0x438,
Hindi = 0x439,
Maltese = 0x43a,
NorthernSami_Norway = 0x43b,
NorthernSami_Sweden = 0x83b,
NorthernSami_Finland = 0xc3b,
LuleSami_Norway = 0x103b,
LuleSami_Sweden = 0x143b,
SouthernSami_Norway = 0x183b,
SouthernSami_Sweden = 0x1c3b,
SkoltSami_Finland = 0x203b,
InariSami_Finland = 0x243b,
Irish = 0x83c,
Yiddish = 0x43d,
Malay_Malaysia = 0x43e,
Malay_BruneiDarussalam = 0x83e,
Kazakh = 0x43f,
Kyrgyz = 0x440,
Kiswahili = 0x441,
Turkmen = 0x442,
Uzbek_Latin = 0x443,
Uzbek_Cyrillic = 0x843,
Tatar = 0x444,
Bangla_India = 0x445,
Bangla_Bangladesh = 0x845,
Punjabi_India = 0x446,
Punjabi_Pakistan = 0x846,
Gujarati = 0x447,
Odia = 0x448,
Tamil_India = 0x449,
Tamil_SriLanka = 0x849,
Telugu = 0x44a,
Kannada = 0x44b,
Malayalam = 0x44c,
Assamese = 0x44d,
Marathi = 0x44e,
Sanskrit = 0x44f,
Mongolian_Cyrillic = 0x450,
Mongolian_TraditionalMongolianPRC = 0x850,
Mongolian_TraditionalMongolianMongolia = 0xc50,
Tibetan_PRC = 0x451,
Welsh = 0x452,
Khmer = 0x453,
Lao = 0x454,
Burmese = 0x455,
Galician = 0x456,
Konkani = 0x457,
Manipuri = 0x458,
Sindhi_Devanagari = 0x459,
Sindhi_Arabic = 0x859,
Syriac = 0x45a,
Sinhala = 0x45b,
Cherokee_Cherokee = 0x45c,
Inuktitut_Syllabics = 0x45d,
Inuktitut_Latin = 0x85d,
Amharic = 0x45e,
Tamazight_ArabicMorocco = 0x45f,
Tamazight_LatinAlgeria = 0x85f,
Tamazight_TifinaghMorocco = 0x105f,
Kashmiri_Arabic = 0x460,
Kashmiri = 0x860,
Nepali = 0x461,
Nepali_India = 0x861,
Frisian = 0x462,
Pashto = 0x463,
Filipino = 0x464,
Divehi = 0x465,
Edo = 0x466,
Fulah_Nigeria = 0x467,
Fulah_LatinSenegal = 0x867,
Hausa = 0x468,
Ibibio_Nigeria = 0x469,
Yoruba = 0x46a,
Quechua_Bolivia = 0x46b,
Quechua_Ecuador = 0x86b,
Quechua_Peru = 0xc6b,
SesothoSaLeboa = 0x46c,
Bashkir = 0x46d,
Luxembourgish = 0x46e,
Greenlandic = 0x46f,
Igbo = 0x470,
Kanuri = 0x471,
Oromo = 0x472,
Tigrinya_Ethiopia = 0x473,
Tigrinya_Eritrea = 0x873,
Guarani = 0x474,
Hawaiian = 0x475,
Latin = 0x476,
Somali = 0x477,
Yi_PRC = 0x478,
Papiamentu = 0x479,
Mapudungun = 0x47a,
Mohawk = 0x47c,
Breton = 0x47e,
Uyghur_PRC = 0x480,
Maori = 0x481,
Occitan = 0x482,
Corsican = 0x483,
Alsatian = 0x484,
Sakha = 0x485,
Kiche = 0x486,
Kinyarwanda = 0x487,
Wolof = 0x488,
Dari = 0x48c,
ScottishGaelic_UnitedKingdom = 0x491,
CentralKurdish_Iraq = 0x492
};
struct DirectoryListingEntry {
type::LEB128 nameLength;
char name[nameLength];
type::LEB128 contentSection;
type::LEB128 offset;
type::LEB128 length;
};
struct DirectoryIndexEntry {
type::LEB128 nameLength;
char name[nameLength];
type::LEB128 directoryListingChunk;
};
struct ListingChunk {
char magic[4];
if (magic == "PMGL") {
type::Size<u32> freeSpaceLength;
u32;
u32 prevChunkNumber, nextChunkNumber;
u16 directoryListingEntryCount @ addressof(this) + parent.directoryChunkSize - 2;
u16 offsets[(freeSpaceLength - 2) / 2] @ addressof(directoryListingEntryCount) - (freeSpaceLength - 2);
DirectoryListingEntry directories[directoryListingEntryCount];
$ = addressof(directoryListingEntryCount) + sizeof(directoryListingEntryCount);
} else if (magic == "PMGI") {
type::Size<u32> freeSpaceLength;
u16 directoryIndexEntryCount @ addressof(this) + parent.directoryChunkSize - 2;
u16 offsets[(freeSpaceLength - 2) / 2] @ addressof(directoryIndexEntryCount) - (freeSpaceLength - 2);
DirectoryIndexEntry indexes[directoryIndexEntryCount];
$ = addressof(directoryIndexEntryCount) + sizeof(directoryIndexEntryCount);
} else {
std::error("Invalid chunk magic!");
}
};
struct HeaderSection {
char magic[4];
if (magic == "\xFE\x01\x00\x00") {
u32;
type::Size<u64> fileSize;
u32;
u32;
} else if (magic == "ITSP") {
u32 version;
type::Size<u32> directoryHeaderLength1;
u32;
u32 directoryChunkSize;
u32 quickRefSectionDensity;
u32 indexTreeDepth;
u32 rootIndexChunkNumber;
u32 firstPMGLChunkNumber;
u32 lastPMGLChunkNumber;
u32;
u32 directoryChunkCount;
WindowsLanguageId languageId;
type::GUID guid;
type::Size<u32> directoryHeaderLength2;
u32;
u32;
u32;
ListingChunk chunk[directoryChunkCount];
} else {
std::error("Invalid header section magic!");
}
};
struct HeaderSectionTableEntry {
u64 offset;
type::Size<u64> size;
HeaderSection headerSection @ offset;
};
struct NameListEntry {
type::Size<u16> nameLength;
char16 name[nameLength];
padding[2];
};
struct NameListFile {
u16 fileLengthWords;
u16 entriesInFile;
NameListEntry nameList[entriesInFile];
padding[0x2E];
};
struct SectionData {
u32 fileLengthWords;
type::Magic<"LZXC"> magic;
u32 version;
u32 lzxResetInterval;
type::Size<u32> windowSize;
type::Size<u32> cacheSize;
u32;
};
struct Content {
NameListFile nameListFile;
SectionData sectionData;
};
struct CHM {
type::Magic<"ITSF"> magic;
u32 version;
type::Size<u32> headerSize;
u32;
be u32 timeStamp;
WindowsLanguageId languageId;
type::GUID guids[2];
HeaderSectionTableEntry headerSectionTable[2];
Content *dataOffset : u64;
};
CHM chm @ 0x00;

View File

@@ -1,7 +1,10 @@
#pragma author WerWolv
#pragma description Common Object File Format (COFF) executable
#pragma MIME application/x-coff
#include <type/time.pat>
#include <type/size.pat>
import type.time;
import type.size;
enum Machine : u16 {
Unknown = 0x0000,
@@ -113,11 +116,11 @@ struct SymbolTable {
Type type;
StorageClass storageClass;
u8 numberOfAuxSymbols;
countedSymbols += 1 + numberOfAuxSymbols;
AuxSymbol auxSymbols[numberOfAuxSymbols];
if (countedSymbols >= parent.header.numberOfSymbols)
break;
};
@@ -161,7 +164,10 @@ bitfield SectionFlags {
};
fn format_alignment(u8 alignment) {
return 1 << alignment;
if(alignment > 0) {
return 1 << (alignment - 1);
}
return alignment;
};
struct Relocations {
@@ -181,7 +187,7 @@ struct Section {
u16 numberOfRelocations;
u16 numberOfLineNumbers;
SectionFlags characteristics;
u8 rawData[sizeOfRawData] @ pointerToRawData [[sealed]];
Relocations relocations[numberOfRelocations] @ pointerToRelocations;
};
@@ -199,9 +205,9 @@ struct Header {
struct COFF {
Header header;
Section sectionTable[header.numberOfSections];
SymbolTable symbolTable[header.numberOfSymbols] @ header.pointerToSymbolTable;
StringTable stringTable @ addressof(symbolTable) + sizeof(symbolTable);
};

View File

@@ -1,66 +1,69 @@
#include <type/base.pat>
#include <std/time.pat>
#include <std/core.pat>
#include <std/sys.pat>
#include <std/mem.pat>
#pragma MIME application/x-cpio
namespace old_binary {
using Time = u32 [[format("old_binary::format_time")]];
fn swap_32bit(u32 value) {
return ((value >> 16) & 0xFFFF) | ((value & 0xFFFF) << 16);
};
fn format_time(u32 value) {
return std::time::format(std::time::to_utc(swap_32bit(value)));
};
using SwappedU32 = u32 [[transform("old_binary::swap_32bit"), format("old_binary::swap_32bit")]];
bitfield Mode {
x : 3;
w : 3;
r : 3;
sticky : 1;
sgid : 1;
suid : 1;
file_type : 4;
};
struct CpioHeader {
type::Oct<u16> magic;
if (magic == be u16(0o070707))
std::core::set_endian(std::mem::Endian::Big);
else if (magic == le u16(0o070707))
std::core::set_endian(std::mem::Endian::Little);
else
std::error("Invalid CPIO Magic!");
u16 dev;
u16 ino;
Mode mode;
u16 uid;
u16 gid;
u16 nlink;
u16 rdev;
Time mtime;
u16 namesize;
SwappedU32 filesize;
};
struct Cpio {
CpioHeader header;
char pathname[header.namesize % 2 == 0 ? header.namesize : header.namesize + 1];
u8 data[header.filesize % 2 == 0 ? header.filesize : header.filesize + 1];
if (pathname == "TRAILER!!!\x00\x00")
break;
};
}
old_binary::Cpio cpio[while(true)] @ 0x00;
#pragma author WerWolv
#pragma description Old Binary CPIO
import type.base;
import std.time;
import std.core;
import std.sys;
import std.mem;
#pragma MIME application/x-cpio
namespace old_binary {
using Time = u32 [[format("old_binary::format_time")]];
fn swap_32bit(u32 value) {
return ((value >> 16) & 0xFFFF) | ((value & 0xFFFF) << 16);
};
fn format_time(u32 value) {
return std::time::format(std::time::to_utc(swap_32bit(value)));
};
using SwappedU32 = u32 [[transform("old_binary::swap_32bit"), format("old_binary::swap_32bit")]];
bitfield Mode {
x : 3;
w : 3;
r : 3;
sticky : 1;
sgid : 1;
suid : 1;
file_type : 4;
};
struct CpioHeader {
type::Oct<u16> magic;
if (magic == be u16(0o070707))
std::core::set_endian(std::mem::Endian::Big);
else if (magic == le u16(0o070707))
std::core::set_endian(std::mem::Endian::Little);
else
std::error("Invalid CPIO Magic!");
u16 dev;
u16 ino;
Mode mode;
u16 uid;
u16 gid;
u16 nlink;
u16 rdev;
Time mtime;
u16 namesize;
SwappedU32 filesize;
};
struct Cpio {
CpioHeader header;
char pathname[header.namesize % 2 == 0 ? header.namesize : header.namesize + 1];
u8 data[header.filesize % 2 == 0 ? header.filesize : header.filesize + 1];
if (pathname == "TRAILER!!!\x00\x00")
break;
};
}
old_binary::Cpio cpio[while(true)] @ 0x00;

99
patterns/credhist.hexpat Normal file
View File

@@ -0,0 +1,99 @@
#pragma description "CREDHIST"
/*
FilePath: C:\Users\<USER>\AppData\Roaming\Microsoft\Protect\
The files/folders are hidden.
To unhide it
1. Open Command Prompt (cmd.exe).
2. Run the following command:
=> attrib -h -s
*/
import type.guid;
import std.mem;
// https://learn.microsoft.com/en-us/windows/win32/seccrypto/alg-id
enum ALG_ID : u32 {
CALG_DH_EPHEM = 0x0000aa02, // Diffie-Hellman ephemeral key exchange algorithm.
CALG_DH_SF = 0x0000aa01, // Diffie-Hellman store and forward key exchange algorithm.
CALG_DSS_SIGN = 0x00002200, // DSA public key signature algorithm.
CALG_ECDH = 0x0000aa05, // Elliptic curve Diffie-Hellman key exchange algorithm.
CALG_ECDH_EPHEM = 0x0000ae06, // Ephemeral elliptic curve Diffie-Hellman key exchange algorithm.
CALG_ECDSA = 0x00002203, // Elliptic curve digital signature algorithm.
CALG_ECMQV = 0x0000a001, // Elliptic curve Menezes, Qu, and Vanstone (MQV) key exchange algorithm.
CALG_HASH_REPLACE_OWF = 0x0000800b, // One way function hashing algorithm.
CALG_HUGHES_MD5 = 0x0000a003, // Hughes MD5 hashing algorithm.
CALG_HMAC = 0x00008009, // HMAC keyed hash algorithm.
CALG_KEA_KEYX = 0x0000aa04, // KEA key exchange algorithm (FORTEZZA).
CALG_MAC = 0x00008005, // MAC keyed hash algorithm.
CALG_MD2 = 0x00008001, // MD2 hashing algorithm.
CALG_MD4 = 0x00008002, // MD4 hashing algorithm.
CALG_MD5 = 0x00008003, // MD5 hashing algorithm.
CALG_NO_SIGN = 0x00002000, // No signature algorithm.
CALG_OID_INFO_CNG_ONLY = 0xffffffff, // Algorithm is only implemented in CNG.
CALG_OID_INFO_PARAMETERS = 0xfffffffe, // Algorithm is defined in the encoded parameters.
CALG_PCT1_MASTER = 0x00004c04, // Used by the Schannel.dll operations system.
CALG_RC2 = 0x00006602, // RC2 block encryption algorithm.
CALG_RC4 = 0x00006801, // RC4 stream encryption algorithm.
CALG_RC5 = 0x0000660d, // RC5 block encryption algorithm.
CALG_RSA_KEYX = 0x0000a400, // RSA public key exchange algorithm.
CALG_RSA_SIGN = 0x00002400, // RSA public key signature algorithm.
CALG_SCHANNEL_ENC_KEY = 0x00004c07, // Used by the Schannel.dll operations system.
CALG_SCHANNEL_MAC_KEY = 0x00004c03, // Used by the Schannel.dll operations system.
CALG_SCHANNEL_MASTER_HASH = 0x00004c02, // Used by the Schannel.dll operations system.
CALG_SEAL = 0x00006802, // SEAL encryption algorithm.
CALG_SHA = 0x00008004, // SHA hashing algorithm.
CALG_SHA1 = 0x00008004, // Same as CALG_SHA.
CALG_SHA_256 = 0x0000800c, // 256-bit SHA hashing algorithm.
CALG_SHA_384 = 0x0000800d, // 384-bit SHA hashing algorithm.
CALG_SHA_512 = 0x0000800e, // 512-bit SHA hashing algorithm.
CALG_SKIPJACK = 0x0000660a, // Skipjack block encryption algorithm (FORTEZZA).
CALG_SSL2_MASTER = 0x00004c05, // Used by the Schannel.dll operations system.
CALG_SSL3_MASTER = 0x00004c01, // Used by the Schannel.dll operations system.
CALG_SSL3_SHAMD5 = 0x00008008, // Used by the Schannel.dll operations system.
CALG_TEK = 0x0000660b, // TEK (FORTEZZA).
CALG_TLS1_MASTER = 0x00004c06, // Used by the Schannel.dll operations system.
CALG_TLS1PRF = 0x0000800a // Used by the Schannel.dll operations system.
};
// https://devblogs.microsoft.com/oldnewthing/20040315-00/?p=40253
struct SID {
u8 revisionlvl[[name("RevisionLevel"), comment("SID_REVISION")]];
u8 dashes[[name("NoOfDashes"), comment("number of dashes minus two")]]; // dashes = actualdashes - 0x2
char ntauth[0x6][[name("NtAuthority"), comment("SECURITY_NT_AUTHORITY")]];
u32 subatuh1[[name("SubAuthority1"), comment("SECURITY_NT_NON_UNIQUE")]];
u32 subatuh2[[name("SubAuthority2"), comment("these identify the machine that issued the SID")]];
u32 subatuh3[[name("SubAuthority3"), comment("these identify the machine that issued the SID")]];
u32 subatuh4[[name("SubAuthority4"), comment("these identify the machine that issued the SID")]];
u32 rid[[name("RID"), comment("unique user id on the machine")]];
};
struct CREDHIST_HEADER{
u32 version[[name("Version")]];
type::GUID guid[[name("GUID")]];
u32 nextlen[[name("NextCredSize")]];
};
struct CREDHIST {
CREDHIST_HEADER credheader[[name("CredHistHeader")]];
if (std::mem::eof()){
break;
}
u32 flgas [[name("Flags")]];
ALG_ID alghashid[[name("AlgorithmHashId")]];
u32 rounds [[name("Rounds")]];
u32 sidlen [[name("SIDLen")]];
ALG_ID algcryptid[[name("AlgorithmCryptId")]];
u32 sha1len[[name("SHA1Len")]];
u32 md4len[[name("ntlmlen")]];
char salt[0x10][[name("Salt")]];
SID sid[[name("SID")]];
char sha1hash[sha1len][[name("SHA1Hash")]];
char md4hash[md4len][[name("NTLMHash")]];
u64 unk1[[name("Unknown")]];
};
CREDHIST credhist [while(!std::mem::eof())] @ 0x0[[name("CredHist")]];

View File

@@ -1,4 +1,7 @@
#pragma description DirectDraw Surface
#pragma MIME image/vnd-ms.dds
#pragma MIME image/x-dds
#pragma endian little
enum DXGI_FORMAT : u32 {
@@ -165,16 +168,26 @@ bitfield Caps2Flags {
};
bitfield PixelFormatFlags {
alphaPixels : 1;
alpha : 1;
fourCC : 1;
padding : 3;
rgb : 1; // 0x40
padding : 2;
yuv : 1; // 0x200
padding : 3;
luminance : 1; // 0x20000
padding : 17;
alphaPixels : 1; // DDPF_ALPHAPIXELS
alpha : 1; // DDPF_ALPHA
fourCC : 1; // DDPF_FOURCC
paletteIndexed4 : 1; // DDPF_PALETTEINDEXED4
paletteIndexedTo8 : 1; // DDPF_PALETTEINDEXEDTO8
paletteIndexed8 : 1; // DDPF_PALETTEINDEXED8
rgb : 1; // DDPF_RGB
compressed : 1; // DDPF_COMPRESSED
rgbToYuv : 1; // DDPF_RGBTOYUV
yuv : 1; // DDPF_YUV
zBuffer : 1; // DDPF_ZBUFFER
paletteIndexed1 : 1; // DDPF_PALETTEINDEXED1
paletteIndexed2 : 1; // DDPF_PALETTEINDEXED2
zPixels : 1; // DDPF_ZPIXELS
stencilBuffer : 1; // DDPF_STENCILBUFFER
alphaResult : 1; // DDPF_ALPHARESULT
luminance : 1; // DDPF_LUMINANCE
bumpLuminance : 1; // DDPF_BUMPLUMINANCE
bumpDudv : 1; // DDPF_BUMPDUDV
padding : 13; // Padding bits to complete 32-bit structure
};
enum DX10ResourceDimension : u32 {
@@ -190,7 +203,7 @@ enum DX10AlphaMode : u32 {
Straight,
PreMultiplied,
Opaque,
Custom,
Custom,
};
bitfield DX10MiscFlags {

View File

@@ -1,4 +1,6 @@
#include <type/leb128.pat>
#pragma description Dalvik EXecutable
import type.leb128;
struct header_item {
u8 magic[8];
@@ -97,7 +99,7 @@ enum access_flag : type::uLEB128{
static = 0x8,
final = 0x10,
synchronized = 0x20,
volatile = 0x40
volatile = 0x40
};
struct encoded_field {
@@ -132,7 +134,7 @@ struct class_def_item {
u32 class_data_off;
//class_data_item *class_data_off:u32;
u32 static_values_off;
char class_name[] @ addressof(parent.type_ids[class_idx].type_name);
char class_name[] @ addressof(parent.type_ids[class_idx].type_name);
}[[name(class_name)]];
struct type_item {
@@ -170,5 +172,8 @@ struct Dex {
field_id_item field_ids[header.field_ids_size] @ header.field_ids_off;
method_id_item method_ids[header.method_ids_size] @ header.method_ids_off;
class_def_item class_defs[header.class_defs_size] @ header.class_defs_off;
u8 data[header.data_size] @header.data_off;
map_list map_list @ header.map_off;
u8 link_data[header.link_size] @ header.link_off;
};
Dex dex @ 0x00;
Dex dex @ 0x00;

5594
patterns/dicom.hexpat Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,49 +1,51 @@
#pragma description Apple Disk Image Trailer (DMG)
#pragma endian big
#include <type/magic.pat>
#include <type/size.pat>
#include <type/guid.pat>
#include <std/mem.pat>
import type.magic;
import type.size;
import type.guid;
import std.mem;
// Parse DMG Structure per http://newosxbook.com/DMG.html
//
// UDIFResourceFile starts at size(file) - 512
struct UDIFResourceFile {
type::Magic<"koly"> Signature; // Magic ('koly')
u32 Version; // Current version is 4
type::Size<u32> HeaderSize; // sizeof(this), always 512
type::Magic<"koly"> Signature; // Magic ('koly')
u32 Version; // Current version is 4
type::Size<u32> HeaderSize; // sizeof(this), always 512
u32 Flags;
u64 RunningDataForkOffset; //
u64 DataForkOffset; // Data fork offset (usually 0, beginning of file)
type::Size<u64> DataForkLength; // Size of data fork (usually up to the XMLOffset, below)
u64 RsrcForkOffset; // Resource fork offset, if any
type::Size<u64> RsrcForkLength; // Resource fork length, if any
u32 SegmentNumber; // Usually 1, may be 0
u32 SegmentCount; // Usually 1, may be 0
type::GUID SegmentID; // 128-bit GUID identifier of segment (if SegmentNumber !=0)
u64 RunningDataForkOffset; //
u64 DataForkOffset; // Data fork offset (usually 0, beginning of file)
type::Size<u64> DataForkLength; // Size of data fork (usually up to the XMLOffset, below)
u64 RsrcForkOffset; // Resource fork offset, if any
type::Size<u64> RsrcForkLength; // Resource fork length, if any
u32 SegmentNumber; // Usually 1, may be 0
u32 SegmentCount; // Usually 1, may be 0
u32 DataChecksumType; // Data fork
type::GUID SegmentID; // 128-bit GUID identifier of segment (if SegmentNumber !=0)
u32 DataChecksumType; // Data fork
type::Size<u32> DataChecksumSize; // Checksum Information
u32 DataChecksum[DataChecksumSize]; // Up to 128-bytes (32 x 4) of checksum
u32 DataChecksum[32]; // Up to 128-bytes (32 x 4) of checksum
u64 XMLOffset; // Offset of property list in DMG, from beginning
type::Size<u64> XMLLength; // Length of property list
u8 Reserved1[120]; // 120 reserved bytes - zeroed
u64 XMLOffset; // Offset of property list in DMG, from beginning
type::Size<u64> XMLLength; // Length of property list
u8 Reserved1[120]; // 120 reserved bytes - zeroed
u32 ChecksumType; // Master
type::Size<u32> ChecksumSize; // Checksum information
u32 Checksum[ChecksumSize]; // Up to 128-bytes (32 x 4) of checksum
u32 ChecksumType; // Master
type::Size<u32> ChecksumSize; // Checksum information
u32 Checksum[32]; // Up to 128-bytes (32 x 4) of checksum
u32 ImageVariant; // Commonly 1
u64 SectorCount; // Size of DMG when expanded, in sectors
u32 ImageVariant; // Commonly 1
u64 SectorCount; // Size of DMG when expanded, in sectors
u32 reserved2; // 0
u32 reserved3; // 0
u32 reserved4; // 0
u32 reserved2; // 0
u32 reserved3; // 0
u32 reserved4; // 0
};
UDIFResourceFile trailer @ std::mem::size() - 512;
char metadata_plist[trailer.XMLLength] @ trailer.XMLOffset;
char metadata_plist[trailer.XMLLength] @ trailer.XMLOffset;

102
patterns/dmp64.hexpat Normal file
View File

@@ -0,0 +1,102 @@
#pragma magic [50 41 47 45] // PAGE
#pragma author "5h4rrK"
#pragma description "KERNEL DUMP"
import std.core;
import std.io;
import std.array;
#define COMMENT_SIZE 0x80
fn format_values(auto val){
return std::format("{:#x}", val);
};
fn format_size_values(auto val){
return std::format(
"{:#x} ({}) ",
val,
std::format("{:#x}",val * 0x1000)
);
};
union DUMP_FILE_ATTRIBUTES {
u32 bitfields[[name("BitFields")]];
u32 attributes[[name("Attributes")]];
};
enum DUMP_TYPE : u32 {
FULL_DUMP = 0x01,
BITMAP_DUMP = 0x05
};
struct EXCEPTION_RECORD64
{
u32 exception_code[[name("ExceptionCode"), format("format_values")]];
u32 exception_flags[[name("ExceptionFlags"), format("format_values")]];
u64 exception_record[[name("ExceptionRecord"), format("format_values")]];
u64 exception_address[[name("ExceptionAddress"), format("format_values")]];
u32 number_parameters[[name("NumberParameters"), format("format_values")]];
u32 unused_alignment[[name("Alignment"), format("format_values")]];
u64 exception_information[15][[name("ExceptionInformation")]];
};
struct PHYSICAL_MEMORY_RUN64 {
u64 base_page [[ name("BasePage"), format("format_size_values"), comment("StartOffset = BasePage * PageSize")]];
u64 page_count[[ name("PageCount"),format("format_size_values"), comment("Length = PageCount * PageSize")]];
}[[name("PHYSICAL_MEMORY_RUN_ENTRY")]];
struct PHYSICAL_MEMORY_DESCRIPTOR64 {
u32 no_of_runs [[name("NumberOfRuns")]];
char description[4][[name("Description")]];
u64 no_of_pages[[name("NumberOfPages"),format("format_values")]];
// PHYSICAL_MEMORY_RUN64 pmr64[no_of_runs] [[name("PHYSICAL_MEMORY_RUN64")]];
std::Array<PHYSICAL_MEMORY_RUN64, no_of_runs> pmrObjs[[name("PHYSICAL_MEMORY_RUN64")]];
};
struct DUMP_HEADER64 {
char signature[4][[name("Signature")]];
char validdump[4][[name("ValidDump")]];
u32 major_version[[name("MajorVersion")]];
u32 minor_version[[name("MinorVersion")]];
u64 dtb [[name("DirectoryBaseTable"),format("format_values")]];
u64 pfn [[name("PfnDataBase"), format("format_values")]];
u64 ploadedmodulelist [[name("PsLoadedModuleList"), format("format_values")]];
u64 pactiveprocesshead [[name("PsActiveProcessHead"), format("format_values")]];
u32 machine_type [[name("MachineImageType"), format("format_values")]];
u32 processor_counts [[name("ProcessorsCount")]];
u32 bug_check [[name("BugCheckCode"), format("format_values")]];
u32 bug_check_code_desc[[name("BugCheckCodeDescription"), format("format_values")]];
u64 bug_check_param1[[name("BugCheckCodeParameter1"), format("format_values")]];
u64 bug_check_param2[[name("BugCheckCodeParameter2"), format("format_values")]];
u64 bug_check_param3[[name("BugCheckCodeParameter3"), format("format_values")]];
u64 bug_check_param4[[name("BugCheckCodeParameter4"), format("format_values")]];
char version_user[0x20][[name("VersionUser")]];
u64 kdbg[[name("KdDebuggerDataBlock"), format("format_values")]];
PHYSICAL_MEMORY_DESCRIPTOR64 phys_mem_desc[[name("PHYSICAL_MEMORY_DESCRIPTOR64")]];
char mem_block_buffer[0x260][[name("PhysicalMemoryBlockBuffer")]];
char context_record[0xbb8][[name("ContextRecord")]];
EXCEPTION_RECORD64 excr[[name("EXCEPTION_RECORD64")]];
DUMP_TYPE dmp_type[[name("DumpType")]];
char desc1[4][[name("Description")]];
u64 req_dump_space[[name("RequiredDumpSpace"), format("format_values")]];
u64 sys_time[[name("SystemTime"), format("format_values")]];
char comment[COMMENT_SIZE][[name("Comment")]];
u64 sys_up_time[[name("SystemUpTime"), format("format_values")]];
u32 min_dmp_fields[[name("MiniDumpFields"), format("format_values")]];
u32 sec_data_state[[name("SecondaryDataState"), format("format_values")]];
u32 product_type[[name("ProductType"), format("format_values")]];
u32 suite_mask[[name("SuiteMask"), format("format_values")]];
u32 writer_status[[name("WriterStatus"), format("format_values")]];
char unused1[[name("Unused1")]];
char secondary_version[[name("KdSecondaryVersion")]];
char unused2[2][[name("Unused2")]];
DUMP_FILE_ATTRIBUTES dfa[[name("DUMP_FILE_ATTRIBUTES")]];
u32 boot_id[[name("BootId")]];
char reserved[0xfa8][[name("Reserved")]];
};
DUMP_HEADER64 dmp @0x00 [[name("DumpHeader")]];

73
patterns/dpapiblob.hexpat Normal file
View File

@@ -0,0 +1,73 @@
#pragma description "DPAPI Blob"
import type.guid;
import std.mem;
enum ALG_ID : u32 {
CALG_DH_EPHEM = 0x0000aa02,
CALG_DH_SF = 0x0000aa01,
CALG_DSS_SIGN = 0x00002200,
CALG_ECDH = 0x0000aa05,
CALG_ECDH_EPHEM = 0x0000ae06,
CALG_ECDSA = 0x00002203,
CALG_ECMQV = 0x0000a001,
CALG_HASH_REPLACE_OWF = 0x0000800b,
CALG_HUGHES_MD5 = 0x0000a003,
CALG_HMAC = 0x00008009,
CALG_KEA_KEYX = 0x0000aa04,
CALG_MAC = 0x00008005,
CALG_MD2 = 0x00008001,
CALG_MD4 = 0x00008002,
CALG_MD5 = 0x00008003,
CALG_NO_SIGN = 0x00002000,
CALG_OID_INFO_CNG_ONLY = 0xffffffff,
CALG_OID_INFO_PARAMETERS = 0xfffffffe,
CALG_PCT1_MASTER = 0x00004c04,
CALG_RC2 = 0x00006602,
CALG_RC4 = 0x00006801,
CALG_RC5 = 0x0000660d,
CALG_RSA_KEYX = 0x0000a400,
CALG_RSA_SIGN = 0x00002400,
CALG_SCHANNEL_ENC_KEY = 0x00004c07,
CALG_SCHANNEL_MAC_KEY = 0x00004c03,
CALG_SCHANNEL_MASTER_HASH = 0x00004c02,
CALG_SEAL = 0x00006802,
CALG_SHA = 0x00008004,
CALG_SHA1 = 0x00008004,
CALG_SHA_256 = 0x0000800c,
CALG_SHA_384 = 0x0000800d,
CALG_SHA_512 = 0x0000800e,
CALG_SKIPJACK = 0x0000660a,
CALG_SSL2_MASTER = 0x00004c05,
CALG_SSL3_MASTER = 0x00004c01,
CALG_SSL3_SHAMD5 = 0x00008008,
CALG_TEK = 0x0000660b,
CALG_TLS1_MASTER = 0x00004c06,
CALG_TLS1PRF = 0x0000800a
};
struct DPAPI_BLOB{
u32 version[[name("Version")]];
type::GUID providerguid[[name("ProviderGUID")]];
u32 masterguid[[name("MasterKeyVersion")]];
type::GUID guid[[name("MasterKeyGUID")]];
u32 flags[[name("Flags")]];
u32 desclen [[name("DescriptionLen")]];
char16 desc[desclen / 0x02 ] [[name("Description")]];
ALG_ID cryptid [[name("AlgCryptId")]];
u32 algcryptlen[[name("AlgCryptLen")]];
u32 saltlen [[name("SaltLen")]];
char salt[saltlen][[name("Salt")]];
u32 hmackeylen[[name("HMACKeyLen")]];
char hmackey[hmackeylen][[name("HMACKey")]];
ALG_ID algid[[name("AlgHashId")]];
u32 alghashkeylen[[name("AlgHashKeyLen")]];
u32 hmac2keylen[[name("HMAC2keylen")]];
char hmac2[hmac2keylen][[name("HMAC2Key")]];
u32 datalen[[name("DataLen")]];
char data[datalen][[name("Data")]];
u32 signlen[[name("signlen")]];
char signhash[signlen][[name("SignHash")]];
};
DPAPI_BLOB dpapiblob @0x00 [[name("DPAPIBlob")]];

View File

@@ -0,0 +1,124 @@
#pragma description "DPAPIMasterKey"
/*
FilePath: C:\Users\<USER>\AppData\Roaming\Microsoft\Protect\<SID>
This files are hidden.
To unhide it,
1. Open Command Prompt (cmd.exe).
2. Run the following command:
- attrib -h -s
*/
import type.guid;
// https://learn.microsoft.com/en-us/windows/win32/seccrypto/alg-id
enum ALG_ID : u32 {
CALG_DH_EPHEM = 0x0000aa02,
CALG_DH_SF = 0x0000aa01,
CALG_DSS_SIGN = 0x00002200,
CALG_ECDH = 0x0000aa05,
CALG_ECDH_EPHEM = 0x0000ae06,
CALG_ECDSA = 0x00002203,
CALG_ECMQV = 0x0000a001,
CALG_HASH_REPLACE_OWF = 0x0000800b,
CALG_HUGHES_MD5 = 0x0000a003,
CALG_HMAC = 0x00008009,
CALG_KEA_KEYX = 0x0000aa04,
CALG_MAC = 0x00008005,
CALG_MD2 = 0x00008001,
CALG_MD4 = 0x00008002,
CALG_MD5 = 0x00008003,
CALG_NO_SIGN = 0x00002000,
CALG_OID_INFO_CNG_ONLY = 0xffffffff,
CALG_OID_INFO_PARAMETERS = 0xfffffffe,
CALG_PCT1_MASTER = 0x00004c04,
CALG_RC2 = 0x00006602,
CALG_RC4 = 0x00006801,
CALG_RC5 = 0x0000660d,
CALG_RSA_KEYX = 0x0000a400,
CALG_RSA_SIGN = 0x00002400,
CALG_SCHANNEL_ENC_KEY = 0x00004c07,
CALG_SCHANNEL_MAC_KEY = 0x00004c03,
CALG_SCHANNEL_MASTER_HASH = 0x00004c02,
CALG_SEAL = 0x00006802,
CALG_SHA = 0x00008004,
CALG_SHA1 = 0x00008004,
CALG_SHA_256 = 0x0000800c,
CALG_SHA_384 = 0x0000800d,
CALG_SHA_512 = 0x0000800e,
CALG_SKIPJACK = 0x0000660a,
CALG_SSL2_MASTER = 0x00004c05,
CALG_SSL3_MASTER = 0x00004c01,
CALG_SSL3_SHAMD5 = 0x00008008,
CALG_TEK = 0x0000660b,
CALG_TLS1_MASTER = 0x00004c06,
CALG_TLS1PRF = 0x0000800a
};
struct CREDHIST_MASTERKEY {
u32 version[[name("Version")]];
type::GUID guid[[name("GUID")]];
};
struct DOMAINKEY_MASTERKEY {
u32 version[[name("Version")]];
u32 seclen[[name("SecretLen")]];
u32 accesschklen[[name("AccessCheckLen")]];
type::GUID backupguid_[[name("BackupKeyGUID")]];
char blob[seclen][[name("Secret")]];
char accesschk[accesschklen][[name("AccessCheck")]];
};
struct BACKUP_MASTERKEY {
u32 start = $;
u32 version[[name("Version")]];
char salt[16][[name("Salt")]];
u32 rounds [[name("PBKDF2IterationCount")]];
ALG_ID alghashid[[name("HMACAlgId")]];
ALG_ID algcryptid[[name("CryptAlgId")]];
u32 meta = $ - start;
char key[parent.backupkeylen - meta][[name("Key")]];
};
struct PASSWORD_MASTERKEY {
u32 start = $;
u32 version[[name("Version")]];
char salt[16][[name("Salt")]];
u32 rounds [[name("PBKDF2IterationCount")]];
ALG_ID alghashid[[name("HMACAlgId")]];
ALG_ID algcryptid[[name("CryptAlgId")]];
u32 meta = $ - start;
char key[parent.masterkeylen - meta][[name("Key")]];
};
struct DPAPIMasterKey {
u32 version[[name("Version")]];
u32 unk1[[name("Unknown1")]];
u32 unk2[[name("Unknown2")]];
char16 guid[0x24][[name("GUID"), comment("This GUID is the fileName itself")]];
u32 unk3[[name("Unknown3")]];
u32 unk4[[name("Unknown4")]];
u32 policy[[name("Policy")]];
u64 masterkeylen [[name("MasterKeyLen")]];
u64 backupkeylen [[name("BackupKeyLen")]];
u64 credhistlen [[name("CredHistoryLen")]];
u64 domainkeylen [[name("DomainKeyLen")]];
if (masterkeylen > 0){
PASSWORD_MASTERKEY masterkey[[name("MasterKey")]];
}
if (backupkeylen > 0){
BACKUP_MASTERKEY backupkey[[name("BackupKey")]];
}
if (credhistlen > 0){
CREDHIST_MASTERKEY credhistkey[[name("CredHistoryKey")]];
}
if (domainkeylen > 0){
DOMAINKEY_MASTERKEY domainkey[[name("DomainKey")]];
}
};
DPAPIMasterKey masterkey @0x00[[name("DPAPIMasterKey")]];

View File

@@ -1,15 +1,17 @@
#pragma description macOS .DS_Store
// Apple macOS .DS_Store format
#pragma endian big
#include <std/io.pat>
import std.io;
struct RecordEntry {
u32 length;
char16 filename[length];
char id[4];
// either blob or length
char type[4];
if (type == "blob") {
u32 blobCount;
u8 blobData[blobCount];
@@ -65,15 +67,15 @@ struct BuddyBlock {
u8 reserved[4];
// padding for next multiple of 256 entries (1024 bytes)
u32 addresses[blockCount];
// u8 padding[paddingCount];
u32 directoryCount;
// directory entries
u8 count;
u8 name[count];
u32 blockNumber;
// free lists
// 32 free lists
BuddyRootBlockOffsets off[32];
@@ -94,7 +96,7 @@ struct BuddyAllocator {
u32 offsetBookkeeping2;
u32 offsetData;
u8 reserved[12];
BuddyRootBlock root @ offsetBookkeeping + 4;
std::print("TOC {} address 0x{:08x}",
@@ -102,7 +104,7 @@ struct BuddyAllocator {
root.offsets.addresses[root.toc.toc[0].value] >> 0x5 << 0x5);
BlocksList blocks @ (root.offsets.addresses[root.toc.toc[0].value] >> 0x5 << 0x5) + 4;
std::print("Blocks start at address 0x{:08x}, size 0x{:04x}",
root.offsets.addresses[blocks.blockId] >> 0x5 << 0x5,
1 << (root.offsets.addresses[blocks.blockId] & 0x1f));

117
patterns/dted.hexpat Normal file
View File

@@ -0,0 +1,117 @@
#pragma description Digital Terrain Elevation Data
#pragma endian big
import std.core;
import std.io;
import std.mem;
import std.string;
enum Magic:u24 {
UHL = 0x55484C,
DSI = 0x445349,
ACC = 0x414343,
};
struct UHL {
Magic magic;
char one;
char lon[8];
char lat[8];
char lon_data_interval[4];
char lat_data_interval[4];
char accuracy[4];
char security_code[3];
char uniq_ref[12];
char lon_lines[4];
char lat_points[4];
char multi_accuracy;
char reserved[24];
};
struct DSI {
Magic magic;
char classification;
char stuff1[29];
char stuff2[26];
char product_level[5];
char uniq_ref[15];
char reserved[8];
char data_edition[2];
char match_version;
char maint_date[4];
char match_date[4];
char main_desc_code[4];
char producer_code[8];
char reserved2[16];
char product_spec[9];
char numbers[2];
char product_spec_date[4];
char vertical_datum[3];
char horizontal_datum[5];
char digitizing_system[10];
char compilation_date[4];
char reserved3[22];
char lat_origin[9];
char lon_origin[10];
char lat_sw_corner[7];
char lon_sw_corner[8];
char lat_nw_corner[7];
char lon_nw_corner[8];
char lat_ne_corner[7];
char lon_ne_corner[8];
char lat_se_corner[7];
char lon_se_corner[8];
char clockwise_orientation[9];
char lat_interval[4];
char lon_interval[4];
char lat_lines[4];
char lon_lines[4];
char partial_cell[2];
char reserved4[101];
char reserved5[100];
char reserved6[156];
};
struct ACCSub {
char abs_vertical_accuracy[4];
char abs_horizontal_accuracy[4];
char rel_vertical_accuracy[4];
char rel_horizontal_accuracy[4];
char num_coords[2];
char pairs[19*14];
};
struct ACC {
Magic magic;
char abs_horizontal_accuracy[4];
char abs_vertical_accuracy[4];
char rel_horizontal_accuracy[4];
char rel_vertical_accuracy[4];
char reserved1[4];
char reserved2[1];
char reserved3[31];
char multi_accuracy_outline[2]; // determines sub regions
ACCSub subs[9];
char reserved4[18];
char reserved5[69];
};
struct DataRecords {
char magic;
s24 data_block_count;
s16 lon_count;
s16 lat_count;
s16 elevation[std::string::parse_int(parent.dsi.lat_lines, 10)];
u32 checksum;
};
struct DTED {
UHL uhl;
DSI dsi;
ACC acc;
DataRecords records[std::string::parse_int(this.dsi.lon_lines, 10)];
};
DTED dted @ 0x00;

View File

@@ -1,12 +1,16 @@
#pragma author WerWolv
#pragma description Executable and Linkable Format executable (ELF)
#pragma MIME application/x-executable
#pragma MIME application/x-elf
#pragma MIME application/x-coredump
#pragma MIME application/x-object
#pragma MIME application/x-sharedlib
#include <std/core.pat>
#include <std/io.pat>
#include <std/mem.pat>
import std.core;
import std.io;
import std.mem;
import type.magic;
using BitfieldOrder = std::core::BitfieldOrder;
@@ -495,12 +499,12 @@ bitfield SHF {
bitfield ELF32_R_INFO {
SYM : 8;
TYPE : 8;
} [[left_to_right]];
} [[bitfield_order(BitfieldOrder::MostToLeastSignificant, 16)]];
bitfield ELF64_R_INFO {
SYM : 32;
TYPE : 32;
} [[left_to_right]];
} [[bitfield_order(BitfieldOrder::MostToLeastSignificant, 64)]];
bitfield PF {
X : 1;
@@ -512,7 +516,7 @@ bitfield PF {
};
struct E_IDENT {
char EI_MAG[4];
type::Magic<"\x7fELF"> EI_MAG;
EI_CLASS EI_CLASS;
EI_DATA EI_DATA;
EI_VERSION EI_VERSION;
@@ -562,8 +566,8 @@ struct Elf32_Phdr {
Elf32_Word p_memsz;
PF p_flags;
Elf32_Word p_align;
if (p_offset > 0 && p_filesz > 0 && (p_offset + p_filesz) < std::mem::size() && p_filesz < std::mem::size())
if (p_offset >= 0 && p_filesz > 0 && (p_offset + p_filesz) <= std::mem::size() && p_filesz <= std::mem::size())
u8 p_data[p_filesz] @ p_offset [[sealed]];
};
@@ -576,8 +580,8 @@ struct Elf64_Phdr {
Elf64_Xword p_filesz;
Elf64_Xword p_memsz;
Elf64_Xword p_align;
if (p_offset > 0 && p_filesz > 0 && (p_offset + p_filesz) < std::mem::size() && p_filesz < std::mem::size())
if (p_offset >= 0 && p_filesz > 0 && (p_offset + p_filesz) <= std::mem::size() && p_filesz <= std::mem::size())
u8 p_data[p_filesz] @ p_offset [[sealed]];
};
@@ -633,13 +637,13 @@ struct Elf32_Shdr {
Elf32_Word sh_info;
Elf32_Word sh_addralign;
Elf32_Word sh_entsize;
if (sh_size > 0 && sh_offset + sh_size < std::mem::size()) {
if (sh_type == SHT::NOBITS || sh_type == SHT::NULL) {
// Section has no data
} else if (sh_type == SHT::STRTAB) {
String stringTable[while($ < (sh_offset + sh_size))] @ sh_offset;
stringTableIndex = std::core::array_index();
stringTableIndex = std::core::array_index();
} else if (sh_type == SHT::SYMTAB || sh_type == SHT::DYNSYM) {
Elf32_Sym symbolTable[sh_size / sh_entsize] @ sh_offset;
} else if (sh_type == SHT::INIT_ARRAY || sh_type == SHT::FINI_ARRAY) {
@@ -648,7 +652,7 @@ struct Elf32_Shdr {
u8 data[sh_size] @ sh_offset [[sealed]];
}
}
} [[format("format_section_header")]];;
} [[format("format_section_header")]];
struct Elf64_Chdr {
u32 ch_type;
@@ -693,13 +697,13 @@ struct Elf64_Shdr {
Elf64_Word sh_info;
Elf64_Xword sh_addralign;
Elf64_Xword sh_entsize;
if (sh_size > 0 && sh_offset + sh_size < std::mem::size()) {
if (sh_type == SHT::NOBITS || sh_type == SHT::NULL) {
// Section has no data
} else if (sh_type == SHT::STRTAB) {
String stringTable[while($ < (sh_offset + sh_size))] @ sh_offset;
stringTableIndex = std::core::array_index();
stringTableIndex = std::core::array_index();
} else if (sh_type == SHT::SYMTAB || sh_type == SHT::DYNSYM) {
Elf64_Sym symbolTable[sh_size / sh_entsize] @ sh_offset;
} else if (sh_type == SHT::INIT_ARRAY || sh_type == SHT::FINI_ARRAY) {
@@ -712,27 +716,22 @@ struct Elf64_Shdr {
fn format_section_header(auto shdr) {
u32 i = 0;
u32 nameAddress = addressof(elf.shdr[stringTableIndex].stringTable) + shdr.sh_name;
while (i < std::core::member_count(elf.shdr[stringTableIndex].stringTable)) {
if (nameAddress >= addressof(elf.shdr[stringTableIndex].stringTable[i]) && nameAddress < (addressof(elf.shdr[stringTableIndex].stringTable[i]) + sizeof(elf.shdr[stringTableIndex].stringTable[i])))
break;
i += 1;
}
return elf.shdr[stringTableIndex].stringTable[i].value;
u32 nameAddress = addressof(elf.shdr[stringTableIndex].stringTable) + shdr.sh_name;
String string @ nameAddress;
return string;
};
struct ELF {
E_IDENT e_ident;
if (e_ident.EI_DATA == EI_DATA::ELFDATA2LSB)
std::core::set_endian(std::mem::Endian::Little);
else
std::core::set_endian(std::mem::Endian::Big);
if (e_ident.EI_CLASS == EI_CLASS::ELFCLASS32) {
Elf32_Ehdr ehdr;
Elf32_Phdr phdr[ehdr.e_phnum] @ ehdr.e_phoff;
@@ -819,4 +818,4 @@ fn main() {
);
}
}
};
};

View File

@@ -1,3 +1,5 @@
#pragma description MS Windows Vista Event Log
#pragma endian little
struct Header {

543
patterns/ext4.hexpat Normal file
View File

@@ -0,0 +1,543 @@
#pragma author endes
#pragma description ext4 volume layout parser (until inodes)
// Decodes the ext4 superblock, group descriptors and inodes.
// Does not decode the directory entries, inode data, jornal or superblock backups.
// Heavily based on the linux kernel documentation:
// https://www.kernel.org/doc/html/latest/filesystems/ext4/
#pragma endian little
#pragma magic [53 EF] @ 0x438
#pragma pattern_limit 0x90000
import type.time;
import type.size;
import type.magic;
import std.core;
import std.mem;
import std.math;
enum ext4_super_state : u16 {
Cleanlyumounted = 0x01,
Errorsdetected = 0x02,
Orphansbeingrecovered = 0x03
};
enum ext4_super_errors : u16 {
Continue = 0x01,
RemountReadOnly = 0x02,
Panic = 0x03
};
enum ext4_super_creator : u32 {
Linux = 0x00,
Hurd = 0x01,
Masix = 0x02,
FreeBSD = 0x03,
Lites = 0x04
};
enum ext4_super_revision : u32 {
ORIGINAL = 0x00,
V2_DYNAMIC_REV = 0x01
};
bitfield ext4_super_compat {
COMPAT_DIR_PREALLOC : 1 [[comment("Directory preallocation.")]];
COMPAT_IMAGIC_INODES : 1 [[comment("“imagic inodes”. Not clear from the code what this does.")]];
COMPAT_HAS_JOURNAL : 1 [[comment("Has a journal.")]];
COMPAT_EXT_ATTR : 1 [[comment("Supports extended attributes.")]];
COMPAT_RESIZE_INODE : 1 [[comment("Has reserved GDT blocks for filesystem expansion.")]];
COMPAT_DIR_INDEX : 1 [[comment("Has directory indices.")]];
COMPAT_LAZY_BG : 1 [[comment("“Lazy BG”. Not in Linux kernel, seems to have been for uninitialized block groups?.")]];
COMPAT_EXCLUDE_INODE : 1 [[comment("“Exclude inode”. Not used.")]];
COMPAT_EXCLUDE_BITMAP : 1 [[comment("“Exclude bitmap”. Seems to be used to indicate the presence of snapshot-related exclude bitmaps? Not defined in linux kernel or used in e2fsprogs.")]];
COMPAT_SPARSE_SUPER2 : 1 [[comment("Sparse Super Block, v2. If this flag is set, the SB field s_backup_bgs points to the two block groups that contain backup superblocks.")]];
COMPAT_FAST_COMMIT : 1 [[comment("Journal fast commits supported.")]];
padding : 1;
RO_COMPAT_ORPHAN_PRESENT : 1 [[comment("Orphan file allocated. This is the special file for more efficient tracking of unlinked but still open inodes.")]];
};
bitfield ext4_super_incompat {
INCOMPAT_COMPRESSION : 1;
INCOMPAT_FILETYPE : 1 [[comment("Directory entries record the file type.")]];
INCOMPAT_RECOVER : 1 [[comment("Filesystem needs recovery.")]];
INCOMPAT_JOURNAL_DEV : 1 [[comment("Filesystem has a separate journal device.")]];
INCOMPAT_META_BG : 1 [[comment("Meta block groups.")]];
padding : 1;
INCOMPAT_EXTENTS : 1 [[comment("Files in this filesystem use extents.")]];
INCOMPAT_64BIT : 1 [[comment("Enable a filesystem size of 2^64 blocks.")]];
INCOMPAT_MMP : 1 [[comment("Multiple mount protection.")]];
INCOMPAT_FLEX_BG : 1 [[comment("Flexible block groups.")]];
INCOMPAT_EA_INODE : 1 [[comment("Inodes can be used to store large extended attribute values.")]];
padding : 1 [[comment("Data in directory entry.")]];
INCOMPAT_DIRDATA : 1;
INCOMPAT_CSUM_SEED : 1 [[comment("Metadata checksum seed is stored in the superblock.")]];
INCOMPAT_LARGEDIR : 1 [[comment("Large directory >2GB or 3-level htree.")]];
INCOMPAT_INLINE_DATA : 1 [[comment("Data in inode.")]];
INCOMPAT_ENCRYPT : 1 [[comment("Encrypted inodes are present on the filesystem.")]];
};
bitfield ext4_super_compat_ro {
RO_COMPAT_SPARSE_SUPER : 1 [[comment("Sparse superblocks.")]];
RO_COMPAT_LARGE_FILE : 1 [[comment("This filesystem has been used to store a file greater than 2GiB.")]];
RO_COMPAT_BTREE_DIR : 1 [[comment("Not used in linux kernel or e2fsprogs.")]];
RO_COMPAT_HUGE_FILE : 1 [[comment("This filesystem has files whose sizes are represented in units of logical blocks, not 512-byte sectors. This implies a very large file indeed!.")]];
RO_COMPAT_GDT_CSUM : 1 [[comment("Group descriptors have checksums.")]];
RO_COMPAT_DIR_NLINK : 1 [[comment("Indicates that the old ext3 32,000 subdirectory limit no longer applies.")]];
RO_COMPAT_EXTRA_ISIZE : 1 [[comment("Indicates that large inodes exist on this filesystem.")]];
RO_COMPAT_HAS_SNAPSHOT : 1 [[comment("This filesystem has a snapshot.")]];
RO_COMPAT_QUOTA : 1;
RO_COMPAT_BIGALLOC : 1 [[comment("This filesystem supports “bigalloc”, which means that file extents are tracked in units of clusters (of blocks) instead of blocks.")]];
RO_COMPAT_METADATA_CSUM : 1 [[comment("This filesystem supports metadata checksumming.")]];
RO_COMPAT_REPLICA : 1 [[comment("Filesystem supports replicas. This feature is neither in the kernel nor e2fsprogs.")]];
RO_COMPAT_READONLY : 1 [[comment("Read-only filesystem image.")]];
RO_COMPAT_PROJECT : 1 [[comment("Filesystem tracks project quotas.")]];
padding : 1;
RO_COMPAT_VERITY : 1 [[comment("Verity inodes may be present on the filesystem.")]];
RO_COMPAT_ORPHAN_PRESENT : 1 [[comment("Indicates orphan file may have valid orphan entries and thus we need to clean them up when mounting the filesystem.")]];
};
enum ext4_super_def_hash : u8 {
LEGACY = 0x00,
HALF_MD4 = 0x01,
TEA = 0x02,
LEGACY_UNSIGNED = 0x03,
HALF_MD4_UNSIGNED = 0x04,
TEA_UNSIGNED = 0x05
};
bitfield ext4_super_mountopts {
EXT4_DEFM_DEBUG : 1 [[comment("Print debugging info upon (re)mount.")]];
EXT4_DEFM_BSDGROUPS : 1 [[comment("New files take the gid of the containing directory (instead of the fsgid of the current process).")]];
EXT4_DEFM_XATTR_USER : 1 [[comment("Support userspace-provided extended attributes.")]];
EXT4_DEFM_ACL : 1 [[comment("Support POSIX access control lists (ACLs).")]];
EXT4_DEFM_UID16 : 1 [[comment("Do not support 32-bit UIDs.")]];
EXT4_DEFM_JMODE_DATA : 1 [[comment("All data and metadata are committed to the journal.")]];
EXT4_DEFM_JMODE_ORDER : 1 [[comment("All data are flushed to the disk before metadata are committed to the journal.")]];
padding : 1;
EXT4_DEFM_NOBARRIER : 1 [[comment("Disable write flushes.")]];
EXT4_DEFM_BLOCK_VALIDITY : 1 [[comment("Track which blocks in a filesystem are metadata and therefore should not be used as data blocks.")]];
EXT4_DEFM_DISCARD : 1 [[comment("Enable DISCARD support, where the storage device is told about blocks becoming unused.")]];
EXT4_DEFM_NODELALLOC : 1 [[comment("Disable delayed allocation.")]];
};
bitfield ext4_super_flags {
SIGNED_HASH_DIRECTORY : 1;
UNSIGNED_HASH_DIRECTORY : 1;
TEST_DEV_CODE : 1;
};
enum ext4_super_encrypt_algos : u8 {
ENCRYPTION_MODE_INVALID = 0x00,
ENCRYPTION_MODE_AES_256_XTS = 0x01,
ENCRYPTION_MODE_AES_256_GCM = 0x02,
ENCRYPTION_MODE_AES_256_CBC = 0x03,
};
struct ext4_super_block {
u32 s_inodes_count [[comment("Total inode count.")]];
u32 s_blocks_count_lo [[comment("Total block count.")]];
u32 s_r_blocks_count_lo [[comment("This number of blocks can only be allocated by the super-user.")]];
u32 s_free_blocks_count_lo [[comment("Free block count.")]];
u32 s_free_inodes_count [[comment("Free inode count.")]];
u32 s_first_data_block [[comment("First data block. This must be at least 1 for 1k-block filesystems and is typically 0 for all other block sizes.")]];
u32 s_log_block_size;
u32 s_log_cluster_size;
u64 block_size = std::math::pow(2, 10+s_log_block_size);
u64 cluster_size = std::math::pow(2, 10+s_log_cluster_size);
u32 s_blocks_per_group [[comment("Blocks per group.")]];
u32 s_clusters_per_group [[comment("Clusters per group, if bigalloc is enabled. Otherwise s_clusters_per_group must equal s_blocks_per_group.")]];
u32 s_inodes_per_group [[comment("Inodes per group.")]];
type::time32_t s_mtime [[comment("Last mount time, in seconds since the epoch.")]];
type::time32_t s_wtime [[comment("Last write time, in seconds since the epoch.")]];
u16 s_mnt_count [[comment("Number of mounts since the last fsck.")]];
u16 s_max_mnt_count [[comment("Number of mounts beyond which a fsck is needed.")]];
type::Magic<"\x53\xEF"> s_magic;
ext4_super_state s_state [[comment("File system state.")]];
ext4_super_errors s_errors [[comment("Behaviour when detecting errors.")]];
u16 s_minor_rev_level [[comment("Minor revision level.")]];
type::time32_t s_lastcheck [[comment("Time of last check, in seconds since the epoch.")]];
u32 s_checkinterval [[comment("Maximum time between checks, in seconds.")]];
ext4_super_creator s_creator_os [[comment("Creator OS.")]];
ext4_super_revision s_rev_level [[comment("Revision level.")]];
u16 s_def_resuid [[comment("Default uid for reserved blocks.")]];
u16 s_def_resgid [[comment("Default gid for reserved blocks.")]];
// EXT2_DYNAMIC_REV superblock
if (s_rev_level >= ext4_super_revision::V2_DYNAMIC_REV) {
u32 s_first_ino [[comment("First non-reserved inode.")]];
u16 s_inode_size [[comment("Size of inode structure, in bytes.")]];
u16 s_block_group_nr [[comment("Block group number of this superblock.")]];
ext4_super_compat s_feature_compat [[comment("Compatible feature set flags. Kernel can still read/write this fs even if it doesnt understand a flag; fsck should not do that.")]];
padding[2];
ext4_super_incompat s_feature_incompat [[comment("Incompatible feature set. If the kernel or fsck doesnt understand one of these bits, it should stop.")]];
padding[1];
ext4_super_compat_ro s_feature_ro_compat [[comment("Readonly-compatible feature set. If the kernel doesnt understand one of these bits, it can still mount read-only.")]];
padding[1];
u8 s_uuid[16] [[comment("128-bit UUID for volume.")]];
char s_volume_name[16] [[comment("Volume label.")]];
char s_last_mounted[64] [[comment("Directory where filesystem was last mounted.")]];
if (s_feature_incompat.INCOMPAT_COMPRESSION) {
u32 s_algorithm_usage_bitmap;
} else {
padding[4];
}
// Performance hints
if (s_feature_compat.COMPAT_DIR_PREALLOC) {
u8 s_prealloc_blocks [[comment("Number of blocks to try to preallocate for ... files? (Not used in e2fsprogs/Linux).")]];
u8 s_prealloc_dir_blocks [[comment("Number of blocks to preallocate for directories. (Not used in e2fsprogs/Linux).")]];
} else {
padding[2];
}
u16 s_reserved_gdt_blocks [[comment("Number of reserved GDT entries for future filesystem expansion.")]];
// Journaling support
if (s_feature_compat.COMPAT_HAS_JOURNAL) {
u8 s_journal_uuid[16] [[comment("UUID of journal superblock.")]];
u32 s_journal_inum [[comment("Inode number of journal file.")]];
if (s_feature_incompat.INCOMPAT_JOURNAL_DEV) {
u32 s_journal_dev [[comment("Device number of journal file.")]];
} else {
padding[4];
}
} else {
padding[24];
}
u32 s_last_orphan [[comment("Inode start of list of orphaned inodes to delete.")]];
u32 s_hash_seed[4] [[comment("HTREE hash seed.")]];
ext4_super_def_hash s_def_hash_version [[comment("Default hash algorithm to use for directory hashes.")]];
u8 s_jnl_backup_type [[comment("If this value is 0 or EXT3_JNL_BACKUP_BLOCKS (1), then the s_jnl_blocks field contains a duplicate copy of the inodes i_block[] array and i_size.")]];
if (s_feature_incompat.INCOMPAT_64BIT) {
u16 s_desc_size [[comment("Size of group descriptors, in bytes, if the 64bit incompat feature flag is set.")]];
} else {
padding[2];
}
ext4_super_mountopts s_default_mount_opts [[comment("Default mount options.")]];
padding[2];
if (s_feature_incompat.INCOMPAT_META_BG) {
u32 s_first_meta_bg [[comment("First metablock block group, if the meta_bg feature is enabled.")]];
} else {
padding[4];
}
type::time32_t s_mkfs_time [[comment("When the filesystem was created, in seconds since the epoch.")]];
u32 s_jnl_blocks[17] [[comment("Backup copy of the journal inodes i_block[] array in the first 15 elements and i_size_high and i_size in the 16th and 17th elements, respectively.")]];
if (s_feature_incompat.INCOMPAT_64BIT) {
u32 s_blocks_count_hi [[comment("High 32-bits of the block count.")]];
u32 s_r_blocks_count_hi [[comment("High 32-bits of the reserved block count.")]];
u32 s_free_blocks_count_hi [[comment("High 32-bits of the free block count.")]];
u64 s_blocks_count = (u64(s_blocks_count_hi) << 32) + s_blocks_count_lo;
u64 s_r_blocks_count = (u64(s_r_blocks_count_hi) << 32) + s_r_blocks_count_lo;
u64 s_free_blocks_count = (u64(s_free_blocks_count_hi) << 32) + s_free_blocks_count_lo;
u64 groups_count = std::math::ceil(s_blocks_count/float(s_blocks_per_group));
} else {
padding[12];
u64 s_blocks_count = s_blocks_count_lo;
u64 s_r_blocks_count = s_r_blocks_count_lo;
u64 s_free_blocks_count = s_free_blocks_count_lo;
u64 groups_count = std::math::ceil(s_blocks_count/float(s_blocks_per_group));
}
if (s_feature_ro_compat.RO_COMPAT_EXTRA_ISIZE) {
u16 s_min_extra_isize [[comment("All inodes have at least # bytes.")]];
u16 s_want_extra_isize [[comment("New inodes should reserve # bytes.")]];
} else {
padding[4];
}
ext4_super_flags s_flags [[comment("Miscellaneous flags.")]];
padding[3];
u16 s_raid_stride [[comment("RAID stride. This is the number of logical blocks read from or written to the disk before moving to the next disk. This affects the placement of filesystem metadata.")]];
if (s_feature_incompat.INCOMPAT_MMP) {
u16 s_mmp_interval [[comment("Number of seconds to wait in multi-mount prevention (MMP) checking.")]];
u64 s_mmp_block [[comment("Block number for multi-mount protection data.")]];
} else {
padding[10];
}
u32 s_raid_stripe_width [[comment("RAID stripe width. This is the number of logical blocks read from or written to the disk before coming back to the current disk.")]];
if (s_feature_incompat.INCOMPAT_FLEX_BG) {
u8 s_log_groups_per_flex;
u64 groups_per_flex = std::math::pow(2, s_log_groups_per_flex);
} else {
padding[1];
}
if (s_feature_ro_compat.RO_COMPAT_METADATA_CSUM) {
u8 s_checksum_type [[comment("Metadata checksum algorithm type.")]];
} else {
padding[1];
}
padding[2];
u64 s_kbytes_written [[comment("Number of KiB written to this filesystem over its lifetime.")]];
if (s_feature_ro_compat.RO_COMPAT_HAS_SNAPSHOT) {
u32 s_snapshot_inum [[comment("inode number of active snapshot. (Not used in e2fsprogs/Linux.)")]];
u32 s_snapshot_id [[comment("Sequential ID of active snapshot. (Not used in e2fsprogs/Linux.)")]];
u64 s_snapshot_r_blocks_count [[comment("Number of blocks reserved for active snapshots future use. (Not used in e2fsprogs/Linux.)")]];
u32 s_snapshot_list [[comment("inode number of the head of the on-disk snapshot list. (Not used in e2fsprogs/Linux.)")]];
} else {
padding[20];
}
u32 s_error_count [[comment("Number of errors seen.")]];
if (s_error_count > 0) {
type::time32_t s_first_error_time [[comment("First time an error happened.")]];
u32 s_first_error_ino [[comment("inode involved in first error.")]];
u64 s_first_error_block [[comment("Number of block involved of first error.")]];
char s_first_error_func[32] [[comment("Name of function where the error happened.")]];
u32 s_first_error_line [[comment("Line number where error happened.")]];
type::time32_t s_last_error_time [[comment("Last time an error happened.")]];
u32 s_last_error_ino [[comment("inode involved in most recent error.")]];
u32 s_last_error_line [[comment("Line number where most recent error happened.")]];
u64 s_last_error_block [[comment("Number of block involved in most recent error.")]];
char s_last_error_func[32] [[comment("Name of function where the most recent error happened.")]];
} else {
padding[104];
}
char s_mount_opts[64] [[comment("ASCIIZ string of mount options.")]];
if (s_feature_ro_compat.RO_COMPAT_QUOTA) {
u32 s_usr_quota_inum [[comment("Inode number of user quota file.")]];
u32 s_grp_quota_inum [[comment("Inode number of group quota file.")]];
} else {
padding[8];
}
u32 s_overhead_blocks [[comment("Overhead blocks/clusters in fs. (Huh? This field is always zero, which means that the linux kernel calculates it dynamically.)")]];
if (s_feature_compat.COMPAT_SPARSE_SUPER2) {
u32 s_backup_bgs[2] [[comment("Block groups containing superblock backups.")]];
} else {
padding[8];
}
if (s_feature_incompat.INCOMPAT_ENCRYPT) {
ext4_super_encrypt_algos s_encrypt_algos[4] [[comment("Encryption algorithms in use. There can be up to four algorithms in use at any time.")]];
u8 s_encrypt_pw_salt[16] [[comment("Salt for the string2key algorithm for encryption.")]];
} else {
padding[20];
}
u32 s_lpf_ino [[comment("Inode number of lost+found.")]];
if (s_feature_ro_compat.RO_COMPAT_PROJECT) {
u32 s_prj_quota_inum [[comment("Inode that tracks project quotas.")]];
} else {
padding[4];
}
if (s_feature_ro_compat.RO_COMPAT_METADATA_CSUM) {
u32 s_checksum_seed [[comment("Checksum seed used for metadata_csum calculations. This value is crc32c(~0, $orig_fs_uuid).")]];
} else {
padding[4];
}
u8 s_wtime_hi [[comment("Upper 8 bits of the s_wtime field.")]];
u8 s_mtime_hi [[comment("Upper 8 bits of the s_mtime field.")]];
u8 s_mkfs_time_hi [[comment("Upper 8 bits of the s_mkfs_time field.")]];
u8 s_lastcheck_hi [[comment("Upper 8 bits of the s_lastcheck field.")]];
u8 s_first_error_time_hi [[comment("Upper 8 bits of the s_first_error_time field.")]];
u8 s_last_error_time_hi [[comment("Upper 8 bits of the s_last_error_time field.")]];
padding[2];
u16 s_encoding [[comment("Filename charset encoding.")]];
u16 s_encoding_flags [[comment("Filename charset encoding flags.")]];
if (s_feature_compat.RO_COMPAT_ORPHAN_PRESENT) {
u32 s_orphan_file_inum [[comment("Orphan file inode number.")]];
} else {
padding[4];
}
padding[376];
if (s_feature_ro_compat.RO_COMPAT_METADATA_CSUM) {
u32 s_checksum [[comment("Superblock checksum.")]];
} else {
padding[4];
}
}
};
ext4_super_block super_block @ 0x400;
fn block_to_address(u32 block) {
return super_block.block_size * block;
};
fn block_pointer_to_address(u32 block) {
return block_to_address(block) - block;
};
struct ext4_bitmap {
u8 data[super_block.block_size];
};
bitfield ext4_i_mode {
S_IXOTH : 1 [[comment("Others may execute.")]];
S_IWOTH : 1 [[comment("Others may write.")]];
S_IROTH : 1 [[comment("Others may read.")]];
S_IXGRP : 1 [[comment("Group members may execute.")]];
S_IWGRP : 1 [[comment("Group members may write.")]];
S_IRGRP : 1 [[comment("Group members may read.")]];
S_IXUSR : 1 [[comment("Owner may execute.")]];
S_IWUSR : 1 [[comment("Owner may write.")]];
S_IRUSR : 1 [[comment("Owner may read.")]];
S_ISVTX : 1 [[comment("Sticky bit.")]];
S_ISGID : 1 [[comment("Set GID.")]];
S_ISUID : 1 [[comment("Set UID.")]];
S_IFIFO : 1 [[comment("FIFO.")]];
S_IFCHR : 1 [[comment("Character device.")]];
S_IFDIR : 1 [[comment("Directory.")]];
S_IFREG : 1 [[comment("Regular file.")]];
};
bitfield ext4_i_flags {
EXT4_SECRM_FL : 1 [[comment("This file requires secure deletion.")]];
EXT4_UNRM_FL : 1 [[comment("This file should be preserved, should undeletion be desired.")]];
EXT4_COMPR_FL : 1 [[comment("File is compressed.")]];
EXT4_SYNC_FL : 1 [[comment("All writes to the file must be synchronous.")]];
EXT4_IMMUTABLE_FL : 1 [[comment("File is immutable.")]];
EXT4_APPEND_FL : 1 [[comment("File can only be appended.")]];
EXT4_NODUMP_FL : 1 [[comment("The dump utility should not dump this file.")]];
EXT4_NOATIME_FL : 1 [[comment("Do not update access time.")]];
EXT4_DIRTY_FL : 1 [[comment("Dirty compressed file.")]];
EXT4_COMPRBLK_FL : 1 [[comment("File has one or more compressed clusters.")]];
EXT4_NOCOMPR_FL : 1 [[comment("Do not compress file.")]];
EXT4_ENCRYPT_FL : 1 [[comment("Encrypted inode.")]];
EXT4_INDEX_FL : 1 [[comment("Directory has hashed indexes.")]];
EXT4_IMAGIC_FL : 1 [[comment("AFS magic directory.")]];
EXT4_JOURNAL_DATA_FL : 1 [[comment("File data must always be written through the journal.")]];
EXT4_NOTAIL_FL : 1 [[comment("File tail should not be merged.")]];
EXT4_DIRSYNC_FL : 1 [[comment("All directory entry data should be written synchronously.")]];
EXT4_TOPDIR_FL : 1 [[comment("Top of directory hierarchy.")]];
EXT4_HUGE_FILE_FL : 1 [[comment("This is a huge file.")]];
EXT4_EXTENTS_FL : 1 [[comment("Inode uses extents.")]];
EXT4_VERITY_FL : 1 [[comment("Verity protected file.")]];
EXT4_EA_INODE_FL : 1 [[comment("Inode stores a large extended attribute value in its data blocks.")]];
EXT4_EOFBLOCKS_FL : 1 [[comment("This file has blocks allocated past EOF.")]];
padding : 1;
EXT4_SNAPFILE_FL : 1 [[comment("Inode is a snapshot.")]];
padding : 1;
EXT4_SNAPFILE_DELETED_FL : 1 [[comment("Snapshot is being deleted.")]];
EXT4_SNAPFILE_SHRUNK_FL : 1 [[comment("Snapshot shrink has completed.")]];
EXT4_INLINE_DATA_FL : 1 [[comment("Inode has inline data.")]];
EXT4_PROJINHERIT_FL : 1 [[comment("Create children with the same project ID.")]];
padding : 1;
EXT4_RESERVED_FL : 1 [[comment("Reserved for ext4 library.")]];
};
struct ext4_inode {
ext4_i_mode i_mode [[comment("File mode.")]];
u16 i_uid [[comment("Lower 16-bits of Owner UID.")]];
u32 i_size [[comment("Lower 32-bits of size in bytes.")]];
type::time32_t i_atime [[comment("Last access time.")]];
type::time32_t i_ctime [[comment("Last inode change time.")]];
type::time32_t i_mtime [[comment("Last data modification time.")]];
type::time32_t i_dtime [[comment("Deletion Time.")]];
u16 i_gid [[comment("Lower 16-bits of GID.")]];
u16 i_links_count [[comment("Hard link count.")]];
u32 i_blocks_lo [[comment("Lower 32-bits of “block” count.")]];
ext4_i_flags i_flags [[comment("Inode flags.")]];
u32 i_osd1 [[comment("Depends of the OS.")]];
u32 i_block[15] [[comment("Block map or extent tree.")]];
u32 i_generation [[comment("File version (for NFS).")]];
u32 i_file_acl [[comment("Lower 32-bits of extended attribute block.")]];
u32 i_dir_acl [[comment("Upper 32-bits of file/directory size.")]];
u32 i_faddr [[comment("Fragment address.")]];
u8 i_osd2[12] [[comment("Depends of the OS.")]];
if (super_block.s_rev_level >= ext4_super_revision::V2_DYNAMIC_REV && super_block.s_inode_size > 0x80) {
u16 i_extra_isize [[comment("Size of this inode - 128.")]];
u16 i_checksum_hi [[comment("Upper 16-bits of the inode checksum.")]];
if (super_block.s_inode_size > 0x84) {
u32 i_ctime_extra [[comment("Extra change time bits.")]];
u32 i_mtime_extra [[comment("Extra modification time bits.")]];
u32 i_atime_extra [[comment("Extra access time bits.")]];
u32 i_crtime [[comment("File creation time.")]];
u32 i_crtime_extra [[comment("Extra file creation time bits.")]];
if (super_block.s_inode_size > 0x98) {
u32 i_version_hi [[comment("Upper 32-bits for version number.")]];
if (super_block.s_inode_size > 0x9C) {
u32 i_projid [[comment("Project ID.")]];
if (super_block.s_inode_size > 0xA0) {
padding[super_block.s_inode_size - 0xA0];
}
}
}
}
}
};
bitfield ext4_bg_flags {
EXT4_BG_INODE_UNINIT : 1 [[comment("Inode table and bitmap are not initialized.")]];
EXT4_BG_BLOCK_UNINIT : 1 [[comment("Block bitmap is not initialized.")]];
EXT4_BG_INODE_ZEROED : 1 [[comment("Inode table is zeroed.")]];
};
struct ext4_group_desc {
ext4_bitmap *bg_block_bitmap : u32 [[pointer_base("block_pointer_to_address"), comment("Lower 32-bits of location of block bitmap.")]];
ext4_bitmap *bg_inode_bitmap : u32 [[pointer_base("block_pointer_to_address"), comment("Lower 32-bits of location of inode bitmap.")]];
ext4_inode *bg_inode_table[super_block.s_inodes_per_group] : u32 [[pointer_base("block_pointer_to_address"), comment("Lower 32-bits of location of inode table.")]];
u16 bg_free_blocks_count [[comment("Lower 16-bits of free block count.")]];
u16 bg_free_inodes_count [[comment("Lower 16-bits of free inode count.")]];
u16 bg_used_dirs_count [[comment("Lower 16-bits of directory count.")]];
ext4_bg_flags bg_flags [[comment("Block group flags.")]];
padding[1];
u32 bg_exclude_bitmap_lo [[comment("Lower 32-bits of location of snapshot exclusion bitmap.")]];
u16 bg_block_bitmap_csum_lo [[comment("Lower 16-bits of the block bitmap checksum.")]];
u16 bg_inode_bitmap_csum_lo [[comment("Lower 16-bits of the inode bitmap checksum.")]];
u16 bg_itable_unused_lo [[comment("Lower 16-bits of unused inode count.")]];
u16 bg_checksum [[comment("Group descriptor checksum.")]];
};
struct ext4_group_desc_64_bit : ext4_group_desc {
u32 bg_block_bitmap_hi [[comment("Upper 32-bits of location of block bitmap.")]];
u32 bg_inode_bitmap_hi [[comment("Upper 32-bits of location of inodes bitmap.")]];
u32 bg_inode_table_hi [[comment("Upper 32-bits of location of inodes table.")]];
u16 bg_free_blocks_count_hi [[comment("Upper 16-bits of free block count.")]];
u16 bg_free_inodes_count_hi [[comment("Upper 16-bits of free inode count.")]];
u16 bg_used_dirs_count_hi [[comment("Upper 16-bits of directory count.")]];
u16 bg_itable_unused_hi [[comment("Upper 16-bits of unused inode count.")]];
u32 bg_exclude_bitmap_hi [[comment("Upper 32-bits of location of snapshot exclusion bitmap.")]];
u16 bg_block_bitmap_csum_hi [[comment("Upper 16-bits of the block bitmap checksum.")]];
u16 bg_inode_bitmap_csum_hi [[comment("Upper 16-bits of the inode bitmap checksum.")]];
padding[4];
};
struct ext4_group_descriptors {
if (super_block.s_rev_level >= ext4_super_revision::V2_DYNAMIC_REV && super_block.s_feature_incompat.INCOMPAT_64BIT) {
ext4_group_desc_64_bit group_desc[super_block.groups_count];
} else {
ext4_group_desc group_desc[super_block.groups_count];
}
};
ext4_group_descriptors group_descs @ block_to_address(2);

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