| 1 |
import sys |
| 2 |
import _rawffi |
| 3 |
from _ctypes.basics import _CData, _CDataMeta, keepalive_key,\ |
| 4 |
store_reference, ensure_objects, CArgObject |
| 5 |
from _ctypes.array import Array, swappedorder, byteorder |
| 6 |
from _ctypes.pointer import _Pointer |
| 7 |
import __pypy__ |
| 8 |
|
| 9 |
|
| 10 |
def names_and_fields(self, _fields_, superclass, anonymous_fields=None): |
| 11 |
|
| 12 |
if isinstance(_fields_, tuple): |
| 13 |
_fields_ = list(_fields_) |
| 14 |
for f in _fields_: |
| 15 |
tp = f[1] |
| 16 |
if not isinstance(tp, _CDataMeta): |
| 17 |
raise TypeError("Expected CData subclass, got %s" % (tp,)) |
| 18 |
if isinstance(tp, StructOrUnionMeta): |
| 19 |
tp._make_final() |
| 20 |
if len(f) == 3: |
| 21 |
if (not hasattr(tp, '_type_') |
| 22 |
or not isinstance(tp._type_, str) |
| 23 |
or tp._type_ not in "iIhHbBlLqQ"): |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
raise TypeError('bit fields not allowed for type ' + tp.__name__) |
| 29 |
|
| 30 |
all_fields = [] |
| 31 |
for cls in reversed(superclass.__mro__): |
| 32 |
|
| 33 |
all_fields.extend(getattr(cls, '_fields_', [])) |
| 34 |
all_fields.extend(_fields_) |
| 35 |
names = [f[0] for f in all_fields] |
| 36 |
rawfields = [] |
| 37 |
for f in all_fields: |
| 38 |
if len(f) > 2: |
| 39 |
rawfields.append((f[0], f[1]._ffishape_, f[2])) |
| 40 |
else: |
| 41 |
rawfields.append((f[0], f[1]._ffishape_)) |
| 42 |
|
| 43 |
|
| 44 |
already_seen = set() |
| 45 |
names1 = names |
| 46 |
names = [] |
| 47 |
for f in names1: |
| 48 |
if f not in already_seen: |
| 49 |
names.append(f) |
| 50 |
already_seen.add(f) |
| 51 |
already_seen = set() |
| 52 |
for i in reversed(range(len(rawfields))): |
| 53 |
if rawfields[i][0] in already_seen: |
| 54 |
rawfields[i] = (('$DUP%d$%s' % (i, rawfields[i][0]),) |
| 55 |
+ rawfields[i][1:]) |
| 56 |
already_seen.add(rawfields[i][0]) |
| 57 |
|
| 58 |
|
| 59 |
_set_shape(self, rawfields, self._is_union) |
| 60 |
|
| 61 |
fields = {} |
| 62 |
for i, field in enumerate(all_fields): |
| 63 |
name = field[0] |
| 64 |
value = field[1] |
| 65 |
is_bitfield = (len(field) == 3) |
| 66 |
fields[name] = Field(name, |
| 67 |
self._ffistruct_.fieldoffset(name), |
| 68 |
self._ffistruct_.fieldsize(name), |
| 69 |
value, i, is_bitfield) |
| 70 |
|
| 71 |
if anonymous_fields: |
| 72 |
resnames = [] |
| 73 |
for i, field in enumerate(all_fields): |
| 74 |
name = field[0] |
| 75 |
value = field[1] |
| 76 |
is_bitfield = (len(field) == 3) |
| 77 |
startpos = self._ffistruct_.fieldoffset(name) |
| 78 |
if name in anonymous_fields: |
| 79 |
for subname in value._names_: |
| 80 |
resnames.append(subname) |
| 81 |
subfield = getattr(value, subname) |
| 82 |
relpos = startpos + subfield.offset |
| 83 |
subvalue = subfield.ctype |
| 84 |
fields[subname] = Field(subname, |
| 85 |
relpos, subvalue._sizeofinstances(), |
| 86 |
subvalue, i, is_bitfield, |
| 87 |
inside_anon_field=fields[name]) |
| 88 |
else: |
| 89 |
resnames.append(name) |
| 90 |
names = resnames |
| 91 |
self._names_ = names |
| 92 |
for name, field in fields.items(): |
| 93 |
setattr(self, name, field) |
| 94 |
|
| 95 |
|
| 96 |
class Field(object): |
| 97 |
def __init__(self, name, offset, size, ctype, num, is_bitfield, |
| 98 |
inside_anon_field=None): |
| 99 |
self.__dict__['name'] = name |
| 100 |
self.__dict__['offset'] = offset |
| 101 |
self.__dict__['size'] = size |
| 102 |
self.__dict__['ctype'] = ctype |
| 103 |
self.__dict__['num'] = num |
| 104 |
self.__dict__['is_bitfield'] = is_bitfield |
| 105 |
self.__dict__['inside_anon_field'] = inside_anon_field |
| 106 |
|
| 107 |
def __setattr__(self, name, value): |
| 108 |
raise AttributeError(name) |
| 109 |
|
| 110 |
def __repr__(self): |
| 111 |
return "<Field '%s' offset=%d size=%d>" % (self.name, self.offset, |
| 112 |
self.size) |
| 113 |
|
| 114 |
def __get__(self, obj, cls=None): |
| 115 |
if obj is None: |
| 116 |
return self |
| 117 |
if self.inside_anon_field is not None: |
| 118 |
return getattr(self.inside_anon_field.__get__(obj), self.name) |
| 119 |
if self.is_bitfield: |
| 120 |
|
| 121 |
return obj._buffer.__getattr__(self.name) |
| 122 |
elif not isinstance(obj, _CData): |
| 123 |
raise(TypeError, 'not a ctype instance') |
| 124 |
else: |
| 125 |
fieldtype = self.ctype |
| 126 |
offset = self.num |
| 127 |
suba = obj._subarray(fieldtype, self.name) |
| 128 |
return fieldtype._CData_output(suba, obj, offset) |
| 129 |
|
| 130 |
def __delete__(self, obj): |
| 131 |
raise TypeError("cannot delete attribute") |
| 132 |
|
| 133 |
def __set__(self, obj, value): |
| 134 |
if self.inside_anon_field is not None: |
| 135 |
setattr(self.inside_anon_field.__get__(obj), self.name, value) |
| 136 |
return |
| 137 |
fieldtype = self.ctype |
| 138 |
cobj = fieldtype.from_param(value) |
| 139 |
key = keepalive_key(self.num) |
| 140 |
if issubclass(fieldtype, _Pointer) and isinstance(cobj, Array): |
| 141 |
|
| 142 |
store_reference(obj, key, cobj) |
| 143 |
elif ensure_objects(cobj) is not None: |
| 144 |
store_reference(obj, key, cobj._objects) |
| 145 |
arg = cobj._get_buffer_value() |
| 146 |
if fieldtype._fficompositesize_ is not None: |
| 147 |
from ctypes import memmove |
| 148 |
dest = obj._buffer.fieldaddress(self.name) |
| 149 |
memmove(dest, arg, fieldtype._fficompositesize_) |
| 150 |
elif not isinstance(obj, _CData): |
| 151 |
raise(TypeError, 'not a ctype instance') |
| 152 |
else: |
| 153 |
obj._buffer.__setattr__(self.name, arg) |
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
def _set_shape(tp, rawfields, is_union=False): |
| 158 |
tp._ffistruct_ = _rawffi.Structure(rawfields, is_union, |
| 159 |
getattr(tp, '_pack_', 0)) |
| 160 |
tp._ffiargshape_ = tp._ffishape_ = (tp._ffistruct_, 1) |
| 161 |
tp._fficompositesize_ = tp._ffistruct_.size |
| 162 |
|
| 163 |
|
| 164 |
def struct_setattr(self, name, value): |
| 165 |
if name == '_fields_': |
| 166 |
if self.__dict__.get('_fields_', None) is not None: |
| 167 |
raise AttributeError("_fields_ is final") |
| 168 |
if self in [f[1] for f in value]: |
| 169 |
raise AttributeError("Structure or union cannot contain itself") |
| 170 |
if self._ffiargtype is not None: |
| 171 |
raise NotImplementedError("Too late to set _fields_: we already " |
| 172 |
"said to libffi that the structure type %s is opaque" |
| 173 |
% (self,)) |
| 174 |
names_and_fields( |
| 175 |
self, |
| 176 |
value, self.__bases__[0], |
| 177 |
self.__dict__.get('_anonymous_', None)) |
| 178 |
_CDataMeta.__setattr__(self, '_fields_', value) |
| 179 |
return |
| 180 |
_CDataMeta.__setattr__(self, name, value) |
| 181 |
|
| 182 |
|
| 183 |
class StructOrUnionMeta(_CDataMeta): |
| 184 |
def __new__(self, name, cls, typedict): |
| 185 |
res = type.__new__(self, name, cls, typedict) |
| 186 |
if hasattr(res, '_swappedbytes_') and '_fields_' in typedict: |
| 187 |
|
| 188 |
tmp = res._fields_ |
| 189 |
delattr(res, '_fields_') |
| 190 |
setattr(res, '_fields_', tmp) |
| 191 |
if "_abstract_" in typedict: |
| 192 |
return res |
| 193 |
cls = cls or (object,) |
| 194 |
if isinstance(cls[0], StructOrUnionMeta): |
| 195 |
cls[0]._make_final() |
| 196 |
if '_pack_' in typedict: |
| 197 |
if not 0 <= typedict['_pack_'] < 2**31: |
| 198 |
raise ValueError("_pack_ must be a non-negative integer") |
| 199 |
if '_fields_' in typedict: |
| 200 |
if not hasattr(typedict.get('_anonymous_', []), '__iter__'): |
| 201 |
raise TypeError("Anonymous field must be iterable") |
| 202 |
for item in typedict.get('_anonymous_', []): |
| 203 |
if item not in dict(typedict['_fields_']): |
| 204 |
raise AttributeError("Anonymous field not found") |
| 205 |
names_and_fields( |
| 206 |
res, |
| 207 |
typedict['_fields_'], cls[0], |
| 208 |
typedict.get('_anonymous_', None)) |
| 209 |
return res |
| 210 |
|
| 211 |
def _make_final(self): |
| 212 |
if self is StructOrUnion: |
| 213 |
return |
| 214 |
if '_fields_' not in self.__dict__: |
| 215 |
self._fields_ = [] |
| 216 |
|
| 217 |
__setattr__ = struct_setattr |
| 218 |
|
| 219 |
def _is_abstract(self): |
| 220 |
return False |
| 221 |
|
| 222 |
def from_address(self, address): |
| 223 |
instance = StructOrUnion.__new__(self) |
| 224 |
if isinstance(address, _rawffi.StructureInstance): |
| 225 |
address = address.buffer |
| 226 |
|
| 227 |
address = address & (sys.maxsize * 2 + 1) |
| 228 |
instance.__dict__['_buffer'] = self._ffistruct_.fromaddress(address) |
| 229 |
return instance |
| 230 |
|
| 231 |
def _sizeofinstances(self): |
| 232 |
if not hasattr(self, '_ffistruct_'): |
| 233 |
return 0 |
| 234 |
return self._ffistruct_.size |
| 235 |
|
| 236 |
def _alignmentofinstances(self): |
| 237 |
return self._ffistruct_.alignment |
| 238 |
|
| 239 |
def from_param(self, value): |
| 240 |
if isinstance(value, tuple): |
| 241 |
try: |
| 242 |
value = self(*value) |
| 243 |
except Exception as e: |
| 244 |
|
| 245 |
raise RuntimeError("(%s) %s: %s" % (self.__name__, type(e).__name__, e)) |
| 246 |
return _CDataMeta.from_param(self, value) |
| 247 |
|
| 248 |
def _CData_output(self, resarray, base=None, index=-1): |
| 249 |
res = StructOrUnion.__new__(self) |
| 250 |
ffistruct = self._ffistruct_.fromaddress(resarray.buffer) |
| 251 |
res.__dict__['_buffer'] = ffistruct |
| 252 |
res.__dict__['_base'] = base |
| 253 |
res.__dict__['_index'] = index |
| 254 |
return res |
| 255 |
|
| 256 |
def _CData_retval(self, resbuffer): |
| 257 |
res = StructOrUnion.__new__(self) |
| 258 |
res.__dict__['_buffer'] = resbuffer |
| 259 |
res.__dict__['_base'] = None |
| 260 |
res.__dict__['_index'] = -1 |
| 261 |
return res |
| 262 |
|
| 263 |
def _getformat(self): |
| 264 |
if self._is_union or hasattr(self, '_pack_'): |
| 265 |
return "B" |
| 266 |
if hasattr(self, '_swappedbytes_'): |
| 267 |
bo = swappedorder[sys.byteorder] |
| 268 |
else: |
| 269 |
bo = byteorder[sys.byteorder] |
| 270 |
flds = [] |
| 271 |
cum_size = 0 |
| 272 |
for name, obj in self._fields_: |
| 273 |
padding = self._ffistruct_.fieldoffset(name) - cum_size |
| 274 |
if padding: |
| 275 |
flds.append('%dx' % padding) |
| 276 |
flds.append(obj._getformat()) |
| 277 |
flds.append(':') |
| 278 |
flds.append(name) |
| 279 |
flds.append(':') |
| 280 |
cum_size += self._ffistruct_.fieldsize(name) |
| 281 |
return 'T{' + ''.join(flds) + '}' |
| 282 |
|
| 283 |
def _has_pointer(self): |
| 284 |
for fieldname, typ in self._fields_: |
| 285 |
if typ._is_pointer_like() or typ._has_pointer(): |
| 286 |
return True |
| 287 |
return False |
| 288 |
|
| 289 |
class StructOrUnion(_CData, metaclass=StructOrUnionMeta): |
| 290 |
|
| 291 |
def __new__(cls, *args, **kwds): |
| 292 |
from _ctypes import union |
| 293 |
if ('_abstract_' in cls.__dict__ or cls is Structure |
| 294 |
or cls is union.Union): |
| 295 |
raise TypeError("abstract class") |
| 296 |
if hasattr(cls, '_swappedbytes_'): |
| 297 |
names_and_fields(cls, cls._fields_, _CData, cls.__dict__.get('_anonymous_', None)) |
| 298 |
self = super(_CData, cls).__new__(cls) |
| 299 |
if hasattr(cls, '_ffistruct_'): |
| 300 |
self.__dict__['_buffer'] = self._ffistruct_(autofree=True) |
| 301 |
return self |
| 302 |
|
| 303 |
def __init__(self, *args, **kwds): |
| 304 |
type(self)._make_final() |
| 305 |
if len(args) > len(self._names_): |
| 306 |
raise TypeError("too many initializers") |
| 307 |
for name, arg in zip(self._names_, args): |
| 308 |
if name in kwds: |
| 309 |
raise TypeError("duplicate value for argument %r" % ( |
| 310 |
name,)) |
| 311 |
self.__setattr__(name, arg) |
| 312 |
for name, arg in kwds.items(): |
| 313 |
self.__setattr__(name, arg) |
| 314 |
_init_no_arg_ = __init__ |
| 315 |
|
| 316 |
def _subarray(self, fieldtype, name): |
| 317 |
"""Return a _rawffi array of length 1 whose address is the same as |
| 318 |
the address of the field 'name' of self.""" |
| 319 |
address = self._buffer.fieldaddress(name) |
| 320 |
A = _rawffi.Array(fieldtype._ffishape_) |
| 321 |
return A.fromaddress(address, 1) |
| 322 |
|
| 323 |
def _get_buffer_for_param(self): |
| 324 |
return self |
| 325 |
|
| 326 |
def _get_buffer_value(self): |
| 327 |
return self._buffer.buffer |
| 328 |
|
| 329 |
def _copy_to(self, addr): |
| 330 |
from ctypes import memmove |
| 331 |
origin = self._get_buffer_value() |
| 332 |
memmove(addr, origin, self._fficompositesize_) |
| 333 |
|
| 334 |
def _to_ffi_param(self): |
| 335 |
|
| 336 |
return self._buffer |
| 337 |
|
| 338 |
def __buffer__(self, flags): |
| 339 |
fmt = type(self)._getformat() |
| 340 |
itemsize = type(self)._sizeofinstances() |
| 341 |
return __pypy__.newmemoryview(memoryview(self._buffer), itemsize, fmt, ()) |
| 342 |
|
| 343 |
class StructureMeta(StructOrUnionMeta): |
| 344 |
_is_union = False |
| 345 |
|
| 346 |
|
| 347 |
class Structure(StructOrUnion, metaclass=StructureMeta): |
| 348 |
pass |