Example #1
0
 def _write(self, value):
     res = bitmap.new(value, self.length * 8)
     string = ""
     while res[1] > 0:
         res, value = bitmap.consume(res, 8)
         string += chr(value)
     return string
Example #2
0
    def __relocate__(self, data, symbol, section, namespace=None):
        '''Apply relocations for the specified ``symbol`` to the ``data``.'''
        namespace = namespace or {}

        # figure out the relocation information
        relocationva, relocationtype = self['VirtualAddress'].int(), self['Type'].int()

        # figure out the symbol type
        storageclass = symbol['StorageClass'].int()

        # get the symbol name so that it can be looked up against the namespace
        name = symbol['Name'].str()

        # lookup the symbol's value in the namespace first...otherwise, use what was actually assigned in the symbol table
        value = namespace.get(name, symbol['Value'].int())

        # extract the value that's already encoded within the section's data
        result = ptypes.bitmap.zero
        generator = ( bitmap.new(ch, 8) for ch in data[relocationva : relocationva + 4] )
        for x in generator:
            result = bitmap.insert(result, x)
        result = bitmap.int(result)

        currentva = relocationva + 4

        # FIXME: figure out the machine type in order to determine the relocation types and how to apply them

        # XXX: this is only for x86
        # figure out where to get the relocation's value from based on the relocation type
        if section is None:       # externally defined
            result = value
        elif relocationtype == 0:
            pass
        # XXX: will these relocations work?
        elif relocationtype == 6:                                           # 32-bit VA
            result = (value+result)
        #    print '>',name,hex(result),targetsectionname,hex(namespace[targetsectionname])
        elif relocationtype == 0x14:                                        # 32-bit relative displacement
            result = (value+result+4) - (currentva)
            #raise NotImplementedError(relocationtype)
        elif relocationtype == 7:                                           # use real virtual address (???)
            result = value
        elif relocationtype in [0xA, 0xB]:                                  # [section index, offset from section]
            raise NotImplementedError(relocationtype)
        else:
            raise NotImplementedError(relocationtype)

        # calculate relocation and assign it into an array
        result, serialized = bitmap.new(result, 32), array.array('B','')
        while result[1] > 0:
            result, value = bitmap.consume(result, 8)
            serialized.append(value)

        # update segment data with new serialized relocation
        if len(serialized) != 4:
            raise AssertionError("Expected size of relocation was expected to be {:d} bytes : {:d} != {:d}".format(4, len(serialized), 4))
        data[relocationva : relocationva + len(serialized)] = serialized

        # we're done. so return it back to the user
        return data
Example #3
0
    def set(self, string):
        if string in self._values_.viewvalues():
            res = dict((v, k) for k, v in self._values_.viewitems())
            return self.set(res[string])

        res = map(int, string.split('.'))
        val = [res.pop(0)*40 + res.pop(0)]
        for n in res:
            if n <= 127:
                val.append(n)
                continue

            # convert integer to a bitmap
            x = bitmap.new(0,0)
            while n > 0:
                x = bitmap.insert(x, (n&0xf,4))
                n //= 0x10

            # shuffle bitmap into oid components
            y = []
            while bitmap.size(x) > 0:
                x,v = bitmap.consume(x, 7)
                y.insert(0, v)

            val.extend([x|0x80 for x in y[:-1]] + [y[-1]])
        return super(OBJECT_IDENTIFIER, self).set(str().join(map(six.int2byte, val)))
Example #4
0
    def enumerate(self):
        index, res = 0, self.header()
        while bitmap.size(res) > 1:
            # check to see if the msize moves us to a header bit that's unset
            if bitmap.int(bitmap.get(res, 0, 1))  == 0:
                fixup = bitmap.runlength(res, 0, 0)
                logging.warn('Index {:d} of header is not set. Possibly corrupt? Forced to consume {:d} bits.'.format(index, fixup))
                res, _ = bitmap.consume(res, fixup)
                if bitmap.size(res) == 0: break

            # search for how long this run is
            msize = bitmap.runlength(res, 0, 1) + 1
            yield index, msize

            # consume msize bits
            index += msize
            res, _ = bitmap.consume(res, msize)
        return
Example #5
0
def encodeInteger(number, bytes):
    '''given an integer and a number of bytes, will return a string encoded in the native endianness'''
    number &= (0x100**bytes) - 1  # convert to absolute using side-effect of &

    counter = bitmap.new(number, bytes * 8)
    res = ''
    while counter[1] > 0:
        counter, _ = bitmap.consume(counter, 8)
        res += chr(_)
    return res
Example #6
0
def encodeInteger(number, bytes):
    '''given an integer and a number of bytes, will return a string encoded in the native endianness'''
    number &= (0x100**bytes) - 1    # convert to absolute using side-effect of &

    counter = bitmap.new(number,bytes*8)
    res = ''
    while counter[1] > 0:
        counter,_ = bitmap.consume(counter,8)
        res += chr(_)
    return res
Example #7
0
    def used(self):
        m, res = self.getparent(magazine_t), self.header()
        index = m['mag_bytes_free_at_start'].int() / self.QUANTUM
        sentinel = (m['num_bytes_in_magazine'].int() - m['mag_bytes_free_at_end'].int()) / self.QUANTUM
        while index <= sentinel:
            # check to see if the msize moves us to a header bit that's unset
            if bitmap.int(bitmap.get(res, 0, 1))  == 0:
                fixup = bitmap.runlength(res, 0, 0)
                logging.warn('Index {:d} of header is not set. Possibly corrupt? Forced to consume {:d} bits.'.format(index, fixup))
                res, _ = bitmap.consume(res, fixup)
                if bitmap.size(res) == 0: break

            # search for how long this run is
            msize = bitmap.runlength(res, 0, 1) + 1
            yield index, msize

            # consume msize bits
            index += msize
            res, _ = bitmap.consume(res, msize)
        return
Example #8
0
    def enumerate(self):
        index, res = 0, self.header()
        while bitmap.size(res) > 1:
            # check to see if the msize moves us to a header bit that's unset
            if bitmap.int(bitmap.get(res, 0, 1)) == 0:
                fixup = bitmap.runlength(res, 0, 0)
                logging.warn(
                    'Index {:d} of header is not set. Possibly corrupt? Forced to consume {:d} bits.'
                    .format(index, fixup))
                res, _ = bitmap.consume(res, fixup)
                if bitmap.size(res) == 0: break

            # search for how long this run is
            msize = bitmap.runlength(res, 0, 1) + 1
            yield index, msize

            # consume msize bits
            index += msize
            res, _ = bitmap.consume(res, msize)
        return
Example #9
0
    def used(self):
        m, res = self.getparent(magazine_t), self.header()
        index = m['mag_bytes_free_at_start'].int() / self.QUANTUM
        sentinel = (m['num_bytes_in_magazine'].int() -
                    m['mag_bytes_free_at_end'].int()) / self.QUANTUM
        while index <= sentinel:
            # check to see if the msize moves us to a header bit that's unset
            if bitmap.int(bitmap.get(res, 0, 1)) == 0:
                fixup = bitmap.runlength(res, 0, 0)
                logging.warn(
                    'Index {:d} of header is not set. Possibly corrupt? Forced to consume {:d} bits.'
                    .format(index, fixup))
                res, _ = bitmap.consume(res, fixup)
                if bitmap.size(res) == 0: break

            # search for how long this run is
            msize = bitmap.runlength(res, 0, 1) + 1
            yield index, msize

            # consume msize bits
            index += msize
            res, _ = bitmap.consume(res, msize)
        return
Example #10
0
    def __relocate(self, data, symbol, sectionarray, currentsectionname, targetsectionname, namespace):
        relocationva, relocationtype = self["VirtualAddress"].int(), self["Type"].num()
        name = symbol["Name"].str()
        storageclass, value = symbol["StorageClass"].num(), namespace[name]

        if value is None:
            raise ValueError("Attempted relocation for an undefined symbol `%s'." % name)

        result = bitmap.new(0, 0)
        generator = (bitmap.new(ord(x), 8) for x in data[relocationva : relocationva + 4])
        for x in generator:
            result = bitmap.insert(result, x)
        result = result[0]

        currentva = relocationva + 4

        if targetsectionname is None:  # externally defined
            result = value

        elif relocationtype == 0:
            pass

        # XXX: will these relocations work?
        elif relocationtype == 6:  # 32-bit VA
            result = value + result
        #            print '>',name,hex(result),targetsectionname,hex(namespace[targetsectionname])

        elif relocationtype == 0x14:  # 32-bit relative displacement
            result = (value + result + 4) - (currentva)
            raise NotImplementedError(relocationtype)
        elif relocationtype == 7:  # use real virtual address (???)
            result = value
        elif relocationtype in [0xA, 0xB]:  # [section index, offset from section]
            raise NotImplementedError(relocationtype)
        else:
            raise NotImplementedError(relocationtype)

        result, serialized = bitmap.new(result, 32), array.array("c", "")
        while result[1] > 0:
            result, value = bitmap.consume(result, 8)
            serialized.append(chr(value))
        assert len(serialized) == 4

        data[relocationva : relocationva + len(serialized)] = serialized
        return data
Example #11
0
    def set(self, string):
        res = map(int, string.split('.'))
        val = [res.pop(0) * 40 + res.pop(0)]
        for n in res:
            if n <= 127:
                val.append(n)
                continue

            # convert integer to a bitmap
            x = bitmap.new(0, 0)
            while n > 0:
                x = bitmap.insert(x, (n & 0xf, 4))
                n /= 0x10

            # shuffle bitmap into oid components
            y = []
            while bitmap.size(x) > 0:
                x, v = bitmap.consume(x, 7)
                y.insert(0, v)

            val.extend([x | 0x80 for x in y[:-1]] + [y[-1]])
        return super(OBJECT_IDENTIFIER).set(''.join(map(chr, val)))
Example #12
0
 def consume_empty_bitmap():
     x = (0, 0)
     res, n = bitmap.consume(x, 8)
     if n == 0 and res == x:
         raise Success
Example #13
0
 def consume_zero_bitmap_signed():
     x = (0x41424344, -32)
     res, n = bitmap.consume(x, 0)
     if n == 0 and res == x:
         raise Success
Example #14
0
 def consume_signed_bitmap_signed():
     x = (0x414243ff, -32)
     res, n = bitmap.consume(x, 8)
     if n == -1 and res == (0x414243, -24):
         raise Success
Example #15
0
 def consume_unsigned_bitmap_signed():
     x = (0x41424344, -32)
     res, n = bitmap.consume(x, 8)
     if n == 0x44 and res == (0x414243, -24):
         raise Success
Example #16
0
 def consume_signed_bitmap_unsigned():
     x = (0x414243ff, 32)
     res, n = bitmap.consume(x, 8)
     if n == 0xff and res == (0x414243, 24):
         raise Success
Example #17
0
 def consume_signed_bitmap_unsigned():
     x = (0x414243ff,32)
     res,n = bitmap.consume(x, 8)
     if n == 0xff and res == (0x414243,24):
         raise Success
Example #18
0
 def iterate(self):
     res = self.bitmap()
     while bitmap.size(res) > 0:
         res, val = bitmap.consume(res, 1)
         yield val
     return
Example #19
0
 def consume_unsigned_bitmap_signed():
     x = (0x41424344,-32)
     res,n = bitmap.consume(x, 8)
     if n == 0x44 and res == (0x414243,-24):
         raise Success
Example #20
0
 def consume_signed_bitmap_signed():
     x = (0x414243ff,-32)
     res,n = bitmap.consume(x, 8)
     if n == -1 and res == (0x414243,-24):
         raise Success
Example #21
0
 def iterate(self):
     res = self.bitmap()
     while bitmap.size(res) > 0:
         res, val = bitmap.consume(res, 1)
         yield val
     return
Example #22
0
    def __relocate__(self, data, symbol, section, namespace=None):
        '''Apply relocations for the specified ``symbol`` to the ``data``.'''
        raise NotImplementedError(
            'This internal method has been deprecated due to a refactor')

        namespace = namespace or {}

        # figure out the relocation information
        relocationva, relocationtype = self['VirtualAddress'].int(
        ), self['Type'].int()

        # figure out the symbol type
        storageclass = symbol['StorageClass'].int()

        # get the symbol name so that it can be looked up against the namespace
        name = symbol['Name'].str()

        # lookup the symbol's value in the namespace first...otherwise, use what was actually assigned in the symbol table
        value = namespace.get(name, symbol['Value'].int())

        # extract the value that's already encoded within the section's data
        result = ptypes.bitmap.zero
        generator = (bitmap.new(ch, 8)
                     for ch in data[relocationva:relocationva + 4])
        for x in generator:
            result = bitmap.insert(result, x)
        result = bitmap.int(result)

        currentva = relocationva + 4

        # FIXME: figure out the machine type in order to determine the relocation types and how to apply them

        # XXX: this is only for x86
        # figure out where to get the relocation's value from based on the relocation type
        if section is None:  # externally defined
            result = value
        elif relocationtype == 0:
            pass
        # XXX: will these relocations work?
        elif relocationtype == 6:  # 32-bit VA
            result = (value + result)
        #    print('>',name,hex(result),targetsectionname,hex(namespace[targetsectionname]))
        elif relocationtype == 0x14:  # 32-bit relative displacement
            result = (value + result + 4) - (currentva)
            #raise NotImplementedError(relocationtype)
        elif relocationtype == 7:  # use real virtual address (???)
            result = value
        elif relocationtype in [0xA,
                                0xB]:  # [section index, offset from section]
            raise NotImplementedError(relocationtype)
        else:
            raise NotImplementedError(relocationtype)

        # calculate relocation and assign it into an array
        result, serialized = bitmap.new(result, 32), array.array('B', '')
        while result[1] > 0:
            result, value = bitmap.consume(result, 8)
            serialized.append(value)

        # update segment data with new serialized relocation
        if len(serialized) != 4:
            raise AssertionError(
                "Expected size of relocation was expected to be {:d} bytes : {:d} != {:d}"
                .format(4, len(serialized), 4))
        data[relocationva:relocationva + len(serialized)] = serialized

        # we're done. so return it back to the user
        return data
Example #23
0
 def consume_zero_bitmap_signed():
     x = (0x41424344,-32)
     res,n = bitmap.consume(x, 0)
     if n == 0 and res == x:
         raise Success
Example #24
0
 def consume_empty_bitmap():
     x = (0,0)
     res,n = bitmap.consume(x, 8)
     if n == 0 and res == x:
         raise Success