[Issue 22809] New: ImportC: druntime’s definition of __builtin_offsetof leads to dereference of invalid pointer.

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Feb 22 06:52:20 UTC 2022


https://issues.dlang.org/show_bug.cgi?id=22809

          Issue ID: 22809
           Summary: ImportC: druntime’s definition of __builtin_offsetof
                    leads to dereference of invalid pointer.
           Product: D
           Version: D2
          Hardware: x86
                OS: Mac OS X
            Status: NEW
          Keywords: ImportC
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: dave287091 at gmail.com

This C code, using the importc.h from druntime:

typedef unsigned long size_t;
#include "../druntime/import/importc.h"
struct Foo {
    int x;
};

int y = __builtin_offsetof(struct Foo, x);
_Static_assert(__builtin_offsetof(struct Foo, x)==0, "");


Expands to:
// off.i
typedef unsigned long size_t;

struct Foo {
    int x;
};

int y = ((size_t)((char *)&((struct Foo *)0)->x - (char *)0)); // Error:
dereference of invalid pointer `cast(Foo*)0LU`
Static_assert(((size_t)((char *)&((struct Foo *)0)->x - (char *)0))==0, “”);

Which fails to compile.


Additionally, that C code fails to compile with clang, which complains:

off.c:8:16: error: static_assert expression is not an integral constant
expression
_Static_assert(__builtin_offsetof(struct Foo, x)==0, "");
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./../druntime/import/importc.h:50:33: note: expanded from macro
      '__builtin_offsetof'
#define __builtin_offsetof(t,i) ((size_t)((char *)&((t *)0)->i - (char *)0))
                                ^
off.c:8:47: note: cannot access field of null pointer
_Static_assert(__builtin_offsetof(struct Foo, x)==0, "");
                                              ^
1 error generated.

--


More information about the Digitalmars-d-bugs mailing list