[Haskell-beginners] problem with hsc2hs

Jose A. Ortega Ruiz jao at gnu.org
Mon Feb 1 06:48:02 EST 2010


I'm trying to writing a simple C binding for statfs(2). Simplifying,
writing an hsc file that contains the following snippet:

  #include <sys/vfs.h>

  data CStatfs
  foreign import ccall unsafe "sys/vfs.h statfs"
    c_statfs :: CString -> Ptr CStatfs -> IO CInt

  getFileSystemStats :: String -> IO CLong
  getFileSystemStats path =
    allocaBytes (#size struct statfs) $ \vfs ->
    useAsCString (pack path) $ \cpath -> do
      res <- c_statfs cpath vfs
      case res of
        -1 -> return 0
        _  -> do
          bsize <- (#peek struct statfs, f_bsize) vfs
          bcount <- (#peek struct statfs, f_blocks) vfs
          bfree <- (#peek struct statfs, f_bfree) vfs
          bavail <- (#peek struct statfs, f_bavail) vfs
          -- Just for demonstration: the original code creates a data structure
          return $ bsize + bcount + bavail + bfree

gives rise, when using hsc2hs, to this translation:

  getFileSystemStats path =
    allocaBytes ((84)) $ \vfs ->
    useAsCString (pack path) $ \cpath -> do
      res <- c_statfs cpath vfs
      case res of
        -1 -> return 0
        _  -> do
          bsize <- ((\hsc_ptr -> peekByteOff hsc_ptr 4)) vfs
          bcount <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) vfs
          bfree <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) vfs
          bavail <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) vfs
          return $ bsize + bcount + bavail + bfree

(where i have deleted LINE directives). The problem is that the size and
some of the offsets of the C struct statfs computed by hsc2c are wrong:
i'm in a 32bit linux system, and i've checked, using a C program, that
sizeof(struct statfs) is 64 (hsc2 is giving 84 -- although perhaps
Haskell needs additional space for housekeeping?), and that the offsets
of f_bfree and f_bavail are, respectively, 12 and 16 (not 16 and 24).
Also, i know that 12 and 16 are the right values because putting them by
hand gives me the correct statfs values.

(This is ghc 6.10.4 on a debian/sid system)

What am i doing wrong?


More information about the Beginners mailing list