Debian Codegraph @

rpython/rtyper/lltypesystem/ll2ctypes.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import sys
4
5 try:
6 import ctypes
7 import ctypes.util
8
9 if not hasattr(ctypes, 'c_longdouble'):
10 ctypes.c_longdouble = ctypes.c_double
11 except ImportError:
12 ctypes = None
13
14 if sys.version_info >= (2, 6):
15 load_library_kwargs = {'use_errno': True}
16 else:
17 load_library_kwargs = {}
18
19 import os, platform as host_platform
20 from rpython.rtyper.lltypesystem import lltype, llmemory
21 from rpython.rtyper.extfunc import ExtRegistryEntry
22 from rpython.rlib.objectmodel import Symbolic, ComputedIntSymbolic
23 from rpython.tool.uid import fixid
24 from rpython.rlib.rarithmetic import r_singlefloat, r_longfloat, base_int, intmask
25 from rpython.rlib.rarithmetic import is_emulated_long, maxint
26 from rpython.annotator import model as annmodel
27 from rpython.rtyper.llannotation import lltype_to_annotation
28 from rpython.rtyper.llannotation import SomePtr
29 from rpython.rtyper.llinterp import LLInterpreter, LLException
30 from rpython.rtyper.rclass import OBJECT, OBJECT_VTABLE
31 from rpython.rtyper import raddress
32 from rpython.translator.platform import platform
33 from array import array
34 try:
35 from thread import _local as tlsobject
36 except ImportError:
37 class tlsobject(object):
38 pass
39 try:
40 from threading import RLock
41 except ImportError:
42 class RLock(object):
43 def __enter__(self):
44 pass
45 def __exit__(self, *args):
46 pass
47 rlock = RLock()
48
49 _POSIX = os.name == "posix"
50 _MS_WINDOWS = os.name == "nt"
51 _FREEBSD = sys.platform.startswith('freebsd')
52 _64BIT = "64bit" in host_platform.architecture()[0]
53
54
55 # ____________________________________________________________
56
57 far_regions = None
58
59 def allocate_ctypes(ctype):
60 if far_regions:
61 import random
62 pieces = far_regions._ll2ctypes_pieces
63 num = random.randrange(len(pieces)+1)
64 if num == len(pieces):
65 return ctype()
66 i1, stop = pieces[num]
67 i2 = i1 + ((ctypes.sizeof(ctype) or 1) + 7) & ~7
68 if i2 > stop:
69 raise MemoryError("out of memory in far_regions")
70 pieces[num] = i2, stop
71 p = lltype2ctypes(far_regions.getptr(i1))
72 return ctypes.cast(p, ctypes.POINTER(ctype)).contents
73 else:
74 return ctype()
75
76 def do_allocation_in_far_regions():
77 """On 32 bits: this reserves 1.25GB of address space, or 2.5GB on POSIX,
78 which helps test this module for address values that are signed or
79 unsigned.
80
81 On 64-bits: reserves 10 times 2GB of address space. This should help
82 to find 32-vs-64-bit issues in the JIT. It is likely that objects
83 are further apart than 32 bits can represent; it is also possible
84 to hit the corner case of being precisely e.g. 2GB - 8 bytes apart.
85
86 Avoid this function if your OS reserves actual RAM from mmap() eagerly.
87 """
88 global far_regions
89 if not far_regions:
90 from rpython.rlib import rmmap
91 if _64BIT:
92 PIECE_STRIDE = 0x80000000
93 else:
94 if _POSIX:
95 PIECE_STRIDE = 0x10000000
96 else:
97 PIECE_STRIDE = 0x08000000
98 if _POSIX:
99 PIECE_SIZE = 0x04000000
100 else:
101 PIECE_SIZE = PIECE_STRIDE
102 PIECES = 10
103 flags = (0,)
104 if _POSIX:
105 flags = (rmmap.MAP_PRIVATE|rmmap.MAP_ANONYMOUS|rmmap.MAP_NORESERVE,
106 rmmap.PROT_READ|rmmap.PROT_WRITE)
107 elif _MS_WINDOWS:
108 flags = (rmmap.MEM_RESERVE,)
109 # XXX seems not to work
110 else:
111 assert False # should always generate flags
112
113 # Map and unmap something just to exercise unmap so that we (lazily)
114 # build the ctypes callable. Otherwise, when we reach unmap below
115 # we may already have a giant map and be unable to fork, as for the
116 # /sbin/ldconfig call inside ctypes.util.find_library().
117 rmmap.mmap(-1, 4096, *flags).close()
118
119 m = rmmap.mmap(-1, PIECES * PIECE_STRIDE, *flags)
120 m.close = lambda : None # leak instead of giving a spurious
121 # error at CPython's shutdown
122 m._ll2ctypes_pieces = []
123 for i in range(PIECES):
124 start = i * PIECE_STRIDE
125 m._ll2ctypes_pieces.append((start, start + PIECE_SIZE))
126 if _POSIX:
127 m.unmap_range(start + PIECE_SIZE, PIECE_STRIDE - PIECE_SIZE)
128 far_regions = m
129
130 # ____________________________________________________________
131
132 _ctypes_cache = {}
133 _eci_cache = {}
134
135 def _setup_ctypes_cache():
136 from rpython.rtyper.lltypesystem import rffi
137
138 if is_emulated_long:
139 signed_as_ctype = ctypes.c_longlong
140 unsigned_as_ctypes = ctypes.c_ulonglong
141 else:
142 signed_as_ctype = ctypes.c_long
143 unsigned_as_ctypes = ctypes.c_ulong
144
145 _ctypes_cache.update({
146 lltype.Signed: signed_as_ctype,
147 lltype.Unsigned: unsigned_as_ctypes,
148 lltype.Char: ctypes.c_ubyte,
149 rffi.DOUBLE: ctypes.c_double,
150 rffi.FLOAT: ctypes.c_float,
151 rffi.LONGDOUBLE: ctypes.c_longdouble,
152 rffi.SIGNEDCHAR: ctypes.c_byte,
153 rffi.UCHAR: ctypes.c_ubyte,
154 rffi.SHORT: ctypes.c_short,
155 rffi.USHORT: ctypes.c_ushort,
156 rffi.INT: ctypes.c_int,
157 rffi.INT_real: ctypes.c_int,
158 rffi.UINT: ctypes.c_uint,
159 rffi.UINT_real: ctypes.c_uint,
160 rffi.LONG: ctypes.c_long,
161 rffi.ULONG: ctypes.c_ulong,
162 rffi.LONGLONG: ctypes.c_longlong,
163 rffi.ULONGLONG: ctypes.c_ulonglong,
164 rffi.SIZE_T: ctypes.c_size_t,
165 lltype.Bool: getattr(ctypes, "c_bool", ctypes.c_byte),
166 llmemory.Address: ctypes.c_void_p,
167 llmemory.GCREF: ctypes.c_void_p,
168 llmemory.WeakRef: ctypes.c_void_p, # XXX
169 })
170
171 if '__int128_t' in rffi.TYPES:
172 class c_int128(ctypes.Array): # based on 2 ulongs
173 _type_ = ctypes.c_uint64
174 _length_ = 2
175 @property
176 def value(self):
177 res = self[0] | (self[1] << 64)
178 if res >= (1 << 127):
179 res -= 1 << 128
180 return res
181 class c_uint128(ctypes.Array): # based on 2 ulongs
182 _type_ = ctypes.c_uint64
183 _length_ = 2
184 @property
185 def value(self):
186 res = self[0] | (self[1] << 64)
187 return res
188
189 _ctypes_cache[rffi.__INT128_T] = c_int128
190 _ctypes_cache[rffi.__UINT128_T] = c_uint128
191
192 # for unicode strings, do not use ctypes.c_wchar because ctypes
193 # automatically converts arrays into unicode strings.
194 # Pick the unsigned int that has the same size.
195 if ctypes.sizeof(ctypes.c_wchar) == ctypes.sizeof(ctypes.c_uint16):
196 _ctypes_cache[lltype.UniChar] = ctypes.c_uint16
197 else:
198 _ctypes_cache[lltype.UniChar] = ctypes.c_uint32
199
200 def build_ctypes_struct(S, delayed_builders, max_n=None):
201 def builder():
202 # called a bit later to fill in _fields_
203 # (to handle recursive structure pointers)
204 fields = []
205 for fieldname in S._names:
206 FIELDTYPE = S._flds[fieldname]
207 if max_n is not None and fieldname == S._arrayfld:
208 cls = get_ctypes_array_of_size(FIELDTYPE, max_n)
209 else:
210 if isinstance(FIELDTYPE, lltype.Ptr):
211 cls = get_ctypes_type(FIELDTYPE, delayed_builders)
212 else:
213 cls = get_ctypes_type(FIELDTYPE, delayed_builders,
214 cannot_delay=True)
215 fields.append((fieldname, cls))
216 CStruct._fields_ = fields
217
218 if S._hints.get('union', False):
219 base = ctypes.Union
220 else:
221 base = ctypes.Structure
222
223 class CStruct(base):
224 # no _fields_: filled later by builder()
225
226 def _malloc(cls, n=None):
227 if S._arrayfld is None:
228 if n is not None:
229 raise TypeError("%r is not variable-sized" % (S,))
230 storage = allocate_ctypes(cls)
231 return storage
232 else:
233 if n is None:
234 raise TypeError("%r is variable-sized" % (S,))
235 biggercls = build_ctypes_struct(S, None, n)
236 bigstruct = allocate_ctypes(biggercls)
237 array = getattr(bigstruct, S._arrayfld)
238 if hasattr(array, 'length'):
239 array.length = n
240 return bigstruct
241 _malloc = classmethod(_malloc)
242
243 CStruct.__name__ = 'ctypes_%s' % (S,)
244 if max_n is not None:
245 CStruct._normalized_ctype = get_ctypes_type(S)
246 builder() # no need to be lazy here
247 else:
248 delayed_builders.append((S, builder))
249 return CStruct
250
251 def build_ctypes_array(A, delayed_builders, max_n=0):
252 assert max_n >= 0
253 ITEM = A.OF
254 ctypes_item = get_ctypes_type(ITEM, delayed_builders)
255 ctypes_item_ptr = ctypes.POINTER(ctypes_item)
256
257 class CArray(ctypes.Structure):
258 if is_emulated_long:
259 lentype = ctypes.c_longlong
260 else:
261 lentype = ctypes.c_long
262
263 if not A._hints.get('nolength'):
264 _fields_ = [('length', lentype),
265 ('items',
266 (max_n + A._hints.get('extra_item_after_alloc', 0))
267 * ctypes_item)]
268 else:
269 _fields_ = [('items', max_n * ctypes_item)]
270
271 @classmethod
272 def _malloc(cls, n=None):
273 if not isinstance(n, int):
274 raise TypeError("array length must be an int")
275 biggercls = get_ctypes_array_of_size(A, n)
276 bigarray = allocate_ctypes(biggercls)
277 if hasattr(bigarray, 'length'):
278 bigarray.length = n
279 return bigarray
280
281 def _indexable(self, index):
282 p = ctypes.cast(self.items, ctypes_item_ptr)
283 return p
284
285 def _getitem(self, index, boundscheck=True):
286 if boundscheck:
287 items = self.items
288 else:
289 items = self._indexable(index)
290 cobj = items[index]
291 if isinstance(ITEM, lltype.ContainerType):
292 return ctypes2lltype(lltype.Ptr(ITEM), ctypes.pointer(cobj))
293 else:
294 return ctypes2lltype(ITEM, cobj)
295
296 def _setitem(self, index, value, boundscheck=True):
297 if boundscheck:
298 items = self.items
299 else:
300 items = self._indexable(index)
301 cobj = lltype2ctypes(value)
302 items[index] = cobj
303
304 CArray.__name__ = 'ctypes_%s*%d' % (A, max_n)
305 if max_n > 0:
306 CArray._normalized_ctype = get_ctypes_type(A)
307 return CArray
308
309 def get_ctypes_array_of_size(FIELDTYPE, max_n):
310 if max_n > 0:
311 # no need to cache the results in this case, because the exact
312 # type is never seen - the array instances are cast to the
313 # array's _normalized_ctype, which is always the same.
314 return build_ctypes_array(FIELDTYPE, None, max_n)
315 else:
316 return get_ctypes_type(FIELDTYPE)
317
318 def get_ctypes_type(T, delayed_builders=None, cannot_delay=False):
319 # Check delayed builders
320 if cannot_delay and delayed_builders:
321 for T2, builder in delayed_builders:
322 if T2 is T:
323 builder()
324 delayed_builders.remove((T2, builder))
325 return _ctypes_cache[T]
326
327 try:
328 return _ctypes_cache[T]
329 except KeyError:
330 toplevel = cannot_delay or delayed_builders is None
331 if toplevel:
332 delayed_builders = []
333 cls = build_new_ctypes_type(T, delayed_builders)
334 if T not in _ctypes_cache:
335 _ctypes_cache[T] = cls
336 else:
337 # check for buggy recursive structure logic
338 assert _ctypes_cache[T] is cls
339 if toplevel:
340 complete_builders(delayed_builders)
341 return cls
342
343 def build_new_ctypes_type(T, delayed_builders):
344 if isinstance(T, lltype.Typedef):
345 T = T.OF
346
347 if isinstance(T, lltype.Ptr):
348 if isinstance(T.TO, lltype.FuncType):
349 functype = ctypes.CFUNCTYPE
350 if sys.platform == 'win32' and not _64BIT:
351 from rpython.rlib.clibffi import FFI_STDCALL, FFI_DEFAULT_ABI
352 if getattr(T.TO, 'ABI', FFI_DEFAULT_ABI) == FFI_STDCALL:
353 # for win32 system call
354 functype = ctypes.WINFUNCTYPE
355 argtypes = [get_ctypes_type(ARG) for ARG in T.TO.ARGS
356 if ARG is not lltype.Void]
357 if T.TO.RESULT is lltype.Void:
358 restype = None
359 else:
360 restype = get_ctypes_type(T.TO.RESULT)
361 try:
362 kwds = {'use_errno': True}
363 return functype(restype, *argtypes, **kwds)
364 except TypeError:
365 # unexpected 'use_errno' argument, old ctypes version
366 return functype(restype, *argtypes)
367 elif isinstance(T.TO, lltype.OpaqueType):
368 return ctypes.c_void_p
369 else:
370 return ctypes.POINTER(get_ctypes_type(T.TO, delayed_builders))
371 elif T is lltype.Void:
372 return ctypes.c_long # opaque pointer
373 elif isinstance(T, lltype.Struct):
374 return build_ctypes_struct(T, delayed_builders)
375 elif isinstance(T, lltype.Array):
376 return build_ctypes_array(T, delayed_builders)
377 elif isinstance(T, lltype.OpaqueType):
378 if T is lltype.RuntimeTypeInfo:
379 return ctypes.c_char * 2
380 if T._hints.get('external', None) != 'C':
381 raise TypeError("%s is not external" % T)
382 return ctypes.c_char * T._hints['getsize']()
383 else:
384 _setup_ctypes_cache()
385 if T in _ctypes_cache:
386 return _ctypes_cache[T]
387 raise NotImplementedError(T)
388
389 def complete_builders(delayed_builders):
390 while delayed_builders:
391 T, builder = delayed_builders[0]
392 builder()
393 delayed_builders.pop(0)
394
395 def convert_struct(container, cstruct=None, delayed_converters=None):
396 STRUCT = container._TYPE
397 if cstruct is None:
398 # if 'container' is an inlined substructure, convert the whole
399 # bigger structure at once
400 parent, parentindex = lltype.parentlink(container)
401 if parent is not None:
402 if isinstance(parent, lltype._struct):
403 convert_struct(parent)
404 elif isinstance(parent, lltype._array):
405 convert_array(parent)
406 else:
407 raise AssertionError(type(parent))
408 return
409 # regular case: allocate a new ctypes Structure of the proper type
410 cls = get_ctypes_type(STRUCT)
411 if STRUCT._arrayfld is not None:
412 n = getattr(container, STRUCT._arrayfld).getlength()
413 else:
414 n = None
415 cstruct = cls._malloc(n)
416
417 if isinstance(container, lltype._fixedsizearray):
418 cls_mixin = _fixedsizedarray_mixin
419 else:
420 cls_mixin = _struct_mixin
421 add_storage(container, cls_mixin, ctypes.pointer(cstruct))
422
423 if delayed_converters is None:
424 delayed_converters_was_None = True
425 delayed_converters = []
426 else:
427 delayed_converters_was_None = False
428 for field_name in STRUCT._names:
429 FIELDTYPE = getattr(STRUCT, field_name)
430 field_value = getattr(container, field_name)
431 if not isinstance(FIELDTYPE, lltype.ContainerType):
432 # regular field
433 if FIELDTYPE != lltype.Void:
434 def convert(field_name=field_name, field_value=field_value):
435 setattr(cstruct, field_name, lltype2ctypes(field_value))
436 if isinstance(FIELDTYPE, lltype.Ptr):
437 delayed_converters.append(convert)
438 else:
439 convert()
440 else:
441 # inlined substructure/subarray
442 if isinstance(FIELDTYPE, lltype.Struct):
443 csubstruct = getattr(cstruct, field_name)
444 convert_struct(field_value, csubstruct,
445 delayed_converters=delayed_converters)
446 elif field_name == STRUCT._arrayfld: # inlined var-sized part
447 csubarray = getattr(cstruct, field_name)
448 convert_array(field_value, csubarray)
449 else:
450 raise NotImplementedError('inlined field', FIELDTYPE)
451 if delayed_converters_was_None:
452 for converter in delayed_converters:
453 converter()
454
455 remove_regular_struct_content(container)
456
457 def remove_regular_struct_content(container):
458 STRUCT = container._TYPE
459 if isinstance(STRUCT, lltype.FixedSizeArray):
460 del container._items
461 return
462 for field_name in STRUCT._names:
463 FIELDTYPE = getattr(STRUCT, field_name)
464 if not isinstance(FIELDTYPE, lltype.ContainerType):
465 delattr(container, field_name)
466
467 def convert_array(container, carray=None):
468 ARRAY = container._TYPE
469 if carray is None:
470 # if 'container' is an inlined substructure, convert the whole
471 # bigger structure at once
472 parent, parentindex = lltype.parentlink(container)
473 if parent is not None:
474 if not isinstance(parent, _parentable_mixin):
475 convert_struct(parent)
476 return
477 # regular case: allocate a new ctypes array of the proper type
478 cls = get_ctypes_type(ARRAY)
479 carray = cls._malloc(container.getlength())
480 add_storage(container, _array_mixin, ctypes.pointer(carray))
481 if not isinstance(ARRAY.OF, lltype.ContainerType):
482 # fish that we have enough space
483 ctypes_array = ctypes.cast(carray.items,
484 ctypes.POINTER(carray.items._type_))
485 for i in range(container.getlength()):
486 item_value = container.items[i] # fish fish
487 ctypes_array[i] = lltype2ctypes(item_value)
488 remove_regular_array_content(container)
489 else:
490 assert isinstance(ARRAY.OF, lltype.Struct)
491 for i in range(container.getlength()):
492 item_ptr = container.items[i] # fish fish
493 convert_struct(item_ptr, carray.items[i])
494
495 def remove_regular_array_content(container):
496 for i in range(container.getlength()):
497 container.items[i] = None
498
499 def struct_use_ctypes_storage(container, ctypes_storage):
500 STRUCT = container._TYPE
501 assert isinstance(STRUCT, lltype.Struct)
502 if isinstance(container, lltype._fixedsizearray):
503 cls_mixin = _fixedsizedarray_mixin
504 else:
505 cls_mixin = _struct_mixin
506 add_storage(container, cls_mixin, ctypes_storage)
507 remove_regular_struct_content(container)
508 for field_name in STRUCT._names:
509 FIELDTYPE = getattr(STRUCT, field_name)
510 if isinstance(FIELDTYPE, lltype.ContainerType):
511 if isinstance(FIELDTYPE, lltype.Struct):
512 struct_container = getattr(container, field_name)
513 struct_storage = ctypes.pointer(
514 getattr(ctypes_storage.contents, field_name))
515 struct_use_ctypes_storage(struct_container, struct_storage)
516 struct_container._setparentstructure(container, field_name)
517 elif isinstance(FIELDTYPE, lltype.Array):
518 if FIELDTYPE._hints.get('nolength', False):
519 arraycontainer = _array_of_unknown_length(FIELDTYPE)
520 else:
521 arraycontainer = _array_of_known_length(FIELDTYPE)
522 arraycontainer._storage = ctypes.pointer(
523 getattr(ctypes_storage.contents, field_name))
524 arraycontainer._setparentstructure(container, field_name)
525 object.__setattr__(container, field_name, arraycontainer)
526 else:
527 raise NotImplementedError(FIELDTYPE)
528
529 # ____________________________________________________________
530 # Ctypes-aware subclasses of the _parentable classes
531
532 ALLOCATED = {} # mapping {address: _container}
533 DEBUG_ALLOCATED = False
534
535 def get_common_subclass(cls1, cls2, cache={}):
536 """Return a unique subclass with (cls1, cls2) as bases."""
537 try:
538 return cache[cls1, cls2]
539 except KeyError:
540 subcls = type('_ctypes_%s' % (cls1.__name__,),
541 (cls1, cls2),
542 {'__slots__': ()})
543 cache[cls1, cls2] = subcls
544 return subcls
545
546 def add_storage(instance, mixin_cls, ctypes_storage):
547 """Put ctypes_storage on the instance, changing its __class__ so that it
548 sees the methods of the given mixin class."""
549 # _storage is a ctypes pointer to a structure
550 # except for Opaque objects which use a c_void_p.
551 assert not isinstance(instance, _parentable_mixin) # not yet
552 subcls = get_common_subclass(mixin_cls, instance.__class__)
553 instance.__class__ = subcls
554 instance._storage = ctypes_storage
555 assert ctypes_storage # null pointer?
556
557 class NotCtypesAllocatedStructure(ValueError):
558 pass
559
560 class _parentable_mixin(object):
561 """Mixin added to _parentable containers when they become ctypes-based.
562 (This is done by changing the __class__ of the instance to reference
563 a subclass of both its original class and of this mixin class.)
564 """
565 __slots__ = ()
566
567 def _ctypes_storage_was_allocated(self):
568 addr = ctypes.cast(self._storage, ctypes.c_void_p).value
569 if addr in ALLOCATED:
570 raise Exception("internal ll2ctypes error - "
571 "double conversion from lltype to ctypes?")
572 # XXX don't store here immortal structures
573 if DEBUG_ALLOCATED:
574 print("LL2CTYPES:", hex(addr), file=sys.stderr)
575 ALLOCATED[addr] = self
576
577 def _addressof_storage(self):
578 "Returns the storage address as an int"
579 if self._storage is None or self._storage is True:
580 raise NotCtypesAllocatedStructure("Not a ctypes allocated structure")
581 return intmask(ctypes.cast(self._storage, ctypes.c_void_p).value)
582
583 def _free(self):
584 self._check() # no double-frees
585 # allow the ctypes object to go away now
586 addr = ctypes.cast(self._storage, ctypes.c_void_p).value
587 if DEBUG_ALLOCATED:
588 print("LL2C FREE:", hex(addr), file=sys.stderr)
589 try:
590 del ALLOCATED[addr]
591 except KeyError:
592 raise Exception("invalid free() - data already freed or "
593 "not allocated from RPython at all")
594 self._storage = None
595
596 def _getid(self):
597 return self._addressof_storage()
598
599 def __eq__(self, other):
600 if isinstance(other, _llgcopaque):
601 addressof_other = other.intval
602 else:
603 if not isinstance(other, lltype._parentable):
604 return False
605 if self._storage is None:
606 raise RuntimeError("pointer comparison with a freed structure")
607 if other._storage is None:
608 return False # stale WeakKeyDictionary entry
609 if other._storage is True:
610 return False # the other container is not ctypes-based
611 addressof_other = other._addressof_storage()
612 # both containers are ctypes-based, compare the addresses
613 return self._addressof_storage() == addressof_other
614
615 def __ne__(self, other):
616 return not (self == other)
617
618 def __hash__(self):
619 if self._storage is not None:
620 return self._addressof_storage()
621 else:
622 return object.__hash__(self)
623
624 def __repr__(self):
625 if '__str__' in self._TYPE._adtmeths:
626 r = self._TYPE._adtmeths['__str__'](self)
627 else:
628 r = 'C object %s' % (self._TYPE,)
629 if self._storage is None:
630 return '<freed %s>' % (r,)
631 else:
632 return '<%s at 0x%x>' % (r, fixid(self._addressof_storage()))
633
634 def __str__(self):
635 return repr(self)
636
637 def _setparentstructure(self, parent, parentindex):
638 super(_parentable_mixin, self)._setparentstructure(parent, parentindex)
639 self._keepparent = parent # always keep a strong ref
640
641 class _struct_mixin(_parentable_mixin):
642 """Mixin added to _struct containers when they become ctypes-based."""
643 __slots__ = ()
644
645 def __getattr__(self, field_name):
646 T = getattr(self._TYPE, field_name)
647 cobj = getattr(self._storage.contents, field_name)
648 return ctypes2lltype(T, cobj)
649
650 def __setattr__(self, field_name, value):
651 if field_name.startswith('_'):
652 object.__setattr__(self, field_name, value) # '_xxx' attributes
653 else:
654 cobj = lltype2ctypes(value)
655 setattr(self._storage.contents, field_name, cobj)
656
657 class _fixedsizedarray_mixin(_parentable_mixin):
658 """Mixin added to _fixedsizearray containers when they become ctypes-based."""
659 __slots__ = ()
660
661 def __getattr__(self, field_name):
662 if hasattr(self, '_items'):
663 obj = lltype._fixedsizearray.__getattr__.im_func(self, field_name)
664 return obj
665 else:
666 cobj = getattr(self._storage.contents, field_name)
667 T = getattr(self._TYPE, field_name)
668 return ctypes2lltype(T, cobj)
669
670 def __setattr__(self, field_name, value):
671 if field_name.startswith('_'):
672 object.__setattr__(self, field_name, value) # '_xxx' attributes
673 else:
674 cobj = lltype2ctypes(value)
675 if hasattr(self, '_items'):
676 lltype._fixedsizearray.__setattr__.im_func(self, field_name, cobj)
677 else:
678 setattr(self._storage.contents, field_name, cobj)
679
680
681 def getitem(self, index, uninitialized_ok=False):
682 if hasattr(self, '_items'):
683 obj = lltype._fixedsizearray.getitem.im_func(self,
684 index, uninitialized_ok=uninitialized_ok)
685 return obj
686 else:
687 return getattr(self, 'item%d' % index)
688
689 def setitem(self, index, value):
690 cobj = lltype2ctypes(value)
691 if hasattr(self, '_items'):
692 lltype._fixedsizearray.setitem.im_func(self, index, value)
693 else:
694 setattr(self, 'item%d' % index, cobj)
695
696 class _array_mixin(_parentable_mixin):
697 """Mixin added to _array containers when they become ctypes-based."""
698 __slots__ = ()
699
700 def getitem(self, index, uninitialized_ok=False):
701 return self._storage.contents._getitem(index)
702
703 def setitem(self, index, value):
704 self._storage.contents._setitem(index, value)
705
706 class _array_of_unknown_length(_parentable_mixin, lltype._parentable):
707 _kind = "array"
708 __slots__ = ()
709
710 def getbounds(self):
711 # we have no clue, so we allow whatever index
712 return 0, maxint
713
714 def shrinklength(self, newlength):
715 raise NotImplementedError
716
717 def getitem(self, index, uninitialized_ok=False):
718 res = self._storage.contents._getitem(index, boundscheck=False)
719 if isinstance(self._TYPE.OF, lltype.ContainerType):
720 res._obj._setparentstructure(self, index)
721 return res
722
723 def setitem(self, index, value):
724 self._storage.contents._setitem(index, value, boundscheck=False)
725
726 def getitems(self):
727 if self._TYPE.OF != lltype.Char:
728 raise Exception("cannot get all items of an unknown-length "
729 "array of %r" % self._TYPE.OF)
730 _items = []
731 i = 0
732 while 1:
733 nextitem = self.getitem(i)
734 if nextitem == '\x00':
735 _items.append('\x00')
736 return _items
737 _items.append(nextitem)
738 i += 1
739
740 items = property(getitems)
741
742 class _array_of_known_length(_array_of_unknown_length):
743 __slots__ = ()
744
745 def getlength(self):
746 return self._storage.contents.length
747
748 def getbounds(self):
749 return 0, self.getlength()
750
751 # ____________________________________________________________
752
753 def _find_parent(llobj):
754 parent, parentindex = lltype.parentlink(llobj)
755 if parent is None:
756 return llobj, 0
757 next_p, next_i = _find_parent(parent)
758 if isinstance(parentindex, int):
759 c_tp = get_ctypes_type(lltype.typeOf(parent))
760 sizeof = ctypes.sizeof(get_ctypes_type(lltype.typeOf(parent).OF))
761 ofs = c_tp.items.offset + parentindex * sizeof
762 return next_p, next_i + ofs
763 else:
764 c_tp = get_ctypes_type(lltype.typeOf(parent))
765 ofs = getattr(c_tp, parentindex).offset
766 return next_p, next_i + ofs
767
768 # ____________________________________________________________
769
770 # XXX THIS IS A HACK XXX
771 # ctypes does not keep callback arguments alive. So we do. Forever
772 # we need to think deeper how to approach this problem
773 # additionally, this adds mess to __del__ "semantics"
774 _all_callbacks = {}
775 _all_callbacks_results = []
776 _int2obj = {}
777 _callback_exc_info = None
778 _opaque_objs = [None]
779 _opaque_objs_seen = {}
780
781 def get_rtyper():
782 llinterp = LLInterpreter.current_interpreter
783 if llinterp is not None:
784 return llinterp.typer
785 else:
786 return None
787
788 def lltype2ctypes(llobj, normalize=True):
789 """Convert the lltype object 'llobj' to its ctypes equivalent.
790 'normalize' should only be False in tests, where we want to
791 inspect the resulting ctypes object manually.
792 """
793 with rlock:
794 if isinstance(llobj, lltype._uninitialized):
795 return uninitialized2ctypes(llobj.TYPE)
796 if isinstance(llobj, llmemory.AddressAsInt):
797 cobj = ctypes.cast(lltype2ctypes(llobj.adr), ctypes.c_void_p)
798 res = intmask(cobj.value)
799 _int2obj[res] = llobj.adr.ptr._obj
800 return res
801 if isinstance(llobj, llmemory.fakeaddress):
802 llobj = llobj.ptr or 0
803
804 T = lltype.typeOf(llobj)
805
806 if isinstance(T, lltype.Ptr):
807 if not llobj: # NULL pointer
808 if T == llmemory.GCREF:
809 return ctypes.c_void_p(0)
810 return get_ctypes_type(T)()
811
812 if T == llmemory.GCREF:
813 if isinstance(llobj._obj, _llgcopaque):
814 return ctypes.c_void_p(llobj._obj.intval)
815 if isinstance(llobj._obj, int): # tagged pointer
816 return ctypes.c_void_p(llobj._obj)
817 container = llobj._obj.container
818 T = lltype.Ptr(lltype.typeOf(container))
819 # otherwise it came from integer and we want a c_void_p with
820 # the same value
821 if getattr(container, 'llopaque', None):
822 try:
823 no = _opaque_objs_seen[container]
824 except KeyError:
825 no = len(_opaque_objs)
826 _opaque_objs.append(container)
827 _opaque_objs_seen[container] = no
828 return no * 2 + 1
829 else:
830 container = llobj._obj
831 if isinstance(T.TO, lltype.FuncType):
832 if hasattr(llobj._obj0, '_real_integer_addr'):
833 ctypes_func_type = get_ctypes_type(T)
834 return ctypes.cast(llobj._obj0._real_integer_addr(),
835 ctypes_func_type)
836 # XXX a temporary workaround for comparison of lltype.FuncType
837 key = llobj._obj.__dict__.copy()
838 key['_TYPE'] = repr(key['_TYPE'])
839 items = key.items()
840 items.sort()
841 key = tuple(items)
842 if key in _all_callbacks:
843 return _all_callbacks[key]
844 v1voidlist = [(i, getattr(container, '_void' + str(i), None))
845 for i in range(len(T.TO.ARGS))
846 if T.TO.ARGS[i] is lltype.Void]
847 def callback_internal(*cargs):
848 cargs = list(cargs)
849 for v1 in v1voidlist:
850 cargs.insert(v1[0], v1[1])
851 assert len(cargs) == len(T.TO.ARGS)
852 llargs = []
853 for ARG, carg in zip(T.TO.ARGS, cargs):
854 if ARG is lltype.Void:
855 llargs.append(carg)
856 else:
857 llargs.append(ctypes2lltype(ARG, carg))
858 if hasattr(container, 'graph'):
859 if LLInterpreter.current_interpreter is None:
860 raise AssertionError
861 llinterp = LLInterpreter.current_interpreter
862 try:
863 llres = llinterp.eval_graph(container.graph, llargs)
864 except LLException as lle:
865 llinterp._store_exception(lle)
866 return 0
867 #except:
868 # import pdb
869 # pdb.set_trace()
870 else:
871 try:
872 llres = container._callable(*llargs)
873 except LLException as lle:
874 llinterp = LLInterpreter.current_interpreter
875 llinterp._store_exception(lle)
876 return 0
877 return ctypes_return_value(llres)
878
879 def ctypes_return_value(llres):
880 assert lltype.typeOf(llres) == T.TO.RESULT
881 if T.TO.RESULT is lltype.Void:
882 return None
883 res = lltype2ctypes(llres)
884 if isinstance(T.TO.RESULT, lltype.Ptr):
885 _all_callbacks_results.append(res)
886 res = ctypes.cast(res, ctypes.c_void_p).value
887 if res is None:
888 return 0
889 if T.TO.RESULT == lltype.SingleFloat:
890 res = res.value # baaaah, cannot return a c_float()
891 return res
892
893 def callback(*cargs):
894 try:
895 return callback_internal(*cargs)
896 except:
897 import sys
898 #if option.usepdb:
899 # import pdb; pdb.post_mortem(sys.exc_traceback)
900 global _callback_exc_info
901 _callback_exc_info = sys.exc_info()
902 _callable = getattr(container, '_callable', None)
903 if hasattr(_callable, '_llhelper_error_value_'):
904 # see rlib.objectmodel.llhelper_error_value
905 llres = _callable._llhelper_error_value_
906 assert lltype.typeOf(llres) == T.TO.RESULT
907 return ctypes_return_value(llres)
908 else:
909 raise
910
911 if isinstance(T.TO.RESULT, lltype.Ptr):
912 TMod = lltype.Ptr(lltype.FuncType(T.TO.ARGS,
913 lltype.Signed))
914 ctypes_func_type = get_ctypes_type(TMod)
915 res = ctypes_func_type(callback)
916 ctypes_func_type = get_ctypes_type(T)
917 res = ctypes.cast(res, ctypes_func_type)
918 else:
919 ctypes_func_type = get_ctypes_type(T)
920 res = ctypes_func_type(callback)
921 _all_callbacks[key] = res
922 key2 = intmask(ctypes.cast(res, ctypes.c_void_p).value)
923 _int2obj[key2] = container
924 return res
925
926 index = 0
927 if isinstance(container, lltype._subarray):
928 topmost, index = _find_parent(container)
929 container = topmost
930 T = lltype.Ptr(lltype.typeOf(container))
931
932 if container._storage is None:
933 raise RuntimeError("attempting to pass a freed structure to C")
934 if container._storage is True:
935 # container has regular lltype storage, convert it to ctypes
936 if isinstance(T.TO, lltype.Struct):
937 convert_struct(container)
938 elif isinstance(T.TO, lltype.Array):
939 convert_array(container)
940 elif isinstance(T.TO, lltype.OpaqueType):
941 if T.TO != lltype.RuntimeTypeInfo:
942 cbuf = ctypes.create_string_buffer(T.TO._hints['getsize']())
943 else:
944 cbuf = ctypes.create_string_buffer("\x00")
945 cbuf = ctypes.cast(cbuf, ctypes.c_void_p)
946 add_storage(container, _parentable_mixin, cbuf)
947 else:
948 raise NotImplementedError(T)
949 container._ctypes_storage_was_allocated()
950
951 if isinstance(T.TO, lltype.OpaqueType):
952 return container._storage.value
953
954 storage = container._storage
955 p = storage
956 if index:
957 p = ctypes.cast(p, ctypes.c_void_p)
958 p = ctypes.c_void_p(p.value + index)
959 c_tp = get_ctypes_type(T.TO)
960 storage.contents._normalized_ctype = c_tp
961 if normalize and hasattr(storage.contents, '_normalized_ctype'):
962 normalized_ctype = storage.contents._normalized_ctype
963 p = ctypes.cast(p, ctypes.POINTER(normalized_ctype))
964 if lltype.typeOf(llobj) == llmemory.GCREF:
965 p = ctypes.cast(p, ctypes.c_void_p)
966 return p
967
968 if isinstance(llobj, Symbolic):
969 if isinstance(llobj, llmemory.ItemOffset):
970 llobj = ctypes.sizeof(get_ctypes_type(llobj.TYPE)) * llobj.repeat
971 elif isinstance(llobj, ComputedIntSymbolic):
972 llobj = llobj.compute_fn()
973 elif isinstance(llobj, llmemory.CompositeOffset):
974 llobj = sum([lltype2ctypes(c) for c in llobj.offsets])
975 elif isinstance(llobj, llmemory.FieldOffset):
976 CSTRUCT = get_ctypes_type(llobj.TYPE)
977 llobj = getattr(CSTRUCT, llobj.fldname).offset
978 elif isinstance(llobj, llmemory.ArrayItemsOffset):
979 CARRAY = get_ctypes_type(llobj.TYPE)
980 llobj = CARRAY.items.offset
981 else:
982 raise NotImplementedError(llobj) # don't know about symbolic value
983
984 if T is lltype.Char or T is lltype.UniChar:
985 return ord(llobj)
986
987 if T is lltype.SingleFloat:
988 return ctypes.c_float(float(llobj))
989
990 return llobj
991
992 def ctypes2lltype(T, cobj, force_real_ctypes_function=False):
993 """Convert the ctypes object 'cobj' to its lltype equivalent.
994 'T' is the expected lltype type.
995 """
996 with rlock:
997 if T is lltype.Void:
998 return None
999 if isinstance(T, lltype.Typedef):
1000 T = T.OF
1001 if isinstance(T, lltype.Ptr):
1002 ptrval = ctypes.cast(cobj, ctypes.c_void_p).value
1003 if not cobj or not ptrval: # NULL pointer
1004 # CFunctionType.__nonzero__ is broken before Python 2.6
1005 return lltype.nullptr(T.TO)
1006 if isinstance(T.TO, lltype.Struct):
1007 if T.TO._gckind == 'gc' and ptrval & 1: # a tagged pointer
1008 gcref = _opaque_objs[ptrval // 2].hide()
1009 return lltype.cast_opaque_ptr(T, gcref)
1010 REAL_TYPE = T.TO
1011 if T.TO._arrayfld is not None:
1012 carray = getattr(cobj.contents, T.TO._arrayfld)
1013 length = getattr(carray, 'length', 9999) # XXX
1014 container = lltype._struct(T.TO, length)
1015 else:
1016 # special treatment of 'OBJECT' subclasses
1017 if get_rtyper() and lltype._castdepth(REAL_TYPE, OBJECT) >= 0:
1018 # figure out the real type of the object
1019 containerheader = lltype._struct(OBJECT)
1020 cobjheader = ctypes.cast(cobj,
1021 get_ctypes_type(lltype.Ptr(OBJECT)))
1022 struct_use_ctypes_storage(containerheader,
1023 cobjheader)
1024 REAL_TYPE = get_rtyper().get_type_for_typeptr(
1025 containerheader.typeptr)
1026 REAL_T = lltype.Ptr(REAL_TYPE)
1027 cobj = ctypes.cast(cobj, get_ctypes_type(REAL_T))
1028 container = lltype._struct(REAL_TYPE)
1029 # obscuuuuuuuuure: 'cobj' is a ctypes pointer, which is
1030 # mutable; and so if we save away the 'cobj' object
1031 # itself, it might suddenly later be unexpectedly
1032 # modified! Make a copy.
1033 cobj = ctypes.cast(cobj, type(cobj))
1034 struct_use_ctypes_storage(container, cobj)
1035 if REAL_TYPE != T.TO:
1036 p = container._as_ptr()
1037 container = lltype.cast_pointer(T, p)._as_obj()
1038 # special treatment of 'OBJECT_VTABLE' subclasses
1039 if get_rtyper() and lltype._castdepth(REAL_TYPE,
1040 OBJECT_VTABLE) >= 0:
1041 # figure out the real object that this vtable points to,
1042 # and just return that
1043 p = get_rtyper().get_real_typeptr_for_typeptr(
1044 container._as_ptr())
1045 container = lltype.cast_pointer(T, p)._as_obj()
1046 elif isinstance(T.TO, lltype.Array):
1047 if T.TO._hints.get('nolength', False):
1048 container = _array_of_unknown_length(T.TO)
1049 container._storage = type(cobj)(cobj.contents)
1050 else:
1051 container = _array_of_known_length(T.TO)
1052 container._storage = type(cobj)(cobj.contents)
1053 elif isinstance(T.TO, lltype.FuncType):
1054 # cobj is a CFunctionType object. We naively think
1055 # that it should be a function pointer. No no no. If
1056 # it was read out of an array, say, then it is a *pointer*
1057 # to a function pointer. In other words, the read doesn't
1058 # read anything, it just takes the address of the function
1059 # pointer inside the array. If later the array is modified
1060 # or goes out of scope, then we crash. CTypes is fun.
1061 # It works if we cast it now to an int and back.
1062 cobjkey = intmask(ctypes.cast(cobj, ctypes.c_void_p).value)
1063 if cobjkey in _int2obj and not force_real_ctypes_function:
1064 container = _int2obj[cobjkey]
1065 else:
1066 name = getattr(cobj, '__name__', '?')
1067 cobj = ctypes.cast(cobjkey, type(cobj))
1068 _callable = get_ctypes_trampoline(T.TO, cobj)
1069 return lltype.functionptr(T.TO, name,
1070 _callable=_callable,
1071 _real_integer_addr=lambda: cobjkey)
1072 elif isinstance(T.TO, lltype.OpaqueType):
1073 if T == llmemory.GCREF:
1074 container = _llgcopaque(cobj)
1075 else:
1076 container = lltype._opaque(T.TO)
1077 cbuf = ctypes.cast(cobj, ctypes.c_void_p)
1078 add_storage(container, _parentable_mixin, cbuf)
1079 else:
1080 raise NotImplementedError(T)
1081 llobj = lltype._ptr(T, container, solid=True)
1082 elif T is llmemory.Address:
1083 if cobj is None:
1084 llobj = llmemory.NULL
1085 else:
1086 llobj = _lladdress(cobj)
1087 elif T is lltype.Char:
1088 llobj = chr(cobj)
1089 elif T is lltype.UniChar:
1090 try:
1091 llobj = unichr(cobj)
1092 except (ValueError, OverflowError):
1093 for tc in 'HIL':
1094 if array(tc).itemsize == array('u').itemsize:
1095 import struct
1096 cobj &= 256 ** struct.calcsize(tc) - 1
1097 # CPython2 allows this
1098 # PyPy2 will create the array but not allow indexing it
1099 llobj = array('u', array(tc, (cobj,)).tostring())[0]
1100 break
1101 else:
1102 raise
1103 elif T is lltype.Signed:
1104 llobj = cobj
1105 elif T is lltype.Bool:
1106 assert cobj == True or cobj == False # 0 and 1 work too
1107 llobj = bool(cobj)
1108 elif T is lltype.SingleFloat:
1109 if isinstance(cobj, ctypes.c_float):
1110 cobj = cobj.value
1111 llobj = r_singlefloat(cobj)
1112 elif T is lltype.LongFloat:
1113 if isinstance(cobj, ctypes.c_longdouble):
1114 cobj = cobj.value
1115 llobj = r_longfloat(cobj)
1116 elif T is lltype.Void:
1117 llobj = cobj
1118 else:
1119 from rpython.rtyper.lltypesystem import rffi
1120 try:
1121 inttype = rffi.platform.numbertype_to_rclass[T]
1122 except KeyError:
1123 llobj = cobj
1124 else:
1125 llobj = inttype(cobj)
1126
1127 assert lltype.typeOf(llobj) == T
1128 return llobj
1129
1130 def uninitialized2ctypes(T):
1131 "For debugging, create a ctypes object filled with 0xDD."
1132 ctype = get_ctypes_type(T)
1133 cobj = ctype()
1134 size = ctypes.sizeof(cobj)
1135 p = ctypes.cast(ctypes.pointer(cobj),
1136 ctypes.POINTER(ctypes.c_ubyte * size))
1137 for i in range(size):
1138 p.contents[i] = 0xDD
1139 if isinstance(T, lltype.Primitive):
1140 return cobj.value
1141 else:
1142 return cobj
1143
1144 # __________ the standard C library __________
1145
1146 if ctypes:
1147 def get_libc_name():
1148 if sys.platform == 'win32':
1149 # Parses sys.version and deduces the version of the compiler
1150 import distutils.msvccompiler
1151 version = distutils.msvccompiler.get_build_version()
1152 if version is None:
1153 # This logic works with official builds of Python.
1154 if sys.version_info < (2, 4):
1155 clibname = 'msvcrt'
1156 else:
1157 clibname = 'msvcr71'
1158 else:
1159 if version <= 6:
1160 clibname = 'msvcrt'
1161 elif version >= 13:
1162 clibname = 'ucrtbase'
1163 else:
1164 clibname = 'msvcr%d' % (version * 10)
1165
1166 # If python was built with in debug mode
1167 import imp
1168 if imp.get_suffixes()[0][0] == '_d.pyd':
1169 clibname += 'd'
1170
1171 return clibname+'.dll'
1172 else:
1173 return ctypes.util.find_library('c')
1174
1175 libc_name = get_libc_name() # Make sure the name is determined during import, not at runtime
1176 if _FREEBSD:
1177 RTLD_DEFAULT = -2 # see <dlfcn.h>
1178 rtld_default_lib = ctypes.CDLL("ld-elf.so.1", handle=RTLD_DEFAULT, **load_library_kwargs)
1179 # XXX is this always correct???
1180 standard_c_lib = ctypes.CDLL(libc_name, **load_library_kwargs)
1181 else:
1182 libc_name = 'no ctypes'
1183
1184 # ____________________________________________
1185
1186 # xxx from ctypes.util, this code is a useful fallback on darwin too
1187 if sys.platform == 'darwin':
1188 # Andreas Degert's find function using gcc
1189 import re, tempfile, errno
1190
1191 def _findLib_gcc_fallback(name):
1192 expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
1193 fdout, ccout = tempfile.mkstemp()
1194 os.close(fdout)
1195 cmd = 'if type gcc >/dev/null 2>&1; then : ${CC:=gcc}; else : ${CC:=cc}; fi;' \
1196 '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name
1197 try:
1198 f = os.popen(cmd)
1199 trace = f.read()
1200 f.close()
1201 finally:
1202 try:
1203 os.unlink(ccout)
1204 except OSError as e:
1205 if e.errno != errno.ENOENT:
1206 raise
1207 res = re.search(expr, trace)
1208 if not res:
1209 return None
1210 return res.group(0)
1211 else:
1212 _findLib_gcc_fallback = lambda name: None
1213
1214 def get_ctypes_callable(funcptr, calling_conv, natural_arity):
1215 if not ctypes:
1216 raise ImportError("ctypes is needed to use ll2ctypes")
1217
1218 def get_on_lib(lib, elem):
1219 """ Wrapper to always use lib[func] instead of lib.func
1220 """
1221 try:
1222 return lib[elem]
1223 except AttributeError:
1224 pass
1225
1226 old_eci = funcptr._obj.compilation_info
1227 funcname = funcptr._obj._name
1228 if hasattr(old_eci, '_with_ctypes'):
1229 old_eci = old_eci._with_ctypes
1230
1231 try:
1232 eci = _eci_cache[old_eci]
1233 except KeyError:
1234 eci = old_eci.compile_shared_lib(ignore_a_files=True,
1235 defines=['RPYTHON_LL2CTYPES'],
1236 symbolic=True)
1237 _eci_cache[old_eci] = eci
1238
1239 libraries = eci.testonly_libraries + eci.libraries + eci.frameworks
1240
1241 FUNCTYPE = lltype.typeOf(funcptr).TO
1242 cfunc = None
1243 if libraries:
1244 not_found = []
1245 for libname in libraries:
1246 libpath = None
1247 ext = platform.so_ext
1248 prefixes = platform.so_prefixes
1249 for dir in eci.library_dirs:
1250 if libpath:
1251 break
1252 for prefix in prefixes:
1253 tryfile = os.path.join(dir, prefix + libname + '.' + ext)
1254 if os.path.isfile(tryfile):
1255 libpath = tryfile
1256 break
1257 if not libpath:
1258 libpath = ctypes.util.find_library(libname)
1259 if not libpath:
1260 libpath = _findLib_gcc_fallback(libname)
1261 if not libpath and os.path.isabs(libname):
1262 libpath = libname
1263 if libpath:
1264 dllclass = getattr(ctypes, calling_conv + 'dll')
1265 # on ie slackware there was need for RTLD_GLOBAL here.
1266 # this breaks a lot of things, since passing RTLD_GLOBAL
1267 # creates symbol conflicts on C level.
1268 clib = dllclass._dlltype(libpath, **load_library_kwargs)
1269 cfunc = get_on_lib(clib, funcname)
1270 if cfunc is not None:
1271 break
1272 else:
1273 not_found.append(libname)
1274
1275 if cfunc is None:
1276 if _FREEBSD and funcname in ('dlopen', 'fdlopen', 'dlsym', 'dlfunc', 'dlerror', 'dlclose'):
1277 cfunc = rtld_default_lib[funcname]
1278 else:
1279 cfunc = get_on_lib(standard_c_lib, funcname)
1280 # XXX magic: on Windows try to load the function from 'kernel32' too
1281 if cfunc is None and hasattr(ctypes, 'windll'):
1282 cfunc = get_on_lib(ctypes.windll.kernel32, funcname)
1283 if cfunc is None and hasattr(ctypes, 'windll'):
1284 cfunc = get_on_lib(ctypes.cdll.msvcrt, funcname)
1285
1286 if cfunc is None:
1287 # function name not found in any of the libraries
1288 if not libraries:
1289 place = 'the standard C library (missing libraries=...?)'
1290 elif len(not_found) == len(libraries):
1291 if len(not_found) == 1:
1292 raise NotImplementedError(
1293 'cannot find the library %r' % (not_found[0],))
1294 else:
1295 raise NotImplementedError(
1296 'cannot find any of the libraries %r' % (not_found,))
1297 elif len(libraries) == 1:
1298 place = 'library %r' % (libraries[0],)
1299 else:
1300 place = 'any of the libraries %r' % (libraries,)
1301 if not_found:
1302 place += ' (did not find %r)' % (not_found,)
1303 raise NotImplementedError("function %r not found in %s" % (
1304 funcname, place))
1305
1306 # get_ctypes_type() can raise NotImplementedError too
1307 from rpython.rtyper.lltypesystem import rffi
1308 argtypes = [get_ctypes_type(T) if T is not rffi.VOIDP
1309 else ctypes.c_void_p
1310 for T in FUNCTYPE.ARGS
1311 if not T is lltype.Void]
1312 if natural_arity != -1:
1313 cfunc.argtypes = argtypes[:natural_arity]
1314 cfunc.extraargs = argtypes[natural_arity:]
1315 else:
1316 cfunc.argtypes = argtypes
1317 cfunc.extraargs = []
1318 if FUNCTYPE.RESULT is lltype.Void:
1319 cfunc.restype = None
1320 else:
1321 cfunc.restype = get_ctypes_type(FUNCTYPE.RESULT)
1322 return cfunc
1323
1324 class LL2CtypesCallable(object):
1325 # a special '_callable' object that invokes ctypes
1326
1327 def __init__(self, FUNCTYPE, calling_conv, natural_arity):
1328 self.FUNCTYPE = FUNCTYPE
1329 self.calling_conv = calling_conv
1330 self.trampoline = None
1331 self.natural_arity = natural_arity
1332 #self.funcptr = ... set later
1333
1334 def __call__(self, *argvalues):
1335 with rlock:
1336 if self.trampoline is None:
1337 # lazily build the corresponding ctypes function object
1338 cfunc = get_ctypes_callable(self.funcptr, self.calling_conv,
1339 self.natural_arity)
1340 self.trampoline = get_ctypes_trampoline(self.FUNCTYPE, cfunc, self.natural_arity)
1341 # perform the call
1342 return self.trampoline(*argvalues)
1343
1344 def get_real_address(self):
1345 cfunc = get_ctypes_callable(self.funcptr, self.calling_conv,
1346 self.natural_arity)
1347 return ctypes.cast(cfunc, ctypes.c_void_p).value
1348
1349 def get_ctypes_trampoline(FUNCTYPE, cfunc, natural_arity=-1):
1350 RESULT = FUNCTYPE.RESULT
1351 container_arguments = []
1352 for i in range(len(FUNCTYPE.ARGS)):
1353 if isinstance(FUNCTYPE.ARGS[i], lltype.ContainerType):
1354 container_arguments.append(i)
1355 void_arguments = []
1356 for i in range(len(FUNCTYPE.ARGS)):
1357 if FUNCTYPE.ARGS[i] is lltype.Void:
1358 void_arguments.append(i)
1359 def callme(cargs): # an extra indirection: workaround for rlib.rstacklet
1360 return cfunc(*cargs)
1361 def invoke_via_ctypes(*argvalues):
1362 global _callback_exc_info
1363 cargs = []
1364 for i in range(len(argvalues)):
1365 if i not in void_arguments:
1366 cvalue = lltype2ctypes(argvalues[i])
1367 if i in container_arguments:
1368 cvalue = cvalue.contents
1369 if natural_arity > 0 and i >= natural_arity:
1370 cvalue = cfunc.extraargs[i - natural_arity](cvalue)
1371 cargs.append(cvalue)
1372 _callback_exc_info = None
1373 _restore_c_errno()
1374 cres = callme(cargs)
1375 _save_c_errno()
1376 if _callback_exc_info:
1377 etype, evalue, etb = _callback_exc_info
1378 # cres is the actual C result returned by the function. Stick it
1379 # into the exception so that we can check it inside tests (see
1380 # e.g. test_llhelper_error_value)
1381 evalue._ll2ctypes_c_result = cres
1382 _callback_exc_info = None
1383 raise etype, evalue, etb
1384 return ctypes2lltype(RESULT, cres)
1385 return invoke_via_ctypes
1386
1387
1388 def force_cast(RESTYPE, value):
1389 with rlock:
1390 if not isinstance(RESTYPE, lltype.LowLevelType):
1391 raise TypeError("rffi.cast() first arg should be a TYPE")
1392 if isinstance(value, llmemory.AddressAsInt):
1393 value = value.adr
1394 if isinstance(value, llmemory.fakeaddress):
1395 value = value.ptr or 0
1396 if isinstance(value, r_singlefloat):
1397 value = float(value)
1398 TYPE1 = lltype.typeOf(value)
1399 cvalue = lltype2ctypes(value)
1400 cresulttype = get_ctypes_type(RESTYPE)
1401 if RESTYPE == TYPE1:
1402 return value
1403 elif isinstance(TYPE1, lltype.Ptr):
1404 if isinstance(RESTYPE, lltype.Ptr):
1405 # shortcut: ptr->ptr cast
1406 cptr = ctypes.cast(cvalue, cresulttype)
1407 return ctypes2lltype(RESTYPE, cptr)
1408 # first cast the input pointer to an integer
1409 cvalue = ctypes.cast(cvalue, ctypes.c_void_p).value
1410 if cvalue is None:
1411 cvalue = 0
1412 elif isinstance(cvalue, (str, unicode)):
1413 cvalue = ord(cvalue) # character -> integer
1414 elif hasattr(RESTYPE, "_type") and issubclass(RESTYPE._type, base_int):
1415 cvalue = int(cvalue)
1416 elif isinstance(cvalue, r_longfloat):
1417 cvalue = cvalue.value
1418
1419 if not isinstance(cvalue, (int, long, float)):
1420 raise NotImplementedError("casting %r to %r" % (TYPE1, RESTYPE))
1421
1422 if isinstance(RESTYPE, lltype.Ptr):
1423 # upgrade to a more recent ctypes (e.g. 1.0.2) if you get
1424 # an OverflowError on the following line.
1425 cvalue = ctypes.cast(ctypes.c_void_p(cvalue), cresulttype)
1426 elif RESTYPE == lltype.Bool:
1427 cvalue = bool(cvalue)
1428 else:
1429 try:
1430 cvalue = cresulttype(cvalue).value # mask high bits off if needed
1431 except TypeError:
1432 cvalue = int(cvalue) # float -> int
1433 cvalue = cresulttype(cvalue).value # try again
1434 return ctypes2lltype(RESTYPE, cvalue)
1435
1436 class ForceCastEntry(ExtRegistryEntry):
1437 _about_ = force_cast
1438
1439 def compute_result_annotation(self, s_RESTYPE, s_value):
1440 assert s_RESTYPE.is_constant()
1441 RESTYPE = s_RESTYPE.const
1442 return lltype_to_annotation(RESTYPE)
1443
1444 def specialize_call(self, hop):
1445 hop.exception_cannot_occur()
1446 s_RESTYPE = hop.args_s[0]
1447 assert s_RESTYPE.is_constant()
1448 RESTYPE = s_RESTYPE.const
1449 v_arg = hop.inputarg(hop.args_r[1], arg=1)
1450 return hop.genop('force_cast', [v_arg], resulttype = RESTYPE)
1451
1452 def typecheck_ptradd(T):
1453 # --- ptradd() is only for pointers to non-GC, no-length arrays.
1454 assert isinstance(T, lltype.Ptr)
1455 assert isinstance(T.TO, lltype.Array)
1456 assert T.TO._hints.get('nolength')
1457
1458 def force_ptradd(ptr, n):
1459 """'ptr' must be a pointer to an array. Equivalent of 'ptr + n' in
1460 C, i.e. gives a pointer to the n'th item of the array. The type of
1461 the result is again a pointer to an array, the same as the type of
1462 'ptr'.
1463 """
1464 T = lltype.typeOf(ptr)
1465 typecheck_ptradd(T)
1466 ctypes_item_type = get_ctypes_type(T.TO.OF)
1467 ctypes_arrayptr_type = get_ctypes_type(T)
1468 cptr = lltype2ctypes(ptr)
1469 baseaddr = ctypes.addressof(cptr.contents.items)
1470 addr = baseaddr + n * ctypes.sizeof(ctypes_item_type)
1471 cptr = ctypes.cast(ctypes.c_void_p(addr), ctypes_arrayptr_type)
1472 return ctypes2lltype(T, cptr)
1473
1474 class ForcePtrAddEntry(ExtRegistryEntry):
1475 _about_ = force_ptradd
1476
1477 def compute_result_annotation(self, s_ptr, s_n):
1478 assert isinstance(s_n, annmodel.SomeInteger)
1479 assert isinstance(s_ptr, SomePtr)
1480 typecheck_ptradd(s_ptr.ll_ptrtype)
1481 return lltype_to_annotation(s_ptr.ll_ptrtype)
1482
1483 def specialize_call(self, hop):
1484 hop.exception_cannot_occur()
1485 v_ptr, v_n = hop.inputargs(hop.args_r[0], lltype.Signed)
1486 return hop.genop('direct_ptradd', [v_ptr, v_n],
1487 resulttype = v_ptr.concretetype)
1488
1489 class _lladdress(long):
1490 _TYPE = llmemory.Address
1491
1492 def __new__(cls, void_p):
1493 if isinstance(void_p, (int, long)):
1494 void_p = ctypes.c_void_p(void_p)
1495 self = long.__new__(cls, intmask(void_p.value))
1496 self.void_p = void_p
1497 self.intval = intmask(void_p.value)
1498 return self
1499
1500 def _cast_to_ptr(self, TP):
1501 return force_cast(TP, self.intval)
1502
1503 def __repr__(self):
1504 return '<_lladdress %s>' % (self.void_p,)
1505
1506 def __eq__(self, other):
1507 if not isinstance(other, (int, long)):
1508 other = cast_adr_to_int(other)
1509 return intmask(other) == self.intval
1510
1511 def __ne__(self, other):
1512 return not self == other
1513
1514 class _llgcopaque(lltype._container):
1515 _TYPE = llmemory.GCREF.TO
1516 _name = "_llgcopaque"
1517 _read_directly_intval = True # for _ptr._cast_to_int()
1518
1519 def __init__(self, void_p):
1520 if isinstance(void_p, (int, long)):
1521 self.intval = intmask(void_p)
1522 else:
1523 self.intval = intmask(void_p.value)
1524
1525 def __eq__(self, other):
1526 if not other:
1527 return self.intval == 0
1528 if isinstance(other, _llgcopaque):
1529 return self.intval == other.intval
1530 storage = object()
1531 if hasattr(other, 'container'):
1532 storage = other.container._storage
1533 else:
1534 storage = other._storage
1535
1536 if storage in (None, True):
1537 return False
1538 return force_cast(lltype.Signed, other._as_ptr()) == self.intval
1539
1540 def __hash__(self):
1541 return self.intval
1542
1543 def __ne__(self, other):
1544 return not self == other
1545
1546 def _cast_to_ptr(self, PTRTYPE):
1547 if self.intval & 1:
1548 return _opaque_objs[self.intval // 2]
1549 return force_cast(PTRTYPE, self.intval)
1550
1551
1552 def cast_adr_to_int(addr):
1553 if isinstance(addr, llmemory.fakeaddress):
1554 # use ll2ctypes to obtain a real ctypes-based representation of
1555 # the memory, and cast that address as an integer
1556 if addr.ptr is None:
1557 res = 0
1558 else:
1559 res = force_cast(lltype.Signed, addr.ptr)
1560 else:
1561 res = addr._cast_to_int()
1562 if res > maxint:
1563 res = res - 2*(maxint + 1)
1564 assert int(res) == res
1565 return int(res)
1566 return res
1567
1568 class CastAdrToIntEntry(ExtRegistryEntry):
1569 _about_ = cast_adr_to_int
1570
1571 def compute_result_annotation(self, s_addr):
1572 return annmodel.SomeInteger()
1573
1574 def specialize_call(self, hop):
1575 assert isinstance(hop.args_r[0], raddress.AddressRepr)
1576 adr, = hop.inputargs(hop.args_r[0])
1577 hop.exception_cannot_occur()
1578 return hop.genop('cast_adr_to_int', [adr],
1579 resulttype = lltype.Signed)
1580
1581 # ____________________________________________________________
1582 # errno
1583
1584 # this saves in a thread-local way the "current" value that errno
1585 # should have in C. We have to save it away from one external C function
1586 # call to the next. Otherwise a non-zero value left behind will confuse
1587 # CPython itself a bit later, and/or CPython will stamp on it before we
1588 # try to inspect it via rposix.get_errno().
1589 TLS = tlsobject()
1590
1591 # helpers to save/restore the C-level errno -- platform-specific because
1592 # ctypes doesn't just do the right thing and expose it directly :-(
1593
1594 # on 2.6 ctypes does it right, use it
1595
1596 if sys.version_info >= (2, 6):
1597 def _save_c_errno():
1598 TLS.errno = ctypes.get_errno()
1599
1600 def _restore_c_errno():
1601 pass
1602
1603 else:
1604 def _where_is_errno():
1605 raise NotImplementedError("don't know how to get the C-level errno!")
1606
1607 def _save_c_errno():
1608 errno_p = _where_is_errno()
1609 TLS.errno = errno_p.contents.value
1610 errno_p.contents.value = 0
1611
1612 def _restore_c_errno():
1613 if hasattr(TLS, 'errno'):
1614 _where_is_errno().contents.value = TLS.errno
1615
1616 if ctypes:
1617 if _MS_WINDOWS:
1618 standard_c_lib._errno.restype = ctypes.POINTER(ctypes.c_int)
1619 def _where_is_errno():
1620 return standard_c_lib._errno()
1621
1622 elif sys.platform.startswith('linux'):
1623 standard_c_lib.__errno_location.restype = ctypes.POINTER(ctypes.c_int)
1624 def _where_is_errno():
1625 return standard_c_lib.__errno_location()
1626
1627 elif sys.platform == 'darwin' or _FREEBSD:
1628 standard_c_lib.__error.restype = ctypes.POINTER(ctypes.c_int)
1629 def _where_is_errno():
1630 return standard_c_lib.__error()