Armin Rigo avatar Armin Rigo committed 369b47a

In-progress: verify fully-declared structs.

Comments (0)

Files changed (10)

     return PyInt_FromLong(align);
 }
 
-static PyObject *b_sizeof_type(PyObject *self, PyObject *arg)
+static PyObject *b_sizeof(PyObject *self, PyObject *arg)
 {
-    if (!CTypeDescr_Check(arg)) {
-        PyErr_SetString(PyExc_TypeError, "expected a 'ctype' object");
+    Py_ssize_t size;
+
+    if (CData_Check(arg)) {
+        CDataObject *cd = (CDataObject *)arg;
+
+        if (cd->c_type->ct_flags & CT_ARRAY)
+            size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
+        else
+            size = cd->c_type->ct_size;
+    }
+    else if (CTypeDescr_Check(arg)) {
+        if (((CTypeDescrObject *)arg)->ct_size < 0) {
+            PyErr_Format(PyExc_ValueError, "ctype '%s' is of unknown size",
+                         ((CTypeDescrObject *)arg)->ct_name);
+            return NULL;
+        }
+        size = ((CTypeDescrObject *)arg)->ct_size;
+    }
+    else {
+        PyErr_SetString(PyExc_TypeError,
+                        "expected a 'cdata' or 'ctype' object");
         return NULL;
     }
-    if (((CTypeDescrObject *)arg)->ct_size < 0) {
-        PyErr_Format(PyExc_ValueError, "ctype '%s' is of unknown size",
-                     ((CTypeDescrObject *)arg)->ct_name);
-        return NULL;
-    }
-    return PyInt_FromSsize_t(((CTypeDescrObject *)arg)->ct_size);
-}
-
-static PyObject *b_sizeof_instance(PyObject *self, PyObject *arg)
-{
-    CDataObject *cd;
-    Py_ssize_t size;
-
-    if (!CData_Check(arg)) {
-        PyErr_SetString(PyExc_TypeError, "expected a 'cdata' object");
-        return NULL;
-    }
-    cd = (CDataObject *)arg;
-
-    if (cd->c_type->ct_flags & CT_ARRAY)
-        size = get_array_length(cd) * cd->c_type->ct_itemdescr->ct_size;
-    else
-        size = cd->c_type->ct_size;
-
     return PyInt_FromSsize_t(size);
 }
 
-static PyObject *b_typeof_instance(PyObject *self, PyObject *arg)
+static PyObject *b_typeof(PyObject *self, PyObject *arg)
 {
     PyObject *res;
 
     {"cast", b_cast, METH_VARARGS},
     {"callback", b_callback, METH_VARARGS},
     {"alignof", b_alignof, METH_O},
-    {"sizeof_type", b_sizeof_type, METH_O},
-    {"sizeof_instance", b_sizeof_instance, METH_O},
-    {"typeof_instance", b_typeof_instance, METH_O},
+    {"sizeof", b_sizeof, METH_O},
+    {"typeof", b_typeof, METH_O},
     {"offsetof", b_offsetof, METH_VARARGS},
     {"string", b_string, METH_VARARGS},
     {"get_errno", b_get_errno, METH_NOARGS},
                 self._parsed_types[cdecl] = btype
                 return btype
         else:
-            return self._backend.typeof_instance(cdecl)
+            return self._backend.typeof(cdecl)
 
     def sizeof(self, cdecl):
         """Return the size in bytes of the argument.  It can be a
         """
         if isinstance(cdecl, (str, unicode)):
             BType = self.typeof(cdecl)
-            return self._backend.sizeof_type(BType)
+            return self._backend.sizeof(BType)
         else:
-            return self._backend.sizeof_instance(cdecl)
+            return self._backend.sizeof(cdecl)
 
     def alignof(self, cdecl):
         """Return the natural alignment size in bytes of the C type
         """ Verify that the current ffi signatures compile on this machine
         """
         from .verifier import Verifier
-        return Verifier().verify(self, preamble, **kwargs)
+        return Verifier(self).verify(preamble, **kwargs)
 
 def _make_ffi_library(ffi, libname):
     name = libname

cffi/backend_ctypes.py

         p = ctypes.cast(bptr._as_ctype_ptr, ctypes.POINTER(ctypes.c_char))
         return ''.join([p[i] for i in range(length)])
 
-    def sizeof_type(self, BType):
-        assert issubclass(BType, CTypesData)
-        return BType._get_size()
-
-    def sizeof_instance(self, cdata):
-        assert isinstance(cdata, CTypesData)
-        return cdata._get_size_of_instance()
+    def sizeof(self, cdata_or_BType):
+        if isinstance(cdata_or_BType, CTypesData):
+            return cdata_or_BType._get_size_of_instance()
+        else:
+            assert issubclass(cdata_or_BType, CTypesData)
+            return cdata_or_BType._get_size()
 
     def alignof(self, BType):
         assert issubclass(BType, CTypesData)
     def callback(self, BType, source):
         return BType(source)
 
-    typeof_instance = type
+    typeof = type
 
 
 class CTypesLibrary(object):
                 nextenumvalue += 1
             enumvalues = tuple(enumvalues) 
             tp = model.EnumType(name, enumerators, enumvalues)
-            self._declarations[key] = tp
+            self._declare(key, tp)
         else:   # opaque enum
             enumerators = ()
             enumvalues = ()
         return ffi._backend.new_struct_type(self.name)
 
     def verifier_declare_struct(self, verifier, name):
-        if self.fldnames is None:
-            assert not self.partial
-            return
+        if self.partial:
+            self.verifier_decl_partial(verifier, name)
+        else:
+            self.verifier_decl_notpartial(verifier, name)
+
+    def verifier_decl_notpartial(self, verifier, name):
+        if self.fldnames is None:    # not partial, but fully opaque:
+            return                   # cannot really test even for existence
+        struct = verifier.ffi._get_cached_btype(self)
+        verifier.write('__sameconstant__(sizeof(struct %s), %d)' % (
+            name, verifier.ffi.sizeof(struct)))
+
+    def verifier_decl_partial(self, verifier, name):
+        assert self.fldnames is not None
         verifier.write('{')
         verifier.write('struct __aligncheck__ { char x; struct %s y; };' %
                        self.name)
 
 class Verifier(object):
 
+    def __init__(self, ffi):
+        self.ffi = ffi
+
     def write(self, what):
         print >> self.f, '  ' + what
 
             print >> self.f, '  printf("%s\\n", %s);' % (
                 what, ', '.join(args))
 
-    def verify(self, ffi, preamble, **kwargs):
+    def verify(self, preamble, **kwargs):
         tst_file_base = ffiplatform._get_test_file_base()
         self.has_printf = False
         with open(tst_file_base + '.c', 'w') as f:
-            f.write('#include <stdio.h>\n')
-            f.write('#include <stdint.h>\n')
-            f.write('#include <stddef.h>\n')
-            f.write('#include <unistd.h>\n')
+            f.write('#include <stdio.h>\n'
+                    '#include <stdint.h>\n'
+                    '#include <stddef.h>\n'
+                    '#include <unistd.h>\n'
+                    '\n'
+                    '#define __sameconstant__(x, y) \\\n'
+                    '  { int result[1-2*((x)-(y))*((x)-(y))]; }\n'
+                    '\n'
+                    )
             f.write(preamble + "\n\n")
             f.write('int main() {\n')
             self.f = f
-            for name, tp in ffi._parser._declarations.iteritems():
+            for name, tp in self.ffi._parser._declarations.iteritems():
                 kind, realname = name.split(' ', 1)
                 method = getattr(tp, 'verifier_declare_' + kind)
                 method(self, realname)
             del self.f
             f.write('  return 0;\n')
             f.write('}\n')
-        err = os.system('gcc -Werror -c %s.c -o %s.o' %
+        err = os.system('gcc -Werror -S %s.c -o %s.s' %
                         (tst_file_base, tst_file_base))
         if err:
             raise ffiplatform.VerificationError(

testing/backend_tests.py

 SIZE_OF_LONG  = ctypes.sizeof(ctypes.c_long)
 SIZE_OF_SHORT = ctypes.sizeof(ctypes.c_short)
 SIZE_OF_PTR   = ctypes.sizeof(ctypes.c_void_p)
-SIZE_OF_WCHAR = ctypes.sizeof(ctypes.c_wchar)
+#SIZE_OF_WCHAR = ctypes.sizeof(ctypes.c_wchar)
 
 
 class BackendTests:
         self._test_int_type(ffi, 'ptrdiff_t', SIZE_OF_PTR, False)
         self._test_int_type(ffi, 'size_t', SIZE_OF_PTR, True)
         self._test_int_type(ffi, 'ssize_t', SIZE_OF_PTR, False)
-        self._test_int_type(ffi, 'wchar_t', SIZE_OF_WCHAR, True)
+        #self._test_int_type(ffi, 'wchar_t', SIZE_OF_WCHAR, True)
 
     def _test_int_type(self, ffi, c_decl, size, unsigned):
         if unsigned:

testing/test_cdata.py

     def nonstandard_integer_types(self):
         return {}
 
-    def sizeof_type(self, name):
+    def sizeof(self, name):
         return 1
 
     def load_library(self, path):

testing/test_parsing.py

     def nonstandard_integer_types(self):
         return {}
 
-    def sizeof_type(self, name):
+    def sizeof(self, name):
         return 1
 
     def load_library(self, name):

testing/test_verify.py

                                "typedef %s foo_t;" % real)
 
 
+def test_ffi_full_struct():
+    ffi = FFI()
+    ffi.cdef("struct foo_s { char x; int y; long *z; };")
+    ffi.verify("struct foo_s { char x; int y; long *z; };")
+    #
+    for real in [
+        "struct foo_s { char x; int y; int *z; };",
+        "struct foo_s { char x; long *z; int y; };",
+        "struct foo_s { int y; long *z; };",
+        "struct foo_s { char x; int y; long *z; char extra; };",
+        ]:
+        py.test.raises(VerificationError, ffi.verify, real)
+    #
+    # a corner case that we cannot really detect, but where it has no
+    # bad consequences: the size is the same, but there is an extra field
+    # that replaces what is just padding in our declaration above
+    ffi.verify("struct foo_s { char x, extra; int y; long *z; };")
+
+
 def test_ffi_nonfull_struct():
     py.test.skip("XXX")
     ffi = FFI()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.