Python bitstring.ReadError() Examples

The following are 12 code examples of bitstring.ReadError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bitstring , or try the search function .
Example #1
Source File: game_data.py    From swarfarm with Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        if not _Strings._tables:
            f = _Strings._get_file()

            _Strings.version = f.read('intle:32')

            try:
                while True:
                    table_len = f.read('intle:32')
                    tbl = {}

                    for _ in range(table_len):
                        str_id, str_len = f.readlist('intle:32, intle:32')
                        parsed_str = binascii.a2b_hex(f.read('hex:{}'.format(str_len * 8))[:-4])
                        tbl[str_id] = parsed_str.decode("utf-8").strip()

                    _Strings._tables.append(tbl)

            except ReadError:
                # EOF
                pass 
Example #2
Source File: static.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def decrypt_images(**kwargs):
    path = kwargs.pop('path', 'herders/static/herders/images')
    for im_path in iglob(f'{path}/**/*.png', recursive=True):
        encrypted = BitStream(filename=im_path)

        # Check if it is 'encrypted'. 8th byte is 0x0B instead of the correct signature 0x0A
        encrypted.pos = 0x07 * 8
        signature = encrypted.peek('uint:8')
        if signature == 0x0B:
            print(f'Decrypting {im_path}')
            # Correct the PNG signature
            encrypted.overwrite('0x0A', encrypted.pos)

            # Replace bits with magic decrypted values
            try:
                while True:
                    pos = encrypted.pos
                    val = encrypted.peek('uint:8')
                    encrypted.overwrite(Bits(uint=com2us_decrypt_values[val], length=8), pos)
            except ReadError:
                # EOF
                pass

            # Write it back to the file
            with open(im_path, 'wb') as f:
                encrypted.tofile(f)

            continue

        # Check for weird jpeg format with extra header junk. Convert to png.
        encrypted.pos = 0
        if encrypted.peek('bytes:5') == b'Joker':
            print(f'Trimming and converting weird JPEG to PNG {im_path}')
            del encrypted[0:16 * 8]

            # Open it as a jpg and resave to disk
            try:
                new_imfile = Image.open(io.BytesIO(encrypted.tobytes()))
                new_imfile.save(im_path)
            except IOError:
                print(f'Unable to open {im_path}') 
Example #3
Source File: lift_bf.py    From angr-platforms with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse(self, bitstrm):
        self.last_instruction = False
        data = Instruction.parse(self, bitstrm)
        try:
            bitstrm.peek(8)
        except bitstring.ReadError:
            # We ran off the end!
            self.last_instruction = True
        return data 
Example #4
Source File: test_bitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testReadUE(self):
        with self.assertRaises(bitstring.InterpretError):
            BitStream('').ue
        # The numbers 0 to 8 as unsigned Exponential-Golomb codes
        s = BitStream(bin='1 010 011 00100 00101 00110 00111 0001000 0001001')
        self.assertEqual(s.pos, 0)
        for i in range(9):
            self.assertEqual(s.read('ue'), i)
        with self.assertRaises(bitstring.ReadError):
            s.read('ue') 
Example #5
Source File: test_bitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testEmptyBitstring(self):
        s = BitStream()
        self.assertRaises(bitstring.ReadError, s.read, 1)
        self.assertEqual(s.bin, '')
        self.assertEqual(s.hex, '')
        self.assertRaises(bitstring.InterpretError, s._getint)
        self.assertRaises(bitstring.InterpretError, s._getuint)
        self.assertFalse(s) 
Example #6
Source File: test_bitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testBitPosition(self):
        s = BitStream(bytes=b'\x00\x00\x00')
        self.assertEqual(s.bitpos, 0)
        s.read(5)
        self.assertEqual(s.pos, 5)
        s.pos = s.len
        self.assertRaises(bitstring.ReadError, s.read, 1) 
Example #7
Source File: test_bitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testPeekBit(self):
        s = BitStream(bin='01')
        self.assertEqual(s.peek(1), [0])
        self.assertEqual(s.peek(1), [0])
        self.assertEqual(s.read(1), [0])
        self.assertEqual(s.peek(1), [1])
        self.assertEqual(s.peek(1), [1])

        s = BitStream(bytes=b'\x1f', offset=3)
        self.assertEqual(s.len, 5)
        self.assertEqual(s.peek(5).bin, '11111')
        self.assertEqual(s.peek(5).bin, '11111')
        s.pos += 1
        self.assertRaises(bitstring.ReadError, s.peek, 5)

        s = BitStream(hex='001122334455')
        self.assertEqual(s.peek(8).hex, '00')
        self.assertEqual(s.read(8).hex, '00')
        s.pos += 33
        self.assertRaises(bitstring.ReadError, s.peek, 8)

        s = BitStream(hex='001122334455')
        self.assertEqual(s.peek(8 * 2).hex, '0011')
        self.assertEqual(s.read(8 * 3).hex, '001122')
        self.assertEqual(s.peek(8 * 3).hex, '334455')
        self.assertRaises(bitstring.ReadError, s.peek, 25) 
Example #8
Source File: test_bitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testReadingProblems(self):
        a = BitStream('0x000001')
        b = a.read('uint:24')
        self.assertEqual(b, 1)
        a.pos = 0
        self.assertRaises(bitstring.ReadError, a.read, 'bytes:4') 
Example #9
Source File: test_constbitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testReadingErrors(self):
        s = CBS(10)
        with self.assertRaises(bitstring.ReadError):
            s.read('uie')
        self.assertEqual(s.pos, 0)
        with self.assertRaises(bitstring.ReadError):
            s.read('sie')
        self.assertEqual(s.pos, 0) 
Example #10
Source File: test_constbitstream.py    From bitstring with MIT License 5 votes vote down vote up
def testByteAligned(self):
        a = CBS('0xaabb00aa00bb')
        b = a.readto('0x00', bytealigned=True)
        self.assertEqual(b, '0xaabb00')
        self.assertEqual(a.bytepos, 3)
        b = a.readto('0xaa', bytealigned=True)
        self.assertEqual(b, '0xaa')
        with self.assertRaises(bitstring.ReadError):
            b.readto('0xcc', bytealigned=True) 
Example #11
Source File: models.py    From rocket-league-replays with GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        if self.pk:
            return

        if self.file:
            # Ensure we're at the start of the file as `clean()` can sometimes
            # be called multiple times (for some reason..)
            self.file.seek(0)

            file_url = self.file.url  # To help the exception handler

            try:
                replay = Pyrope(self.file.read())
            except bitstring.ReadError:
                raise ValidationError("The file you selected does not seem to be a valid replay file.")

            # Check if this replay has already been uploaded.
            replays = Replay.objects.filter(
                replay_id=replay.header['Id'],
            )

            if replays.count() > 0:
                raise ValidationError(mark_safe("This replay has already been uploaded, <a target='_blank' href='{}'>you can view it here</a>.".format(
                    replays[0].get_absolute_url()
                )))

            self.replay_id = replay.header['Id'] 
Example #12
Source File: coresight.py    From avatar2 with Apache License 2.0 4 votes vote down vote up
def run(self):
        DWT_PKTSIZE_BITS = 24
        trace_re = re.compile("type target_trace data ([0-9a-f]+)")
        logger.debug("Starting interrupt thread")
        try:
            while not self._close.is_set():
                if self._close.is_set():
                    break
                # OpenOCD gives us target_trace events packed with many, many packets.
                # Get them out, then do them packet-at-a-time
                if not self.has_bits_to_read(self.trace_buffer,
                                             DWT_PKTSIZE_BITS):
                    # get some more data
                    if self.trace_queue.empty():
                        # make sure we can see the shutdown flag
                        continue
                    new_data = self.trace_queue.get()
                    m = trace_re.match(new_data)
                    if m:
                        self.trace_buffer.append("0x" + m.group(1))
                    else:
                        raise ValueError(
                            "Got a really weird trace packet " + new_data)
                if not self.has_bits_to_read(self.trace_buffer,
                                             DWT_PKTSIZE_BITS):
                    continue
                try:
                    pkt = self.trace_buffer.peek(DWT_PKTSIZE_BITS).bytes
                except ReadError:
                    logger.error("Fuck you length is " + repr(
                        len(self.trace_buffer)) + " " + repr(DWT_PKTSIZE_BITS))
                if ord(pkt[0]) == 0x0E:  # exception packets
                    pkt = pkt[1:]
                    self.dispatch_exception_packet(pkt)
                    # eat the bytes
                    self.trace_buffer.read(DWT_PKTSIZE_BITS)
                # the first byte didn't match, rotate it out
                else:
                    self.trace_buffer.read(8)
        except:
            logger.exception("Error processing trace")
        self._closed.set()
        logger.debug("Interrupt thread exiting...")