From 83341bbc3f00eea6797d40e4cc0a446b23d275af Mon Sep 17 00:00:00 2001
From: Cheng Shao <terrorjack@type.dance>
Date: Mon, 27 May 2024 18:27:56 +0000
Subject: [PATCH] rts: use __builtin_offsetof to implement STG_FIELD_OFFSET

This patch fixes the STG_FIELD_OFFSET macro definition by using
__builtin_offsetof, which is what gcc/clang uses to implement offsetof
in standard C. The previous definition that uses NULL pointer involves
subtle undefined behavior in C and thus reported by
UndefinedBehaviorSanitizer as well:

```
rts/Capability.h:243:58: runtime error: member access within null pointer of type 'Capability' (aka 'struct Capability_')
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior rts/Capability.h:243:58
```
---
 rts/include/Stg.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/rts/include/Stg.h b/rts/include/Stg.h
index 4d1a5f71be8..edce9504681 100644
--- a/rts/include/Stg.h
+++ b/rts/include/Stg.h
@@ -108,7 +108,7 @@
 
 /* Compute offsets of struct fields
  */
-#define STG_FIELD_OFFSET(s_type, field) ((StgWord)&(((s_type*)0)->field))
+#define STG_FIELD_OFFSET(s_type, field) __builtin_offsetof(s_type, field)
 
 /*
  * 'Portable' inlining:
-- 
GitLab