CERT.MSC.SIG_HANDLER.POF

A signal handler must be a plain old function.

Vulnerability and risk

Failing to use a plain old function as a signal handler can result in implementation-defined behavior as well as undefined behavior. Given the number of features that exist in C++ that do not also exist in C, the consequences that arise from failure to comply with this rule can range from benign (harmless) behavior to abnormal program termination, or even arbitrary code execution.

Mitigation and prevention

A signal handler must be a plain old function.

Example

Copy
  #include <csignal>
  static void sig_handler1(int sig) {
    // Implementation details elided.
  }
  
  
  extern "C" void sig_handler2(int sig) {
    // Implementation details elided.
  }
 
 void install_signal_handler1() {
   if (SIG_ERR == std::signal(SIGTERM, sig_handler1)) { //Uncompliant code, sig_handler1 is not declared as extern "C" linkage.
     // Handle error
   }
 }
 
 
 void install_signal_handler2() {
   if (SIG_ERR == std::signal(SIGTERM, sig_handler2)) {  //Compliant code, sig_handler2 is a C linkage function.
     // Handle error
   }
 }
 
 static void g3() noexcept(false);
 
 static void g3() noexcept(false) {}
 
 extern "C" void sig_handler3(int sig) {
   try {
     g3();                                         // Uncompliant, call g3 which is not a POF
   } catch (...) {
     // Handle error
   }
 }
 
 void install_signal_handler3() {
   if (SIG_ERR == std::signal(SIGTERM, sig_handler3)) {
     // Handle error
   }
 }