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.
python类CDLL的实例源码
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 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 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 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 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 _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 _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 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 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 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 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 __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 _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 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 __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 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 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 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 __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 _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 _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 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)