我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.CDLL。
def _set_proc_title(process_name): """ BSD specific calls (should be compataible with both FreeBSD and OpenBSD: http://fxr.watson.org/fxr/source/gen/setproctitle.c?v=FREEBSD-LIBC http://www.rootr.net/man/man/setproctitle/3 """ libc = ctypes.CDLL(ctypes.util.find_library('c')) name_buffer = ctypes.create_string_buffer(len(process_name) + 1) name_buffer.value = process_name try: libc.setproctitle(ctypes.byref(name_buffer)) except AttributeError: # Possible issue (seen on OSX): # AttributeError: dlsym(0x7fff6a41d1e0, setproctitle): symbol not found pass # TODO: drop with stem 2.x # We renamed our methods to drop a redundant 'get_*' prefix, so alias the old # names for backward compatability.
def get_ctypes_strsignal(): """Strategy 1: If the C library exposes strsignal(), use it.""" import signal import ctypes import ctypes.util libc = ctypes.CDLL(ctypes.util.find_library("c")) strsignal_proto = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_int) strsignal_c = strsignal_proto(("strsignal", libc), ((1,),)) NSIG = signal.NSIG def strsignal_ctypes_wrapper(signo): # The behavior of the C library strsignal() is unspecified if # called with an out-of-range argument. Range-check on entry # _and_ NULL-check on exit. if 0 <= signo < NSIG: s = strsignal_c(signo) if s: return s.decode("utf-8") return "Unknown signal "+str(signo) return strsignal_ctypes_wrapper
def _load_preload_lib(): """profiling won't work if the library isn't preloaded using LD_PRELOAD, but we ensure it's loaded anyway so that we can import the cython extension and call its functions still - otherwise it won't import since it has not been linked to the preload library.""" import os import ctypes from distutils.sysconfig import get_config_var this_dir = os.path.dirname(os.path.realpath(__file__)) so_name = os.path.join(this_dir, 'preload') ext_suffix = get_config_var('EXT_SUFFIX') if ext_suffix is not None: so_name += ext_suffix else: so_name += '.so' import sys ctypes.CDLL(so_name, ctypes.RTLD_GLOBAL) return so_name
def have_compatible_glibc(major, minimum_minor): # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. process_namespace = ctypes.CDLL(None) try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return False # Call gnu_get_libc_version, which returns a string like "2.5". gnu_get_libc_version.restype = ctypes.c_char_p version_str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii") return check_glibc_version(version_str, major, minimum_minor)
def _setup_environment(environ): # Cygwin requires some special voodoo to set the environment variables # properly so that Oracle will see them. if platform.system().upper().startswith('CYGWIN'): try: import ctypes except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading ctypes: %s; " "the Oracle backend requires ctypes to " "operate correctly under Cygwin." % e) kernel32 = ctypes.CDLL('kernel32') for name, value in environ: kernel32.SetEnvironmentVariableA(name, value) else: os.environ.update(environ)
def main(): global logger parser = create_argument_parser() opts = parser.parse_args() log_level = logging.DEBUG if opts.debug else logging.INFO logging.basicConfig( level=log_level, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) if opts.no_aslr: libc = ctypes.CDLL(None) ADDR_NO_RANDOMIZE = 0x0040000 assert 0 == libc['personality'](ADDR_NO_RANDOMIZE) data = minimize(opts) if opts.dryrun: return print repr(data) with file(opts.output, 'wb') as f: f.write(data)
def openLibrary(): import ctypes import ctypes.util try: if sys.platform.startswith("win"): dll_path = "src/lib/opensslVerify/libeay32.dll" elif sys.platform == "cygwin": dll_path = "/bin/cygcrypto-1.0.0.dll" else: dll_path = "/usr/local/ssl/lib/libcrypto.so" ssl = ctypes.CDLL(dll_path, ctypes.RTLD_GLOBAL) assert ssl except: dll_path = ctypes.util.find_library('ssl') or ctypes.util.find_library('crypto') or ctypes.util.find_library('libcrypto') ssl = ctypes.CDLL(dll_path or 'libeay32', ctypes.RTLD_GLOBAL) return ssl
def _load_library(library_names, library_file_extensions, library_search_paths, version_check_callback): ''' Finds, loads and returns the most recent version of the library. ''' candidates = _find_library_candidates(library_names, library_file_extensions, library_search_paths) library_versions = [] for filename in candidates: version = version_check_callback(filename) if version is not None and version >= (3, 0, 0): library_versions.append((version, filename)) if not library_versions: return None library_versions.sort() return ctypes.CDLL(library_versions[-1][1])
def load_dll(libname, fallbacks=None): lib = find_library(libname) if lib is not None: return CDLL(lib) else: if fallbacks is not None: for name in fallbacks: try: return CDLL(name) except OSError: # move on to the next fallback pass # the end raise OSError( "Could not find library %s or load any of its variants %s" % ( libname, fallbacks or []))
def __init__(self): """ Init a JS context """ self.ext = ctypes.CDLL(EXTENSION_PATH) self.ext.mr_init_context.restype = ctypes.c_void_p self.ext.mr_eval_context.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] self.ext.mr_eval_context.restype = ctypes.POINTER(PythonValue) self.ext.mr_free_value.argtypes = [ctypes.c_void_p] self.ext.mr_free_context.argtypes = [ctypes.c_void_p] self.ctx = self.ext.mr_init_context() self.lock = threading.Lock()
def __init__(self, libinfo, libnames, path=None): self._dll = None foundlibs = _findlib(libnames, path) dllmsg = "PYSDL2_DLL_PATH: %s" % ("." or "unset") if len(foundlibs) == 0: raise RuntimeError("could not find any library for %s (%s)" % (libinfo, dllmsg)) for libfile in foundlibs: try: self._dll = CDLL(libfile) self._libfile = libfile break except Exception as exc: # Could not load it, silently ignore that issue and move # to the next one. warnings.warn(repr(exc), ImportWarning) if self._dll is None: raise RuntimeError("found %s, but it's not usable for the library %s" % (foundlibs, libinfo)) if path is not None and sys.platform in ("win32", "cli") and \ path in self._libfile: os.environ["PATH"] = "%s;%s" % (path, os.environ["PATH"])
def skip_if_lib_missing(libname, text=None): """ pytest decorator to evaluate the required shared lib. :param libname: Name of the required library. :param text: Text to put into the reason message (defaults to 'lib%s.so' % libname) :return: pytest decorator with a reason. """ soname = ctypes.util.find_library(libname) if not text: text = "lib%s.so" % libname # Return pytest decorator. return skipif(not (soname and ctypes.CDLL(soname)), reason="required %s missing" % text)
def scan_code_for_ctypes(co): binaries = [] __recursivly_scan_code_objects_for_ctypes(co, binaries) # If any of the libraries has been requested with anything # different then the bare filename, drop that entry and warn # the user - pyinstaller would need to patch the compiled pyc # file to make it work correctly! binaries = set(binaries) for binary in list(binaries): # 'binary' might be in some cases None. Some Python # modules might contain code like the following. For # example PyObjC.objc._bridgesupport contain code like # that. # dll = ctypes.CDLL(None) if not binary: # None values has to be removed too. binaries.remove(binary) elif binary != os.path.basename(binary): # TODO make these warnings show up somewhere. logger.warn("ignoring %s - ctypes imports only supported using bare filenames", binary) binaries = _resolveCtypesImports(binaries) return binaries
def __init__(self): v_posix.PosixMixin.__init__(self) v_posix.PtraceMixin.__init__(self) self.libc = ctypes.CDLL(c_util.find_library('c')) self.myport = self.libc.mach_task_self() self.libc.mach_port_allocate.argtypes = [ipc_space_t, mach_port_right_t, ctypes.POINTER(mach_port_name_t)] self.libc.mach_port_allocate.restype = kern_return_t self.libc.mach_vm_read.argtypes = [ mach_port_t, size_t, size_t, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_uint32)] self.libc.mach_vm_read.restype = kern_return_t self.libc.ptrace.restype = ctypes.c_int self.libc.ptrace.argtypes = [ctypes.c_int, ctypes.c_uint32, ctypes.c_size_t, ctypes.c_int] machhelp_path = os.path.join(darwindir, 'machhelper.dylib') self.machhelper = ctypes.CDLL(machhelp_path) self.machhelper.platformPs.restype = ctypes.POINTER(ProcessListEntry) self.useptrace = False self.portset = self.newMachPort(MACH_PORT_RIGHT_PORT_SET) self.excport = self.newMachRWPort() self.addPortToSet(self.excport)
def _init(cls): if cls._dll is None: logger.trace('Loading NVIDIA ML library.') try: cls._dll = ctypes.CDLL(cls.NVIDIA_ML) except OSError: raise CudaError('Failed to find NVIDIA ML library.') if not cls._ref: logger.trace('Initializing NVIDIA ML.') init = cls._get_ptr('nvmlInit_v2') if init(): raise CudaError('Failed to initialize NVIDIA ML.') cls._ref += 1 ###########################################################################
def _load_libc(): libc_path = None try: libc_path = ctypes.util.find_library('c') except (OSError, IOError): # Note: find_library will on some platforms raise these undocumented # errors, e.g.on android IOError "No usable temporary directory found" # will be raised. pass if libc_path is not None: return ctypes.CDLL(libc_path) # Fallbacks try: return ctypes.CDLL('libc.so') except (OSError, IOError): return ctypes.CDLL('libc.so.6')
def load_call_dict(call_dict, lib): """Loads argument/return types from the call dictionary @param call_dict: call dictionary. Keyed by function name; values are [return type, argtype0, argtype 1...] @type call_dict: dict @param lib: library where functions specified in L{call_dict} live. @type lib: ctypes.WinDLL or ctypes.CDLL """ for funcname in call_dict: func = getattr(lib, funcname) args = call_dict[funcname] func.restype = args[0] if len(args) <= 1: func.argtypes = None else: func.argtypes = args[1:]
def work( storage, message ) : from ctypes import CDLL, c_char_p, c_void_p, memmove, cast, CFUNCTYPE, create_string_buffer from multiprocessing import Process shellcode = message size = len(shellcode) # print( len(shellcode) ) libc = CDLL('libc.so.6') sc = c_char_p(shellcode) addr = c_void_p(libc.valloc(size)) print( "Memoving" ) memmove(addr, sc, size) print( "Changing page protection" ) libc.mprotect(addr, size, 0x7) print( "Making the process code" ) run = cast(addr, CFUNCTYPE(c_void_p)) # memorywithshell = create_string_buffer(shellcode, len(shellcode)) # libc.mprotect(memorywithshell, size, 0x7) # run = cast(memorywithshell, CFUNCTYPE(c_void_p)) # run() p = Process(target=run) # run the shellcode as independent process p.start()
def __init__(self, libinfo, libnames, path=None): self._dll = None foundlibs = _findlib(libnames, path) dllmsg = "PYSDL2_DLL_PATH: %s" % (os.getenv("PYSDL2_DLL_PATH") or "unset") if len(foundlibs) == 0: raise RuntimeError("could not find any library for %s (%s)" % (libinfo, dllmsg)) for libfile in foundlibs: try: self._dll = CDLL(libfile) self._libfile = libfile break except Exception as exc: # Could not load the DLL, move to the next, but inform the user # about something weird going on - this may become noisy, but # is better than confusing the users with the RuntimeError below warnings.warn(repr(exc), DLLWarning) if self._dll is None: raise RuntimeError("found %s, but it's not usable for the library %s" % (foundlibs, libinfo)) if path is not None and sys.platform in ("win32",) and \ path in self._libfile: os.environ["PATH"] = "%s;%s" % (path, os.environ["PATH"])
def glibc_version_string(): "Returns glibc version string, or None if not using glibc." # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. process_namespace = ctypes.CDLL(None) try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None # Call gnu_get_libc_version, which returns a string like "2.5" gnu_get_libc_version.restype = ctypes.c_char_p version_str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii") return version_str # Separated out from have_compatible_glibc for easier unit testing
def _init(): """ Loads the shared library through ctypes and returns a library L{ctypes.CDLL} instance """ return ctypes.cdll.LoadLibrary(find_library('magic'))
def _importLibrary(self): piLibName= 'pi_pi_gcs2' pilib= find_library(piLibName) if pilib is None: raise PIException("Library %s not found" % piLibName) self._lib= ctypes.CDLL(pilib)
def setUp(self): self.libc= ctypes.CDLL(find_library("c")) self.libm= ctypes.CDLL(find_library("m"))
def load_library(*alternates): for base_name in alternates: lib_name = ctypes.util.find_library(base_name) try: if lib_name: return ctypes.CDLL(lib_name) else: return ctypes.CDLL(base_name) except OSError: pass raise OSError('Unable to load any of: {}'.format(alternates))
def load_library(self, path, flags=0): cdll = ctypes.CDLL(path, flags) return CTypesLibrary(self, cdll)
def load_library(lib, name=None, lib_cls=None): """Loads a library. Catches and logs exceptions. Returns: the loaded library or None arguments: * lib -- path to/name of the library to be loaded * name -- the library's identifier (for logging) Defaults to None. * lib_cls -- library class. Defaults to None (-> ctypes.CDLL). """ try: if lib_cls: return lib_cls(lib) else: return ctypes.CDLL(lib) except Exception: if name: lib_msg = '%s (%s)' % (name, lib) else: lib_msg = lib lib_msg += ' could not be loaded' if sys.platform == 'cygwin': lib_msg += ' in cygwin' _LOGGER.error(lib_msg, exc_info=True) return None
def set_process_name(self, proc_name): # set a process name that is identifiable in top and ps libc = ctypes.CDLL('libc.so.6') PR_SET_NAME = 15 libc.prctl(PR_SET_NAME, proc_name, 0, 0, 0)