haskell / win32

Haskell support for the Win32 API
http://hackage.haskell.org/package/Win32
Other
97 stars 63 forks source link

alignment implementations are wrong for most Storable instances in Win32 #66

Closed RyanGlScott closed 7 years ago

RyanGlScott commented 7 years ago

There are several Storable instances in Win32, but most of them implement alignment like so (example taken from System.Win32.Mem):

instance Storable MEMORY_BASIC_INFORMATION where
    sizeOf _ = #size MEMORY_BASIC_INFORMATION
    alignment = sizeOf

Defining alignment = sizeOf is usually wrong, and in the case of MEMORY_BASIC_INFORMATION, it's definitely wrong, as this C program shows:

#include <windows.h>
#include <inttypes.h>
#include <stdio.h>

int main(int argc, char **argv) {
    printf("Size: %" PRIu64 ", alignment: %" PRIu64 "\n",
           sizeof(MEMORY_BASIC_INFORMATION),
           __alignof__(MEMORY_BASIC_INFORMATION));

    return 0;
}
$ ./foo.exe
Size: 48, alignment: 8

We should define alignment properly using hsc2hs's #alignment macro, introduced in GHC 8.0. Or, on older versions of GHC, use this hsc2hs macro:

#if __GLASGOW_HASKELL__ < 711
#let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t (y__); }, y__)
#endif
Mistuke commented 7 years ago

Wtf!? I hadn't noticed that before. But yeah those are clearly wrong... I'll correct them before the next release.