1*0b57cec5SDimitry Andric //===-- safestack_util.h --------------------------------------------------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This file contains utility code for SafeStack implementation. 10*0b57cec5SDimitry Andric // 11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 12*0b57cec5SDimitry Andric 13*0b57cec5SDimitry Andric #ifndef SAFESTACK_UTIL_H 14*0b57cec5SDimitry Andric #define SAFESTACK_UTIL_H 15*0b57cec5SDimitry Andric 16*0b57cec5SDimitry Andric #include <pthread.h> 17*0b57cec5SDimitry Andric #include <stdio.h> 18*0b57cec5SDimitry Andric #include <stdlib.h> 19*0b57cec5SDimitry Andric 20*0b57cec5SDimitry Andric namespace safestack { 21*0b57cec5SDimitry Andric 22*0b57cec5SDimitry Andric #define SFS_CHECK(a) \ 23*0b57cec5SDimitry Andric do { \ 24*0b57cec5SDimitry Andric if (!(a)) { \ 25*0b57cec5SDimitry Andric fprintf(stderr, "safestack CHECK failed: %s:%d %s\n", __FILE__, \ 26*0b57cec5SDimitry Andric __LINE__, #a); \ 27*0b57cec5SDimitry Andric abort(); \ 28*0b57cec5SDimitry Andric }; \ 29*0b57cec5SDimitry Andric } while (false) 30*0b57cec5SDimitry Andric 31*0b57cec5SDimitry Andric inline size_t RoundUpTo(size_t size, size_t boundary) { 32*0b57cec5SDimitry Andric SFS_CHECK((boundary & (boundary - 1)) == 0); 33*0b57cec5SDimitry Andric return (size + boundary - 1) & ~(boundary - 1); 34*0b57cec5SDimitry Andric } 35*0b57cec5SDimitry Andric 36*0b57cec5SDimitry Andric class MutexLock { 37*0b57cec5SDimitry Andric public: 38*0b57cec5SDimitry Andric explicit MutexLock(pthread_mutex_t &mutex) : mutex_(&mutex) { 39*0b57cec5SDimitry Andric pthread_mutex_lock(mutex_); 40*0b57cec5SDimitry Andric } 41*0b57cec5SDimitry Andric ~MutexLock() { pthread_mutex_unlock(mutex_); } 42*0b57cec5SDimitry Andric 43*0b57cec5SDimitry Andric private: 44*0b57cec5SDimitry Andric pthread_mutex_t *mutex_ = nullptr; 45*0b57cec5SDimitry Andric }; 46*0b57cec5SDimitry Andric 47*0b57cec5SDimitry Andric } // namespace safestack 48*0b57cec5SDimitry Andric 49*0b57cec5SDimitry Andric #endif // SAFESTACK_UTIL_H 50