second draft: add Bitfields to D
Timon Gehr
timon.gehr at gmx.ch
Sun May 5 09:08:27 UTC 2024
On 5/5/24 04:11, Walter Bright wrote:
> On 5/4/2024 4:01 PM, Timon Gehr wrote:
>> You are breaking the previous invariant that data in a struct lives at
>> relative addresses `data.offsetof..data.offsetof+data.sizeof`.
>
> The data.sizeof for a bitfield will always be the size of the memory
> object containing the field. The invariant is not broken.
I do not understand. I thought bitfields are supposed to match the
layout of the associated C compiler. Instead, you seem to now be arguing
that there should actually be stringent layout guarantees.
GCC 11.4.0, clang 14.0.0:
```c
#include <stdio.h>
struct __attribute__((packed)) S{
long long x:8;
};
int main(){
printf("%ld\n",sizeof(long long)); // 8
printf("%ld\n",sizeof(struct S)); // 1
}
```
It indeed seems `dmd 2.108.1` disagrees and gives `8` and `8`, but I
guess this is a mistake.
In any case, laying the struct out like this is in compliance with C
standards even without the additional attribute:
> An implementation may allocate any addressable storage unit large enough to hold a bit-
> field. If enough space remains, a bit-field that immediately follows another bit-field in a
> structure shall be packed into adjacent bits of the same unit. If insufficient space remains,
> whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is
> implementation-defined. The order of allocation of bit-fields within a unit (high-order to
> low-order or low-order to high-order) is i
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
Maybe at least redefine `.sizeof` to give the size of the underlying
storage unit for a bitfield. Otherwise, you exacerbate the risk of
memory corruption due to invalid assumptions about layout.
More information about the dip.development
mailing list