From bd95c397303dcf56b2799645330f1d4db7c2a879 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
```

(cherry picked from commit 05c4fafbc1693164d5f06ed062fc73bbf3f78deb)
---
 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 81e7c354c9c..e652dd4e715 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