From 144546543c37fe6228b8d568fbd3ab341fe0b76b Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 11 Mar 2021 13:08:45 +0200 Subject: [PATCH] cgen: add the __offsetof_ptr C macro --- vlib/v/gen/c/cheaders.v | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/c/cheaders.v b/vlib/v/gen/c/cheaders.v index 8d51ada843..c9fec54afe 100644 --- a/vlib/v/gen/c/cheaders.v +++ b/vlib/v/gen/c/cheaders.v @@ -103,9 +103,14 @@ static inline void __sort_ptr(uintptr_t a[], bool b[], int l) #endif #endif +// Use __offsetof_ptr instead of __offset_of, when you *do* have a valid pointer, to avoid UB: +#ifndef __offsetof_ptr + #define __offsetof_ptr(ptr,PTYPE,FIELDNAME) ((size_t)((byte *)&((PTYPE *)ptr)->FIELDNAME - (byte *)ptr)) +#endif + // for __offset_of #ifndef __offsetof - #define __offsetof(s,memb) ((size_t)((char *)&((s *)0)->memb - (char *)0)) + #define __offsetof(PTYPE,FIELDNAME) ((size_t)((char *)&((PTYPE *)0)->FIELDNAME - (char *)0)) #endif #define OPTION_CAST(x) (x)