Home | History | Annotate | Line # | Download | only in gdbsupport
      1 /* RAII class to install a separate handler for a given signal
      2 
      3    Copyright (C) 2024 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19 
     20 #ifndef SCOPED_SIGNAL_HANDLER_H
     21 #define SCOPED_SIGNAL_HANDLER_H
     22 
     23 #include <signal.h>
     24 
     25 #undef HAVE_SIGACTION
     26 
     27 /* RAII class to set a signal handler for a scope, that will take care of
     28    unsetting the handler when the scope is left.
     29    This class will try to use sigaction whenever available, following the
     30    recommendation on the man page for signal, and only fallback to signal
     31    if necessary.  */
     32 template <int SIG>
     33 class scoped_signal_handler
     34 {
     35 public:
     36   scoped_signal_handler (sighandler_t handler)
     37   {
     38 #if defined (HAVE_SIGACTION)
     39     struct sigaction act;
     40 
     41     act.sa_handler = handler;
     42     sigemptyset (&act.sa_mask);
     43     act.sa_flags = 0;
     44     sigaction (SIG, &act, &m_prev_handler);
     45 #else
     46     /* The return of the function call is the previous signal handler, or
     47        SIG_ERR if the function doesn't succeed.  */
     48     m_prev_handler = signal (SIG, handler);
     49     /* According to the GNU libc manual, the only way signal fails is if
     50        the signum given is invalid, so we should be safe to assert.  */
     51     gdb_assert (m_prev_handler != SIG_ERR);
     52 #endif
     53   }
     54 
     55   ~scoped_signal_handler ()
     56   {
     57 #if defined (HAVE_SIGACTION)
     58     sigaction (SIG, &m_prev_handler, nullptr);
     59 #else
     60     signal (SIG, m_prev_handler);
     61 #endif
     62   }
     63 
     64   DISABLE_COPY_AND_ASSIGN (scoped_signal_handler);
     65 private:
     66 #if defined (HAVE_SIGACTION)
     67   struct sigaction m_prev_handler;
     68 #else
     69   sighandler_t m_prev_handler;
     70 #endif
     71 };
     72 
     73 #endif /* SCOPED_SIGNAL_HANDLER_H  */
     74