RE: Non-packed structures in IP headers
flat view
From: David Laight <hidden>
Date: 2021-10-02 15:55:02
Also in:
netdev
From: Florian Weimer
Sent: 01 October 2021 21:10 * Carles Cufi:quoted
I was looking through the structures for IPv{4,6} packet headers and noticed that several of those that seem to be used to parse a packet directly from the wire are not declared as packed. This surprised me because, although I did find that provisions are made so that the alignment of the structure, it is still technically possible for the compiler to inject padding bytes inside those structures, since AFAIK the C standard makes no guarantees about padding unless it's instructed to pack the structure.The C standards do not make such guarantees, but the platform ABI standards describe struct layout and ensure that there is no padding. Linux relies on that not just for networking, but also for the userspace ABI, support for separately compiled kernel modules, and in other places.
In particular structures are used to map hardware register blocks.
Sometimes there are alignment concerns in the way these structs are used, but I believe the kernel generally controls placement of the data that is being worked on, so that does not matter, either. Therefore, I do not believe this is an actual problem.
And adding __packed forces the compiler to do byte accesses (with shifts) on cpu that don't support misaligned memory accesses. So it really is wrong to specify __packed unless the structure can be unaligned in memory, or has a 'broken' definition that has fields that aren't 'naturally aligned'. In the latter case it is enough to mark the field that requires the padding before it removed as (IIRC) __aligned(1). The compiler will then remove the padding but still assume the field is partially aligned - so my do two 32bit access instead of 8 8bit ones). David - Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)