1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef LIBMEMUNREACHABLE_SCOPED_SIGNAL_HANDLER_H_ 18 #define LIBMEMUNREACHABLE_SCOPED_SIGNAL_HANDLER_H_ 19 20 #include <errno.h> 21 #include <signal.h> 22 23 #include <functional> 24 25 #include "android-base/macros.h" 26 27 #include "log.h" 28 29 namespace android { 30 31 class ScopedSignalHandler { 32 public: 33 using Fn = std::function<void(ScopedSignalHandler&, int, siginfo_t*, void*)>; 34 35 explicit ScopedSignalHandler(Allocator<Fn> allocator) : allocator_(allocator), signal_(-1) {} 36 ~ScopedSignalHandler() { reset(); } 37 38 template <class F> 39 void install(int signal, F&& f) { 40 if (signal_ != -1) MEM_LOG_ALWAYS_FATAL("ScopedSignalHandler already installed"); 41 42 handler_ = SignalFn(std::allocator_arg, allocator_, 43 [=](int signal, siginfo_t* si, void* uctx) { f(*this, signal, si, uctx); }); 44 45 struct sigaction act {}; 46 act.sa_sigaction = [](int signal, siginfo_t* si, void* uctx) { handler_(signal, si, uctx); }; 47 act.sa_flags = SA_SIGINFO; 48 49 int ret = sigaction(signal, &act, &old_act_); 50 if (ret < 0) { 51 MEM_LOG_ALWAYS_FATAL("failed to install segfault handler: %s", strerror(errno)); 52 } 53 54 signal_ = signal; 55 } 56 57 void reset() { 58 if (signal_ != -1) { 59 int ret = sigaction(signal_, &old_act_, NULL); 60 if (ret < 0) { 61 MEM_ALOGE("failed to uninstall segfault handler"); 62 } 63 handler_ = SignalFn{}; 64 signal_ = -1; 65 } 66 } 67 68 private: 69 using SignalFn = std::function<void(int, siginfo_t*, void*)>; 70 DISALLOW_COPY_AND_ASSIGN(ScopedSignalHandler); 71 Allocator<Fn> allocator_; 72 int signal_; 73 struct sigaction old_act_; 74 // TODO(ccross): to support multiple ScopedSignalHandlers handler_ would need 75 // to be a static map of signals to handlers, but allocated with Allocator. 76 static SignalFn handler_; 77 }; 78 79 } // namespace android 80 81 #endif // LIBMEMUNREACHABLE_SCOPED_SIGNAL_HANDLER_H_ 82