xref: /freebsd/contrib/llvm-project/compiler-rt/lib/safestack/safestack_util.h (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1 //===-- safestack_util.h --------------------------------------------------===//
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 // This file contains utility code for SafeStack implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef SAFESTACK_UTIL_H
14 #define SAFESTACK_UTIL_H
15 
16 #include <pthread.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 
20 namespace safestack {
21 
22 #define SFS_CHECK(a)                                                  \
23   do {                                                                \
24     if (!(a)) {                                                       \
25       fprintf(stderr, "safestack CHECK failed: %s:%d %s\n", __FILE__, \
26               __LINE__, #a);                                          \
27       abort();                                                        \
28     };                                                                \
29   } while (false)
30 
31 inline size_t RoundUpTo(size_t size, size_t boundary) {
32   SFS_CHECK((boundary & (boundary - 1)) == 0);
33   return (size + boundary - 1) & ~(boundary - 1);
34 }
35 
36 inline constexpr bool IsAligned(size_t a, size_t alignment) {
37   return (a & (alignment - 1)) == 0;
38 }
39 
40 class MutexLock {
41  public:
42   explicit MutexLock(pthread_mutex_t &mutex) : mutex_(&mutex) {
43     pthread_mutex_lock(mutex_);
44   }
45   ~MutexLock() { pthread_mutex_unlock(mutex_); }
46 
47  private:
48   pthread_mutex_t *mutex_ = nullptr;
49 };
50 
51 }  // namespace safestack
52 
53 #endif  // SAFESTACK_UTIL_H
54