我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.c_void_p()。
def _parse_typedefs(self): """ Determines the ctypes data types of the Task and Cal handles based on the version of the NI-DAQmx driver installed. """ from nidaqmx.system.system import System system = System.local() # If DAQmx 8.8 and lower, TaskHandle is a typedef for uInt32 since # DAQmx didn't support 64-bit applications then. version = system.driver_version if version.major_version <= 8 and version.minor_version <= 8: self._task_handle = ctypes.c_uint else: self._task_handle = ctypes.c_void_p self._cal_handle = ctypes.c_uint
def to_rain(cls, val): if val is None: return cls.new(typi.null, 0, 0, cls.null) elif val is False: return cls.new(typi.bool, 0, 0, cls.null) elif val is True: return cls.new(typi.bool, 0, 1, cls.null) elif isinstance(val, int): return cls.new(typi.int, 0, val, cls.null) elif isinstance(val, float): raw = struct.pack('d', val) intrep = struct.unpack('Q', raw)[0] return cls.new(typi.float, 0, intrep, cls.null) elif isinstance(val, str): str_p = ct.create_string_buffer(val.encode('utf-8')) cls._saves_.append(str_p) return cls.new(typi.str, len(val), ct.cast(str_p, ct.c_void_p).value, cls.null) raise Exception("Can't convert value {!r} to Rain".format(val))
def rawaddressof(self, BTypePtr, cdata, offset=None): if isinstance(cdata, CTypesBaseStructOrUnion): ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata)) elif isinstance(cdata, CTypesGenericPtr): if offset is None or not issubclass(type(cdata)._BItem, CTypesBaseStructOrUnion): raise TypeError("unexpected cdata type") ptr = type(cdata)._to_ctypes(cdata) elif isinstance(cdata, CTypesGenericArray): ptr = type(cdata)._to_ctypes(cdata) else: raise TypeError("expected a <cdata 'struct-or-union'>") if offset: ptr = ctypes.cast( ctypes.c_void_p( ctypes.cast(ptr, ctypes.c_void_p).value + offset), type(ptr)) return BTypePtr._from_ctypes(ptr)
def hook_keyboard(callback): handle = None def low_level_callback(code, rparam, lparam): try: key_code = 0xFFFFFFFF & lparam[0] # key code callback(key_code, rparam & 0xFFFFFFFF) finally: return CallNextHookEx(handle, code, rparam, lparam) # The really big problem is the callback_pointer. # Once it goes out of scope, it is destroyed callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback) __CALLBACK_POINTERS.append(callback_pointer) handle = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0) atexit.register(UnhookWindowsHookEx, handle) return handle
def hook_keyboard(): def handler(key_code, event_code): print("{0} {1}".format(hex(key_code), hex(event_code))) handle = None def low_level_callback(code, rparam, lparam): try: key_code = 0xFFFFFFFF & lparam[0] # key code handler(key_code, rparam & 0xFFFFFFFF) finally: return CallNextHookEx(handle, code, rparam, lparam) callback_pointer = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))(low_level_callback) handle = SetWindowsHookExA(WH_KEYBOARD_LL, callback_pointer, GetModuleHandleA(None), 0) atexit.register(UnhookWindowsHookEx, handle) def on_exit(): pass funcs.shell__pump_messages(on_exit)
def libvlc_media_new_location(p_instance, psz_mrl): '''Create a media with a certain given media resource location, for instance a valid URL. @note: To refer to a local file with this function, the file://... URI syntax B{must} be used (see IETF RFC3986). We recommend using L{libvlc_media_new_path}() instead when dealing with local files. See L{libvlc_media_release}. @param p_instance: the instance. @param psz_mrl: the media location. @return: the newly created media or None on error. ''' f = _Cfunctions.get('libvlc_media_new_location', None) or \ _Cfunction('libvlc_media_new_location', ((1,), (1,),), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, psz_mrl)
def libvlc_media_new_fd(p_instance, fd): '''Create a media for an already open file descriptor. The file descriptor shall be open for reading (or reading and writing). Regular file descriptors, pipe read descriptors and character device descriptors (including TTYs) are supported on all platforms. Block device descriptors are supported where available. Directory descriptors are supported on systems that provide fdopendir(). Sockets are supported on all platforms where they are file descriptors, i.e. all except Windows. @note: This library will B{not} automatically close the file descriptor under any circumstance. Nevertheless, a file descriptor can usually only be rendered once in a media player. To render it a second time, the file descriptor should probably be rewound to the beginning with lseek(). See L{libvlc_media_release}. @param p_instance: the instance. @param fd: open file descriptor. @return: the newly created media or None on error. @version: LibVLC 1.1.5 and later. ''' f = _Cfunctions.get('libvlc_media_new_fd', None) or \ _Cfunction('libvlc_media_new_fd', ((1,), (1,),), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_int) return f(p_instance, fd)
def libvlc_media_get_meta(p_md, e_meta): '''Read the meta of the media. If the media has not yet been parsed this will return None. This methods automatically calls L{libvlc_media_parse_async}(), so after calling it you may receive a libvlc_MediaMetaChanged event. If you prefer a synchronous version ensure that you call L{libvlc_media_parse}() before get_meta(). See L{libvlc_media_parse} See L{libvlc_media_parse_async} See libvlc_MediaMetaChanged. @param p_md: the media descriptor. @param e_meta: the meta to read. @return: the media's meta. ''' f = _Cfunctions.get('libvlc_media_get_meta', None) or \ _Cfunction('libvlc_media_get_meta', ((1,), (1,),), string_result, ctypes.c_void_p, Media, Meta) return f(p_md, e_meta)
def libvlc_media_discoverer_new(p_inst, psz_name): '''Create a media discoverer object by name. After this object is created, you should attach to events in order to be notified of the discoverer state. You should also attach to media_list events in order to be notified of new items discovered. You need to call L{libvlc_media_discoverer_start}() in order to start the discovery. See L{libvlc_media_discoverer_media_list} See L{libvlc_media_discoverer_event_manager} See L{libvlc_media_discoverer_start}. @param p_inst: libvlc instance. @param psz_name: service name; use L{libvlc_media_discoverer_list_get}() to get a list of the discoverer names available in this libVLC instance. @return: media discover object or None in case of error. @version: LibVLC 3.0.0 or later. ''' f = _Cfunctions.get('libvlc_media_discoverer_new', None) or \ _Cfunction('libvlc_media_discoverer_new', ((1,), (1,),), class_result(MediaDiscoverer), ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_inst, psz_name)
def libvlc_video_set_callbacks(mp, lock, unlock, display, opaque): '''Set callbacks and private data to render decoded video to a custom area in memory. Use L{libvlc_video_set_format}() or L{libvlc_video_set_format_callbacks}() to configure the decoded format. @param mp: the media player. @param lock: callback to lock video memory (must not be None). @param unlock: callback to unlock video memory (or None if not needed). @param display: callback to display video (or None if not needed). @param opaque: private pointer for the three callbacks (as first parameter). @version: LibVLC 1.1.1 or later. ''' f = _Cfunctions.get('libvlc_video_set_callbacks', None) or \ _Cfunction('libvlc_video_set_callbacks', ((1,), (1,), (1,), (1,), (1,),), None, None, MediaPlayer, VideoLockCb, VideoUnlockCb, VideoDisplayCb, ctypes.c_void_p) return f(mp, lock, unlock, display, opaque)
def libvlc_audio_set_callbacks(mp, play, pause, resume, flush, drain, opaque): '''Sets callbacks and private data for decoded audio. Use L{libvlc_audio_set_format}() or L{libvlc_audio_set_format_callbacks}() to configure the decoded audio format. @note: The audio callbacks override any other audio output mechanism. If the callbacks are set, LibVLC will B{not} output audio in any way. @param mp: the media player. @param play: callback to play audio samples (must not be None). @param pause: callback to pause playback (or None to ignore). @param resume: callback to resume playback (or None to ignore). @param flush: callback to flush audio buffers (or None to ignore). @param drain: callback to drain audio buffers (or None to ignore). @param opaque: private pointer for the audio callbacks (as first parameter). @version: LibVLC 2.0.0 or later. ''' f = _Cfunctions.get('libvlc_audio_set_callbacks', None) or \ _Cfunction('libvlc_audio_set_callbacks', ((1,), (1,), (1,), (1,), (1,), (1,), (1,),), None, None, MediaPlayer, AudioPlayCb, AudioPauseCb, AudioResumeCb, AudioFlushCb, AudioDrainCb, ctypes.c_void_p) return f(mp, play, pause, resume, flush, drain, opaque)
def libvlc_media_player_set_equalizer(p_mi, p_equalizer): '''Apply new equalizer settings to a media player. The equalizer is first created by invoking L{libvlc_audio_equalizer_new}() or L{libvlc_audio_equalizer_new_from_preset}(). It is possible to apply new equalizer settings to a media player whether the media player is currently playing media or not. Invoking this method will immediately apply the new equalizer settings to the audio output of the currently playing media if there is any. If there is no currently playing media, the new equalizer settings will be applied later if and when new media is played. Equalizer settings will automatically be applied to subsequently played media. To disable the equalizer for a media player invoke this method passing None for the p_equalizer parameter. The media player does not keep a reference to the supplied equalizer so it is safe for an application to release the equalizer reference any time after this method returns. @param p_mi: opaque media player handle. @param p_equalizer: opaque equalizer handle, or None to disable the equalizer for this media player. @return: zero on success, -1 on error. @version: LibVLC 2.2.0 or later. ''' f = _Cfunctions.get('libvlc_media_player_set_equalizer', None) or \ _Cfunction('libvlc_media_player_set_equalizer', ((1,), (1,),), None, ctypes.c_int, MediaPlayer, ctypes.c_void_p) return f(p_mi, p_equalizer)
def libvlc_vlm_show_media(p_instance, psz_name): '''Return information about the named media as a JSON string representation. This function is mainly intended for debugging use, if you want programmatic access to the state of a vlm_media_instance_t, please use the corresponding libvlc_vlm_get_media_instance_xxx -functions. Currently there are no such functions available for vlm_media_t though. @param p_instance: the instance. @param psz_name: the name of the media, if the name is an empty string, all media is described. @return: string with information about named media, or None on error. ''' f = _Cfunctions.get('libvlc_vlm_show_media', None) or \ _Cfunction('libvlc_vlm_show_media', ((1,), (1,),), string_result, ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, psz_name)
def try_enc(): import os inFile = open('x.wav', 'rb') inFile.seek(0, os.SEEK_END) wavFileSize = inFile.tell() inFile.seek(44) # skip wav header outFile = open('x.mp3', 'wb') lame = LameEncoder(44100,1,128) while(1): inBytes = inFile.read(512) if inBytes == '': break #inBuf = ctypes.create_string_buffer(inBytes, 512) sample_count = len(inBytes) /2 output_buff_len = int(1.25 * sample_count + 7200) output_buff = (ctypes.c_char*output_buff_len)() lame.dll.lame_encode_buffer.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_char), ctypes.c_int]; output_size = lame.dll.lame_encode_buffer(lame.lame, inBytes, 0, len(inBytes)/2, output_buff, output_buff_len); outFile.write(output_buff[0:output_size]) outFile.close()
def get_window_prop(dpy, window, prop_name, max_size=2): """ Returns (nitems, property) of specified window or (-1, None) if anything fails. Returned 'property' is POINTER(c_void_p) and has to be freed using X.free(). """ prop_atom = intern_atom(dpy, prop_name, False) type_return, format_return = Atom(), Atom() nitems, bytes_after = c_ulong(), c_ulong() prop = c_void_p() if SUCCESS == get_window_property(dpy, window, prop_atom, 0, max_size, False, ANYPROPERTYTYPE, byref(type_return), byref(format_return), byref(nitems), byref(bytes_after), byref(prop)): return nitems.value, prop return -1, None
def get(self): arg = DrmModeObjGetPropertiesC() arg.obj_id = self.obj_id arg.obj_type = self.obj_type fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, arg) prop_ids = (ctypes.c_uint32*arg.count_props)() arg.props_ptr = ctypes.cast(ctypes.pointer(prop_ids), ctypes.c_void_p).value prop_values = (ctypes.c_uint64*arg.count_props)() arg.prop_values_ptr = ctypes.cast(ctypes.pointer(prop_values), ctypes.c_void_p).value fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, arg) self._arg = arg vals = [v for i, v in zip(prop_ids, prop_values) if i == self.id] return vals[0]
def set(self, fb, x, y, mode, *conns): arg = DrmModeCrtcC() arg.crtc_id = self.id arg.fb_id = fb.id arg.x = x arg.y = y arg.mode_valid = 1 arg.mode = mode._arg connector_ids = (ctypes.c_uint32 * len(conns))(*[conn.id for conn in conns]) arg.set_connectors_ptr = ctypes.cast(ctypes.pointer(connector_ids), ctypes.c_void_p).value arg.count_connectors = len(conns) fcntl.ioctl(self._drm.fd, DRM_IOCTL_MODE_SETCRTC, arg) self.fetch()
def command_detach(self): detach_threads() # unload debugger DLL global debugger_dll_handle if debugger_dll_handle is not None: k32 = ctypes.WinDLL('kernel32') k32.FreeLibrary.argtypes = [ctypes.c_void_p] k32.FreeLibrary(debugger_dll_handle) debugger_dll_handle = None with _SendLockCtx: write_bytes(conn, DETC) detach_process() for callback in DETACH_CALLBACKS: callback() raise DebuggerExitException()
def GetParentDeviceByType(device, parent_type): """ Find the first parent of a device that implements the parent_type @param IOService Service to inspect @return Pointer to the parent type, or None if it was not found. """ # First, try to walk up the IOService tree to find a parent of this device that is a IOUSBDevice. parent_type = parent_type.encode('mac_roman') while IORegistryEntryGetName(device) != parent_type: parent = ctypes.c_void_p() response = iokit.IORegistryEntryGetParentEntry( device, "IOService".encode("mac_roman"), ctypes.byref(parent)) # If we weren't able to find a parent for the device, we're done. if response != 0: return None device = parent return device
def GetIOServicesByType(service_type): """ returns iterator over specified service_type """ serial_port_iterator = ctypes.c_void_p() iokit.IOServiceGetMatchingServices( kIOMasterPortDefault, iokit.IOServiceMatching(service_type.encode('mac_roman')), ctypes.byref(serial_port_iterator)) services = [] while iokit.IOIteratorIsValid(serial_port_iterator): service = iokit.IOIteratorNext(serial_port_iterator) if not service: break services.append(service) iokit.IOObjectRelease(serial_port_iterator) return services
def get_page(self, index): """ Return the sub-bitmap for the given page index. Please close the returned bitmap when done. """ with self._fi as lib: # Create low-level bitmap in freeimage bitmap = lib.FreeImage_LockPage(self._bitmap, index) bitmap = ctypes.c_void_p(bitmap) if not bitmap: # pragma: no cover raise ValueError('Could not open sub-image %i in %r: %s' % (index, self._filename, self._fi._get_error_message())) # Get bitmap object to wrap this bitmap bm = FIBitmap(self._fi, self._filename, self._ftype, self._flags) bm._set_bitmap(bitmap, (lib.FreeImage_UnlockPage, self._bitmap, bitmap, False)) return bm
def add(self, ref, pred): if not isinstance(ref, torch.IntTensor): raise TypeError('ref must be a torch.IntTensor (got {})' .format(type(ref))) if not isinstance(pred, torch.IntTensor): raise TypeError('pred must be a torch.IntTensor(got {})' .format(type(pred))) assert self.unk > 0, 'unknown token index must be >0' rref = ref.clone() rref.apply_(lambda x: x if x != self.unk else -x) rref = rref.contiguous().view(-1) pred = pred.contiguous().view(-1) C.bleu_add( ctypes.byref(self.stat), ctypes.c_size_t(rref.size(0)), ctypes.c_void_p(rref.data_ptr()), ctypes.c_size_t(pred.size(0)), ctypes.c_void_p(pred.data_ptr()), ctypes.c_int(self.pad), ctypes.c_int(self.eos))
def all_reduce(input, output=None, op=SUM, stream=None): comm = communicator() if output is None: output = input if stream is not None: stream = stream.cuda_stream data_type = nccl_types[input.type()] check_error(lib.ncclAllReduce( ctypes.c_void_p(input.data_ptr()), ctypes.c_void_p(output.data_ptr()), ctypes.c_size_t(input.numel()), data_type, op, comm, ctypes.c_void_p(stream))) return output
def AllocateEnv(): if pooling: ret = ODBC_API.SQLSetEnvAttr(SQL_NULL_HANDLE, SQL_ATTR_CONNECTION_POOLING, SQL_CP_ONE_PER_HENV, SQL_IS_UINTEGER) check_success(SQL_NULL_HANDLE, ret) ''' Allocate an ODBC environment by initializing the handle shared_env_h ODBC enviroment needed to be created, so connections can be created under it connections pooling can be shared under one environment ''' global shared_env_h shared_env_h = ctypes.c_void_p() ret = ODBC_API.SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, ADDR(shared_env_h)) check_success(shared_env_h, ret) # Set the ODBC environment's compatibil leve to ODBC 3.0 ret = ODBC_API.SQLSetEnvAttr(shared_env_h, SQL_ATTR_ODBC_VERSION, SQL_OV_ODBC3, 0) check_success(shared_env_h, ret)
def win_create_mdb(mdb_path, sort_order = "General\0\0"): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') else: driver_name = mdb_driver[0].encode('mbcs') #CREATE_DB=<path name> <sort order> ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p] if py_v3: c_Path = bytes("CREATE_DB=" + mdb_path + " " + sort_order,'mbcs') else: c_Path = "CREATE_DB=" + mdb_path + " " + sort_order ODBC_ADD_SYS_DSN = 1 ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path) if not ret: raise Exception('Failed to create Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %mdb_path)
def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"): if sys.platform not in ('win32','cli'): raise Exception('This function is available for use in Windows only.') mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d] if mdb_driver == []: raise Exception('Access Driver is not found.') else: driver_name = mdb_driver[0].encode('mbcs') #COMPACT_DB=<source path> <destination path> <sort order> ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p] #driver_name = "Microsoft Access Driver (*.mdb)" if py_v3: c_Path = bytes("COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order,'mbcs') #driver_name = bytes(driver_name,'mbcs') else: c_Path = "COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order ODBC_ADD_SYS_DSN = 1 ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path) if not ret: raise Exception('Failed to compact Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %compacted_mdb_path)
def init(): global pa, in_stream, out_stream, error error = ctypes.c_int(0) pa = ctypes.cdll.LoadLibrary('libpulse-simple.so.0') pa.strerror.restype = ctypes.c_char_p ss = _struct_pa_sample_spec(_PA_SAMPLE_S16LE, 16000, 1) out_stream = ctypes.c_void_p(pa.pa_simple_new(None, 'Alexa'.encode('ascii'), _PA_STREAM_PLAYBACK, None, 'Alexa voice'.encode('ascii'), ctypes.byref(ss), None, None, ctypes.byref(error))) if not out_stream: raise Exception('Could not create pulse audio output stream: ' + str(pa.strerror(error), 'ascii')) in_stream = ctypes.c_void_p(pa.pa_simple_new(None, 'Alexa'.encode('ascii'), _PA_STREAM_RECORD, None, 'Alexa mic'.encode('ascii'), ctypes.byref(ss), None, None, ctypes.byref(error))) if not in_stream: raise Exception('Could not create pulse audio input stream: ' + str(pa.strerror(error), 'ascii')) logging.info('PulseAudio is initialized.')
def draw_primitive(primitive, gltf, modelview_matrix=None, projection_matrix=None, view_matrix=None, normal_matrix=None): set_draw_state(primitive, gltf, modelview_matrix=modelview_matrix, projection_matrix=projection_matrix, view_matrix=view_matrix, normal_matrix=normal_matrix) index_accessor = gltf['accessors'][primitive['indices']] index_bufferView = gltf['bufferViews'][index_accessor['bufferView']] gl.glBindBuffer(index_bufferView['target'], index_bufferView['id']) gl.glDrawElements(primitive['mode'], index_accessor['count'], index_accessor['componentType'], c_void_p(index_accessor['byteOffset'])) global num_draw_calls num_draw_calls += 1 if CHECK_GL_ERRORS: if gl.glGetError() != gl.GL_NO_ERROR: raise Exception('error drawing elements')
def draw_text(self, text, color=(1.0, 1.0, 1.0, 0.0), view_matrix=None, projection_matrix=None): gl.glUseProgram(self._program_id) gl.glActiveTexture(gl.GL_TEXTURE0+0) gl.glBindTexture(gl.GL_TEXTURE_2D, self._texture_id) gl.glBindSampler(0, self._sampler_id) gl.glUniform1i(self._uniform_locations['u_fonttex'], 0) gl.glUniform4f(self._uniform_locations['u_color'], *color) if view_matrix is not None: self._matrix.dot(view_matrix, out=self._modelview_matrix) gl.glUniformMatrix4fv(self._uniform_locations['u_modelviewMatrix'], 1, False, self._modelview_matrix) if projection_matrix is not None: gl.glUniformMatrix4fv(self._uniform_locations['u_projectionMatrix'], 1, False, projection_matrix) gl.glEnableVertexAttribArray(0) gl.glEnableVertexAttribArray(1) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) x = 0.0 text = [ord(c) - 32 for c in text] for i in text: if i >= 0 and i < 95: gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._buffer_ids[i]) gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, False, 0, c_void_p(0)) gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, False, 0, c_void_p(8*4)) gl.glUniform1f(self._uniform_locations['advance'], x) gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) x += self._advance[i] gl.glDisableVertexAttribArray(0) gl.glDisableVertexAttribArray(1) gl.glDisable(gl.GL_BLEND)
def get_global(self, name, typ): '''Return a global address''' addr = self.engine.get_global_value_address(name) ptr = ct.cast(ct.c_void_p(addr), typ) return ptr # Runtime configuration #####################################################
def to_rain(self, val): if isinstance(val, (list, tuple)): table_box = T.cbox.to_rain(None) self.rain_set_table(table_box) meta_ptr = self.get_global('core.types.array.module', T.carg) self.rain_set_env(table_box, meta_ptr) for i, n in enumerate(val): self.rain_put_py(table_box, i, self.to_rain(n)) return table_box elif isinstance(val, A.node): table_box = T.cbox.to_rain(None) self.rain_set_table(table_box) ast_ptr = self.get_global('core.ast.module', T.carg) meta_ptr = self.rain_get_ptr_py(ast_ptr, val.__tag__) if not ct.cast(meta_ptr, ct.c_void_p).value: Q.abort('Unable to look up core.ast.{}'.format(val.__tag__)) self.rain_set_env(table_box, meta_ptr) slots = [self.to_rain(getattr(val, key, None)) for key in val.__slots__] for key, box in zip(val.__slots__, slots): self.rain_put_py(table_box, key, box) return table_box elif isinstance(val, K.value_token): return T.cbox.to_rain(val.value) return T.cbox.to_rain(val)
def __str__(self): env_p = ct.cast(self.env, ct.c_void_p).value or 0 return 'cbox({}, {}, 0x{:08x}, 0x{:08x})'.format(self.type, self.size, self.data, env_p)
def _copyData(self, archiveR, archiveW): ''' ''' r = ctypes.c_int() buff = ctypes.c_void_p() size = ctypes.c_int() offs = ctypes.c_longlong() while True: # Read in a block r = self._readDataBlock( archiveR, # Archive (reading) ctypes.byref(buff), # Buffer pointer ctypes.byref(size), # Size pointer ctypes.byref(offs)) # Offset pointer # Check ourselves if r == self.ARCH_EOF: return self.ARCH_OK if r != self.ARCH_OK: return r # Write out a block r = self._writeDataBlock( archiveW, # Archive (writing) buff, # Buffer data size, # Size data offs) # Offset data # And check ourselves again if r != self.ARCH_OK: print(self._errorString(archiveB)) return r
def hotpatch(source, destination): source = cast(source, c_void_p).value destination = cast(destination, c_void_p).value old = DWORD() if windll.kernel32.VirtualProtect(source - 5, 8, PAGE_EXECUTE_READWRITE, byref(old)): try: written = c_size_t() jmp_code = struct.pack('<BI', 0xE9, (destination - source) & 0xFFFFFFFF) windll.kernel32.WriteProcessMemory(-1, source - 5, cast(jmp_code, c_char_p), len(jmp_code), byref(written)) windll.kernel32.WriteProcessMemory(-1, source, cast(struct.pack('<H', 0xF9EB), c_char_p), 2, byref(written)) finally: windll.kernel32.VirtualProtect(source - 5, 8, old, byref(old)) return source + 2
def unhotpatch(source): source = cast(source, c_void_p).value old = DWORD() if windll.kernel32.VirtualProtect(source, 2, PAGE_EXECUTE_READWRITE, byref(old)): try: written = c_size_t() windll.kernel32.WriteProcessMemory(-1, source, cast(b'\x8B\xFF', c_char_p), 2, byref(written)) finally: windll.kernel32.VirtualProtect(source, 2, old, byref(old))
def _unwrap_window_id(window_id): try: return int(window_id) except: ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object] return int(ctypes.pythonapi.PyCapsule_GetPointer(window_id, None))
def _addr_repr(self, address): if address == 0: return 'NULL' else: if address < 0: address += 1 << (8*ctypes.sizeof(ctypes.c_void_p)) return '0x%x' % address
def _from_ctypes(cls, ctypes_ptr): address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0 return cls._new_pointer_at(address)
def handler(exc): print("==Entry of VEH handler==") if exc[0].ExceptionRecord[0].ExceptionCode == EXCEPTION_ACCESS_VIOLATION: target_addr = ctypes.cast(exc[0].ExceptionRecord[0].ExceptionInformation[1], ctypes.c_void_p).value print("Instr at {0} accessed to addr {1}".format(hex(exc[0].ExceptionRecord[0].ExceptionAddress), hex(target_addr))) print("Resetting page protection to <PAGE_READWRITE>") windows.winproxy.VirtualProtect(target_page, 0x1000, windef.PAGE_READWRITE) exc[0].ContextRecord[0].EEFlags.TF = 1 return windef.EXCEPTION_CONTINUE_EXECUTION else: print("Exception of type {0}".format(exc[0].ExceptionRecord[0].ExceptionCode)) print("Resetting page protection to <PAGE_NOACCESS>") windows.winproxy.VirtualProtect(target_page, 0x1000, windef.PAGE_NOACCESS) return windef.EXCEPTION_CONTINUE_EXECUTION
def ptr_flink_to_remote_module(self, ptr_value): return RemoteLoadedModule(ptr_value - ctypes.sizeof(ctypes.c_void_p) * 2, self._target)
def try_generate_stub_target(shellcode, argument_buffer, target, errcheck=None): if not windows.current_process.is_wow_64: raise ValueError("Calling execute_64bits_code_from_syswow from non-syswow process") native_caller = generate_64bits_execution_stub_from_syswow(shellcode) native_caller.errcheck = errcheck if errcheck is not None else target.errcheck # Generate the wrapper function that fill the argument_buffer expected_arguments_number = len(target.prototype._argtypes_) def wrapper(*args): if len(args) != expected_arguments_number: raise ValueError("{0} syswow accept {1} args ({2} given)".format(target.__name__, expected_arguments_number, len(args))) # Transform args (ctypes byref possibly) to int writable_args = [] for i, value in enumerate(args): if not isinstance(value, (int, long)): try: value = ctypes.cast(value, ctypes.c_void_p).value except ctypes.ArgumentError as e: raise ctypes.ArgumentError("Argument {0}: wrong type <{1}>".format(i, type(value).__name__)) writable_args.append(value) # Build buffer buffer = struct.pack("<" + "Q" * len(writable_args), *writable_args) ctypes.memmove(argument_buffer, buffer, len(buffer)) # Copy origincal args in function, for errcheck if needed native_caller.current_original_args = args # TODO: THIS IS NOT THREAD SAFE return native_caller() wrapper.__name__ = "{0}<syswow64>".format(target.__name__,) wrapper.__doc__ = "This is a wrapper to {0} in 64b mode, it accept <{1}> args".format(target.__name__, expected_arguments_number) return wrapper
def transform_arguments(self, types): res = [] for type in types: if type in (ctypes.c_wchar_p, ctypes.c_char_p): res.append(ctypes.c_void_p) else: res.append(type) return res
def raw_value(self): return ctypes.cast(self, ctypes.c_void_p).value
def _create_vtable(self, interface): implems = [] names = [] for index, name, method in self.extract_methods_order(interface): func_implem = getattr(self, name) #PVOID is 'this' types = [method.restype, PVOID] + list(method.argtypes) implems.append(ctypes.WINFUNCTYPE(*types)(func_implem)) names.append(name) class Vtable(ctypes.Structure): _fields_ = [(name, ctypes.c_void_p) for name in names] return Vtable(*[ctypes.cast(x, ctypes.c_void_p) for x in implems]), implems