Revert "Make sigchain actually own the signal chain."

This reverts commit 7600fa9234e02cf5108a3a82babf3d3ab82fcddd.

Change-Id: Ia46db2a7df0c0ac07107a8db06f42ff1afd4a97e
diff --git a/sigchainlib/sigchain.cc b/sigchainlib/sigchain.cc
index ed6d7cd..c1efecd 100644
--- a/sigchainlib/sigchain.cc
+++ b/sigchainlib/sigchain.cc
@@ -25,9 +25,6 @@
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <ucontext.h>
-
-#include <utility>
 
 #include "sigchain.h"
 
@@ -36,24 +33,70 @@
 #define sighandler_t sig_t
 #endif
 
-// libsigchain provides an interception layer for signal handlers, to allow ART and others to give
-// their signal handlers the first stab at handling signals before passing them on to user code.
-//
-// It implements wrapper functions for signal, sigaction, and sigprocmask, and a handler that
-// forwards signals appropriately.
-//
-// In our handler, we start off with all signals blocked, fetch the original signal mask from the
-// passed in ucontext, and then adjust our signal mask appropriately for the user handler.
-//
-// It's somewhat tricky for us to properly handle some flag cases:
-//   SA_NOCLDSTOP and SA_NOCLDWAIT: shouldn't matter, we don't have special handlers for SIGCHLD.
-//   SA_NODEFER: unimplemented, we can manually change the signal mask appropriately.
-//  ~SA_ONSTACK: always silently enable this
-//   SA_RESETHAND: unimplemented, but we can probably do this?
-//  ~SA_RESTART: unimplemented, maybe we can reserve an RT signal, register an empty handler that
-//               doesn't have SA_RESTART, and raise the signal to avoid restarting syscalls that are
-//               expected to be interrupted?
+namespace art {
 
+typedef int (*SigActionFnPtr)(int, const struct sigaction*, struct sigaction*);
+
+class SignalAction {
+ public:
+  SignalAction() : claimed_(false), uses_old_style_(false), special_handler_(nullptr) {
+  }
+
+  // Claim the signal and keep the action specified.
+  void Claim(const struct sigaction& action) {
+    action_ = action;
+    claimed_ = true;
+  }
+
+  // Unclaim the signal and restore the old action.
+  void Unclaim(int signal) {
+    claimed_ = false;
+    sigaction(signal, &action_, nullptr);        // Restore old action.
+  }
+
+  // Get the action associated with this signal.
+  const struct sigaction& GetAction() const {
+    return action_;
+  }
+
+  // Is the signal claimed?
+  bool IsClaimed() const {
+    return claimed_;
+  }
+
+  // Change the recorded action to that specified.
+  // If oldstyle is true then this action is from an older style signal()
+  // call as opposed to sigaction().  In this case the sa_handler is
+  // used when invoking the user's handler.
+  void SetAction(const struct sigaction& action, bool oldstyle) {
+    action_ = action;
+    uses_old_style_ = oldstyle;
+  }
+
+  bool OldStyle() const {
+    return uses_old_style_;
+  }
+
+  void SetSpecialHandler(SpecialSignalHandlerFn fn) {
+    special_handler_ = fn;
+  }
+
+  SpecialSignalHandlerFn GetSpecialHandler() {
+    return special_handler_;
+  }
+
+ private:
+  struct sigaction action_;                 // Action to be performed.
+  bool claimed_;                            // Whether signal is claimed or not.
+  bool uses_old_style_;                     // Action is created using signal().  Use sa_handler.
+  SpecialSignalHandlerFn special_handler_;  // A special handler executed before user handlers.
+};
+
+// User's signal handlers
+static SignalAction user_sigactions[_NSIG];
+static bool initialized;
+static void* linked_sigaction_sym;
+static void* linked_sigprocmask_sym;
 
 static void log(const char* format, ...) {
   char buf[256];
@@ -68,168 +111,89 @@
   va_end(ap);
 }
 
-#define fatal(...) log(__VA_ARGS__); abort()
-
-static int sigorset(sigset_t* dest, sigset_t* left, sigset_t* right) {
-  sigemptyset(dest);
-  for (size_t i = 0; i < sizeof(sigset_t) * CHAR_BIT; ++i) {
-    if (sigismember(left, i) == 1 || sigismember(right, i) == 1) {
-      sigaddset(dest, i);
-    }
+static void CheckSignalValid(int signal) {
+  if (signal <= 0 || signal >= _NSIG) {
+    log("Invalid signal %d", signal);
+    abort();
   }
-  return 0;
 }
 
-namespace art {
+// Sigchainlib's own handler so we can ensure a managed handler is called first even if nobody
+// claimed a chain. Simply forward to InvokeUserSignalHandler.
+static void sigchainlib_managed_handler_sigaction(int sig, siginfo_t* info, void* context) {
+  InvokeUserSignalHandler(sig, info, context);
+}
 
-static decltype(&sigaction) linked_sigaction;
-static decltype(&sigprocmask) linked_sigprocmask;
-__thread bool handling_signal;
+// Claim a signal chain for a particular signal.
+extern "C" void ClaimSignalChain(int signal, struct sigaction* oldaction) {
+  CheckSignalValid(signal);
 
-class SignalChain {
- public:
-  SignalChain() : claimed_(false) {
+  user_sigactions[signal].Claim(*oldaction);
+}
+
+extern "C" void UnclaimSignalChain(int signal) {
+  CheckSignalValid(signal);
+
+  user_sigactions[signal].Unclaim(signal);
+}
+
+// Invoke the user's signal handler.
+extern "C" void InvokeUserSignalHandler(int sig, siginfo_t* info, void* context) {
+  // Check the arguments.
+  CheckSignalValid(sig);
+
+  // The signal must have been claimed in order to get here.  Check it.
+  if (!user_sigactions[sig].IsClaimed()) {
+    abort();
   }
 
-  bool IsClaimed() {
-    return claimed_;
-  }
-
-  void Claim(int signo) {
-    if (!claimed_) {
-      Register(signo);
-      claimed_ = true;
-    }
-  }
-
-  // Register the signal chain with the kernel if needed.
-  void Register(int signo) {
-    struct sigaction handler_action = {};
-    handler_action.sa_sigaction = SignalChain::Handler;
-    handler_action.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
-    sigfillset(&handler_action.sa_mask);
-    linked_sigaction(signo, &handler_action, &action_);
-  }
-
-  void SetAction(const struct sigaction* action) {
-    action_ = *action;
-  }
-
-  struct sigaction GetAction() {
-    return action_;
-  }
-
-  void AddSpecialHandler(SpecialSignalHandlerFn fn) {
-    for (SpecialSignalHandlerFn& slot : special_handlers_) {
-      if (slot == nullptr) {
-        slot = fn;
-        return;
-      }
-    }
-
-    fatal("too many special signal handlers");
-  }
-
-  void RemoveSpecialHandler(SpecialSignalHandlerFn fn) {
-    // This isn't thread safe, but it's unlikely to be a real problem.
-    size_t len = sizeof(special_handlers_)/sizeof(*special_handlers_);
-    for (size_t i = 0; i < len; ++i) {
-      if (special_handlers_[i] == fn) {
-        for (size_t j = i; j < len - 1; ++j) {
-          special_handlers_[j] = special_handlers_[j + 1];
-        }
-        special_handlers_[len - 1] = nullptr;
-        return;
-      }
-    }
-
-    fatal("failed to find special handler to remove");
-  }
-
-
-  static void Handler(int signo, siginfo_t* siginfo, void*);
-
- private:
-  bool claimed_;
-  struct sigaction action_;
-  SpecialSignalHandlerFn special_handlers_[2];
-};
-
-static SignalChain chains[_NSIG];
-
-class ScopedFlagSetter {
- public:
-  explicit ScopedFlagSetter(bool* flag) : flag_(flag) {
-    *flag_ = true;
-  }
-
-  ~ScopedFlagSetter() {
-    *flag_ = false;
-  }
-
- private:
-  bool* flag_;
-};
-
-class ScopedSignalUnblocker {
- public:
-  explicit ScopedSignalUnblocker(const std::initializer_list<int>& signals) {
-    sigset_t new_mask;
-    sigemptyset(&new_mask);
-    for (int signal : signals) {
-      sigaddset(&new_mask, signal);
-    }
-    if (sigprocmask(SIG_UNBLOCK, &new_mask, &previous_mask_) != 0) {
-      fatal("failed to unblock signals: %s", strerror(errno));
-    }
-  }
-
-  ~ScopedSignalUnblocker() {
-    if (sigprocmask(SIG_SETMASK, &previous_mask_, nullptr) != 0) {
-      fatal("failed to unblock signals: %s", strerror(errno));
-    }
-  }
-
- private:
-  sigset_t previous_mask_;
-};
-
-
-void SignalChain::Handler(int signo, siginfo_t* siginfo, void* ucontext_raw) {
-  // Try the special handlers first.
-  // If one of them crashes, we'll reenter this handler and pass that crash onto the user handler.
-  if (!handling_signal) {
-    ScopedFlagSetter flag(&handling_signal);
-    ScopedSignalUnblocker unblocked { SIGABRT, SIGSEGV, SIGBUS }; // NOLINT
-
-    for (const auto& handler : chains[signo].special_handlers_) {
-      if (handler != nullptr && handler(signo, siginfo, ucontext_raw)) {
-        return;
-      }
-    }
-  }
-
-  // Forward to the user's signal handler.
-  int handler_flags = chains[signo].action_.sa_flags;
-  ucontext_t* ucontext = static_cast<ucontext_t*>(ucontext_raw);
-  sigset_t mask;
-  sigorset(&mask, &ucontext->uc_sigmask, &chains[signo].action_.sa_mask);
-  if ((handler_flags & SA_NODEFER)) {
-    sigdelset(&mask, signo);
-  }
-  sigprocmask(SIG_SETMASK, &mask, nullptr);
-
-  if ((handler_flags & SA_SIGINFO)) {
-    chains[signo].action_.sa_sigaction(signo, siginfo, ucontext_raw);
-  } else {
-    auto handler = chains[signo].action_.sa_handler;
-    if (handler == SIG_IGN) {
+  // Do we have a managed handler? If so, run it first.
+  SpecialSignalHandlerFn managed = user_sigactions[sig].GetSpecialHandler();
+  if (managed != nullptr) {
+    sigset_t mask, old_mask;
+    sigfillset(&mask);
+    sigprocmask(SIG_BLOCK, &mask, &old_mask);
+    // Call the handler. If it succeeds, we're done.
+    if (managed(sig, info, context)) {
+      sigprocmask(SIG_SETMASK, &old_mask, nullptr);
       return;
-    } else if (handler == SIG_DFL) {
-      raise(signo);
-    } else {
-      handler(signo);
     }
+    sigprocmask(SIG_SETMASK, &old_mask, nullptr);
+  }
+
+  const struct sigaction& action = user_sigactions[sig].GetAction();
+  if (user_sigactions[sig].OldStyle()) {
+    if (action.sa_handler != nullptr) {
+      action.sa_handler(sig);
+    } else {
+      signal(sig, SIG_DFL);
+      raise(sig);
+    }
+  } else {
+    if (action.sa_sigaction != nullptr) {
+      sigset_t old_mask;
+      sigprocmask(SIG_BLOCK, &action.sa_mask, &old_mask);
+      action.sa_sigaction(sig, info, context);
+      sigprocmask(SIG_SETMASK, &old_mask, nullptr);
+    } else {
+      signal(sig, SIG_DFL);
+      raise(sig);
+    }
+  }
+}
+
+extern "C" void EnsureFrontOfChain(int signal, struct sigaction* expected_action) {
+  CheckSignalValid(signal);
+  // Read the current action without looking at the chain, it should be the expected action.
+  SigActionFnPtr linked_sigaction = reinterpret_cast<SigActionFnPtr>(linked_sigaction_sym);
+  struct sigaction current_action;
+  linked_sigaction(signal, nullptr, &current_action);
+  // If the sigactions don't match then we put the current action on the chain and make ourself as
+  // the main action.
+  if (current_action.sa_sigaction != expected_action->sa_sigaction) {
+    log("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
+    user_sigactions[signal].Claim(current_action);
+    linked_sigaction(signal, expected_action, nullptr);
   }
 }
 
@@ -238,15 +202,11 @@
   // action but don't pass it on to the kernel.
   // Note that we check that the signal number is in range here.  An out of range signal
   // number should behave exactly as the libc sigaction.
-  if (signal < 0 || signal >= _NSIG) {
-    errno = EINVAL;
-    return -1;
-  }
-
-  if (chains[signal].IsClaimed() && new_action != nullptr) {
-    struct sigaction saved_action = chains[signal].GetAction();
+  if (signal > 0 && signal < _NSIG && user_sigactions[signal].IsClaimed() &&
+      (new_action == nullptr || new_action->sa_handler != SIG_DFL)) {
+    struct sigaction saved_action = user_sigactions[signal].GetAction();
     if (new_action != nullptr) {
-      chains[signal].SetAction(new_action);
+      user_sigactions[signal].SetAction(*new_action, false);
     }
     if (old_action != nullptr) {
       *old_action = saved_action;
@@ -256,43 +216,69 @@
 
   // Will only get here if the signal chain has not been claimed.  We want
   // to pass the sigaction on to the kernel via the real sigaction in libc.
-  InitializeSignalChain();
+
+  if (linked_sigaction_sym == nullptr) {
+    // Perform lazy initialization.
+    // This will only occur outside of a signal context since we have
+    // not been initialized and therefore cannot be within the ART
+    // runtime.
+    InitializeSignalChain();
+  }
+
+  if (linked_sigaction_sym == nullptr) {
+    log("Unable to find next sigaction in signal chain");
+    abort();
+  }
+  SigActionFnPtr linked_sigaction = reinterpret_cast<SigActionFnPtr>(linked_sigaction_sym);
   return linked_sigaction(signal, new_action, old_action);
 }
 
-extern "C" sighandler_t signal(int signo, sighandler_t handler) {
-  if (signo < 0 || signo > _NSIG) {
-    errno = EINVAL;
-    return SIG_ERR;
-  }
-
-  struct sigaction sa = {};
+static sighandler_t signal_impl(int signal, sighandler_t handler) {
+  struct sigaction sa;
   sigemptyset(&sa.sa_mask);
   sa.sa_handler = handler;
-  sa.sa_flags = SA_RESTART | SA_ONSTACK;
+  sa.sa_flags = SA_RESTART;
   sighandler_t oldhandler;
 
   // If this signal has been claimed as a signal chain, record the user's
   // action but don't pass it on to the kernel.
-  if (chains[signo].IsClaimed()) {
-    oldhandler = reinterpret_cast<sighandler_t>(chains[signo].GetAction().sa_handler);
-    chains[signo].SetAction(&sa);
+  // Note that we check that the signal number is in range here.  An out of range signal
+  // number should behave exactly as the libc sigaction.
+  if (signal > 0 && signal < _NSIG && user_sigactions[signal].IsClaimed() && handler != SIG_DFL) {
+    oldhandler = reinterpret_cast<sighandler_t>(user_sigactions[signal].GetAction().sa_handler);
+    user_sigactions[signal].SetAction(sa, true);
     return oldhandler;
   }
 
   // Will only get here if the signal chain has not been claimed.  We want
   // to pass the sigaction on to the kernel via the real sigaction in libc.
-  InitializeSignalChain();
-  if (linked_sigaction(signo, &sa, &sa) == -1) {
+
+  if (linked_sigaction_sym == nullptr) {
+    // Perform lazy initialization.
+    InitializeSignalChain();
+  }
+
+  if (linked_sigaction_sym == nullptr) {
+    log("Unable to find next sigaction in signal chain");
+    abort();
+  }
+
+  typedef int (*SigAction)(int, const struct sigaction*, struct sigaction*);
+  SigAction linked_sigaction = reinterpret_cast<SigAction>(linked_sigaction_sym);
+  if (linked_sigaction(signal, &sa, &sa) == -1) {
     return SIG_ERR;
   }
 
   return reinterpret_cast<sighandler_t>(sa.sa_handler);
 }
 
+extern "C" sighandler_t signal(int signal, sighandler_t handler) {
+  return signal_impl(signal, handler);
+}
+
 #if !defined(__LP64__)
-extern "C" sighandler_t bsd_signal(int signo, sighandler_t handler) {
-  return signal(signo, handler);
+extern "C" sighandler_t bsd_signal(int signal, sighandler_t handler) {
+  return signal_impl(signal, handler);
 }
 #endif
 
@@ -306,7 +292,7 @@
       // Don't allow claimed signals in the mask.  If a signal chain has been claimed
       // we can't allow the user to block that signal.
       for (int i = 0 ; i < _NSIG; ++i) {
-        if (chains[i].IsClaimed() && sigismember(&tmpset, i)) {
+        if (user_sigactions[i].IsClaimed() && sigismember(&tmpset, i)) {
           sigdelset(&tmpset, i);
         }
       }
@@ -314,7 +300,18 @@
     new_set_ptr = &tmpset;
   }
 
-  InitializeSignalChain();
+  if (linked_sigprocmask_sym == nullptr) {
+    // Perform lazy initialization.
+    InitializeSignalChain();
+  }
+
+  if (linked_sigprocmask_sym == nullptr) {
+    log("Unable to find next sigprocmask in signal chain");
+    abort();
+  }
+
+  typedef int (*SigProcMask)(int how, const sigset_t*, sigset_t*);
+  SigProcMask linked_sigprocmask= reinterpret_cast<SigProcMask>(linked_sigprocmask_sym);
   return linked_sigprocmask(how, new_set_ptr, bionic_old_set);
 }
 
@@ -325,67 +322,49 @@
   // taken and if it so happens that a signal occurs while one of these
   // locks is already taken, dlsym will block trying to reenter a
   // mutex and we will never get out of it.
-  static bool initialized = false;
   if (initialized) {
     // Don't initialize twice.
     return;
   }
-
-  void* linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
+  linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
   if (linked_sigaction_sym == nullptr) {
     linked_sigaction_sym = dlsym(RTLD_DEFAULT, "sigaction");
     if (linked_sigaction_sym == nullptr ||
         linked_sigaction_sym == reinterpret_cast<void*>(sigaction)) {
-      fatal("Unable to find next sigaction in signal chain");
+      linked_sigaction_sym = nullptr;
     }
   }
 
-  void* linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
+  linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
   if (linked_sigprocmask_sym == nullptr) {
     linked_sigprocmask_sym = dlsym(RTLD_DEFAULT, "sigprocmask");
     if (linked_sigprocmask_sym == nullptr ||
         linked_sigprocmask_sym == reinterpret_cast<void*>(sigprocmask)) {
-      fatal("Unable to find next sigprocmask in signal chain");
+      linked_sigprocmask_sym = nullptr;
     }
   }
-
-  linked_sigaction = reinterpret_cast<decltype(linked_sigaction)>(linked_sigaction_sym);
-  linked_sigprocmask = reinterpret_cast<decltype(linked_sigprocmask)>(linked_sigprocmask_sym);
   initialized = true;
 }
 
-extern "C" void AddSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
-  if (signal <= 0 || signal >= _NSIG) {
-    fatal("Invalid signal %d", signal);
-  }
+extern "C" void SetSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
+  CheckSignalValid(signal);
 
   // Set the managed_handler.
-  chains[signal].AddSpecialHandler(fn);
-  chains[signal].Claim(signal);
-}
+  user_sigactions[signal].SetSpecialHandler(fn);
 
-extern "C" void RemoveSpecialSignalHandlerFn(int signal, SpecialSignalHandlerFn fn) {
-  if (signal <= 0 || signal >= _NSIG) {
-    fatal("Invalid signal %d", signal);
-  }
-
-  chains[signal].RemoveSpecialHandler(fn);
-}
-
-extern "C" void EnsureFrontOfChain(int signal) {
-  if (signal <= 0 || signal >= _NSIG) {
-    fatal("Invalid signal %d", signal);
-  }
-
-  // Read the current action without looking at the chain, it should be the expected action.
-  struct sigaction current_action;
-  InitializeSignalChain();
-  linked_sigaction(signal, nullptr, &current_action);
-  // If the sigactions don't match then we put the current action on the chain and make ourself as
-  // the main action.
-  if (current_action.sa_sigaction != SignalChain::Handler) {
-    log("Warning: Unexpected sigaction action found %p\n", current_action.sa_sigaction);
-    chains[signal].Register(signal);
+  // In case the chain isn't claimed, claim it for ourself so we can ensure the managed handler
+  // goes first.
+  if (!user_sigactions[signal].IsClaimed()) {
+    struct sigaction act, old_act;
+    act.sa_sigaction = sigchainlib_managed_handler_sigaction;
+    sigemptyset(&act.sa_mask);
+    act.sa_flags = SA_SIGINFO | SA_ONSTACK;
+#if !defined(__APPLE__) && !defined(__mips__)
+    act.sa_restorer = nullptr;
+#endif
+    if (sigaction(signal, &act, &old_act) != -1) {
+      user_sigactions[signal].Claim(old_act);
+    }
   }
 }