| 1 |
""" Libffi wrapping |
| 2 |
""" |
| 3 |
from __future__ import with_statement |
| 4 |
|
| 5 |
from rpython.rtyper.tool import rffi_platform |
| 6 |
from rpython.rtyper.lltypesystem import lltype, rffi |
| 7 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 8 |
from rpython.rtyper.tool import rffi_platform |
| 9 |
from rpython.rlib.unroll import unrolling_iterable |
| 10 |
from rpython.rlib.rarithmetic import intmask, is_emulated_long |
| 11 |
from rpython.rlib.objectmodel import we_are_translated |
| 12 |
from rpython.rlib.rmmap import alloc |
| 13 |
from rpython.rlib.rdynload import dlopen, dlclose, dlsym, dlsym_byordinal |
| 14 |
from rpython.rlib.rdynload import DLOpenError, DLLHANDLE |
| 15 |
from rpython.rlib import jit, rposix |
| 16 |
from rpython.rlib.objectmodel import specialize |
| 17 |
from rpython.translator.tool.cbuild import ExternalCompilationInfo |
| 18 |
from rpython.translator.platform import platform |
| 19 |
from rpython.translator import cdir |
| 20 |
from platform import machine |
| 21 |
import py |
| 22 |
import os |
| 23 |
import sys |
| 24 |
import ctypes |
| 25 |
import ctypes.util |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
_MSVC = platform.name == "msvc" |
| 30 |
_MINGW = platform.name == "mingw32" |
| 31 |
_WIN32 = _MSVC or _MINGW |
| 32 |
_WIN64 = _WIN32 and is_emulated_long |
| 33 |
_MAC_OS = platform.name.startswith("darwin") |
| 34 |
|
| 35 |
_LITTLE_ENDIAN = sys.byteorder == 'little' |
| 36 |
_BIG_ENDIAN = sys.byteorder == 'big' |
| 37 |
|
| 38 |
_ARM32 = rffi_platform.getdefined('__arm__', '') |
| 39 |
_ARM64 = rffi_platform.getdefined('__aarch64', '') |
| 40 |
_MAC_OS_ARM64 = _MAC_OS and _ARM64 |
| 41 |
|
| 42 |
if _WIN32: |
| 43 |
from rpython.rlib import rwin32 |
| 44 |
separate_module_sources = [''' |
| 45 |
#include <stdio.h> |
| 46 |
#include <windows.h> |
| 47 |
|
| 48 |
/* Get the module where the "fopen" function resides in */ |
| 49 |
RPY_EXTERN |
| 50 |
HMODULE pypy_get_libc_handle(void) { |
| 51 |
MEMORY_BASIC_INFORMATION mi; |
| 52 |
char buf[1000]; |
| 53 |
memset(&mi, 0, sizeof(mi)); |
| 54 |
|
| 55 |
if( !VirtualQueryEx(GetCurrentProcess(), &fopen, &mi, sizeof(mi)) ) |
| 56 |
return (HMODULE)0; |
| 57 |
|
| 58 |
GetModuleFileName((HMODULE)mi.AllocationBase, buf, 500); |
| 59 |
|
| 60 |
return (HMODULE)mi.AllocationBase; |
| 61 |
} |
| 62 |
'''] |
| 63 |
post_include_bits = ['RPY_EXTERN HMODULE pypy_get_libc_handle(void);\n',] |
| 64 |
else: |
| 65 |
separate_module_sources = [] |
| 66 |
post_include_bits = [] |
| 67 |
|
| 68 |
|
| 69 |
if not _WIN32: |
| 70 |
includes = ['ffi.h'] |
| 71 |
|
| 72 |
if _MAC_OS: |
| 73 |
pre_include_bits = ['#define MACOSX\n#define USE_FFI_CLOSURE_ALLOC 1'] |
| 74 |
else: |
| 75 |
pre_include_bits = [] |
| 76 |
|
| 77 |
library_dirs = platform.library_dirs_for_libffi() |
| 78 |
libraries = ['ffi'] |
| 79 |
link_files = [] |
| 80 |
for libdir in library_dirs: |
| 81 |
candidate = os.path.join(libdir, "libffi.a") |
| 82 |
if os.path.exists(candidate): |
| 83 |
link_files.append(candidate) |
| 84 |
libraries = [] |
| 85 |
|
| 86 |
eci = ExternalCompilationInfo( |
| 87 |
pre_include_bits = pre_include_bits, |
| 88 |
includes = includes, |
| 89 |
libraries = libraries, |
| 90 |
separate_module_sources = separate_module_sources, |
| 91 |
post_include_bits = post_include_bits, |
| 92 |
include_dirs = platform.include_dirs_for_libffi(), |
| 93 |
library_dirs = library_dirs, |
| 94 |
link_files = link_files, |
| 95 |
testonly_libraries = ['ffi'], |
| 96 |
) |
| 97 |
elif _MINGW: |
| 98 |
includes = ['ffi.h'] |
| 99 |
libraries = ['libffi-5'] |
| 100 |
|
| 101 |
eci = ExternalCompilationInfo( |
| 102 |
libraries = libraries, |
| 103 |
includes = includes, |
| 104 |
separate_module_sources = separate_module_sources, |
| 105 |
post_include_bits = post_include_bits, |
| 106 |
) |
| 107 |
|
| 108 |
eci = rffi_platform.configure_external_library( |
| 109 |
'ffi-5', eci, |
| 110 |
[dict(prefix='libffi-', |
| 111 |
include_dir='include', library_dir='.libs'), |
| 112 |
dict(prefix=r'c:\\mingw64', include_dir='include', library_dir='lib'), |
| 113 |
]) |
| 114 |
else: |
| 115 |
eci = ExternalCompilationInfo( |
| 116 |
includes = ['ffi.h', 'windows.h'], |
| 117 |
libraries = ['kernel32', 'libffi-8'], |
| 118 |
separate_module_sources = separate_module_sources, |
| 119 |
post_include_bits = post_include_bits, |
| 120 |
) |
| 121 |
|
| 122 |
FFI_TYPE_P = lltype.Ptr(lltype.ForwardReference()) |
| 123 |
FFI_TYPE_PP = rffi.CArrayPtr(FFI_TYPE_P) |
| 124 |
FFI_TYPE_NULL = lltype.nullptr(FFI_TYPE_P.TO) |
| 125 |
|
| 126 |
class CConfig: |
| 127 |
_compilation_info_ = eci |
| 128 |
|
| 129 |
FFI_OK = rffi_platform.ConstantInteger('FFI_OK') |
| 130 |
FFI_BAD_TYPEDEF = rffi_platform.ConstantInteger('FFI_BAD_TYPEDEF') |
| 131 |
FFI_DEFAULT_ABI = rffi_platform.ConstantInteger('FFI_DEFAULT_ABI') |
| 132 |
if _WIN32 and not _WIN64: |
| 133 |
FFI_STDCALL = rffi_platform.ConstantInteger('FFI_STDCALL') |
| 134 |
|
| 135 |
if _ARM32: |
| 136 |
FFI_SYSV = rffi_platform.ConstantInteger('FFI_SYSV') |
| 137 |
FFI_VFP = rffi_platform.ConstantInteger('FFI_VFP') |
| 138 |
|
| 139 |
FFI_TYPE_STRUCT = rffi_platform.ConstantInteger('FFI_TYPE_STRUCT') |
| 140 |
|
| 141 |
size_t = rffi_platform.SimpleType("size_t", rffi.ULONG) |
| 142 |
ffi_abi = rffi_platform.SimpleType("ffi_abi", rffi.USHORT) |
| 143 |
ffi_arg = rffi_platform.SimpleType("ffi_arg", lltype.Signed) |
| 144 |
|
| 145 |
ffi_type = rffi_platform.Struct('ffi_type', [('size', rffi.ULONG), |
| 146 |
('alignment', rffi.USHORT), |
| 147 |
('type', rffi.USHORT), |
| 148 |
('elements', FFI_TYPE_PP)]) |
| 149 |
|
| 150 |
ffi_cif = rffi_platform.Struct('ffi_cif', []) |
| 151 |
ffi_closure = rffi_platform.Struct('ffi_closure', |
| 152 |
[('user_data', rffi.VOIDP)]) |
| 153 |
|
| 154 |
def add_simple_type(type_name): |
| 155 |
for name in ['size', 'alignment', 'type']: |
| 156 |
setattr(CConfig, type_name + '_' + name, |
| 157 |
rffi_platform.ConstantInteger(type_name + '.' + name)) |
| 158 |
|
| 159 |
def configure_simple_type(type_name): |
| 160 |
l = lltype.malloc(FFI_TYPE_P.TO, flavor='raw', immortal=True) |
| 161 |
for tp, name in [(size_t, 'size'), |
| 162 |
(rffi.USHORT, 'alignment'), |
| 163 |
(rffi.USHORT, 'type')]: |
| 164 |
value = getattr(cConfig, '%s_%s' % (type_name, name)) |
| 165 |
setattr(l, 'c_' + name, rffi.cast(tp, value)) |
| 166 |
l.c_elements = lltype.nullptr(FFI_TYPE_PP.TO) |
| 167 |
return l |
| 168 |
|
| 169 |
base_names = ['double', 'uchar', 'schar', 'sshort', 'ushort', 'uint', 'sint', |
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
'float', 'longdouble', 'pointer', 'void', |
| 174 |
|
| 175 |
'sint8', 'uint8', 'sint16', 'uint16', 'sint32', 'uint32', |
| 176 |
'sint64', 'uint64'] |
| 177 |
type_names = ['ffi_type_%s' % name for name in base_names] |
| 178 |
for i in type_names: |
| 179 |
add_simple_type(i) |
| 180 |
|
| 181 |
class cConfig: |
| 182 |
pass |
| 183 |
|
| 184 |
for k, v in rffi_platform.configure(CConfig).items(): |
| 185 |
setattr(cConfig, k, v) |
| 186 |
|
| 187 |
FFI_TYPE_P.TO.become(cConfig.ffi_type) |
| 188 |
size_t = cConfig.size_t |
| 189 |
FFI_ABI = cConfig.ffi_abi |
| 190 |
ffi_arg = cConfig.ffi_arg |
| 191 |
|
| 192 |
for name in type_names: |
| 193 |
locals()[name] = configure_simple_type(name) |
| 194 |
|
| 195 |
def _signed_type_for(TYPE): |
| 196 |
sz = rffi.sizeof(TYPE) |
| 197 |
if sz == 1: return ffi_type_sint8 |
| 198 |
elif sz == 2: return ffi_type_sint16 |
| 199 |
elif sz == 4: return ffi_type_sint32 |
| 200 |
elif sz == 8: return ffi_type_sint64 |
| 201 |
else: raise ValueError("unsupported type size for %r" % (TYPE,)) |
| 202 |
|
| 203 |
def _unsigned_type_for(TYPE): |
| 204 |
sz = rffi.sizeof(TYPE) |
| 205 |
if sz == 1: return ffi_type_uint8 |
| 206 |
elif sz == 2: return ffi_type_uint16 |
| 207 |
elif sz == 4: return ffi_type_uint32 |
| 208 |
elif sz == 8: return ffi_type_uint64 |
| 209 |
else: raise ValueError("unsupported type size for %r" % (TYPE,)) |
| 210 |
|
| 211 |
__int_type_map = [ |
| 212 |
(rffi.UCHAR, ffi_type_uchar), |
| 213 |
(rffi.SIGNEDCHAR, ffi_type_schar), |
| 214 |
(rffi.SHORT, ffi_type_sshort), |
| 215 |
(rffi.USHORT, ffi_type_ushort), |
| 216 |
(rffi.UINT, ffi_type_uint), |
| 217 |
(rffi.INT, ffi_type_sint), |
| 218 |
|
| 219 |
|
| 220 |
(rffi.ULONG, _unsigned_type_for(rffi.ULONG)), |
| 221 |
(rffi.LONG, _signed_type_for(rffi.LONG)), |
| 222 |
(rffi.ULONGLONG, _unsigned_type_for(rffi.ULONGLONG)), |
| 223 |
(rffi.LONGLONG, _signed_type_for(rffi.LONGLONG)), |
| 224 |
(lltype.UniChar, _unsigned_type_for(lltype.UniChar)), |
| 225 |
(lltype.Bool, _unsigned_type_for(lltype.Bool)), |
| 226 |
(lltype.Char, _signed_type_for(lltype.Char)), |
| 227 |
] |
| 228 |
|
| 229 |
__float_type_map = [ |
| 230 |
(rffi.DOUBLE, ffi_type_double), |
| 231 |
(rffi.FLOAT, ffi_type_float), |
| 232 |
(rffi.LONGDOUBLE, ffi_type_longdouble), |
| 233 |
] |
| 234 |
|
| 235 |
__ptr_type_map = [ |
| 236 |
(rffi.VOIDP, ffi_type_pointer), |
| 237 |
] |
| 238 |
|
| 239 |
__type_map = __int_type_map + __float_type_map + [ |
| 240 |
(lltype.Void, ffi_type_void) |
| 241 |
] |
| 242 |
|
| 243 |
TYPE_MAP_INT = dict(__int_type_map) |
| 244 |
TYPE_MAP_FLOAT = dict(__float_type_map) |
| 245 |
TYPE_MAP = dict(__type_map) |
| 246 |
|
| 247 |
ffitype_map_int = unrolling_iterable(__int_type_map) |
| 248 |
ffitype_map_int_or_ptr = unrolling_iterable(__int_type_map + __ptr_type_map) |
| 249 |
ffitype_map_float = unrolling_iterable(__float_type_map) |
| 250 |
ffitype_map = unrolling_iterable(__type_map) |
| 251 |
|
| 252 |
del __int_type_map, __float_type_map, __ptr_type_map, __type_map |
| 253 |
|
| 254 |
|
| 255 |
def external(name, args, result, **kwds): |
| 256 |
return rffi.llexternal(name, args, result, compilation_info=eci, **kwds) |
| 257 |
|
| 258 |
def winexternal(name, args, result): |
| 259 |
return rffi.llexternal(name, args, result, compilation_info=eci, calling_conv='win') |
| 260 |
|
| 261 |
|
| 262 |
if 1 or not _MSVC: |
| 263 |
def check_fficall_result(result, flags): |
| 264 |
pass |
| 265 |
else: |
| 266 |
def check_fficall_result(result, flags): |
| 267 |
if result == 0: |
| 268 |
return |
| 269 |
|
| 270 |
|
| 271 |
if result < 0: |
| 272 |
if flags & FUNCFLAG_CDECL: |
| 273 |
raise StackCheckError( |
| 274 |
"Procedure called with not enough arguments" |
| 275 |
" (%d bytes missing)" |
| 276 |
" or wrong calling convention" % (-result,)) |
| 277 |
else: |
| 278 |
raise StackCheckError( |
| 279 |
"Procedure called with not enough arguments " |
| 280 |
" (%d bytes missing) " % (-result,)) |
| 281 |
else: |
| 282 |
raise StackCheckError( |
| 283 |
"Procedure called with too many " |
| 284 |
"arguments (%d bytes in excess) " % (result,)) |
| 285 |
|
| 286 |
if not _WIN32: |
| 287 |
|
| 288 |
|
| 289 |
libc_name = ctypes.util.find_library('c') |
| 290 |
if libc_name is not None: |
| 291 |
def get_libc_name(): |
| 292 |
return libc_name |
| 293 |
elif sys.platform == 'darwin': |
| 294 |
def get_libc_name(): |
| 295 |
return '/usr/lib/libc.dylib' |
| 296 |
else: |
| 297 |
|
| 298 |
|
| 299 |
try: |
| 300 |
ctypes.CDLL('libc.so') |
| 301 |
except OSError: |
| 302 |
raise AssertionError( |
| 303 |
"Cannot find C library, ctypes.util.find_library('c') returned None") |
| 304 |
else: |
| 305 |
def get_libc_name(): |
| 306 |
return 'libc.so' |
| 307 |
elif _MSVC: |
| 308 |
get_libc_handle = external('pypy_get_libc_handle', [], DLLHANDLE) |
| 309 |
|
| 310 |
@jit.dont_look_inside |
| 311 |
def get_libc_name(): |
| 312 |
return rwin32.GetModuleFileName(get_libc_handle()) |
| 313 |
|
| 314 |
libc_name = get_libc_name().lower() |
| 315 |
assert "msvcr" in libc_name or 'ucrtbase' in libc_name, \ |
| 316 |
"Suspect msvcrt library: %s" % (get_libc_name(),) |
| 317 |
elif _MINGW: |
| 318 |
def get_libc_name(): |
| 319 |
return 'msvcrt.dll' |
| 320 |
|
| 321 |
if _WIN32: |
| 322 |
LoadLibrary = rwin32.LoadLibrary |
| 323 |
|
| 324 |
FFI_OK = cConfig.FFI_OK |
| 325 |
FFI_BAD_TYPEDEF = cConfig.FFI_BAD_TYPEDEF |
| 326 |
FFI_DEFAULT_ABI = cConfig.FFI_DEFAULT_ABI |
| 327 |
if _WIN32 and not _WIN64: |
| 328 |
FFI_STDCALL = cConfig.FFI_STDCALL |
| 329 |
if _ARM32: |
| 330 |
FFI_SYSV = cConfig.FFI_SYSV |
| 331 |
FFI_VFP = cConfig.FFI_VFP |
| 332 |
FFI_TYPE_STRUCT = cConfig.FFI_TYPE_STRUCT |
| 333 |
FFI_CIFP = lltype.Ptr(cConfig.ffi_cif) |
| 334 |
|
| 335 |
FFI_CLOSUREP = lltype.Ptr(cConfig.ffi_closure) |
| 336 |
|
| 337 |
VOIDPP = rffi.CArrayPtr(rffi.VOIDP) |
| 338 |
|
| 339 |
c_ffi_prep_cif = external('ffi_prep_cif', [FFI_CIFP, FFI_ABI, rffi.UINT, |
| 340 |
FFI_TYPE_P, FFI_TYPE_PP], rffi.INT) |
| 341 |
c_ffi_prep_cif_var = external('ffi_prep_cif_var', [FFI_CIFP, FFI_ABI, rffi.UINT, rffi.UINT, |
| 342 |
FFI_TYPE_P, FFI_TYPE_PP], rffi.INT) |
| 343 |
c_ffi_closure_alloc = external('ffi_closure_alloc', [rffi.SIZE_T, rffi.VOIDPP], |
| 344 |
rffi.VOIDP, _nowrapper=True) |
| 345 |
c_ffi_closure_free = external('ffi_closure_free', [rffi.VOIDP], lltype.Void, _nowrapper=True) |
| 346 |
if 0 and _MSVC: |
| 347 |
c_ffi_call_return_type = rffi.INT |
| 348 |
else: |
| 349 |
c_ffi_call_return_type = lltype.Void |
| 350 |
c_ffi_call = external('ffi_call', [FFI_CIFP, rffi.VOIDP, rffi.VOIDP, |
| 351 |
VOIDPP], c_ffi_call_return_type, |
| 352 |
save_err=rffi.RFFI_ERR_ALL | rffi.RFFI_ALT_ERRNO) |
| 353 |
|
| 354 |
CALLBACK_TP = rffi.CCallback([FFI_CIFP, rffi.VOIDP, rffi.VOIDPP, rffi.VOIDP], |
| 355 |
lltype.Void) |
| 356 |
c_ffi_prep_closure_loc = external('ffi_prep_closure_loc', [FFI_CLOSUREP, FFI_CIFP, |
| 357 |
CALLBACK_TP, rffi.VOIDP, rffi.VOIDP], |
| 358 |
rffi.INT) |
| 359 |
|
| 360 |
FFI_STRUCT_P = lltype.Ptr(lltype.Struct('FFI_STRUCT', |
| 361 |
('ffistruct', FFI_TYPE_P.TO), |
| 362 |
('members', lltype.Array(FFI_TYPE_P)))) |
| 363 |
|
| 364 |
@specialize.arg(3) |
| 365 |
def make_struct_ffitype_e(size, aligment, field_types, track_allocation=True): |
| 366 |
"""Compute the type of a structure. Returns a FFI_STRUCT_P out of |
| 367 |
which the 'ffistruct' member is a regular FFI_TYPE. |
| 368 |
""" |
| 369 |
tpe = lltype.malloc(FFI_STRUCT_P.TO, len(field_types)+1, flavor='raw', |
| 370 |
track_allocation=track_allocation) |
| 371 |
tpe.ffistruct.c_type = rffi.cast(rffi.USHORT, FFI_TYPE_STRUCT) |
| 372 |
tpe.ffistruct.c_size = rffi.cast(rffi.SIZE_T, size) |
| 373 |
tpe.ffistruct.c_alignment = rffi.cast(rffi.USHORT, aligment) |
| 374 |
tpe.ffistruct.c_elements = rffi.cast(FFI_TYPE_PP, |
| 375 |
lltype.direct_arrayitems(tpe.members)) |
| 376 |
n = 0 |
| 377 |
while n < len(field_types): |
| 378 |
tpe.members[n] = field_types[n] |
| 379 |
n += 1 |
| 380 |
tpe.members[n] = lltype.nullptr(FFI_TYPE_P.TO) |
| 381 |
return tpe |
| 382 |
|
| 383 |
@specialize.memo() |
| 384 |
def cast_type_to_ffitype(tp): |
| 385 |
""" This function returns ffi representation of rpython type tp |
| 386 |
""" |
| 387 |
return TYPE_MAP[tp] |
| 388 |
|
| 389 |
@specialize.argtype(1) |
| 390 |
def push_arg_as_ffiptr(ffitp, arg, ll_buf): |
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
TP = lltype.typeOf(arg) |
| 395 |
TP_P = lltype.Ptr(rffi.CArray(TP)) |
| 396 |
TP_size = rffi.sizeof(TP) |
| 397 |
c_size = intmask(ffitp.c_size) |
| 398 |
|
| 399 |
|
| 400 |
if c_size == TP_size: |
| 401 |
buf = rffi.cast(TP_P, ll_buf) |
| 402 |
buf[0] = arg |
| 403 |
else: |
| 404 |
|
| 405 |
|
| 406 |
assert TP is not rffi.FLOAT and TP is not rffi.DOUBLE |
| 407 |
if TP_size <= rffi.sizeof(lltype.Signed): |
| 408 |
arg = rffi.cast(lltype.Unsigned, arg) |
| 409 |
else: |
| 410 |
arg = rffi.cast(lltype.UnsignedLongLong, arg) |
| 411 |
if _LITTLE_ENDIAN: |
| 412 |
for i in range(c_size): |
| 413 |
ll_buf[i] = chr(arg & 0xFF) |
| 414 |
arg >>= 8 |
| 415 |
elif _BIG_ENDIAN: |
| 416 |
for i in range(c_size-1, -1, -1): |
| 417 |
ll_buf[i] = chr(arg & 0xFF) |
| 418 |
arg >>= 8 |
| 419 |
else: |
| 420 |
raise AssertionError |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
USERDATA_P = lltype.Ptr(lltype.ForwardReference()) |
| 425 |
CALLBACK_TP = lltype.Ptr(lltype.FuncType([rffi.VOIDPP, rffi.VOIDP, USERDATA_P], |
| 426 |
lltype.Void)) |
| 427 |
USERDATA_P.TO.become(lltype.Struct('userdata', |
| 428 |
('callback', CALLBACK_TP), |
| 429 |
('addarg', lltype.Signed), |
| 430 |
hints={'callback':True})) |
| 431 |
|
| 432 |
|
| 433 |
@jit.jit_callback("CLIBFFI") |
| 434 |
def _ll_callback(ffi_cif, ll_res, ll_args, ll_userdata): |
| 435 |
""" Callback specification. |
| 436 |
ffi_cif - something ffi specific, don't care |
| 437 |
ll_args - rffi.VOIDPP - pointer to array of pointers to args |
| 438 |
ll_restype - rffi.VOIDP - pointer to result |
| 439 |
ll_userdata - a special structure which holds necessary information |
| 440 |
(what the real callback is for example), casted to VOIDP |
| 441 |
""" |
| 442 |
userdata = rffi.cast(USERDATA_P, ll_userdata) |
| 443 |
llop.revdb_do_next_call(lltype.Void) |
| 444 |
userdata.callback(ll_args, ll_res, userdata) |
| 445 |
|
| 446 |
def ll_callback(ffi_cif, ll_res, ll_args, ll_userdata): |
| 447 |
rposix._errno_after(rffi.RFFI_ERR_ALL | rffi.RFFI_ALT_ERRNO) |
| 448 |
_ll_callback(ffi_cif, ll_res, ll_args, ll_userdata) |
| 449 |
rposix._errno_before(rffi.RFFI_ERR_ALL | rffi.RFFI_ALT_ERRNO) |
| 450 |
|
| 451 |
|
| 452 |
class StackCheckError(ValueError): |
| 453 |
message = None |
| 454 |
def __init__(self, message): |
| 455 |
self.message = message |
| 456 |
|
| 457 |
class LibFFIError(Exception): |
| 458 |
pass |
| 459 |
|
| 460 |
FUNCFLAG_STDCALL = 0 |
| 461 |
FUNCFLAG_CDECL = 1 |
| 462 |
FUNCFLAG_PYTHONAPI = 4 |
| 463 |
FUNCFLAG_USE_ERRNO = 8 |
| 464 |
FUNCFLAG_USE_LASTERROR = 16 |
| 465 |
|
| 466 |
@specialize.arg(1) |
| 467 |
def get_call_conv(flags, from_jit): |
| 468 |
if _WIN32 and not _WIN64 and (flags & FUNCFLAG_CDECL == 0): |
| 469 |
return FFI_STDCALL |
| 470 |
else: |
| 471 |
return FFI_DEFAULT_ABI |
| 472 |
|
| 473 |
|
| 474 |
class AbstractFuncPtr(object): |
| 475 |
ll_cif = lltype.nullptr(FFI_CIFP.TO) |
| 476 |
ll_argtypes = lltype.nullptr(FFI_TYPE_PP.TO) |
| 477 |
|
| 478 |
_immutable_fields_ = ['argtypes', 'restype'] |
| 479 |
|
| 480 |
def __init__(self, name, argtypes, restype, flags=FUNCFLAG_CDECL, variadic_args=0): |
| 481 |
self.name = name |
| 482 |
self.argtypes = argtypes |
| 483 |
self.restype = restype |
| 484 |
self.flags = flags |
| 485 |
argnum = len(argtypes) |
| 486 |
self.ll_argtypes = lltype.malloc(FFI_TYPE_PP.TO, argnum, flavor='raw', |
| 487 |
track_allocation=False) |
| 488 |
for i in range(argnum): |
| 489 |
self.ll_argtypes[i] = argtypes[i] |
| 490 |
self.ll_cif = lltype.malloc(FFI_CIFP.TO, flavor='raw', |
| 491 |
track_allocation=False) |
| 492 |
|
| 493 |
if _MSVC: |
| 494 |
|
| 495 |
|
| 496 |
if intmask(restype.c_type) == FFI_TYPE_STRUCT: |
| 497 |
if restype.c_size <= 4: |
| 498 |
restype = ffi_type_sint32 |
| 499 |
elif restype.c_size <= 8: |
| 500 |
restype = ffi_type_sint64 |
| 501 |
|
| 502 |
if variadic_args > 0: |
| 503 |
res = c_ffi_prep_cif_var(self.ll_cif, |
| 504 |
rffi.cast(rffi.USHORT, get_call_conv(flags,False)), |
| 505 |
rffi.cast(rffi.UINT, argnum - variadic_args), |
| 506 |
rffi.cast(rffi.UINT, argnum), restype, |
| 507 |
self.ll_argtypes) |
| 508 |
else: |
| 509 |
res = c_ffi_prep_cif(self.ll_cif, |
| 510 |
rffi.cast(rffi.USHORT, get_call_conv(flags,False)), |
| 511 |
rffi.cast(rffi.UINT, argnum), restype, |
| 512 |
self.ll_argtypes) |
| 513 |
if not res == FFI_OK: |
| 514 |
raise LibFFIError |
| 515 |
|
| 516 |
def __del__(self): |
| 517 |
if self.ll_cif: |
| 518 |
lltype.free(self.ll_cif, flavor='raw', track_allocation=False) |
| 519 |
self.ll_cif = lltype.nullptr(FFI_CIFP.TO) |
| 520 |
if self.ll_argtypes: |
| 521 |
lltype.free(self.ll_argtypes, flavor='raw', track_allocation=False) |
| 522 |
self.ll_argtypes = lltype.nullptr(FFI_TYPE_PP.TO) |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
class CallbackFuncPtr(AbstractFuncPtr): |
| 527 |
ll_closure = lltype.nullptr(FFI_CLOSUREP.TO) |
| 528 |
ll_userdata = lltype.nullptr(USERDATA_P.TO) |
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
def __init__(self, argtypes, restype, func, additional_arg=0, |
| 533 |
flags=FUNCFLAG_CDECL, variadic_args=0): |
| 534 |
AbstractFuncPtr.__init__(self, "callback", argtypes, restype, flags, |
| 535 |
variadic_args) |
| 536 |
self.ll_code = lltype.malloc(rffi.VOIDPP.TO, 1, flavor='raw') |
| 537 |
self.ll_closure = rffi.cast(FFI_CLOSUREP, |
| 538 |
c_ffi_closure_alloc(rffi.cast(rffi.SIZE_T, rffi.sizeof(FFI_CLOSUREP.TO)), self.ll_code)) |
| 539 |
self.ll_userdata = lltype.malloc(USERDATA_P.TO, flavor='raw', |
| 540 |
track_allocation=False) |
| 541 |
self.ll_userdata.callback = rffi.llhelper(CALLBACK_TP, func) |
| 542 |
self.ll_userdata.addarg = additional_arg |
| 543 |
res = c_ffi_prep_closure_loc(self.ll_closure, self.ll_cif, |
| 544 |
ll_callback, rffi.cast(rffi.VOIDP, |
| 545 |
self.ll_userdata), |
| 546 |
self.ll_code[0]) |
| 547 |
if not res == FFI_OK: |
| 548 |
raise LibFFIError |
| 549 |
|
| 550 |
def get_closure(self): |
| 551 |
return self.ll_code[0] |
| 552 |
|
| 553 |
def __del__(self): |
| 554 |
AbstractFuncPtr.__del__(self) |
| 555 |
if self.ll_closure: |
| 556 |
c_ffi_closure_free(self.ll_closure) |
| 557 |
lltype.free(self.ll_code, flavor='raw') |
| 558 |
self.ll_closure = lltype.nullptr(FFI_CLOSUREP.TO) |
| 559 |
if self.ll_userdata: |
| 560 |
lltype.free(self.ll_userdata, flavor='raw', track_allocation=False) |
| 561 |
self.ll_userdata = lltype.nullptr(USERDATA_P.TO) |
| 562 |
|
| 563 |
class RawFuncPtr(AbstractFuncPtr): |
| 564 |
|
| 565 |
def __init__(self, name, argtypes, restype, funcsym, flags=FUNCFLAG_CDECL, |
| 566 |
keepalive=None, variadic_args=0): |
| 567 |
AbstractFuncPtr.__init__(self, name, argtypes, restype, flags, variadic_args) |
| 568 |
self.keepalive = keepalive |
| 569 |
self.funcsym = funcsym |
| 570 |
|
| 571 |
def call(self, args_ll, ll_result): |
| 572 |
|
| 573 |
assert len(args_ll) == len(self.argtypes), ( |
| 574 |
"wrong number of arguments in call to %s(): " |
| 575 |
"%d instead of %d" % (self.name, len(args_ll), len(self.argtypes))) |
| 576 |
ll_args = lltype.malloc(rffi.VOIDPP.TO, len(args_ll), flavor='raw') |
| 577 |
for i in range(len(args_ll)): |
| 578 |
assert args_ll[i] |
| 579 |
ll_args[i] = args_ll[i] |
| 580 |
ffires = c_ffi_call(self.ll_cif, self.funcsym, ll_result, ll_args) |
| 581 |
lltype.free(ll_args, flavor='raw') |
| 582 |
check_fficall_result(ffires, self.flags) |
| 583 |
|
| 584 |
class FuncPtr(AbstractFuncPtr): |
| 585 |
ll_args = lltype.nullptr(rffi.VOIDPP.TO) |
| 586 |
ll_result = lltype.nullptr(rffi.VOIDP.TO) |
| 587 |
|
| 588 |
def __init__(self, name, argtypes, restype, funcsym, flags=FUNCFLAG_CDECL, |
| 589 |
keepalive=None, variadic_args=0): |
| 590 |
|
| 591 |
AbstractFuncPtr.__init__(self, name, argtypes, restype, flags, variadic_args) |
| 592 |
self.keepalive = keepalive |
| 593 |
self.funcsym = funcsym |
| 594 |
self.argnum = len(self.argtypes) |
| 595 |
self.pushed_args = 0 |
| 596 |
self.ll_args = lltype.malloc(rffi.VOIDPP.TO, self.argnum, flavor='raw') |
| 597 |
for i in range(self.argnum): |
| 598 |
|
| 599 |
self.ll_args[i] = lltype.malloc(rffi.VOIDP.TO, |
| 600 |
intmask(argtypes[i].c_size), |
| 601 |
flavor='raw') |
| 602 |
if restype != ffi_type_void: |
| 603 |
self.restype_size = intmask(restype.c_size) |
| 604 |
size = adjust_return_size(self.restype_size) |
| 605 |
self.ll_result = lltype.malloc(rffi.VOIDP.TO, size, |
| 606 |
flavor='raw') |
| 607 |
else: |
| 608 |
self.restype_size = -1 |
| 609 |
|
| 610 |
@specialize.argtype(1) |
| 611 |
def push_arg(self, value): |
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
if not we_are_translated(): |
| 616 |
TP = lltype.typeOf(value) |
| 617 |
if isinstance(TP, lltype.Ptr): |
| 618 |
if TP.TO._gckind != 'raw': |
| 619 |
raise ValueError("Can only push raw values to C, not 'gc'") |
| 620 |
|
| 621 |
|
| 622 |
if isinstance(TP.TO, lltype.Array): |
| 623 |
try: |
| 624 |
TP.TO._hints['nolength'] |
| 625 |
except KeyError: |
| 626 |
raise ValueError("Can only push to C arrays without length info") |
| 627 |
push_arg_as_ffiptr(self.argtypes[self.pushed_args], value, |
| 628 |
self.ll_args[self.pushed_args]) |
| 629 |
self.pushed_args += 1 |
| 630 |
|
| 631 |
def _check_args(self): |
| 632 |
if self.pushed_args < self.argnum: |
| 633 |
raise TypeError("Did not specify arg nr %d" % (self.pushed_args + 1)) |
| 634 |
|
| 635 |
def _clean_args(self): |
| 636 |
self.pushed_args = 0 |
| 637 |
|
| 638 |
@specialize.arg(1) |
| 639 |
def call(self, RES_TP): |
| 640 |
self._check_args() |
| 641 |
ffires = c_ffi_call(self.ll_cif, self.funcsym, |
| 642 |
rffi.cast(rffi.VOIDP, self.ll_result), |
| 643 |
rffi.cast(VOIDPP, self.ll_args)) |
| 644 |
if RES_TP is not lltype.Void: |
| 645 |
TP = lltype.Ptr(rffi.CArray(RES_TP)) |
| 646 |
ptr = self.ll_result |
| 647 |
if _BIG_ENDIAN and RES_TP in TYPE_MAP_INT: |
| 648 |
|
| 649 |
n = rffi.sizeof(lltype.Signed) - self.restype_size |
| 650 |
ptr = rffi.ptradd(ptr, n) |
| 651 |
res = rffi.cast(TP, ptr)[0] |
| 652 |
else: |
| 653 |
res = None |
| 654 |
self._clean_args() |
| 655 |
check_fficall_result(ffires, self.flags) |
| 656 |
return res |
| 657 |
|
| 658 |
def __del__(self): |
| 659 |
if self.ll_args: |
| 660 |
argnum = len(self.argtypes) |
| 661 |
for i in range(argnum): |
| 662 |
if self.ll_args[i]: |
| 663 |
lltype.free(self.ll_args[i], flavor='raw') |
| 664 |
lltype.free(self.ll_args, flavor='raw') |
| 665 |
self.ll_args = lltype.nullptr(rffi.VOIDPP.TO) |
| 666 |
if self.ll_result: |
| 667 |
lltype.free(self.ll_result, flavor='raw') |
| 668 |
self.ll_result = lltype.nullptr(rffi.VOIDP.TO) |
| 669 |
AbstractFuncPtr.__del__(self) |
| 670 |
|
| 671 |
class RawCDLL(object): |
| 672 |
def __init__(self, handle): |
| 673 |
self.lib = handle |
| 674 |
|
| 675 |
def getpointer(self, name, argtypes, restype, flags=FUNCFLAG_CDECL, variadic_args=0): |
| 676 |
|
| 677 |
|
| 678 |
return FuncPtr(name, argtypes, restype, dlsym(self.lib, name), |
| 679 |
flags=flags, keepalive=self, variadic_args=variadic_args) |
| 680 |
|
| 681 |
def getrawpointer(self, name, argtypes, restype, flags=FUNCFLAG_CDECL, variadic_args=0): |
| 682 |
|
| 683 |
|
| 684 |
return RawFuncPtr(name, argtypes, restype, dlsym(self.lib, name), |
| 685 |
flags=flags, keepalive=self, variadic_args=variadic_args) |
| 686 |
|
| 687 |
def getrawpointer_byordinal(self, ordinal, argtypes, restype, |
| 688 |
flags=FUNCFLAG_CDECL, variadic_args=0): |
| 689 |
|
| 690 |
|
| 691 |
return RawFuncPtr(name, argtypes, restype, |
| 692 |
dlsym_byordinal(self.lib, ordinal), flags=flags, |
| 693 |
keepalive=self, variadic_args=variadic_args) |
| 694 |
|
| 695 |
def getaddressindll(self, name): |
| 696 |
return dlsym(self.lib, name) |
| 697 |
|
| 698 |
class CDLL(RawCDLL): |
| 699 |
def __init__(self, libname, mode=-1): |
| 700 |
"""Load the library, or raises DLOpenError.""" |
| 701 |
RawCDLL.__init__(self, rffi.cast(DLLHANDLE, -1)) |
| 702 |
self.lib = dlopen(libname, mode) |
| 703 |
|
| 704 |
def __del__(self): |
| 705 |
if self.lib != rffi.cast(DLLHANDLE, -1): |
| 706 |
dlclose(self.lib) |
| 707 |
self.lib = rffi.cast(DLLHANDLE, -1) |
| 708 |
|
| 709 |
|
| 710 |
def adjust_return_size(memsize): |
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
if memsize < 8: |
| 716 |
memsize = 8 |
| 717 |
return memsize |