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 class ScopedSignalHandler {
30  public:
31   using Fn = std::function<void(ScopedSignalHandler&, int, siginfo_t*, void*)>;
32 
ScopedSignalHandler(Allocator<Fn> allocator)33   explicit ScopedSignalHandler(Allocator<Fn> allocator) : allocator_(allocator), signal_(-1) {}
~ScopedSignalHandler()34   ~ScopedSignalHandler() {
35     reset();
36   }
37 
38   template <class F>
install(int signal,F && f)39   void install(int signal, F&& f) {
40     LOG_ALWAYS_FATAL_IF(signal_ != -1, "ScopedSignalHandler already installed");
41 
42     handler_ = SignalFn(std::allocator_arg, allocator_,
43         [=](int signal, siginfo_t* si, void* uctx) {
44           f(*this, signal, si, uctx);
45         });
46 
47     struct sigaction act{};
48     act.sa_sigaction = [](int signal, siginfo_t* si, void* uctx) {
49       handler_(signal, si, uctx);
50     };
51     act.sa_flags = SA_SIGINFO;
52 
53     int ret = sigaction(signal, &act, &old_act_);
54     if (ret < 0) {
55       LOG_ALWAYS_FATAL("failed to install segfault handler: %s", strerror(errno));
56     }
57 
58     signal_ = signal;
59   }
60 
reset()61   void reset() {
62     if (signal_ != -1) {
63       int ret = sigaction(signal_, &old_act_, NULL);
64       if (ret < 0) {
65         ALOGE("failed to uninstall segfault handler");
66       }
67       handler_ = SignalFn{};
68       signal_ = -1;
69     }
70   }
71 
72 
73  private:
74   using SignalFn = std::function<void(int, siginfo_t*, void*)>;
75   DISALLOW_COPY_AND_ASSIGN(ScopedSignalHandler);
76   Allocator<Fn> allocator_;
77   int signal_;
78   struct sigaction old_act_;
79   // TODO(ccross): to support multiple ScopedSignalHandlers handler_ would need
80   // to be a static map of signals to handlers, but allocated with Allocator.
81   static SignalFn handler_;
82 };
83 
84 #endif // LIBMEMUNREACHABLE_SCOPED_SIGNAL_HANDLER_H_
85