Bug 24193 – Incorrect size of unions with bit fields
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2023-10-23T03:01:15Z
Last change time
2023-10-30T04:59:55Z
Keywords
pull
Assigned to
No Owner
Creator
Tomoya Tanjo
Comments
Comment #0 by ttanjo — 2023-10-23T03:01:15Z
Here is a C code that declares a union with a struct and bitfields:
```c
#include <stdio.h>
typedef union {
struct {
int type:8;
int magic32;
} data;
int type:8;
} U;
int main(void)
{
printf("%ld\n", sizeof(U));
return 0;
}
```
```console
$ gcc --version
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gcc sample.c -o sample
$ ./sample
8
```
I expect that the size of the following equivalent D union `U` is same as the result of C (i.e., 8).
```d
union U {
struct S {
int type:8;
int magic32;
}
S data;
int type:8;
}
pragma(msg, U.sizeof);
void main() {}
```
I checked the size with the following command:
```console
$ dmd --version
DMD64 D Compiler v2.105.2
Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved written by Walter Bright
$ dmd -preview=bitfields sample.d
```
Expected result:
```console
$ dmd -preview=bitfields sample.d
8LU
```
Actual result:
```console
$ dmd -preview=bitfields sample.d
4LU
```
It causes problems when using C libraries in D including with importC.
Related: https://github.com/ldc-developers/ldc/issues/4477
Comment #1 by bugzilla — 2023-10-29T08:06:01Z
The following:
```
union U {
struct S {
int a,b;
}
S data;
int type:8;
}
pragma(msg, U.S.sizeof);
pragma(msg, U.sizeof);
```
prints:
8LU
4LU
Which is, of course, wrong. Curiously, if `int a,b;` is replaced with `long x;`, it prints:
8LU
8LU
Comment #2 by bugzilla — 2023-10-30T01:28:58Z
Not specific to C, it equally affects D.
Comment #3 by dlang-bot — 2023-10-30T01:36:04Z
@WalterBright created dlang/dmd pull request #15750 "fix Issue 24193 - Incorrect size of unions with bit fields" fixing this issue:
- fix Issue 24193 - Incorrect size of unions with bit fields
https://github.com/dlang/dmd/pull/15750
Comment #4 by dlang-bot — 2023-10-30T04:59:55Z
dlang/dmd pull request #15750 "fix Issue 24193 - Incorrect size of unions with bit fields" was merged into master:
- 0f96f556335ae162673f4c0e11be0365594ba7a8 by Walter Bright:
fix Issue 24193 - Incorrect size of unions with bit fields
https://github.com/dlang/dmd/pull/15750