unaligned.h 1.7 KB

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