def _aggregate_final(ctx): addr = sqlite3_aggregate_context(ctx, sizeof(py_object)) instance = py_object.from_address(addr) try: obj = instance.value except ValueError: return o = PyObject.from_address(id(obj)) o.ob_refcnt -= 1 c_void_p.from_address(addr).value = None restore = sys.exc_info()[0] is not None try: ret = obj.finalize() except Exception: if _enable_callback_tracebacks: print_exc() sqlite3_result_error(ctx, b"user-defined aggregate's 'finalize' method raised error", -1) else: sqlite3_result(ctx, ret) if restore: throw() raise
def _get_gsl_rng_type_p_dict(): """ Get all ``gsl_rng_type`` as dict which has pointer to each object This is equivalent to C code bellow which is from GSL document: .. sourcecode:: c const gsl_rng_type **t, **t0; t0 = gsl_rng_types_setup (); for (t = t0; *t != 0; t++) { printf ("%s\n", (*t)->name); /* instead, store t to dict */ } """ t = func.gsl_rng_types_setup() dt = ctypes.sizeof(c_void_p) dct = {} while True: a = c_void_p.from_address(t) if a.value is None: break name = c_char_p.from_address(a.value).value name = name.decode() # for Python 3 (bytes to str) dct[name] = ctypes.cast(a, _c_gsl_rng_type_p) t += dt return dct
def __get__(self, obj, cls, c_void_p=ctypes.c_void_p, addressof=ctypes.addressof): field_addr = addressof(obj) + getattr(cls, self.name).offset addr = c_void_p.from_address(field_addr).value return utf16tostr(addr)
def install_readline(hook): """Set up things for the interpreter to call our function like GNU readline.""" global readline_hook, readline_ref # save the hook so the wrapper can call it readline_hook = hook # get the address of PyOS_ReadlineFunctionPointer so we can update it PyOS_RFP = c_void_p.from_address( Console.GetProcAddress( sys.dllhandle, "PyOS_ReadlineFunctionPointer".encode("ascii") ) ) # save a reference to the generated C-callable so it doesn't go away readline_ref = HOOKFUNC23(hook_wrapper_23) # get the address of the function func_start = c_void_p.from_address(addressof(readline_ref)).value # write the function address into PyOS_ReadlineFunctionPointer PyOS_RFP.value = func_start
def tp_methods(self): method_size = ctypes.sizeof(PyMethodDef) offset = 0 while c_void_p.from_address(self._tp_methods + offset): offset += method_size method_count = offset // method_size array_type = PyMethodDef * method_count return array_type.from_address(self._tp_methods)
def create_dissection_node(self, func, params): ''' @summary: Creates a new dissection node. @param func: A dissectuin function (either dissect_func_t or PSdissect_func). @param params: The appropriate param's structure for the func. @return: A pointer to a new PSdissection_node. ''' if params is None: p_params = None else: p_params = addressof(params) return pointer(PSdissection_node(c_void_p.from_address(addressof(func)).value, p_params))
def __init__(self, newbuffer=0): """Initialize the Console object. newbuffer=1 will allocate a new buffer so the old content will be restored on exit. """ # Do I need the following line? It causes a console to be created whenever # readline is imported into a pythonw application which seems wrong. Things # seem to work without it... # self.AllocConsole() if newbuffer: self.hout = self.CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, None, 1, None ) self.SetConsoleActiveScreenBuffer(self.hout) else: self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE) self.hin = self.GetStdHandle(STD_INPUT_HANDLE) self.inmode = DWORD(0) self.GetConsoleMode(self.hin, byref(self.inmode)) self.SetConsoleMode(self.hin, 0xF) info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) self.attr = info.wAttributes self.saveattr = info.wAttributes # remember the initial colors self.defaultstate = AnsiState() self.defaultstate.winattr = info.wAttributes self.ansiwriter = AnsiWriter(self.defaultstate) background = self.attr & 0xF0 for escape in self.escape_to_color: if self.escape_to_color[escape] is not None: self.escape_to_color[escape] |= background log("initial attr=%x" % self.attr) self.softspace = 0 # this is for using it as a file-like object self.serial = 0 self.pythondll = ctypes.pythonapi self.inputHookPtr = c_void_p.from_address( addressof(self.pythondll.PyOS_InputHook) ).value if sys.version_info[:2] > (3, 4): self.pythondll.PyMem_RawMalloc.restype = c_size_t self.pythondll.PyMem_Malloc.argtypes = [c_size_t] setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_RawMalloc) else: self.pythondll.PyMem_Malloc.restype = c_size_t self.pythondll.PyMem_Malloc.argtypes = [c_size_t] setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_Malloc)
def get(self): """Get next event from queue.""" inputHookFunc = c_void_p.from_address(self.inputHookPtr).value Cevent = INPUT_RECORD() count = DWORD(0) while 1: if inputHookFunc: call_function(inputHookFunc, ()) status = self.ReadConsoleInputW( self.hin, byref(Cevent), 1, byref(count)) if status and count.value == 1: e = event(self, Cevent) return e
def __init__(self): self.readline_wrapper_ref = HOOKFUNC(self.readline_wrapper) self.address = c_void_p.from_address(addressof(self.readline_wrapper_ref)).value self.original_address = PyOS_ReadlineFunctionPointer.value self.readline_hook = None
def append_text(self, text): if not c_void_p.from_address(addressof(self.pointer)).value is None: self._cal.wslib.proto_item_append_text(self.pointer, c_char_p(text))
def addrofaddr2addr(addrofptr): voidp = c_void_p.from_address(addrofptr) return voidp.value pp = c_void_p(addrofptr)
def __init__(self): self.readline_wrapper_ref = HOOKFUNC(self.readline_wrapper) self.address = c_void_p.from_address( addressof(self.readline_wrapper_ref)).value self.original_address = PyOS_ReadlineFunctionPointer.value self.readline_hook = None
# We have set `get` to `tp_as_number.nb_invert`, so this in turn looks up # `__invert__` in the types dictionary mapping and calls that python function with the argument `frame` # the result of this python function is returned by `get` # get function address of nb_invert from `f_locals` class # we dont need to care about the offset that `nb_invert` is at because it is the only non-null address nb_invert = sum( POINTER(c_ssize_t * 36).from_address(id(f_locals) + 12 * base_size).contents) # delete the attribute, we already have the address we needed del f_locals.__invert__ # offsetof(PyGetSetDef) // base_size == 31 # the `f_locals` PyGetSetDef happens to be first in this array # NOTE: alternatively, this address could be retrieved from `FrameType.f_locals` # which is a `getset_descriptor` object getset_ptr = c_void_p.from_address(id(FrameType) + 31 * base_size).value # `get` is the second pointer in the PyGetSetDef structure # NOTE: the first is a `c_char_p` that contains its attribute name f_locals_get_ptr = c_void_p.from_address(getset_ptr + base_size) # we set this function pointer to `nb_invert` f_locals_get_ptr.value = nb_invert # set `__invert__` in the class dictionary # otherwise `nb_invert` will raise an AttributeError getclsdict(FrameType)['__invert__'] = lambda frame: f_locals(frame) # NOTE: This does not enable `~frame == frame.f_locals` # To do that, `FrameType.tp_as_number.nb_invert` must be set (__builtins__ if isinstance(__builtins__, dict) else __builtins__.__dict__)['locals'] = lambda: sys._getframe(1).f_locals
def _get_gsl_rng_type_p_dict(): """ Get all ``gsl_rng_type`` as dict which has pointer to each object This is equivalent to C code bellow which is from GSL document: .. sourcecode:: c const gsl_rng_type **t, **t0; t0 = gsl_rng_types_setup (); for (t = t0; *t != 0; t++) { printf ("%s\n", (*t)->name); /* instead, store t to dict */ } """ t = func.gsl_rng_types_setup() dt = ctypes.sizeof(c_void_p) dct = {} while True: a = c_void_p.from_address(t) if a.value is None: break name = c_char_p.from_address(a.value).value dct[name] = ctypes.cast(a, _c_gsl_rng_type_p) t += dt return dct