10b57cec5SDimitry Andric //===-- safestack_util.h --------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file contains utility code for SafeStack implementation. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #ifndef SAFESTACK_UTIL_H 140b57cec5SDimitry Andric #define SAFESTACK_UTIL_H 150b57cec5SDimitry Andric 160b57cec5SDimitry Andric #include <pthread.h> 170b57cec5SDimitry Andric #include <stdio.h> 180b57cec5SDimitry Andric #include <stdlib.h> 190b57cec5SDimitry Andric 200b57cec5SDimitry Andric namespace safestack { 210b57cec5SDimitry Andric 220b57cec5SDimitry Andric #define SFS_CHECK(a) \ 230b57cec5SDimitry Andric do { \ 240b57cec5SDimitry Andric if (!(a)) { \ 250b57cec5SDimitry Andric fprintf(stderr, "safestack CHECK failed: %s:%d %s\n", __FILE__, \ 260b57cec5SDimitry Andric __LINE__, #a); \ 270b57cec5SDimitry Andric abort(); \ 280b57cec5SDimitry Andric }; \ 290b57cec5SDimitry Andric } while (false) 300b57cec5SDimitry Andric RoundUpTo(size_t size,size_t boundary)310b57cec5SDimitry Andricinline size_t RoundUpTo(size_t size, size_t boundary) { 320b57cec5SDimitry Andric SFS_CHECK((boundary & (boundary - 1)) == 0); 330b57cec5SDimitry Andric return (size + boundary - 1) & ~(boundary - 1); 340b57cec5SDimitry Andric } 350b57cec5SDimitry Andric IsAligned(size_t a,size_t alignment)36*0fca6ea1SDimitry Andricinline constexpr bool IsAligned(size_t a, size_t alignment) { 37*0fca6ea1SDimitry Andric return (a & (alignment - 1)) == 0; 38*0fca6ea1SDimitry Andric } 39*0fca6ea1SDimitry Andric 400b57cec5SDimitry Andric class MutexLock { 410b57cec5SDimitry Andric public: MutexLock(pthread_mutex_t & mutex)420b57cec5SDimitry Andric explicit MutexLock(pthread_mutex_t &mutex) : mutex_(&mutex) { 430b57cec5SDimitry Andric pthread_mutex_lock(mutex_); 440b57cec5SDimitry Andric } ~MutexLock()450b57cec5SDimitry Andric ~MutexLock() { pthread_mutex_unlock(mutex_); } 460b57cec5SDimitry Andric 470b57cec5SDimitry Andric private: 480b57cec5SDimitry Andric pthread_mutex_t *mutex_ = nullptr; 490b57cec5SDimitry Andric }; 500b57cec5SDimitry Andric 510b57cec5SDimitry Andric } // namespace safestack 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric #endif // SAFESTACK_UTIL_H 54