jmckaskill / luaffi

Standalone FFI library for calling C functions from lua. Compatible with the luajit FFI interface.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

__attribute__((packed)) should pack its members

daurnimator opened this issue · comments

With this declaration:

typedef union epoll_data
{
  void *ptr;
  int fd;
  uint32_t u32;
  uint64_t u64;
} epoll_data_t;
struct epoll_event
{
  uint32_t events;
  epoll_data_t data;
} __attribute__ ((__packed__));

Running this:

local __events = ffi.new ( "struct epoll_event[1]" )
__events[0].events = 8193
__events[0].data.fd = fd.fd
for i=0,2 do
    print("A",i,ffi.cast("int*",__events[0])[i])
end

Will print:

A   0   8193
A   1   0
A   2   5

As opposed to the expected

A   0   8193
A   1   5
A   2   0

Thanks for the report. The issue is that attribute((packed)) is not being applied correctly. From the GCC docs:

Specifying this attribute for struct and union types is equivalent to specifying the packed attribute on each of the structure or union members. Specifying the -fshort-enums flag on the line is equivalent to specifying the packed attribute on all enum definitions.

In this case the alignment is being updated for the outer struct, but it needs to update the members as well.

For the moment you can get around this by adding an attribute packed on the union member:

typedef union epoll_data
{
  void *ptr;
  int fd;
  uint32_t u32;
  uint64_t u64;
} epoll_data_t;
struct epoll_event
{
  uint32_t events;
  epoll_data_t data __attribute__((__packed__));
} __attribute__ ((__packed__));

So the state is that packed does not work? Or does it work when applying packed attribute inside the struct decl?