safemath.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * GRUB -- GRand Unified Bootloader
  3. * Copyright (C) 2020 Free Software Foundation, Inc.
  4. *
  5. * GRUB is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * GRUB is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * Arithmetic operations that protect against overflow.
  19. */
  20. #ifndef GRUB_SAFEMATH_H
  21. #define GRUB_SAFEMATH_H 1
  22. #include <grub/compiler.h>
  23. /* These appear in gcc 5.1 and clang 8.0. */
  24. #if GNUC_PREREQ(5, 1) || CLANG_PREREQ(8, 0)
  25. #define grub_add(a, b, res) __builtin_add_overflow(a, b, res)
  26. #define grub_sub(a, b, res) __builtin_sub_overflow(a, b, res)
  27. #define grub_mul(a, b, res) __builtin_mul_overflow(a, b, res)
  28. #define grub_cast(a, res) grub_add ((a), 0, (res))
  29. /*
  30. * It's caller's responsibility to check "align" does not equal 0 and
  31. * is power of 2.
  32. */
  33. #define ALIGN_UP_OVF(v, align, res) \
  34. ({ \
  35. bool __failed; \
  36. typeof(v) __a = ((typeof(v))(align) - 1); \
  37. \
  38. __failed = grub_add (v, __a, res); \
  39. if (__failed == false) \
  40. *(res) &= ~__a; \
  41. __failed; \
  42. })
  43. #else
  44. #error gcc 5.1 or newer or clang 8.0 or newer is required
  45. #endif
  46. #endif /* GRUB_SAFEMATH_H */