Skip to content

Instantly share code, notes, and snippets.

@danofsteel32
Created November 10, 2022 22:21
Show Gist options
  • Select an option

  • Save danofsteel32/3ba1b129e47bb4b7d5cc0836648f90c0 to your computer and use it in GitHub Desktop.

Select an option

Save danofsteel32/3ba1b129e47bb4b7d5cc0836648f90c0 to your computer and use it in GitHub Desktop.
Visualize Construct in Python
"""
MIT License
Copyright 2022 Dan Davis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import itertools
import re
from dataclasses import dataclass
from typing import List, Optional
import construct as c
from rich import print
from rich.text import Text
FORMAT_CHAR = {
">B": "Int8ub",
">H": "Int16ub",
">L": "Int32ul",
">Q": "Int32ub",
">b": "Int8sb",
">h": "Int16sb",
">l": "Int32sb",
">q": "Int64sb",
"<B": "Int8ul",
"<H": "Int16ul",
"<L": "Int32ul",
"<Q": "Int64ul",
"<b": "Int8ub",
"<h": "Int16ub",
"<l": "Int32ub",
"<q": "Int64ub",
"=B": "Int8un",
"=H": "Int16un",
"=L": "Int32un",
"=Q": "Int32un",
"=b": "Int8sn",
"=h": "Int16sn",
"=l": "Int32sn",
"=q": "Int64sn",
">e": "Float16b",
"<e": "Float16l",
"=e": "Float16n",
">f": "Float32b",
"<f": "Float32l",
"=f": "Float32n",
">d": "Float64b",
"<d": "Float64l",
"=d": "Float64n",
}
def tokens(text):
"""Hacky regex based parser."""
TOKEN_RX = r"""(?xm)
(?P<nonbuild> \+nonbuild )|
(?P<docs> \+docs )|
(?P<type> [^<\s]\w+[^>\s] )|
(?P<name> \s\w+\s )|
(?P<open> [<] )|
(?P<close> [>] )|
( \#.$ )|
( \s+ )
"""
for match in re.finditer(TOKEN_RX, text):
if match.lastgroup:
if match.lastgroup == "name":
yield (match.lastgroup, match[0].strip())
continue
yield (match.lastgroup, match[0])
@dataclass
class Field:
"""Used instead of a dict, its just a container."""
name: str
type: str
length: int
offset: int = 0 # has to be set later
color: str = ""
class VisiStruct:
"""
Visualize a Construct
Given a Construct and either some bytes that can build it or an already
parsed construct, try to work out the type, size, and offsets of every
subconstruct.
Notes:
- incredibly hacky
- would want flag for color output
"""
def __init__(
self,
format: c.Construct,
raw: Optional[bytes] = None,
parsed: Optional[c.Container] = None,
):
self.format = format
self._raw = raw
self._parsed = parsed
self.fields: List[Field]
@property
def raw(self):
if not self._raw:
if self._parsed:
self._raw = self.format.build(self._parsed)
return self._raw
@property
def parsed(self):
if not self._parsed:
if self._raw:
self._parsed = self.format.parse(self.raw)
return self._parsed
def create_fields(self, subcon=None) -> List[Field]:
"""Called recursively until all subcons parsed."""
fields = []
subcons = subcon if subcon else self.format.subcons
for sub in subcons:
types = []
name = ""
for kind, text in tokens(str(sub)):
if kind == "type" and text != "Renamed":
types.append(text)
elif kind == "name":
name = text
# print(sub)
# print(f" name: {name}")
# print(f" types: {types}")
# print()
if "Const" in types:
fields.append(Field(name, type=" ".join(types), length=sub.sizeof()))
elif "FormatField" in types:
if "Enum" in types:
type = sub.subcon.subcon.fmtstr
length = sub.subcon.subcon.length
else:
type = sub.subcon.fmtstr
length = sub.subcon.length
fields.append(Field(name, FORMAT_CHAR[type], length))
# Only handles CString rn
elif "StringEncoded" in types:
enc = sub.subcon.encoding
length = len(self.parsed[name].encode(enc))
if "NullTerminated" in types:
type = "CString"
length += 1 # NULL byte
fields.append(Field(name, type, length))
elif types == ["Struct"]:
fields.extend(self.create_fields(sub.subcon.subcons))
color_wheel = itertools.cycle(
["cyan", "grey", "green", "yellow", "purple", "orange"]
)
# Set offsets and colors
offset = 0
for f in fields:
offset += f.length
f.offset = offset
f.color = next(color_wheel)
self.fields = fields
return fields
def chunk_bytes(self, chunk_size: int) -> list:
if not self._raw:
raise Exception("raw is None")
fields = iter(self.fields)
field = next(fields)
as_hex = self._raw.hex()
as_hex += ".." * (len(as_hex) // 8 + 1)
out = []
n = 0
while n < (len(as_hex) - 2):
if n // 2 > field.offset - 1 and n > 0:
try:
field = next(fields)
except StopIteration:
pass
text = as_hex[n : n + 2]
if text == "..":
encoded = Text(f" {text} ")
else:
encoded = Text(f" {text} ", style=f"bold {field.color}")
out.append(encoded)
n += 2
return [out[i : i + chunk_size] for i in range(0, len(out), chunk_size)]
def print(self, width: int = 8):
# width sets how many bytes to print per line
fields = con.create_fields()
print("Name Type Sz Offset")
print("-----------------------------------------------")
for field in fields:
print(
Text(
f"{field.name:12} {field.type:16} {field.length:4} {field.offset:12}",
style=f"{field.color}",
)
)
print()
for chunk in self.chunk_bytes(width):
text = Text()
[text.append(c) for c in chunk]
print(text)
if __name__ == "__main__":
inner = c.Struct(
"my_id" / c.Int16ul,
"my_value" / c.Enum(c.Int32ul, HOT=1, COLD=2, JUST_RIGHT=3),
)
format = c.Struct(
"my_header" / c.Const(b"FAKE"),
"my_int" / c.Int32ul,
"my_string" / c.CString("ascii"),
"my_enum" / c.Enum(c.Int8ul, ONE=1, TWO=2, THREE=3),
"my_inner" / inner,
)
args = dict(
my_int=17,
my_string="helloworld",
my_enum="ONE",
my_inner=dict(my_id=3, my_value="HOT"),
)
raw = format.build(args)
con = VisiStruct(format, raw)
con.print(8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment