This standard recommends the inclusion of diagnostic tests into your program using the assert()
macro or other mechanisms Assertions are a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities (see MSC11-AC. Incorporate diagnostic tests using assertions). Static assertion is a new facility in the C++ 0X draft standard. This facility enables assertions to be made at compile time rather than runtime, providing the following advantages:
- All processing must be performed during compile time - no runtime cost in space or time is tolerable.
- Assertion failure must result in a meaningful and informative diagnostic error message.
- It can be used at file or block scope.
- Misuse does not result in silent malfunction but is diagnosed at compile time.
Static assertions take the form
The runtime assert()
macro has some limitations, however, in that it incurs a runtime overhead and because it calls abort()
. Consequently, the runtime assert()
macro is useful only for identifying incorrect assumptions and not for runtime error checking. As a result, runtime assertions are generally unsuitable for server programs or embedded systems.
Static assertion is a new facility in the C Standard. It takes the form
Code Block |
---|
Code Block |
static_assert(constant-expression, string-literal);
|
...
Subclause 6.7.10 of the C Standard [ISO/IEC 9899:2011] states:
The constant expression shall be an integer constant expression. If the value of
...
the constant expression compares unequal to 0, the declaration has no effect. Otherwise
...
, the constraint is violated and the implementation shall produce a diagnostic message
...
that includes the text of the string literal, except that characters not in the basic source character set are not required to appear in the message.
It means that if constant-expression
is true, nothing will happen. However, if constant-expression
is false, an error message containing string-literal
) is issued will be output at compile time. For example:
Code Block |
---|
/* Passes */ static_assert( sizeof(int) <= sizeof(void*), "sizeof(int) <= sizeof(void*)" ); /* PassesFails */ static_assert( sizeof(double) <= sizeof(int), "sizeof(double) <= sizeof(int)" ); /* Fails */ |
...
|
Static assertion is not available in C99.
Noncompliant Code Example
This non-compliant noncompliant code uses the assert()
macro to assert a property concerning a memory-mapped structure that is essential for the code that uses this structure to behave correctly.:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> struct timer { unsigned uint8_tchar MODE; unsigned uint32_tint DATA; unsigned uint32_tint COUNT; }; int mainfunc(void) { assert(offsetofsizeof(struct timer, DATA) == 4 sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int)); } |
While the Although the use of the runtime assertion is better than nothing, it needs to be placed in a function and executed, typically removed from . This means that it is usually far away from the definition of the actual structure to which it refers. The diagnostic occurs only occurs at runtime , and only if the code path containing the assertion is executed.
Compliant Solution
For assertions involving only constant expressions, some implementations allow the use of a preprocessor conditional statement may be used, as in this examplecompliant solution:
Code Block | ||||
---|---|---|---|---|
| ||||
struct timer { unsigned uint8_tchar MODE; unsigned uint32_tint DATA; unsigned uint32_tint COUNT; }; #if (offsetofsizeof(struct timer, DATA) != 4 (sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int))) #error DATA"Structure must benot athave offsetany 4padding" #endif |
Using #error
directives allows for clear diagnostic messages. Because this approach evaluates assertions at compile time, there is no run-time penalty.Unfortunately, this solution is not portable. C99 does not require that implementations support sizeof
, offsetof
, or enumeration constants in #if
conditions. According to Section 6.10.1, "Conditional inclusion," all identifiers in the expression that controls conditional inclusion either are or are not macro names. Some compilers allow these constructs in conditionals as an extension, but most do notruntime penalty.
Compliant Solution
This portable compliant solution mimics the behavior of uses static_assert
in a portable manner.:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> #define JOIN(x, y) JOIN_AGAIN(x, y) #define JOIN_AGAIN(x, y) x ## y #define static_assert(e, s) \ typedef char JOIN(assertion_failed_at_line_, __LINE__) [(e) ? 1 : -1] struct timer { unsigned uint8_tchar MODE; unsigned uint32_tint DATA; unsigned uint32_tint COUNT; }; static_assert(offsetofsizeof(struct timer, DATA) == 4, "offsetof(struct timer, DATA) == 4"); |
The static_assert()
macro accepts a constant expression e
, which is evaluated as the first operand to the conditional operator. If e
evaluates to nonzero, an array type with a dimension of 1 is defined; otherwise an array type with a dimension of -1 is defined. Because it is invalid to declare an array with a negative dimension, the resulting type definition will be flagged by the compiler. The name of the array is used to indicate the location of the failed assertion.
The macro argument string-literal
is ignored in this case; this is meant for future compatibility.
Wiki Markup |
---|
The {{JOIN()}} macro used the {{\##}} operator \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] to concatenate tokens. See [PRE05-A. Understand macro replacement when concatenating tokens] to understand how macro replacement behaves in C when using the {{\##}} operator. |
sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int),
"Structure must not have any padding");
|
Static assertions allow incorrect assumptions to be diagnosed at compile time instead of resulting in a silent malfunction or runtime error. Because the assertion is performed at compile time, no runtime cost in space or time is incurred. An assertion can be used at file or block scope, and failure results in a meaningful and informative diagnostic error message.
Other uses of static assertion are shown in STR07-C. Use the bounds-checking interfaces for string manipulation and FIO34-C. Distinguish between characters read from a file and EOF or WEOF.
Risk Assessment
Static assertion is a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities at compile time. The absence of static assertions, however, does not mean that code is incorrect.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL03-C | Low | Unlikely | High | P1 | L3 |
Automated Detection
Tool | Version | Checker | Description | |||||
---|---|---|---|---|---|---|---|---|
Axivion Bauhaus Suite |
| CertC-DCL03 |
1 (low)
1 (unlikely)
1 (high)
P1
Clang |
| misc-static-assert | Checked by clang-tidy | ||||||
CodeSonar |
| (customization) | Users can implement a custom check that reports uses of the assert() macro | ||||||
Compass/ROSE | Could detect violations of this rule merely by looking for calls to | ||||||||
ECLAIR |
| CC2.DCL03 | Fully implemented | ||||||
LDRA tool suite |
| 44 S | Fully implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
...
Related Guidelines
C++ Secure Coding Standard | VOID DCL03-CPP. Use a static assertion to test the value of a constant expression |
Bibliography
[Becker 2008] | |
[Eckel 2007] | |
[ISO/IEC 9899:2011] | Subclause 6.7.10, "Static Assertions" |
[Jones 2010] | |
[Klarer 2004] | |
[Saks 2005] | |
[Saks 2008] |
...
9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.10.1, "Conditional inclusion," and Section 6.10.3.3, "The ## operator" \[[Klarer 04|AA. C References#Klarer 04]\] \[[Saks 05|AA. C References#Saks 05]\] \[[Saks 08|AA. C References#Saks 08]\]DCL02-A. Use visually distinct identifiers 02. Declarations and Initialization (DCL) DCL04-A. Take care when declaring more than one variable per declaration