Re: [PATCH] overflow: Introduce struct_offset() to get offset of member

Steven Rostedt
2025-11-28T01:43:52Z

On Wed, 26 Nov 2025 23:58:01 -0800
Kees Cook <kees@kernel.org> wrote:

> > +/**
> > + * struct_offset() - Calculate the offset of a member within a struct
> > + * @p: Pointer to the struct
> > + * @member: Name of the member to get the offset of
> > + *
> > + * Calculates the offset of a particular @member of the structure pointed
> > + * to by @p.
> > + *
> > + * Return: number of bytes to the location of @member.
> > + */
> > +#define struct_offset(p, member) (offsetof(typeof(*(p)), member))
>
> I wonder if the kerndoc for this and offsetof() should reference each
> other? "For a type instead of a pointer, use offsetof()" etc...

I know I pushed this to my for-next branch already, but it's the top
patch. Looking at my code, I actually have a lot of places that use the
offsetof() for a structure variable and not a pointer to a structure.

Thus, I wonder if it is better to have this as:

#define struct_offset(s, member) (offsetof(typeof(s), member))

And then for pointers we have:

size = struct_offset(*entry, id) + cnt;

If you forget the '*' it will error with a complaint that entry is not
a structure type. Then I could make changes like this:

diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index 1244d2c5c384..55f1bdab4ffa 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -587,19 +587,19 @@ int ring_buffer_print_page_header(struct trace_buffer *buffer, struct trace_seq

trace_seq_printf(s, "\tfield: local_t commit;\t"
"offset:%u;\tsize:%u;\tsigned:%u;\n",
- (unsigned int)offsetof(typeof(field), commit),
+ (unsigned int)struct_offset(field, commit),
(unsigned int)sizeof(field.commit),
(unsigned int)is_signed_type(long));

trace_seq_printf(s, "\tfield: int overwrite;\t"
"offset:%u;\tsize:%u;\tsigned:%u;\n",
- (unsigned int)offsetof(typeof(field), commit),
+ (unsigned int)struct_offset(field, commit),
1,
(unsigned int)is_signed_type(long));

trace_seq_printf(s, "\tfield: char data;\t"
"offset:%u;\tsize:%u;\tsigned:%u;\n",
- (unsigned int)offsetof(typeof(field), data),
+ (unsigned int)struct_offset(field, data),
(unsigned int)buffer->subbuf_size,
(unsigned int)is_signed_type(char));

I would have a lot more places I can make this update then if
struct_offset() took a pointer instead of the struct itself. As adding
a '*' isn't ugly I think I like this way better.

What are your thoughts?

-- Steve