From 2514698596797eb2828d30bbf63ff475b9bfe238 Mon Sep 17 00:00:00 2001
From: Lev Kats <lev-katz@mail.ru>
Date: Fri, 12 Jul 2024 16:35:56 +0300
Subject: [PATCH] trivia: use __builtin* for offsetof macro

Changed default tarantool `offsetof` macro implementation so it don't
access members of null pointer in typeof that triggers UBsan.

Needed for #10143

NO_DOC=bugfix
NO_CHANGELOG=minor
NO_TEST=tested manually with fuzzer

(cherry picked from commit 27e948244c983b2c3fbf02d287216d0260d49d76)
---
 src/box/sql/sqlInt.h | 8 --------
 src/trivia/util.h    | 8 ++++++--
 2 files changed, 6 insertions(+), 10 deletions(-)

diff --git a/src/box/sql/sqlInt.h b/src/box/sql/sqlInt.h
index fc325e63b5..a5008fbc17 100644
--- a/src/box/sql/sqlInt.h
+++ b/src/box/sql/sqlInt.h
@@ -626,14 +626,6 @@ sql_bind_parameter_lindex(sql_stmt * pStmt, const char *zName,
 #define SQL_DEFAULT_COMPOUND_SELECT 30
 #endif
 
-/*
- * GCC does not define the offsetof() macro so we'll have to do it
- * ourselves.
- */
-#ifndef offsetof
-#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
-#endif
-
 /*
  * Macros to compute minimum and maximum of two numbers.
  */
diff --git a/src/trivia/util.h b/src/trivia/util.h
index 3c77be0e94..7b515a1570 100644
--- a/src/trivia/util.h
+++ b/src/trivia/util.h
@@ -245,8 +245,12 @@ alloc_failure(const char *filename, int line, size_t size)
  * including padding if any.
  */
 #ifndef offsetof
-#define offsetof(type, member) ((size_t) &((type *)0)->member)
-#endif
+#  if __has_builtin(__builtin_offsetof)
+#    define offsetof(type, member) __builtin_offsetof(type, member)
+#  else
+#    define offsetof(type, member) ((size_t)&((type *)0)->member)
+#  endif
+#endif /* offsetof */
 
 /**
  * This macro is used to retrieve an enclosing structure from a pointer to
-- 
GitLab