Ejemplo n.º 1
0
Archivo: api.py Proyecto: charred/pypy
def load_extension_module(space, path, name):
    if os.sep not in path:
        path = os.curdir + os.sep + path      # force a '/' in the path
    state = space.fromcache(State)
    if state.find_extension(name, path) is not None:
        return
    old_context = state.package_context
    state.package_context = name, path
    try:
        from rpython.rlib import rdynload
        try:
            ll_libname = rffi.str2charp(path)
            try:
                dll = rdynload.dlopen(ll_libname)
            finally:
                lltype.free(ll_libname, flavor='raw')
        except rdynload.DLOpenError, e:
            raise operationerrfmt(
                space.w_ImportError,
                "unable to load extension module '%s': %s",
                path, e.msg)
        try:
            initptr = rdynload.dlsym(dll, 'init%s' % (name.split('.')[-1],))
        except KeyError:
            raise operationerrfmt(
                space.w_ImportError,
                "function init%s not found in library %s",
                name, path)
        initfunc = rffi.cast(initfunctype, initptr)
        generic_cpy_call(space, initfunc)
        state.check_and_raise_exception()
Ejemplo n.º 2
0
 def getpointer(self, name, argtypes, restype, flags=FUNCFLAG_STDCALL):
     return Func(name,
                 argtypes,
                 restype,
                 dlsym(self.lib, name),
                 flags=flags,
                 keepalive=self)
Ejemplo n.º 3
0
Archivo: api.py Proyecto: juokaz/pypy
def load_extension_module(space, path, name):
    if os.sep not in path:
        path = os.curdir + os.sep + path      # force a '/' in the path
    state = space.fromcache(State)
    if state.find_extension(name, path) is not None:
        return
    old_context = state.package_context
    state.package_context = name, path
    try:
        from rpython.rlib import rdynload
        try:
            ll_libname = rffi.str2charp(path)
            try:
                dll = rdynload.dlopen(ll_libname)
            finally:
                lltype.free(ll_libname, flavor='raw')
        except rdynload.DLOpenError, e:
            raise oefmt(space.w_ImportError,
                        "unable to load extension module '%s': %s",
                        path, e.msg)
        try:
            initptr = rdynload.dlsym(dll, 'init%s' % (name.split('.')[-1],))
        except KeyError:
            raise oefmt(space.w_ImportError,
                        "function init%s not found in library %s", name, path)
        initfunc = rffi.cast(initfunctype, initptr)
        generic_cpy_call(space, initfunc)
        state.check_and_raise_exception()
Ejemplo n.º 4
0
class Library(Object):
    def __init__(self, name, api, lib):
        self.name = name
        self.api = api
        self.lib = lib
        self.namespace = {}

    def getattr(self, name):
        if name in self.namespace:
            return self.namespace[name]
        cname = name.encode('utf-8')
        ctype = null
        if self.api is not null:
            try:
                c = self.api.getitem(String(name))
            except Unwinder, uw:
                if isinstance(uw.exception, LKeyError):
                    return Object.getattr(self, name)
                raise uw
            if isinstance(c, Wrap):
                cname = c.cname.encode('utf-8')
                ctype = c.ctype
            else:
                return c
        try:
            pointer = rdynload.dlsym(self.lib, cname)
        except KeyError, e:
            return Object.getattr(self, name)
Ejemplo n.º 5
0
 def get_fn_ptr(self, nm):
     assert isinstance(nm, unicode)
     self.thaw()
     s = rffi.str2charp(str(nm))
     sym = dynload.dlsym(self._dyn_lib, s)
     rffi.free_charp(s)
     return sym
Ejemplo n.º 6
0
 def get_fn_ptr(self, nm):
     assert isinstance(nm, unicode)
     self.thaw()
     s = rffi.str2charp(str(nm))
     sym = dynload.dlsym(self._dyn_lib, s)
     rffi.free_charp(s)
     return sym
Ejemplo n.º 7
0
 def write_variable(self, w_ctype, name, w_value):
     space = self.space
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_KeyError,
                     "variable '%s' not found in library '%s'",
                     name, self.name)
     w_ctype.convert_from_object(rffi.cast(rffi.CCHARP, cdata), w_value)
Ejemplo n.º 8
0
 def read_variable(self, w_ctype, name):
     space = self.space
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_KeyError,
                     "variable '%s' not found in library '%s'", name,
                     self.name)
     return w_ctype.convert_to_object(rffi.cast(rffi.CCHARP, cdata))
Ejemplo n.º 9
0
 def getrawpointer(self, name, argtypes, restype, flags=FUNCFLAG_CDECL):
     # these arguments are already casted to proper ffi
     # structures!
     return RawFuncPtr(name,
                       argtypes,
                       restype,
                       dlsym(self.lib, name),
                       flags=flags,
                       keepalive=self)
Ejemplo n.º 10
0
 def read_variable(self, w_ctype, name):
     space = self.space
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_KeyError,
                     "variable '%s' not found in library '%s'",
                     name, self.name)
     return w_ctype.convert_to_object(rffi.cast(rffi.CCHARP, cdata))
Ejemplo n.º 11
0
 def write_variable(self, w_ctype, name, w_value):
     space = self.space
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_KeyError,
                     "variable '%s' not found in library '%s'", name,
                     self.name)
     w_ctype.convert_from_object(rffi.cast(rffi.CCHARP, cdata), w_value)
Ejemplo n.º 12
0
 def check_GetTickCount64(self, *args):
     if (self.GetTickCount64_handle != lltype.nullptr(rffi.VOIDP.TO)):
         return True
     from rpython.rlib.rdynload import GetModuleHandle, dlsym
     hKernel32 = GetModuleHandle("KERNEL32")
     try:
         GetTickCount64_handle = dlsym(hKernel32, 'GetTickCount64')
     except KeyError:
         return False
     self.GetTickCount64_handle = GetTickCount64_handle
     return True
Ejemplo n.º 13
0
 def check(self):
     if self.handle != lltype.nullptr(rffi.VOIDP.TO):
         return True
     from rpython.rlib.rdynload import GetModuleHandle, dlsym
     lib = GetModuleHandle("advapi32.dll")
     try:
         handle = dlsym(lib, self.name)
     except KeyError:
         return False
     self.handle = handle
     return True
Ejemplo n.º 14
0
 def cdlopen_fetch(self, name):
     if not self.libhandle:
         raise oefmt(self.ffi.w_FFIError, "library '%s' has been closed",
                     self.libname)
     try:
         cdata = dlsym(self.libhandle, name)
     except KeyError:
         raise oefmt(self.ffi.w_FFIError,
                     "symbol '%s' not found in library '%s'", name,
                     self.libname)
     return rffi.cast(rffi.CCHARP, cdata)
Ejemplo n.º 15
0
 def cdlopen_fetch(self, name):
     if not self.libhandle:
         raise oefmt(self.ffi.w_FFIError, "library '%s' has been closed",
                     self.libname)
     try:
         cdata = dlsym(self.libhandle, name)
     except KeyError:
         raise oefmt(self.ffi.w_FFIError,
                     "symbol '%s' not found in library '%s'",
                     name, self.libname)
     return rffi.cast(rffi.CCHARP, cdata)
Ejemplo n.º 16
0
        def check_GetFinalPathNameByHandle(self):
            if (self.GetFinalPathNameByHandle_HANDLE !=
                lltype.nullptr(rffi.VOIDP.TO)):
                return True

            from rpython.rlib.rdynload import GetModuleHandle, dlsym
            hKernel32 = GetModuleHandle("KERNEL32")
            try:
                func = dlsym(hKernel32, 'GetFinalPathNameByHandleW')
            except KeyError:
                return False

            self.GetFinalPathNameByHandle_HANDLE = func
            return True
Ejemplo n.º 17
0
 def getattr(self, name):
     if name in self.namespace:
         return self.namespace[name]
     cname = name.encode('utf-8')
     ctype = null
     if self.api is not null:
         c = self.api.getitem(String(name))
         if isinstance(c, Wrap):
             cname = c.cname.encode('utf-8')
             ctype = c.ctype
         else:
             return c
     try:
         pointer = rdynload.dlsym(self.lib, cname)
     except KeyError, e:
         return Object.getattr(self, name)
Ejemplo n.º 18
0
 def getattr(self, name):
     if name in self.namespace:
         return self.namespace[name]
     cname = name.encode('utf-8')
     ctype = null
     if self.api is not null:
         c = self.api.getitem(String(name))
         if isinstance(c, Wrap):
             cname = c.cname.encode('utf-8')
             ctype = c.ctype
         else:
             return c
     try:
         pointer = rdynload.dlsym(self.lib, cname)
     except KeyError, e:
         return Object.getattr(self, name)
Ejemplo n.º 19
0
    def loadFunctionFrom(self, module_name, function_name):
        from rpython.rlib.rdynload import dlsym
        if module_name not in self.loaded_modules:
            module = self.load_and_initialize(module_name)
        else:
            module = self.loaded_modules[module_name]

        if function_name in module[1]:
            return module[1][function_name]
        else:
            try:
                _external_function = dlsym(module[0], function_name)
            except KeyError:
                raise ProxyFunctionFailed
            else:
                module[1][function_name] = _external_function
                return _external_function
Ejemplo n.º 20
0
 def load_function(self, w_ctype, name):
     from pypy.module._cffi_backend import ctypeptr, ctypearray
     self.check_closed()
     space = self.space
     #
     if not isinstance(w_ctype, ctypeptr.W_CTypePtrOrArray):
         raise oefmt(space.w_TypeError,
                     "function or pointer or array cdata expected, got '%s'",
                     w_ctype.name)
     #
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_AttributeError,
                     "function/symbol '%s' not found in library '%s'",
                     name, self.name)
     if isinstance(w_ctype, ctypearray.W_CTypeArray) and w_ctype.length < 0:
         w_ctype = w_ctype.ctptr
     return W_CData(space, rffi.cast(rffi.CCHARP, cdata), w_ctype)
Ejemplo n.º 21
0
 def load_function(self, w_ctype, name):
     from pypy.module._cffi_backend import ctypefunc, ctypeptr, ctypevoid
     space = self.space
     #
     ok = False
     if isinstance(w_ctype, ctypefunc.W_CTypeFunc):
         ok = True
     if (isinstance(w_ctype, ctypeptr.W_CTypePointer)
             and isinstance(w_ctype.ctitem, ctypevoid.W_CTypeVoid)):
         ok = True
     if not ok:
         raise oefmt(space.w_TypeError, "function cdata expected, got '%s'",
                     w_ctype.name)
     #
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_KeyError,
                     "function '%s' not found in library '%s'", name,
                     self.name)
     return W_CData(space, rffi.cast(rffi.CCHARP, cdata), w_ctype)
Ejemplo n.º 22
0
 def load_function(self, w_ctype, name):
     from pypy.module._cffi_backend import ctypefunc, ctypeptr, ctypevoid
     space = self.space
     #
     ok = False
     if isinstance(w_ctype, ctypefunc.W_CTypeFunc):
         ok = True
     if (isinstance(w_ctype, ctypeptr.W_CTypePointer) and
         isinstance(w_ctype.ctitem, ctypevoid.W_CTypeVoid)):
         ok = True
     if not ok:
         raise oefmt(space.w_TypeError,
                     "function cdata expected, got '%s'", w_ctype.name)
     #
     try:
         cdata = dlsym(self.handle, name)
     except KeyError:
         raise oefmt(space.w_KeyError,
                     "function '%s' not found in library '%s'",
                     name, self.name)
     return W_CData(space, rffi.cast(rffi.CCHARP, cdata), w_ctype)
Ejemplo n.º 23
0
def descr_load(space, name, libpath):
    state = space.fromcache(State)
    state.setup()
    try:
        with rffi.scoped_str2charp(libpath) as ll_libname:
            lib = dlopen(ll_libname, space.sys.dlopenflags)
    except DLOpenError as e:
        w_path = space.newfilename(libpath)
        raise raise_import_error(space, space.newfilename(e.msg),
                                 space.newtext(name), w_path)

    basename = name.split('.')[-1]
    init_name = 'HPyInit_' + basename
    try:
        initptr = dlsym(lib, init_name)
    except KeyError:
        msg = b"function %s not found in library %s" % (
            init_name, space.utf8_w(space.newfilename(libpath)))
        w_path = space.newfilename(libpath)
        raise raise_import_error(space, space.newtext(msg),
                                 space.newtext(name), w_path)
    return create_hpy_module(space, name, libpath, lib, initptr)
Ejemplo n.º 24
0
def builtin_ffi_call(ctx):
    # parameter validation
    assert len(ctx.params) == 3 and \
            ctx.params[0].type == 'str' and \
            ctx.params[1].type == 'str' and \
            ctx.params[2].type == 'array'

    # extract parameters
    libname = ctx.params[0].strvalue
    symname = ctx.params[1].strvalue
    args = ctx.params[2].arrayvalue
    lib = ctx.machine.space.ffi_libs[libname].lib
    ff = ctx.machine.space.ffi_functions[(libname, symname)]
    cif = ff.cif
    func = rdynload.dlsym(lib, rffi.str2charp(symname))

    # prepare exchange
    exc = lltype.malloc(rffi.VOIDP.TO, cif.exchange_size, flavor='raw')

    # cast ao val to ffi val
    ptr = exc
    for i in range(cif.nargs):
        ptr = rffi.ptradd(exc, cif.exchange_args[i])
        _cast_aovalue_to_ffivalue(ctx.machine.space, args[i], ff.atypes[i],
                                  ptr)

    # ffi call
    jit_libffi.jit_ffi_call(cif, func, exc)

    # cast ffi val back to ao val
    ptr = rffi.ptradd(exc, cif.exchange_result)
    val = _cast_ffivalue_to_aovalue(ctx.machine.space, ptr, ff.rtype)

    # free exc
    lltype.free(exc, flavor='raw')

    # return val
    ctx.tos.push(val)
    def loadFunctionFrom(self, module_name, function_name):
        from rpython.rlib.rdynload import dlsym
        module = None
        if module_name in self.missing_modules:
            raise MissingPlugin
        elif module_name not in self.loaded_modules:
            try:
                module = self.load_and_initialize(module_name)
            finally:
                if module is None: self.missing_modules.append(module_name)
        else:
            module = self.loaded_modules[module_name]

        if function_name in module[1]:
            return module[1][function_name]
        else:
            try:
                _external_function = dlsym(module[0], function_name)
            except KeyError:
                raise ProxyFunctionFailed
            else:
                module[1][function_name] = _external_function
                return _external_function
Ejemplo n.º 26
0
    def loadFunctionFrom(self, module_name, function_name):
        from rpython.rlib.rdynload import dlsym
        module = None
        if module_name in self.missing_modules:
            raise MissingPlugin
        elif module_name not in self.loaded_modules:
            try:
                module = self.load_and_initialize(module_name)
            finally:
                if module is None: self.missing_modules.append(module_name)
        else:
            module = self.loaded_modules[module_name]

        if function_name in module[1]:
            return module[1][function_name]
        else:
            try:
                _external_function = dlsym(module[0], function_name)
            except KeyError:
                raise ProxyFunctionFailed
            else:
                module[1][function_name] = _external_function
                return _external_function
Ejemplo n.º 27
0
 def getrawpointer(self, name, argtypes, restype, flags=FUNCFLAG_CDECL):
     # these arguments are already casted to proper ffi
     # structures!
     return RawFuncPtr(name, argtypes, restype, dlsym(self.lib, name),
                       flags=flags, keepalive=self)
Ejemplo n.º 28
0
Archivo: clibffi.py Proyecto: Mu-L/pypy
 def getaddressindll(self, name):
     return dlsym(self.lib, name)
Ejemplo n.º 29
0
 def getaddressindll(self, name):
     return dlsym(self.lib, name)
Ejemplo n.º 30
0
class _InterpreterProxy(object):
    _immutable_fields_ = ['vm_initialized?']

    def __init__(self):
        self.vm_proxy = lltype.nullptr(VMPtr.TO)
        self.vm_initialized = False
        self.space = None
        self._next_oop = 0
        self.oop_map = {}
        self.object_map = {}
        self.loaded_modules = {}
        self.remappable_objects = []
        self.trace_proxy = objspace.ConstantFlag()
        self.reset()

    def reset(self):
        self.interp = None
        self.s_frame = None
        self.argcount = 0
        self.w_method = None
        self.fail_reason = 0
        self.trace_proxy.deactivate()

    def call(self, signature, interp, s_frame, argcount, w_method):
        self.initialize_from_call(signature, interp, s_frame, argcount, w_method)
        try:
            # eventual errors are caught by the calling function (EXTERNAL_CALL)
            external_function = rffi.cast(func_bool_void,
                            self.loadFunctionFrom(signature[0], signature[1]))
            if interp.is_tracing():
                interp.print_padded("Calling %s >> %s" % (signature[0], signature[1]))
            external_function()

            if not self.fail_reason == 0:
                raise error.PrimitiveFailedError
        finally:
            self.reset()

    def loadFunctionFrom(self, module_name, function_name):
        from rpython.rlib.rdynload import dlsym
        if module_name not in self.loaded_modules:
            module = self.load_and_initialize(module_name)
        else:
            module = self.loaded_modules[module_name]

        if function_name in module[1]:
            return module[1][function_name]
        else:
            try:
                _external_function = dlsym(module[0], function_name)
            except KeyError:
                raise ProxyFunctionFailed
            else:
                module[1][function_name] = _external_function
                return _external_function


    def initialize_from_call(self, signature, interp, s_frame, argcount, w_method):
        self.interp = interp
        self.s_frame = s_frame
        self.argcount = argcount
        self.w_method = w_method
        self.space = interp.space
        self.trace_proxy.set(interp.trace_proxy.is_set())
        # ensure that space.w_nil gets the first possible oop
        self.object_to_oop(self.space.w_nil)

    def failed(self, reason=1):
        assert reason != 0
        self.fail_reason = reason

    def oop_to_object(self, oop):
        try:
            return self.oop_map[oop]
        except KeyError:
            raise ProxyFunctionFailed

    def object_to_oop(self, w_object):
        try:
            return self.object_map[w_object]
        except KeyError:
            new_index = self.next_oop()
            # print "Mapping new Object: %d -> %s" % (new_index, w_object)
            self.oop_map[new_index] = w_object
            self.object_map[w_object] = new_index
            return new_index

    def next_oop(self):
        next_oop = self._next_oop
        self._next_oop = next_oop + 1
        return next_oop

    def pop_remappable(self):
        try:
            return self.remappable_objects.pop()
        except IndexError:
            self.failed()
            return self.space.w_nil

    def push_remappable(self, w_object):
        self.remappable_objects.append(w_object)
        return w_object

    def top_remappable(self):
        if len(self.remappable_objects) == 0:
            raise ProxyFunctionFailed
        return self.remappable_objects[-1]

    def load_and_initialize(self, module_name):
        from rpython.rlib.rdynload import dlopen, dlsym, dlclose, DLOpenError
        import os
        c_name = rffi.str2charp(os.path.join(IProxy.space.executable_path(), module_name))
        try:
            module = dlopen(c_name)
        except DLOpenError, e:
            rffi.free_charp(c_name)
            raise error.PrimitiveFailedError

        try:
            try:
                _getModuleName = dlsym(module, "getModuleName")
            except KeyError:
                pass # the method does not need to exist
            else:
                getModuleName = rffi.cast(func_str_void, _getModuleName)
                if not rffi.charp2str(getModuleName()).startswith(module_name):
                    raise error.PrimitiveFailedError

            try:
                _setInterpreter = dlsym(module, "setInterpreter")
            except KeyError:
                raise error.PrimitiveFailedError
            else:
                setInterpreter = rffi.cast(func_bool_vm, _setInterpreter)
                if not setInterpreter(getInterpreterProxy()):
                    print "Failed setting interpreter on: %s" % module_name
                    raise error.PrimitiveFailedError

            try:
                _initialiseModule = dlsym(module, "initialiseModule")
            except KeyError:
                pass # the method does not need to exist
            else:
                initialiseModule = rffi.cast(func_bool_void, _initialiseModule)
                if not initialiseModule():
                    print "Failed initialization of: %s" % module_name
                    raise error.PrimitiveFailedError

            module_tuple = (module, {})
            self.loaded_modules[module_name] = module_tuple
            return module_tuple
        except error.PrimitiveFailedError:
            dlclose(module)
            raise
        finally:
            rffi.free_charp(c_name)
Ejemplo n.º 31
0
 def getpointer(self, name, argtypes, restype, flags=FUNCFLAG_STDCALL):
     return Func(name, argtypes, restype, dlsym(self.lib, name),
                 flags=flags, keepalive=self)
Ejemplo n.º 32
0
 def getpointer(self, name, argtypes, restype, flags=FUNCFLAG_CDECL, variadic_args=0):
     return Func(name, argtypes, restype, dlsym(self.lib, name),
                 flags=flags, keepalive=self, variadic_args=variadic_args)