Commit 64f6a5d1 authored by Greg Kroah-Hartman's avatar Greg Kroah-Hartman

container_of: add container_of_const() that preserves const-ness of the pointer

container_of does not preserve the const-ness of a pointer that is
passed into it, which can cause C code that passes in a const pointer to
get a pointer back that is not const and then scribble all over the data
in it.  To prevent this, container_of_const() will preserve the const
status of the pointer passed into it using the newly available _Generic()
method.
Suggested-by: default avatarJason Gunthorpe <jgg@ziepe.ca>
Suggested-by: default avatarSakari Ailus <sakari.ailus@linux.intel.com>
Reviewed-by: default avatarMatthew Wilcox (Oracle) <willy@infradead.org>
Reviewed-by: default avatarJason Gunthorpe <jgg@nvidia.com>
Reviewed-by: default avatarAndy Shevchenko <andriy.shevchenko@linux.intel.com>
Reviewed-by: default avatarSakari Ailus <sakari.ailus@linux.intel.com>
Acked-by: default avatarRafael J. Wysocki <rafael@kernel.org>
Link: https://lore.kernel.org/r/20221205121206.166576-1-gregkh@linuxfoundation.orgSigned-off-by: default avatarGreg Kroah-Hartman <gregkh@linuxfoundation.org>
parent 50dc8d18
......@@ -22,4 +22,17 @@
"pointer type mismatch in container_of()"); \
((type *)(__mptr - offsetof(type, member))); })
/**
* container_of_const - cast a member of a structure out to the containing
* structure and preserve the const-ness of the pointer
* @ptr: the pointer to the member
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*/
#define container_of_const(ptr, type, member) \
_Generic(ptr, \
const typeof(*(ptr)) *: ((const type *)container_of(ptr, type, member)),\
default: ((type *)container_of(ptr, type, member)) \
)
#endif /* _LINUX_CONTAINER_OF_H */
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment