Skip to content

Instantly share code, notes, and snippets.

@nonakap
Created October 9, 2024 01:06
Show Gist options
  • Save nonakap/225dc80d41e6664389c2e357be772403 to your computer and use it in GitHub Desktop.
Save nonakap/225dc80d41e6664389c2e357be772403 to your computer and use it in GitHub Desktop.
NetBSDのcontainer_of()マクロでvoid *を特別扱いする
#if defined(__COVERITY__) || defined(__LGTM_BOT__)
#define __validate_container_of(PTR, TYPE, FIELD) 0
#define __validate_const_container_of(PTR, TYPE, FIELD) 0
#else
#define __validate_container_of(PTR, TYPE, FIELD) \
(0 * sizeof(__builtin_choose_expr( \
__builtin_types_compatible_p(typeof(PTR), void *), \
(const char *)(PTR), (PTR)) - \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(PTR), \
void *), (const char *)&(((TYPE *)(((char *)(PTR)) - \
offsetof(TYPE, FIELD)))->FIELD), \
&(((TYPE *)(((char *)(PTR)) - offsetof(TYPE, FIELD)))->FIELD))))
#define __validate_const_container_of(PTR, TYPE, FIELD) \
(0 * sizeof(__builtin_choose_expr( \
__builtin_types_compatible_p(typeof(PTR), void *), \
(const char *)(PTR), (PTR)) - \
__builtin_choose_expr(__builtin_types_compatible_p(typeof(PTR), \
void *), (const char *)&(((const TYPE *)(((const char *)(PTR)) - \
offsetof(TYPE, FIELD)))->FIELD), \
&(((const TYPE *)(((const char *)(PTR)) - offsetof(TYPE, FIELD)))->FIELD))))
#endif
#define container_of(PTR, TYPE, FIELD) \
((TYPE *)(((char *)(PTR)) - offsetof(TYPE, FIELD)) \
+ __validate_container_of(PTR, TYPE, FIELD))
#define const_container_of(PTR, TYPE, FIELD) \
((const TYPE *)(((const char *)(PTR)) - offsetof(TYPE, FIELD)) \
+ __validate_const_container_of(PTR, TYPE, FIELD))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment