Esempio n. 1
0
 def register(self, cname, lname, lib):
     self.name = "{0}::{1}".format(lname, cname)
     if self.__class__.lib is None:
         self.__class__.lib = ffi.open(lib)
     #            if DBG:
     #                print("loading Cni lib %s" % lib)
     return self
Esempio n. 2
0
def open(name, maxver=10, extra=()):
    if not ffi:
        return None
    try:
        return _cache[name]
    except KeyError:
        pass
    def libs():
        if sys.platform == "linux":
            yield '%s.so' % name
            for i in range(maxver, -1, -1):
                yield '%s.so.%u' % (name, i)
        else:
            for ext in ('dylib', 'dll'):
                yield '%s.%s' % (name, ext)
        for n in extra:
            yield n
    err = None
    for n in libs():
        try:
            l = ffi.open(n)
            _cache[name] = l
            return l
        except OSError as e:
            err = e
    raise err
Esempio n. 3
0
def open(name, maxver=10, extra=()):
    if not ffi:
        return None
    try:
        return _cache[name]
    except KeyError:
        pass
    def libs():
        if sys.platform == "linux":
            yield '%s.so' % name
            for i in range(maxver, -1, -1):
                yield '%s.so.%u' % (name, i)
        else:
            for ext in ('dylib', 'dll'):
                yield '%s.%s' % (name, ext)
        for n in extra:
            yield n
    err = None
    for n in libs():
        try:
            l = ffi.open(n)
            _cache[name] = l
            return l
        except OSError as e:
            err = e
    raise err
Esempio n. 4
0
def ffi_open(names):
    err = None
    for n in names:
        try:
            mod = ffi.open(n)
            return mod
        except OSError as e:
            err = e
    raise err
Esempio n. 5
0
class FFI:
    libc = ffi.open('libc.so.6')

    IN_CREATE = 0x00000100
    IN_DELETE = 0x00000200

    inotify_init = libc.func('i', 'inotify_init', '')
    inotify_add_watch = libc.func('i', 'inotify_add_watch', 'isI')
    inotify_rm_watch = libc.func('i', 'inotify_rm_watch', 'ii')
Esempio n. 6
0
def ffi_open(names):
    err = None
    for n in names:
        try:
            mod = ffi.open(n)
            return mod
        except OSError as e:
            err = e
    raise err
Esempio n. 7
0
def get():
    global _h
    if _h:
        return _h
    err = None
    try:
        _h = ffi.open('libmd5.so')
        return _h
    except OSError as e:
        err = e
    raise err
Esempio n. 8
0
def get():
    global _h
    if _h:
        return _h
    err = None
    try:
        _h = ffi.open('libmd5.so')
        return _h
    except OSError as e:
        err = e
    raise err
Esempio n. 9
0
def get():
    global _h
    if _h:
        return _h
    err = None
    for n in names:
        try:
            _h = ffi.open(n)
            return _h
        except OSError as e:
            err = e
    raise err
Esempio n. 10
0
def get():
    global _h
    if _h:
        return _h
    err = None
    for n in names:
        try:
            _h = ffi.open(n)
            return _h
        except OSError as e:
            err = e
    raise err
Esempio n. 11
0
def _get_library_with_ffi(name, maxver, extra=()):
    """MicroPython Unix port may miss some required functions. This function can load them 
    from elsewhere.
    
    Inspired by:
        https://github.com/micropython/micropython-lib/blob/master/ffilib/ffilib.py
        https://github.com/micropython/micropython-lib/blob/master/os/os/__init__.py
    """
    if name in _ffi_library_cache:
        return _ffi_library_cache[name]

    import ffi  # @UnresolvedImport

    def libs():
        if sys.platform == "linux":
            yield "%s.so" % name
            for i in range(maxver, -1, -1):
                yield "%s.so.%u" % (name, i)
        elif sys.platform == "darwin":
            for ext in ("dylib", "dll"):
                yield "%s.%s" % (name, ext)
        else:
            raise RuntimeError(sys.platform + " not supported")

        for n in extra:
            yield n

    err = None
    for n in libs():
        try:
            l = ffi.open(n)
            _ffi_library_cache[name] = l
            return l
        except OSError as e:
            err = e
    raise err
Esempio n. 12
0
#
# This module is part of the Pycopy https://github.com/pfalcon/pycopy
# project.
#
# Copyright (c) 2018-2021 Paul Sokolovsky
#
# The MIT License

import ffi
from uarray import array

import ullvm_c_conf


assert ullvm_c_conf.dynlib
L = ffi.open(ullvm_c_conf.dynlib)


def F(ret, name, params):
    globals()[name] = L.func(ret, name, params)

# Initializer for functions which need Python wrappers.
def F_(ret, name, params):
    globals()[name + "_"] = L.func(ret, name, params)


LLVMAbortProcessAction = 0
LLVMPrintMessageAction = 1
LLVMReturnStatusAction = 2

# LLVMCodeGenOptLevel;
Esempio n. 13
0
# (c) 2015-2018 Paul Sokolovsky. MIT license.
import uarray as array
import ffi
import uctypes
from ubinascii import hexlify


py = ffi.open(None)

def D(ret, name, args):
    globals()[name] = py.func(ret, name, args)

D("v", "mp_unix_alloc_exec", "Lpp")


def alloc_exec(sz):
    ptr = array.array("L", [0])
    size = array.array("L", [0])
    #print(ptr, size)
    mp_unix_alloc_exec(sz, ptr, size)
    #print(ptr, size)
    b = uctypes.bytearray_at(ptr[0], sz)
    #print(b)
    return b
Esempio n. 14
0
def dlopen(lib):

    with open(f"build/{lib}.json", 'r') as jsonf:
        code = json.loads(jsonf.read())

    # platform dependant
    if CNI:
        clib = f"lib{lib}_cni.so"
    else:
        clib = f"lib{lib}_c.so"

    def ffimap(ffi_name):
        global RETURN_TYPE_FIRST
        if RETURN_TYPE_FIRST:
            func, ret, args = ffi_name.rsplit('_', 2)
        else:
            func, args, ret = ffi_name.rsplit('_', 2)
        return func, ret, args

    # FIXME: use readelf tools and wasm tools
    # for func in os.popen(f"nm --demangle --defined-only --dynamic {clib} |grep '. T .*_._.*$'|cut -d' ' -f3"):
    for func in os.popen(
            f"nm -C build/{clib} |grep '. T .*_*_.*$'|cut -d' ' -f3"):
        ffi_name = func.strip()
        if ffi_name.find(FFI_MARK) < 1:
            if DBG:
                print("N/I: globals", func, end='')
            continue

        try:
            func, ret, args = ffimap(ffi_name)
            cls, func = func.split(FFI_MARK, 1)
            code.setdefault(cls, {})
            code[cls].setdefault(func, [])
            code[cls][func].append(
                (code['callmap'].get(ffi_name, 'd'), ret, args, ffi_name))

            if DBG:
                print(cls, '.', func, args, '->', ret)
        except:
            if DBG:
                print("N/I:", func, end='')

    print("Loading native lib", clib, file=sys.stderr)

    try:
        lib = ffi.open(clib)
    except Exception as e:
        sys.print_exception(e)
        print(f'dlopen failed on {clib}')
        raise SystemExit

    code['lib'] = clib
    del code['btypes']

    forward_decl = []
    cls = code['classes']
    ck = list(cls.keys())
    ck.sort()
    mx = 0
    for cn in ck:
        mx = max(mx, len(cls[cn]['bases']))

    print('MAX PARENTS =', mx)
    for p in range(mx + 1):
        lot = []
        for cn in ck:
            if p == len(cls[cn]['bases']):
                lot.append(cn)

        lot.sort()
        forward_decl.extend(lot)

    print(forward_decl)
    forward_decl = sort_inheritance(code, forward_decl)
    forward_decl = sort_inheritance(code, forward_decl)
    code['forward_decl'] = sort_inheritance(code, forward_decl)

    return code
Esempio n. 15
0
def dlopen(name, mode):
    print("dlopen(%s, %x)" % (name, mode))
    return ffi.open(name)
Esempio n. 16
0
def alignment():
    raise NotImplementedError


def resize():
    raise NotImplementedError


def get_errno():
    raise NotImplementedError


def set_errno():
    raise NotImplementedError


def POINTER(type):
    raise NotImplementedError


def pointer(obj):
    raise NotImplementedError


_libc = ffi.open("libc.so.6")
_memmove_addr = _libc.addr("memmove")
_memset_addr = _libc.addr("memset")

_pointer_type_cache = {}
Esempio n. 17
0
import ffi


libc = ffi.open("libc.so.6")

fcntl_l = libc.func("i", "fcntl", "iil")
fcntl_s = libc.func("i", "fcntl", "iis")
ioctl_l = libc.func("i", "ioctl", "iil")
ioctl_s = libc.func("i", "ioctl", "iis")


def fcntl(fd, op, arg):
    if type(arg) is int:
        return fcntl_l(fd, op, arg)
    else:
        raise NotImplementedError


def ioctl(fd, op, arg):
    if type(arg) is int:
        return ioctl_l(fd, op, arg)
    else:
        raise NotImplementedError
Esempio n. 18
0
import uos, usys

try:
    import ffi
except ImportError:
    print("SKIP")
    raise SystemExit

ffi_lib_filename = "./" + usys.argv[0].rsplit("/", 1)[0] + "/ffi_lib.so"
try:
    uos.stat(ffi_lib_filename)
except OSError:
    print("SKIP")
    raise SystemExit

ffi_lib = ffi.open(ffi_lib_filename)

f8i = ffi_lib.func("b", "f8i", "b")
f8u = ffi_lib.func("B", "f8u", "B")
f16i = ffi_lib.func("h", "f16i", "h")
f16u = ffi_lib.func("H", "f16u", "H")
f32i = ffi_lib.func("i", "f32i", "i")
f32u = ffi_lib.func("I", "f32u", "I")
f64i = ffi_lib.func("q", "f64i", "q")
f64u = ffi_lib.func("Q", "f64u", "Q")

for func_name in ("f8i", "f8u", "f16i", "f16u", "f32i", "f32u", "f64i",
                  "f64u"):
    func = globals()[func_name]
    for val in (
            0,
Esempio n. 19
0
# (c) 2018 Paul Sokolovsky. Either zlib or MIT license at your choice.
import ffi
import ustruct

_lib = ffi.open("libSDL2_image-2.0.so.0")

IMG_Load = _lib.func("P", "IMG_Load", "s")
IMG_Load_RW = _lib.func("P", "IMG_Load_RW", "Pi")
Esempio n. 20
0
import ffi


sq3 = ffi.open("libsqlite3.so.0")

sqlite3_open = sq3.func("i", "sqlite3_open", "sp")
#int sqlite3_prepare(
#  sqlite3 *db,            /* Database handle */
#  const char *zSql,       /* SQL statement, UTF-8 encoded */
#  int nByte,              /* Maximum length of zSql in bytes. */
#  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
#  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
#);
sqlite3_prepare = sq3.func("i", "sqlite3_prepare", "psipp")
#int sqlite3_step(sqlite3_stmt*);
sqlite3_step = sq3.func("i", "sqlite3_step", "p")
#int sqlite3_column_count(sqlite3_stmt *pStmt);
sqlite3_column_count = sq3.func("i", "sqlite3_column_count", "p")
#int sqlite3_column_type(sqlite3_stmt*, int iCol);
sqlite3_column_type = sq3.func("i", "sqlite3_column_type", "pi")
sqlite3_column_int = sq3.func("i", "sqlite3_column_int", "pi")
# using "d" return type gives wrong results
sqlite3_column_double = sq3.func("f", "sqlite3_column_double", "pi")
sqlite3_column_text = sq3.func("s", "sqlite3_column_text", "pi")


SQLITE_ERROR      = 1
SQLITE_BUSY       = 5
SQLITE_MISUSE     = 21
SQLITE_ROW        = 100
SQLITE_DONE       = 101
Esempio n. 21
0
SDL_PACKEDLAYOUT_5551 = 4
SDL_PACKEDLAYOUT_565 = 5
SDL_PACKEDLAYOUT_8888 = 6
SDL_PACKEDLAYOUT_2101010 = 7
SDL_PACKEDLAYOUT_1010102 = 8

SDL_PIXELFORMAT_ARGB8888 = \
        SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ARGB,
                               SDL_PACKEDLAYOUT_8888, 32, 4)

SDL_PIXELFORMAT_RGB24 = \
        SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU8, SDL_ARRAYORDER_RGB, 0,
                               24, 3)


_sdl = ffi.open("libSDL2-2.0.so.0")

SDL_Init = _sdl.func("i", "SDL_Init", "I")
SDL_Quit = _sdl.func("v", "SDL_Quit", "")

SDL_CreateWindow = _sdl.func("P", "SDL_CreateWindow", "siiiii")

SDL_CreateRenderer = _sdl.func("P", "SDL_CreateRenderer", "PiI")
SDL_RenderSetLogicalSize = _sdl.func("i", "SDL_RenderSetLogicalSize", "Pii")
SDL_SetRenderDrawColor = _sdl.func("i", "SDL_SetRenderDrawColor", "PBBBB")
SDL_RenderClear = _sdl.func("v", "SDL_RenderClear", "P")
SDL_RenderCopy = _sdl.func("v", "SDL_RenderCopy", "PPPP")
SDL_RenderPresent = _sdl.func("v", "SDL_RenderPresent", "P")

SDL_RenderDrawPoint = _sdl.func("i", "SDL_RenderDrawPoint", "Pii")
SDL_RenderDrawLine = _sdl.func("i", "SDL_RenderDrawLine", "Piiii")
Esempio n. 22
0
# Implementation of native Android "pm list packages"
# command in MicroPython.
import ffi
import jni

# Bootstrap JVM
jni.cls("java/lang/Object")
rt = ffi.open("/system/lib/libandroid_runtime.so")
# Note in 5.x, function may be called: jint registerFrameworkNatives(JNIEnv* env)
# https://android-review.googlesource.com/#/c/157981/1/core/jni/AndroidRuntime.cpp
registerNatives = rt.func("p", "Java_LoadClass_registerNatives", "pp")
registerNatives(jni.env(), None)

# This is older, Java-level way to register framework natives, but
# "registerNatives" method may be absent in 4.x devices, and class
# itself is removed in 5.x.
#fw = jni.cls("com.android.internal.util.WithFramework")
#fw.registerNatives()

ServiceManager = jni.cls("android/os/ServiceManager")
pm = ServiceManager.getService("package")
#print("Service:", pm)
IPackageManager = jni.cls("android/content/pm/IPackageManager")
#print("IPackageManager", IPackageManager)
IPackageManager_Stub = jni.cls("android/content/pm/IPackageManager$Stub")
#print(IPackageManager_Stub)
mPm = IPackageManager_Stub.asInterface(pm)
#print("mPm:", mPm, mPm.toString())
#print("=================")
res = mPm.getInstalledPackages(0, 0)
#res = pm.getInstalledPackages(0)
Esempio n. 23
0
import ffi

sq3 = ffi.open("libsqlite3.so.0")

sqlite3_open = sq3.func("i", "sqlite3_open", "sp")
#int sqlite3_close(sqlite3*);
sqlite3_close = sq3.func("i", "sqlite3_close", "p")
#int sqlite3_prepare(
#  sqlite3 *db,            /* Database handle */
#  const char *zSql,       /* SQL statement, UTF-8 encoded */
#  int nByte,              /* Maximum length of zSql in bytes. */
#  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
#  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
#);
sqlite3_prepare = sq3.func("i", "sqlite3_prepare", "psipp")
#int sqlite3_finalize(sqlite3_stmt *pStmt);
sqlite3_finalize = sq3.func("i", "sqlite3_finalize", "p")
#int sqlite3_step(sqlite3_stmt*);
sqlite3_step = sq3.func("i", "sqlite3_step", "p")
#int sqlite3_column_count(sqlite3_stmt *pStmt);
sqlite3_column_count = sq3.func("i", "sqlite3_column_count", "p")
#int sqlite3_column_type(sqlite3_stmt*, int iCol);
sqlite3_column_type = sq3.func("i", "sqlite3_column_type", "pi")
sqlite3_column_int = sq3.func("i", "sqlite3_column_int", "pi")
# using "d" return type gives wrong results
sqlite3_column_double = sq3.func("f", "sqlite3_column_double", "pi")
sqlite3_column_text = sq3.func("s", "sqlite3_column_text", "pi")
#sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
# TODO: should return long int
sqlite3_last_insert_rowid = sq3.func("i", "sqlite3_last_insert_rowid", "p")
#const char *sqlite3_errmsg(sqlite3*);
Esempio n. 24
0
import ffi


l = ffi.open("libusb-1.0.so.0")

#int libusb_init(libusb_context **context)
libusb_init = l.func("i", "libusb_init", "p")
#const char *libusb_error_name(int errcode);
libusb_error_name = l.func("s", "libusb_error_name", "i")
#libusb_device_handle *libusb_open_device_with_vid_pid (libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
libusb_open_device_with_vid_pid = l.func("P", "libusb_open_device_with_vid_pid", "PHH")
#void libusb_close (libusb_device_handle *dev_handle)
libusb_close = l.func("v", "libusb_close", "P")
#int libusb_control_transfer(libusb_device_handle *dev_handle, uint8_t bmRequestType, uint8_t bRequest,
# uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout)
libusb_control_transfer = l.func("i", "libusb_control_transfer", "PBBHHpHI")
#int libusb_get_string_descriptor_ascii(libusb_device_handle *dev,
#        uint8_t desc_index, unsigned char *data, int length);
libusb_get_string_descriptor_ascii = l.func("i", "libusb_get_string_descriptor_ascii", "PBpi")

#/** In: device-to-host */
LIBUSB_ENDPOINT_IN = 0x80
#/** Out: host-to-device */
LIBUSB_ENDPOINT_OUT = 0x00

# Request type bits of the "bmRequestType" field in control transfers.
LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5)
LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5)
LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5)
LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5)
Esempio n. 25
0
try:
    from ._fasttimer import timeit
except:
    import ffi
    path = __file__.split('/')[:-1]
    if not path: path = '.'
    else: path = '/'.join(path)
    lib = ffi.open(path + '/_mpytimer.so')
    _timeit = lib.func('d','timeit','Ci')
    def timeit(callback,number=1000000):
        cb = ffi.callback('v',callback,'')
        return _timeit(cb,number)

Esempio n. 26
0
def dlopen(name, mode):
    log.debug("dlopen(%s, %x)" % (name, mode))
    return ffi.open(name)
Esempio n. 27
0
# Timer that matches machine.Timer (https://docs.micropython.org/en/latest/library/machine.Timer.html)
# for the unix port.
#
# MIT license; Copyright (c) 2021 Amir Gonnen
#
# Based on timer.py from micropython-lib (https://github.com/micropython/micropython-lib/blob/master/unix-ffi/machine/machine/timer.py)

import ffi
import uctypes
import array
import os
import sys

# FFI libraries

libc = ffi.open("libc.so.6")
librt = ffi.open("librt.so")

# C constants

CLOCK_REALTIME = 0
CLOCK_MONOTONIC = 1
SIGEV_SIGNAL = 0

# C structs

sigaction_t = {
    "sa_handler": (0 | uctypes.UINT64),
    "sa_mask": (8 | uctypes.ARRAY, 16 | uctypes.UINT64),
    "sa_flags": (136 | uctypes.INT32),
    "sa_restorer": (144 | uctypes.PTR, uctypes.UINT8),
Esempio n. 28
0
import ffi
import array


pcre = ffi.open("libpcre.so.3")

#       pcre *pcre_compile(const char *pattern, int options,
#            const char **errptr, int *erroffset,
#            const unsigned char *tableptr);
pcre_compile = pcre.func("p", "pcre_compile", "sipps")

#       int pcre_exec(const pcre *code, const pcre_extra *extra,
#            const char *subject, int length, int startoffset,
#            int options, int *ovector, int ovecsize);
pcre_exec = pcre.func("i", "pcre_exec", "PPsiiipi")

#       int pcre_fullinfo(const pcre *code, const pcre_extra *extra,
#            int what, void *where);
pcre_fullinfo = pcre.func("i", "pcre_fullinfo", "PPip")


IGNORECASE = I = 1
MULTILINE = M = 2
DOTALL = S = 4
VERBOSE = X = 8
PCRE_ANCHORED = 0x10

# TODO. Note that Python3 has unicode by default
ASCII = A = 0
UNICODE = U = 0
Esempio n. 29
0
AV_PIX_FMT_YUYV422 = 1
AV_PIX_FMT_RGB24 = 2


def AVERROR(e):
    assert e > 0
    return -e


def FFERRTAG(a, b, c, d):
    return -(ord(a) | ord(b) << 8 | ord(c) << 16 | ord(d) << 24)


AVERROR_EOF = FFERRTAG('E', 'O', 'F', ' ')

_avcodec = ffi.open("libavcodec.so.57")

avcodec_register_all = _avcodec.func("i", "avcodec_register_all", "")
av_packet_alloc = _avcodec.func("P", "av_packet_alloc", "")
avcodec_find_decoder = _avcodec.func("P", "avcodec_find_decoder", "i")
av_parser_init = _avcodec.func("P", "av_parser_init", "i")
avcodec_alloc_context3 = _avcodec.func("P", "avcodec_alloc_context3", "P")
avcodec_open2 = _avcodec.func("i", "avcodec_open2", "PPP")
av_frame_alloc = _avcodec.func("P", "av_frame_alloc", "")

AVPacket_layout = OrderedDict({
    "buf": (uctypes.PTR, uctypes.VOID),
    "pts": uctypes.INT64,
    "dts": uctypes.INT64,
    "data": (uctypes.PTR, uctypes.UINT8),
    "size": uctypes.INT32,