1 //===-- sanitizer_allocator_checks.h ----------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // Various checks shared between ThreadSanitizer, MemorySanitizer, etc. memory
9 // allocators.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef SANITIZER_ALLOCATOR_CHECKS_H
14 #define SANITIZER_ALLOCATOR_CHECKS_H
15
16 #include "sanitizer_internal_defs.h"
17 #include "sanitizer_common.h"
18 #include "sanitizer_platform.h"
19
20 namespace __sanitizer {
21
22 // The following is defined in a separate compilation unit to avoid pulling in
23 // sanitizer_errno.h in this header, which leads to conflicts when other system
24 // headers include errno.h. This is usually the result of an unlikely event,
25 // and as such we do not care as much about having it inlined.
26 void SetErrnoToENOMEM();
27
28 // A common errno setting logic shared by almost all sanitizer allocator APIs.
SetErrnoOnNull(void * ptr)29 INLINE void *SetErrnoOnNull(void *ptr) {
30 if (UNLIKELY(!ptr))
31 SetErrnoToENOMEM();
32 return ptr;
33 }
34
35 // In case of the check failure, the caller of the following Check... functions
36 // should "return POLICY::OnBadRequest();" where POLICY is the current allocator
37 // failure handling policy.
38
39 // Checks aligned_alloc() parameters, verifies that the alignment is a power of
40 // two and that the size is a multiple of alignment for POSIX implementation,
41 // and a bit relaxed requirement for non-POSIX ones, that the size is a multiple
42 // of alignment.
CheckAlignedAllocAlignmentAndSize(uptr alignment,uptr size)43 INLINE bool CheckAlignedAllocAlignmentAndSize(uptr alignment, uptr size) {
44 #if SANITIZER_POSIX
45 return IsPowerOfTwo(alignment) && (size & (alignment - 1)) == 0;
46 #else
47 return size % alignment == 0;
48 #endif
49 }
50
51 // Checks posix_memalign() parameters, verifies that alignment is a power of two
52 // and a multiple of sizeof(void *).
CheckPosixMemalignAlignment(uptr alignment)53 INLINE bool CheckPosixMemalignAlignment(uptr alignment) {
54 return IsPowerOfTwo(alignment) && (alignment % sizeof(void *)) == 0; // NOLINT
55 }
56
57 // Returns true if calloc(size, n) call overflows on size*n calculation.
CheckForCallocOverflow(uptr size,uptr n)58 INLINE bool CheckForCallocOverflow(uptr size, uptr n) {
59 if (!size)
60 return false;
61 uptr max = (uptr)-1L;
62 return (max / size) < n;
63 }
64
65 // Returns true if the size passed to pvalloc overflows when rounded to the next
66 // multiple of page_size.
CheckForPvallocOverflow(uptr size,uptr page_size)67 INLINE bool CheckForPvallocOverflow(uptr size, uptr page_size) {
68 return RoundUpTo(size, page_size) < size;
69 }
70
71 } // namespace __sanitizer
72
73 #endif // SANITIZER_ALLOCATOR_CHECKS_H
74