...
Section 2.9.1 of the System Interfaces volume of POSIX.1-2008 has a much longer list of functions that are not required to be thread safe.
Noncompliant Code Example
Consider a multithreaded application that encounters an error while calling a system function. The strerror()
function returns a human-readable error string given an error number. According to C99, Section 7.22.6.2 specifically states that strerror()
is not required to avoid data races. Conventionally it could rely on a static array that maps error numbers to error strings, and that array might be accessible and modifiable by other threads.
...
Note that this code first sets errno
to 0 to comply with ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure.
Compliant Solution (POSIX)
The compliant solution uses the POSIX strerror_r()
function, which has the same functionality as strerror()
but guarantees thread safety.
...
Note that Linux provides two versions of strerror_r()
, known as the XSI-compliant version and the GNU-specific version. This compliant solution assumes the XSI-compliant version. You can get the XSI-compliant version if you compile applications in the way POSIX requires (that is, by defining _POSIX_C_SOURCE
or _XOPEN_SOURCE
appropriately). Check your strerror_r()
man page to see which version(s) are available on your system.
Risk Assessment
Race conditions caused by multiple threads invoking the same library function can lead to abnormal termination of the application, data integrity violations, or denial-of-service attack.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
POS40-C | medium | probable | high | P4 | L3 |
Other Languages
This rule appears in the C++ Secure Coding Standard as CON03-CPP. Avoid assuming functions are thread-safe unless otherwise specified.
Automated Detection
A module written in Compass/ROSE can detect violations of this rule.
References
Wiki Markup |
---|
\[[N1401-C1X Draft|http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1401.pdf]\] Section 7.21.2.1 rand() function, Section 7.21.4.6 getenv() function, Section 7.22.5.8 strtok() function, Section 7.22.6.2 strerror() function, Section 7.25.3.1 asctime() function, Section 7.25.3.2 ctime() function \[[Historical information about POSIX.1 Thread Safety|http://www.unix.org/whitepapers/reentrant.html]\] |
...