Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

A signal handler is allowed to call signal(), and if that fails, signal() returns SIG_ERR and sets errno to a positive value.  However, if the event that caused a signal was external (not as the result of the program calling abort() or raise()), the signal handler must only call signal() on the signal currently being handled, and if signal() fails, the value of errno is indeterminate.

This rule is a special case of SIG31-C. Do not access or modify shared objects in signal handlers.   The object designated by errno is of static storage duration and is not a volatile sig_atomic_tThereforeAs a result, performing any action that would require errno to be set would normally cause undefined behavior.  The C standard makes a special exception for errno in this case, saying the only thing that is allowed to go wrong is that errno takes on an indeterminate value.  This makes it possible to call signal() from within a signal handler without risking completely unrestricted undefined behavior, but the handler must not depend on the value of errno being meaningful.

...

Code Block
bgColor#FFcccc
#include <signal.h>
#include <stdlib.h>
#include <string.h>

typedef void (*pfv)(int);

void handler(int signum) {
  pfv old_handler = signal(signum, handler);
  if (old_handler == SIG_ERR) {
    perror("SIGINT handler"); /* undefined behavior */
    /* handle error condition */
  }
  strcpy(err_msg, "SIGINT encountered.");
}

int main(void) {
  pfv old_handler = signal(SIGINT, handler);
  if (old_handler == SIG_ERR) {
    perror("SIGINT handler");
    /* handle error condition */
  }

  /* main code loop */

  return 0;
}

...

Code Block
bgColor#ccccff
#include <signal.h>
#include <stdlib.h>
#include <string.h>

typedef void (*pfv)(int);

void handler(int signum) {
  pfv old_handler = signal(signum, handler);
  if (old_handler == SIG_ERR) {
    /* handle error condition */
  }
}

int main(void) {
  pfv old_handler = signal(SIGINT, handler);
  if (old_handler == SIG_ERR) {
    perror("SIGINT handler");
    /* handle error condition */
  }

  /* main code loop */

  return 0;
}

Risk Assessment

Referencing indeterminate values can result in undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR32-C

1 (low)

1 (unlikely)

3 (low)

P3

L3

...