1//===-- wrappers_c_checks.h -------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef SCUDO_CHECKS_H_
10#define SCUDO_CHECKS_H_
11
12#include "common.h"
13
14#include <errno.h>
15
16#ifndef __has_builtin
17#define __has_builtin(X) 0
18#endif
19
20namespace scudo {
21
22// A common errno setting logic shared by almost all Scudo C wrappers.
23inline void *setErrnoOnNull(void *Ptr) {
24 if (UNLIKELY(!Ptr))
25 errno = ENOMEM;
26 return Ptr;
27}
28
29// Checks return true on failure.
30
31// Checks posix_memalign() parameters, verifies that alignment is a power of two
32// and a multiple of sizeof(void *).
33inline bool checkPosixMemalignAlignment(uptr Alignment) {
34 return !isPowerOfTwo(X: Alignment) || !isAligned(X: Alignment, Alignment: sizeof(void *));
35}
36
37// Returns true if calloc(N, Size) or reallocarray(Ptr, N, Size) overflows on
38// Size*N calculation. Use a builtin supported by recent clang & GCC if it
39// exists, otherwise fallback to a costly division.
40inline bool checkForCallocOverflow(uptr Size, uptr N, uptr *Product) {
41#if __has_builtin(__builtin_umull_overflow) && (SCUDO_WORDSIZE == 64U)
42 return __builtin_umull_overflow(Size, N,
43 reinterpret_cast<unsigned long *>(Product));
44#elif __has_builtin(__builtin_umul_overflow) && (SCUDO_WORDSIZE == 32U)
45 // On, e.g. armv7, uptr/uintptr_t may be defined as unsigned long
46 return __builtin_umul_overflow(Size, N,
47 reinterpret_cast<unsigned int *>(Product));
48#else
49 *Product = Size * N;
50 if (!Size)
51 return false;
52 return (*Product / Size) != N;
53#endif
54}
55
56// Returns true if the size passed to pvalloc overflows when rounded to the next
57// multiple of PageSize.
58inline bool checkForPvallocOverflow(uptr Size, uptr PageSize) {
59 return roundUp(X: Size, Boundary: PageSize) < Size;
60}
61
62} // namespace scudo
63
64#endif // SCUDO_CHECKS_H_
65