def perf_event_header(): return Embedded(Struct(None, Enum(UNInt32("type"), MMAP = 1, LOST = 2, COMM = 3, EXIT = 4, THROTTLE = 5, UNTHROTTLE = 6, FORK = 7, READ = 8, SAMPLE = 9, MMAP2 = 10, RECORD_AUX = 11, ITRACE_START = 12, LOST_SAMPLES = 13, SWITCH = 14, SWITCH_CPU_WIDE = 15, NAMESPACES = 16, KSYMBOL = 17, BPF_EVENT = 18, CGROUP = 19, HEADER_ATTR = 64, HEADER_EVENT_TYPE = 65, TRACING_DATA = 66, HEADER_BUILD_ID = 67, FINISHED_ROUND = 68, ID_INDEX = 69, AUXTRACE_INFO = 70, AUXTRACE = 71, AUXTRACE_ERROR = 72, THREAD_MAP = 73, CPU_MAP = 74, STAT_CONFIG = 75, STAT = 76, STAT_ROUND = 77, EVENT_UPDATE = 78, TIME_CONV = 79, HEADER_FEATURE = 80, COMPRESSED = 81), Embedded(BitStruct(None, Padding(1), Enum(BitField("cpumode", 7), UNKNOWN = 0, KERNEL = 1, USER = 2, HYPERVISOR = 3, GUEST_KERNEL = 4, GUEST_USER = 5), Flag("ext_reserved"), Flag("exact_ip"), Flag("mmap_data"), Padding(5))), UNInt16("size"), If(has_sample_id_all, Pointer(lambda ctx: ctx.start + ctx.size - 8, UNInt64("end_id"))), Value("attr", lookup_event_attr)))
def test_parse_nested(self): struct = BitStruct("foo", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), Struct( "bar", Nibble("d"), Bit("e"), )) self.assertEqual( struct.parse(b"\xe1\x1f"), Container(a=7, b=False, bar=Container(d=15, e=1), c=8))
def test_parse(self): struct = BitStruct("foo", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), BitField("d", 5), ) self.assertEqual(struct.parse(six.b("\xe1\x1f")), Container(a=7, b=False, c=8, d=31))
def world_start(name='world_start'): return Struct( name, Variant('planet'), StarByteArray('sky_data'), StarByteArray('weather_data'), BFloat32('x'), BFloat32('y'), # Dungeon ID stuff here Variant('world_properties'), UBInt32('client_id'), Flag('local_interpolation'))
def DirEntry(name): return Struct( name, Bytes("name", 8), Bytes("extension", 3), BitStruct("attributes", Flag("unused"), Flag("device"), Flag("archive"), Flag("subDirectory"), Flag("volumeLabel"), Flag("system"), Flag("hidden"), Flag("readonly")), # reserved Padding(10), ULInt16("timeRecorded"), ULInt16("dateRecorded"), ULInt16("firstCluster"), ULInt32("fileSize"))
def _parse(self, stream, context): x = Byte("").parse_stream(stream) if x == 0: return None elif x == 1: return star_string().parse_stream(stream) elif x == 2: return None elif x == 3: flag = Flag("").parse_stream(stream) return Field("", 16).parse_stream(stream).encode("hex") elif x == 4: return star_string().parse_stream(stream)
class Variant(Construct): RESPONSES = { 2: BFloat64('').parse_stream, 3: Flag('').parse_stream, 4: SignedVLQ('').parse_stream, 5: star_string().parse_stream, 6: VariantVariant('').parse_stream, 7: DictVariant('').parse_stream } def _parse(self, stream, context): x = Byte('').parse_stream(stream) return self.RESPONSES.get(x, lambda x: None)(stream)
def test(self): struct = BitStruct( "bitstruct", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), BitField("d", 5), ) self.assertEqual(struct.parse(b"\xe1\x1f"), Container(a=7)(b=False)(c=8)(d=31)) self.assertEqual(struct.build(Container(a=7)(b=False)(c=8)(d=31)), b"\xe1\x1f")
def perf_event_header(): return Embedded( Struct( None, Enum(UNInt32("type"), MMAP=1, LOST=2, COMM=3, EXIT=4, THROTTLE=5, UNTHROTTLE=6, FORK=7, READ=8, SAMPLE=9, MMAP2=10, TRACING_DATA=66, FINISHED_ROUND=68, ID_INDEX=69, AUXTRACE_INFO=70, AUXTRACE=71, AUXTRACE_ERROR=72), Embedded( BitStruct( None, Padding(1), Enum(BitField("cpumode", 7), UNKNOWN=0, KERNEL=1, USER=2, HYPERVISOR=3, GUEST_KERNEL=4, GUEST_USER=5), Flag("ext_reserved"), Flag("exact_ip"), Flag("mmap_data"), Padding(5))), UNInt16("size"), If( has_sample_id_all, Pointer(lambda ctx: ctx.start + ctx.size - 8, UNInt64("end_id"))), Value("attr", lookup_event_attr)))
def test_nested(self): struct = BitStruct("bitstruct", BitField("a", 3), Flag("b"), Padding(3), Nibble("c"), Struct( "sub", Nibble("d"), Bit("e"), )) self.assertEqual( struct.parse(b"\xe1\x1f"), Container(a=7)(b=False)(c=8)(sub=Container(d=15)(e=1))) self.assertEqual( struct.build( Container(a=7)(b=False)(c=8)(sub=Container(d=15)(e=1))), b"\xe1\x1f")
def _parse(self, stream, context): x = Byte("").parse_stream(stream) if x == 1: return None elif x == 2: return BFloat64("").parse_stream(stream) elif x == 3: return Flag("").parse_stream(stream) elif x == 4: return SignedVLQ("").parse_stream(stream) elif x == 5: return star_string().parse_stream(stream) elif x == 6: return VariantVariant("").parse_stream(stream) elif x == 7: return DictVariant("").parse_stream(stream)
def Bool(*args, **kwargs): return Flag(*args, default=True, **kwargs)
def test_parse(self): flag = Flag("flag") self.assertTrue(flag.parse(b"\x01"))
def test_build_flipped(self): flag = Flag("flag", truth=0, falsehood=1) self.assertEqual(flag.build(True), b"\x00")
def test_build(self): flag = Flag("flag") self.assertEqual(flag.build(True), b"\x01")
def test_parse_default(self): flag = Flag("flag") self.assertFalse(flag.parse(b"\x02"))
RPLIDAR_ANS_TYPE_DEVHEALTH = 0x6 RPLIDAR_STATUS_OK = 0x0 RPLIDAR_STATUS_WARNING = 0x1 RPLIDAR_STATUS_ERROR = 0x2 RPLIDAR_RESP_MEASUREMENT_SYNCBIT = 0x1 << 0 RPLIDAR_RESP_MEASUREMENT_QUALITY_SHIFT = 2 RPLIDAR_RESP_MEASUREMENT_CHECKBIT = 0x1 << 0 RPLIDAR_RESP_MEASUREMENT_ANGLE_SHIFT = 1 ## #As defined by Figure 9. in "rplidar_interface_protocol_en.pdf" ## rplidar_response_device_measurement_format = Struct( "measurement_format", BitStruct("byte0", BitField("quality", 6), Flag("syncbit_inverse"), Flag("syncbit")), BitStruct( "byte1", BitField("angle_low", 7), Const(Flag("check_bit"), 1) # Must be set to 1 ), ULInt8("angle_high"), ULInt16("distance_q2")) ## # As defined by Figure 12. in "rplidar_interface_protocol_en.pdf" ## rplidar_response_device_info_format = Struct("info_format", ULInt8("model"), ULInt8("firmware_minor"), ULInt8("firmware_major"),
def entity_destroy(name='entity_destroy'): return Struct(name, UBInt32('entity_id'), Flag('death'))
def __init__(self, data): ip = Struct( "ip_header", EmbeddedBitStruct(Const(Nibble("version"), 4), Nibble("header_length")), BitStruct("tos", Bits("precedence", 3), Flag("minimize_delay"), Flag("high_throuput"), Flag("high_reliability"), Flag("minimize_cost"), Padding(1)), UBInt16("total_length"), UBInt16("id"), UBInt16("flags"), UBInt8("ttl"), Enum(UBInt8("proto"), UDP=0x11, TCP=0x06, HOPOPT=0x00, ICMP=0x01, IGMP=0x02, GGP=0x03, IPoIP=0x04, ST=0x05, CBT=0x07, EGP=0x08, IGP=0x09, NVPII=0x0B, PUP=0x0C, ARGUS=0x0D, EMCON=0x0E, XNET=0x0F, CHAOS=0x10, MUX=0x12, DCNMEAS=0x13, HMP=0x14, PRM=0x15, RDP=0x1B, IRTP=0x1C, ISOTP4=0x1D, DCCP=0x21, XTP=0x24, DDP=0x25, IL=0x28, IPv6=0x29, SDRP=0x2A, IPv6Route=0x2B, IPv6Frag=0x2C, IDRP=0x2D, RSVP=0x2E, GRE=0x2F, MHRP=0x30, BNA=0x31, ESP=0x32, AH=0x33, SWIPE=0x35, MOBILE=0x37, TLSP=0x38, SKIP=0x39, IPv6ICMP=0x3A, IPv6NoNxt=0x3B, IPv6Opts=0x3C, CFTP=0x3E, SATEXPAK=0x40, KRYPTOLAN=0x41, RVD=0x42, IPPC=0x43, SATMON=0x45, VISA=0x46, IPCU=0x47, CPNX=0x48, CPHB=0x49, WSN=0x4A, PVP=0x4B, BRSATMON=0x4C, SUNND=0x4D, WBMON=0x4E, WBEXPAK=0x4F, ISOIP=0x50, VMTP=0x51, SECUREVMTP=0x52, VINES=0x53, TTP=0x54, IPTM=0x54, NSFNETIGP=0x55, DGP=0x56, TCF=0x57, EIGRP=0x58, OSPF=0x59, LARP=0x5B, MTP=0x5C, IPIP=0x5E, MICP=0x5F, SCCSP=0x60, ETHERIP=0x61, ENCAP=0x62, GMTP=0x64, IFMP=0x65, PNNI=0x66, PIM=0x67, ARIS=0x68, SCPS=0x69, QNX=0x6A, IPComp=0x6C, SNP=0x6D, VRRP=0x70, PGM=0x71, L2TP=0x73, DDX=0x74, IATP=0x75, STP=0x76, SRP=0x77, UTI=0x78, SMP=0x79, SM=0x7A, PTP=0x7B, ISIS=0x7C, FIRE=0x7D, CRTP=0x7E, CRUDP=0x7F, SSCOPMCE=0x80, IPLT=0x81, SPS=0x82, SCTP=0x84, FC=0x85, UDPLite=0x88, MPLSoIP=0x89, manet=0x8A, HIP=0x8B, Shim6=0x8C, WESP=0x8D, ROHC=0x8E), UBInt16("checksum"), UBInt32("src"), UBInt32("dst"), ) self.ip = ip.parse(data[:ip.sizeof()]) self.ip.src = utils.IPv4Address(self.ip.src) self.ip.dst = utils.IPv4Address(self.ip.dst) data = data[ip.sizeof():] if self.ip.proto in ('TCP', 'UDP'): self.proto = Struct( "proto", UBInt16("sport"), UBInt16("dport"), ).parse(data) self.ip_sport = self.proto.sport self.ip_dport = self.proto.dport
# The DNS packet header itself, combining all of the above DNSHeader = Struct( 'DNSHeader', Anchor('packet_start'), UBInt16('identification'), BitStruct( 'flags_and_codes', Enum( BitField('qr', 1), # query/response QUERY=0, RESPONSE=1, ), Nibble('opcode'), # opcode Enum( Flag('aa'), # authoritative answer NON_AUTHORITATIVE=0, AUTHORITATIVE=1, ), Enum( Flag('tc'), # truncated NOT_TRUNCATED=0, TRUNCATED=1, ), Enum( Flag('rd'), # recursion desired RECURSION_NOT_DESIRED=0, RECURSION_DESIRED=1, ), Enum( Flag('ra'), # recursion available
def test_parse_default_true(self): flag = Flag("flag", default=True) self.assertTrue(flag.parse(b"\x02"))
def player_warp_result(name='player_warp_result'): return Struct(name, Flag('success'), warp_action(), Flag('warp_action_invalid'))
#!/usr/bin/env python import struct from binascii import hexlify from construct import BitStruct, BitField, Padding, Enum, Flag from pyrsp.rsp import CortexM3 from pyrsp.utils import unhex, switch_endian import capstone as cs import sys SCB_VTOR = 0xe000ed08 SCB_ICSR = 0xe000ed04 scb_icsr = BitStruct( "scb_icsr", Flag('NMIPENDSET'), Padding(2), Flag('PENDSVSET'), Flag('PENDSVCLR'), Flag('PENDSTSET'), Flag('PENDSTCLR'), Padding(2), #Padding(1), #Flag('DEBUG'), Flag('ISRPENDING'), BitField('VECTPENDING', 10), Flag('RETOBASE'), Padding(2), BitField('VECTACTIVE', 9), )
def update_tile_protection(name='update_tile_protection'): return Struct( name, GreedyRange( Struct('dungeon_block', UBInt16('dungeon_id'), Flag('is_protected'))))
from serial import Serial from construct import Struct, ULInt8, ULInt16, CString, Flag, Padding import struct from time import sleep _robotResponse = Struct("RobotResponse", Flag("success", truth=0, falsehood=1, default=False)) class RobotSerial(Serial): ''' Serial connection to the robot that allows for sending and receiving commands. ''' def __init__(self, port=None, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False, **kwargs): super(RobotSerial, self).__init__(port=port, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=timeout, xonxoff=xonxoff,
def damage_notification(name='damage_notification'): return Struct(name, UBInt32('source_entity_id'), UBInt32('source_entity_id_wut'), UBInt32('target_entity_id'), VLQ('x'), VLQ('y'), VLQ('damage'), star_string('damage_kind'), star_string('target_material'), Flag('killed'))
perf_event_attr = Struct( "perf_event_attr", Anchor("start"), Enum(UNInt32("type"), HARDWARE=0, SOFTWARE=1, TRACEPOINT=2, HW_CACHE=3, RAW=4, BREAKPOINT=5), UNInt32("size"), UNInt64("config"), UNInt64("sample_period_freq"), # must be in LE order, original is a u64 # each byte is reversed BitStruct("sample_type", Flag("cpu"), Flag("id"), Flag("callchain"), Flag("read"), Flag("addr"), Flag("time"), Flag("tid"), Flag("ip"), Flag("data_src"), Flag("weight"), Flag("stack_user"), Flag("regs_user"), Flag("branch_stack"), Flag("raw"), Flag("stream_id"), Flag("period"), Padding(5), Flag("regs_intr"), Flag("transaction"), Flag("identifier"), Padding(64 - 3 * 8)), BitStruct("read_format", Padding(4), Flag("group"), Flag("id"), Flag("total_time_running"), Flag("total_time_enabled"), Padding(64 - 1 * 8)), Embedded( BitStruct(None, Flag("disabled"), Flag("inherit"), Flag("pinned"), Flag("exclusive"), Flag("exclude_user"), Flag("exclude_kernel"), Flag("exclude_hv"), Flag("exclude_idle"), Flag("mmap"), Flag("comm"), Flag("freq"), Flag("inherit_stat"), Flag("enable_on_exec"), Flag("task"), Flag("watermark"),
def test_parse_flipped(self): flag = Flag("flag", truth=0, falsehood=1) self.assertFalse(flag.parse(b"\x01"))
def event(): return Embedded( Struct( "event", If(lambda ctx: sample_type(ctx).identifier, UNInt64("identifier")), If(lambda ctx: sample_type(ctx).ip, UNInt64("ip")), If(lambda ctx: sample_type(ctx).tid, Embedded(Struct("tid", SNInt32("pid"), SNInt32("tid")))), If(lambda ctx: sample_type(ctx).time, UNInt64("time")), If(lambda ctx: sample_type(ctx).addr, UNInt64("addr")), If(lambda ctx: sample_type(ctx).id, UNInt64("id")), If(lambda ctx: sample_type(ctx).stream_id, UNInt64("stream_id")), If(lambda ctx: sample_type(ctx).cpu, Embedded(Struct("cpu", UNInt32("cpu"), UNInt32("res")))), If(lambda ctx: sample_type(ctx).period, UNInt64("period")), If(lambda ctx: sample_type(ctx).read, read_format()), If( lambda ctx: sample_type(ctx).callchain, Struct("callchain", UNInt64("nr"), Array(lambda ctx: ctx.nr, UNInt64("caller")))), If( lambda ctx: sample_type(ctx).raw, Struct("raw", UNInt32("size"), Bytes("raw", lambda ctx: ctx.size))), If( lambda ctx: sample_type(ctx).branch_stack, Struct( "branch_stack", UNInt64("nr"), Array( lambda ctx: ctx.nr, Struct( "branch", UNInt64("from"), UNInt64("to"), # Little-Endian! BitStruct("flags", Padding(4), Flag("abort"), Flag("in_tx"), Flag("predicted"), Flag("mispred"), Padding(64 - 1 * 8)))))), If( lambda ctx: sample_type(ctx).regs_user, Struct("regs_user", Enum(UNInt64("abi"), NONE=0, ABI_32=1, ABI_64=2), Array(lambda ctx: hweight64(ctx), UNInt64("reg")))), If( lambda ctx: sample_type(ctx).stack_user, Struct("stack_user", UNInt64("size"), Bytes("data", lambda ctx: ctx.size), UNInt64("dyn_size"))), If(lambda ctx: sample_type(ctx).weight, UNInt64("weight")), If(lambda ctx: sample_type(ctx).data_src, UNInt64("data_src")), If(lambda ctx: sample_type(ctx).transaction, UNInt64("transaction")), If( lambda ctx: sample_type(ctx).regs_intr, Struct("regs_intr", Enum(UNInt64("abi"), NONE=0, ABI_32=1, ABI_64=2), Array(lambda ctx: hweight64(ctx), UNInt64("reg")))), Anchor("end_event"), Padding(lambda ctx: max(0, ctx.size - ctx.end_event))))
INDEX_FIELD_ORDER_TYPE_STRUCT = Enum(ULInt16('field_order_type'), ASCENDING=0, DESCENDING=1, _default_='DESCENDING') TABLE_DEFINITION_INDEX_STRUCT = Struct( 'record_table_definition_index', # May be external_filename # if external_filename == 0, no external file index CString('external_filename'), If(lambda x: len(x['external_filename']) == 0, Const(Byte('index_mark'), 1)), CString('name'), Embed( BitStruct('flags', Padding(1), INDEX_TYPE_STRUCT, Padding(2), Flag('NOCASE'), Flag('OPT'), Flag('DUP'))), ULInt16('field_count'), Array( lambda x: x['field_count'], Struct('index_field_propertly', ULInt16('field_number'), INDEX_FIELD_ORDER_TYPE_STRUCT)), ) MEMO_TYPE_STRUCT = Enum(Flag('memo_type'), MEMO=0, BLOB=1) TABLE_DEFINITION_MEMO_STRUCT = Struct( 'record_table_definition_memo', # May be external_filename # if external_filename == 0, no external file index CString('external_filename'), If(lambda x: len(x['external_filename']) == 0, Const(Byte('memo_mark'),