Skip to content

Commit 64f6a5d

Browse files
committed
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: Jason Gunthorpe <[email protected]> Suggested-by: Sakari Ailus <[email protected]> Reviewed-by: Matthew Wilcox (Oracle) <[email protected]> Reviewed-by: Jason Gunthorpe <[email protected]> Reviewed-by: Andy Shevchenko <[email protected]> Reviewed-by: Sakari Ailus <[email protected]> Acked-by: Rafael J. Wysocki <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
1 parent 50dc8d1 commit 64f6a5d

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

include/linux/container_of.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,17 @@
2222
"pointer type mismatch in container_of()"); \
2323
((type *)(__mptr - offsetof(type, member))); })
2424

25+
/**
26+
* container_of_const - cast a member of a structure out to the containing
27+
* structure and preserve the const-ness of the pointer
28+
* @ptr: the pointer to the member
29+
* @type: the type of the container struct this is embedded in.
30+
* @member: the name of the member within the struct.
31+
*/
32+
#define container_of_const(ptr, type, member) \
33+
_Generic(ptr, \
34+
const typeof(*(ptr)) *: ((const type *)container_of(ptr, type, member)),\
35+
default: ((type *)container_of(ptr, type, member)) \
36+
)
37+
2538
#endif /* _LINUX_CONTAINER_OF_H */

0 commit comments

Comments
 (0)