Versions Compared

Key

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

Call only asynchronous-safe functions within signal handlers. This restriction applies to library functions as well as application-defined functions.

According to Section 7.14.1.1 of the C Rationale [ISO/IEC 2003],

When a signal occurs, the normal flow of control of a program is interrupted. If a signal occurs that is being trapped by a signal handler, that handler is invoked. When it is finished, execution continues at the point at which the signal occurred. This arrangement can cause problems if the signal handler invokes a library function that was being executed at the time of the signal.

Similarly, Section 7.14.1.1, para. 5, of the C standard [ISO/IEC 9899:2011], states that if the signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if

the signal handler calls any function in the standard library other than the abort function, the _Exit function, or the signal function with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler.

...

The second problem is that the free() function is also not asynchronous-safe, and its invocation from within a signal handler is also a violation of this rule. If an interrupt signal is received during the free() call in handler(), the heap may be corrupted.

The third problem is that if SIGINT occurs after the call to free(), the memory referenced by info is freed twice. This is a violation of MEM31-C. Free dynamically allocated memory exactly once and SIG31-C. Do not access or modify shared objects in signal handlers.

The fourth problem is that the signal handler reads the variable info, which is not declared to be of type volatile sig_atomic_t. This is a violation of SIG31-C. Do not access or modify shared objects in signal handlers.

...

The following table from the the Open Group Base Specifications [Open Group 2004] defines a set of functions that are asynchronous-signal-safe. Applications may invoke these functions, without restriction, from a signal handler.

...

For an overview of software vulnerabilities resulting from improper signal handling, see Zalewski's paper on understanding, exploiting, and preventing signal-handling-related vulnerabilities [Zalewski 2001]. VU #834865 describes a vulnerability resulting from a violation of this rule.

...

MITRE CWE: CWE ID 479, "Unsafe function call from a signal handler"

Bibliography

[Dowd 2006] Chapter 13, "Synchronization and State"
[ISO/IEC 2003] Section 5.2.3, "Signals and interrupts"
[Open Group 2004] longjmp
[OpenBSD] signal() Man Page
[Zalewski 2001]

...