Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions src/cffi/cparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,7 @@ def _get_type_pointer(self, type, quals, declname=None):
return model.PointerType(type, quals)

def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
typedef_example=None):
typedef_example=None, nested_in=None):
# first, dereference typedefs, if we have it already parsed, we're good
if (isinstance(typenode, pycparser.c_ast.TypeDecl) and
isinstance(typenode.type, pycparser.c_ast.IdentifierType) and
Expand All @@ -624,9 +624,12 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
length = f'_cffi_array_len({typedef_example})'
typedef_example = "*" + typedef_example
#
if nested_in is not None:
nested_in = (nested_in[0], f'{nested_in[1]}[0]')
tp, quals = self._get_type_and_quals(typenode.type,
partial_length_ok=partial_length_ok,
typedef_example=typedef_example)
typedef_example=typedef_example,
nested_in=nested_in)
return model.ArrayType(tp, length), quals
#
if isinstance(typenode, pycparser.c_ast.PtrDecl):
Expand Down Expand Up @@ -674,12 +677,18 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
#
if isinstance(type, pycparser.c_ast.Struct):
# 'struct foobar'
tp = self._get_struct_union_enum_type('struct', type, name)
tp = self._get_struct_union_enum_type(
'struct', type, name,
nested=(nested_in is not None),
nested_in=nested_in)
return tp, quals
#
if isinstance(type, pycparser.c_ast.Union):
# 'union foobar'
tp = self._get_struct_union_enum_type('union', type, name)
tp = self._get_struct_union_enum_type(
'union', type, name,
nested=(nested_in is not None),
nested_in=nested_in)
return tp, quals
#
if isinstance(type, pycparser.c_ast.Enum):
Expand All @@ -694,10 +703,12 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
# nested anonymous structs or unions end up here
if isinstance(typenode, pycparser.c_ast.Struct):
return self._get_struct_union_enum_type('struct', typenode, name,
nested=True), 0
nested=True,
nested_in=nested_in), 0
if isinstance(typenode, pycparser.c_ast.Union):
return self._get_struct_union_enum_type('union', typenode, name,
nested=True), 0
nested=True,
nested_in=nested_in), 0
#
raise FFIError(":%d: bad or unsupported type declaration" %
typenode.coord.line)
Expand Down Expand Up @@ -745,7 +756,8 @@ def _as_func_arg(self, type, quals):
else:
return type

def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
def _get_struct_union_enum_type(self, kind, type, name=None, nested=False,
nested_in=None):
# First, a level of caching on the exact 'type' node of the AST.
# This is obscure, but needed because pycparser "unrolls" declarations
# such as "typedef struct { } foo_t, *foo_p" and we end up with
Expand Down Expand Up @@ -838,6 +850,8 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
#
if tp.fldnames is not None:
raise CDefError(f"duplicate declaration of struct {name}")
if nested_in is not None and not tp.has_c_name() and tp.enclosing is None:
tp.enclosing = nested_in
fldnames = []
fldtypes = []
fldbitsize = []
Expand All @@ -856,10 +870,14 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
bitsize = self._parse_constant(decl.bitsize)
self._partial_length = False
type, fqual = self._get_type_and_quals(decl.type,
partial_length_ok=True)
partial_length_ok=True,
nested_in=(tp, decl.name or ''))
if self._partial_length:
self._make_partial(tp, nested)
if isinstance(type, model.StructType) and type.partial:
item = type
while isinstance(item, model.ArrayType):
item = item.item
if isinstance(item, model.StructOrUnion) and item.partial:
self._make_partial(tp, nested)
fldnames.append(decl.name or '')
fldtypes.append(type)
Expand Down
1 change: 1 addition & 0 deletions src/cffi/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ class StructOrUnion(StructOrUnionOrEnum):
completed = 0
partial = False
packed = 0
enclosing = None

def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None):
self.name = name
Expand Down
50 changes: 43 additions & 7 deletions src/cffi/recompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,12 +816,33 @@ def _generate_cpy_function_ctx(self, tp, name):
# ----------
# named structs or unions

def _struct_access_path(self, tp):
parts = []
cur = tp
while not cur.has_c_name():
enclosing = cur.enclosing
if enclosing is None:
return None, None
parent_tp, field_expr = enclosing
if field_expr:
parts.append(field_expr)
cur = parent_tp
parts.reverse()
return cur.get_c_name(''), '.'.join(parts)

def _field_type(self, tp_struct, field_name, tp_field):
if isinstance(tp_field, model.ArrayType):
actual_length = tp_field.length
if actual_length == '...':
ptr_struct_name = tp_struct.get_c_name('*')
actual_length = f'_cffi_array_len((({ptr_struct_name})0)->{field_name})'
if tp_struct.has_c_name():
ptr_struct_name = tp_struct.get_c_name('*')
actual_length = f'_cffi_array_len((({ptr_struct_name})0)->{field_name})'
else:
root_cname, access_path = self._struct_access_path(tp_struct)
if root_cname is None:
raise VerificationError(
f"cannot generate '{tp_struct._get_c_name()}' in field {field_name!r}: unknown type name")
actual_length = f'_cffi_array_len((({root_cname} *)0)->{access_path}.{field_name})'
tp_item = self._field_type(tp_struct, f'{field_name}[0]',
tp_field.item)
tp_field = model.ArrayType(tp_item, actual_length)
Expand Down Expand Up @@ -897,6 +918,13 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
flags.append("_CFFI_F_EXTERNAL")
reason_for_not_expanding = "external"
flags = '|'.join(flags) or '0'
root_cname = access_path = None
if cname is None and tp.partial:
root_cname, access_path = self._struct_access_path(tp)
if root_cname is None:
raise NotImplementedError(f"internal inconsistency: {tp!r} is "
"partial but was not seen at "
"this point")
c_fields = []
if reason_for_not_expanding is None:
enumfields = list(self._enum_fields(tp))
Expand All @@ -909,17 +937,22 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
if fbitsize >= 0:
op = OP_BITFIELD
size = '%d /* bits */' % fbitsize
elif cname is None or (
elif (cname is None and root_cname is None) or (
isinstance(fldtype, model.ArrayType) and
fldtype.length is None):
size = '(size_t)-1'
elif root_cname is not None:
size = f'sizeof((({root_cname} *)0)->{access_path}.{fldname})'
else:
size = 'sizeof((({})0)->{})'.format(
tp.get_c_name('*') if named_ptr is None
else named_ptr.name,
fldname)
if cname is None or fbitsize >= 0:
if (cname is None and root_cname is None) or fbitsize >= 0:
offset = '(size_t)-1'
elif root_cname is not None:
offset = (f'offsetof({root_cname}, {access_path}.{fldname})'
f' - offsetof({root_cname}, {access_path})')
elif named_ptr is not None:
offset = f'(size_t)(((char *)&(({named_ptr.name})4096)->{fldname}) - (char *)4096)'
else:
Expand All @@ -930,12 +963,15 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
first_field_index = len(self._lsts["field"])
self._lsts["field"].extend(c_fields)
#
if cname is None: # unknown name, for _add_missing_struct_unions
if cname is None and root_cname is None: # unknown name, for _add_missing_struct_unions
size = '(size_t)-2'
align = -2
comment = "unnamed"
else:
if named_ptr is not None:
if root_cname is not None:
size = f'sizeof((({root_cname} *)0)->{access_path})'
align = '-1 /* unknown alignment */'
elif named_ptr is not None:
size = f'sizeof(*({named_ptr.name})0)'
align = '-1 /* unknown alignment */'
else:
Expand Down Expand Up @@ -968,7 +1004,7 @@ def _add_missing_struct_unions(self):
lst.sort(key=lambda tp_order: tp_order[1])
for tp, order in lst:
if tp not in self._seen_struct_unions:
if tp.partial:
if tp.partial and self._struct_access_path(tp)[0] is None:
raise NotImplementedError(f"internal inconsistency: {tp!r} is "
"partial but was not seen at "
"this point")
Expand Down
93 changes: 93 additions & 0 deletions testing/cffi1/test_recompiler_codegen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import io
import pytest

from cffi import FFI, recompiler
from testing.cffi0.test_parsing import FakeBackend


def _emit_c_source(cdef_src, module_name="testmod", preamble=""):
ffi = FFI(backend=FakeBackend())
ffi.cdef(cdef_src)
recomp = recompiler.Recompiler(ffi, module_name)
recomp.collect_type_table()
recomp.collect_step_tables()
buf = io.StringIO()
recomp.write_source_to_f(buf, preamble)
return buf.getvalue()


def test_nested_anonymous_partial_struct():
c_src = _emit_c_source("""
struct a {
struct {
...;
} d;
...;
};
""")
assert "sizeof(((struct a *)0)->d)" in c_src
assert "(size_t)-2" not in c_src


def test_nested_anonymous_partial_struct_with_fields():
c_src = _emit_c_source("""
struct a {
int b;
struct {
int c;
int arr[...];
...;
} d;
};
""")
assert "sizeof(((struct a *)0)->d)" in c_src
assert "offsetof(struct a, d.c) - offsetof(struct a, d)" in c_src
assert "sizeof(((struct a *)0)->d.c)" in c_src
assert "_cffi_array_len(((struct a *)0)->d.arr)" in c_src
assert "(size_t)-2" not in c_src


def test_deeply_nested_anonymous_partial_union_and_array():
c_src = _emit_c_source("""
typedef struct {
union {
struct {
int x;
...;
} inner[2];
...;
} mid;
} outer_t;
""")
assert "sizeof(((outer_t *)0)->mid)" in c_src
assert "sizeof(((outer_t *)0)->mid.inner[0])" in c_src
assert "offsetof(outer_t, mid.inner[0].x) - offsetof(outer_t, mid.inner[0])" in c_src


def test_unnamed_struct_containing_named_partial_struct():
c_src = _emit_c_source("""
struct a {
struct {
struct {
int x;
...;
} inner;
};
...;
};
""")
assert "sizeof(((struct a *)0)->inner)" in c_src
assert "offsetof(struct a, inner.x) - offsetof(struct a, inner)" in c_src
assert "(size_t)-2" not in c_src


def test_pointer_to_anonymous_partial_struct_still_rejected():
ffi = FFI(backend=FakeBackend())
with pytest.raises(NotImplementedError):
ffi.cdef("""
struct a {
struct {
...;
} *d;
};
""")