xref: /linux/tools/include/vdso/unaligned.h (revision 5e85b36768b7bba53a55b1c9a1b1cdcab3684634)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __VDSO_UNALIGNED_H
3 #define __VDSO_UNALIGNED_H
4 
5 #include <linux/compiler_types.h>
6 
7 #ifdef CONFIG_VDSO_UNALIGNED_PACKED
8 
9 #define __get_unaligned_t(type, ptr) ({							\
10 	const struct { type x; } __packed * __get_pptr = (typeof(__get_pptr))(ptr);	\
11 	__get_pptr->x;									\
12 })
13 
14 #define __put_unaligned_t(type, val, ptr) do {						\
15 	struct { type x; } __packed * __put_pptr = (typeof(__put_pptr))(ptr);		\
16 	__put_pptr->x = (val);								\
17 } while (0)
18 
19 #else /* !CONFIG_VDSO_UNALIGNED_PACKED */
20 
21 /**
22  * __get_unaligned_t - read an unaligned value from memory.
23  * @type:	the type to load from the pointer.
24  * @ptr:	the pointer to load from.
25  *
26  * Use memcpy to affect an unaligned type sized load avoiding undefined behavior
27  * from approaches like type punning that require -fno-strict-aliasing in order
28  * to be correct. As type may be const, use __unqual_scalar_typeof to map to a
29  * non-const type - you can't memcpy into a const type. The
30  * __get_unaligned_ctrl_type gives __unqual_scalar_typeof its required
31  * expression rather than type, a pointer is used to avoid warnings about mixing
32  * the use of 0 and NULL. The void* cast silences ubsan warnings.
33  */
34 #define __get_unaligned_t(type, ptr) ({					\
35 	type *__get_unaligned_ctrl_type __always_unused = NULL;		\
36 	__unqual_scalar_typeof(*__get_unaligned_ctrl_type) __get_unaligned_val; \
37 	__builtin_memcpy(&__get_unaligned_val, (void *)(ptr),		\
38 			 sizeof(__get_unaligned_val));			\
39 	__get_unaligned_val;						\
40 })
41 
42 /**
43  * __put_unaligned_t - write an unaligned value to memory.
44  * @type:	the type of the value to store.
45  * @val:	the value to store.
46  * @ptr:	the pointer to store to.
47  *
48  * Use memcpy to affect an unaligned type sized store avoiding undefined
49  * behavior from approaches like type punning that require -fno-strict-aliasing
50  * in order to be correct. The void* cast silences ubsan warnings.
51  */
52 #define __put_unaligned_t(type, val, ptr) do {				\
53 	type __put_unaligned_val = (val);				\
54 	__builtin_memcpy((void *)(ptr), &__put_unaligned_val,		\
55 			 sizeof(__put_unaligned_val));			\
56 } while (0)
57 
58 #endif /* CONFIG_VDSO_UNALIGNED_PACKED */
59 
60 #endif /* __VDSO_UNALIGNED_H */
61