CertC-MSC15¶
Do not depend on undefined behavior
Required inputs: IR, StaticSemanticAnalysis
The C Standard, subclause 3.5.3 [ ISO/IEC 9899:2024 ], defines undefined behavior as
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this document imposes no requirements
Subclause 4 explains how the standard identifies undefined behavior (see also undefined behavior 1 of Annex J).
If a "shall" or "shall not" requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this document by the words "undefined behavior" or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe "behavior that is undefined".
Annex J, subclause J.2, "Undefined behavior," enumerates the circumstances under which the behavior of a program is undefined. This list is duplicated on the CC. Undefined Behavior page.
Behavior can be classified as undefined by the C standards committee for the following reasons:
-
To give the implementor license not to catch certain program errors that are difficult to diagnose
-
To avoid defining obscure corner cases that would favor one implementation strategy over another
-
To identify areas of possible conforming language extension: the implementor may augment the language by providing a definition of the officially undefined behavior
Conforming implementations can deal with undefined behavior in a variety of fashions, such as ignoring the situation completely, with unpredictable results; translating or executing the program in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message); or terminating a translation or execution (with the issuance of a diagnostic message). Because compilers are not obligated to generate code for undefined behavior, these behaviors are candidates for optimization. By assuming that undefined behaviors will not occur, compilers can generate code with better performance characteristics.
Increasingly, compiler writers are taking advantage of undefined behaviors in the C programming languages to improve optimizations. These optimizations frequently interfere with the ability of developers to perform cause-effect analysis on their source code—that is, to analyze the dependence of downstream results on prior results. Consequently, these optimizations are eliminating causality in software and are increasing the probability of software faults, defects, and vulnerabilities .
All of this puts the onus on the programmer to develop code that is free from undefined behaviors, with or without the help of the compiler.
Noncompliant Code Example
An example of undefined behavior in C is the behavior on signed integer overflow (see also INT32-C. Ensure that operations on signed integers do not result in overflow ). This noncompliant code example depends on this behavior to catch the overflow:
#include <assert.h>
#include <limits.h>
#include <stdio.h>
int foo(int a) {
assert(a + 100 > a);
printf("%d %d\n", a + 100, a);
return a;
}
int main(void) {
foo(100);
foo(INT_MAX);
return 0;
}
|
This code checks for signed integer overflow by testing whether a + 100 > a . This test cannot evaluate to false unless an integer overflow occurs. However, because a conforming implementation is not required to generate code for undefined behavior, and signed integer overflow is undefined behavior, this code may be compiled out. For example, GCC 4.1.1 optimizes out the assertion for all optimization levels, and GCC 4.2.3 optimizes out the assertion for programs compiled with -O2 -level optimization and higher.
On some platforms, the integer overflow causes the program to terminate (before it has an opportunity to test).
Compliant Solution
This compliant solution does not depend on undefined behavior:
#include <assert.h>
#include <limits.h>
#include <stdio.h>
int foo(int a) {
assert(a < (INT_MAX - 100));
printf("%d %d\n", a + 100, a);
return a;
}
int main(void) {
foo(100);
foo(INT_MAX);
return 0;
}
|
Risk Assessment
Although it is rare that the entire application can be strictly conforming , the goal should be that almost all the code is allowed for a strictly conforming program (which among other things means that it avoids undefined behavior ), with the implementation-dependent parts confined to modules that the programmer knows are needed to adapt to the platform when it changes.
| Recommendation | Severity | Likelihood | Detectable | Repairable | Priority | Level |
|---|---|---|---|---|---|---|
| MSC15-C | High | Likely | No | No | P9 | L2 |
Related Guidelines
| SEI CERT C++ Coding Standard | VOID MSC15-CPP. Do not depend on undefined behavior |
| ISO/IEC TR 24772 | Unspecified Behaviour [BQF] Undefined Behaviour [EWF] Implementation-Defined Behaviour [FAB] |
Bibliography
| [ ISO/IEC 9899:2024 ] | Subclause 3.5.3, "Undefined Behavior" Subclause 4, "Conformance" Subclause J.2, "Undefined Behavior" |
| [ Seacord 2013 ] | Chapter 5, "Integer Security" |
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
arithmetic_out_of_bounds |
Pointer arithmetic on {node0} might create pointer outside array bounds of {name0} |
None |
False |
assigned_to_pointer_to_const |
Assigning the address of a partially initialized variable to some pointer-to-const |
None |
False |
certain_shift_amount_negative |
Shift by a negative bit count (undefined behavior) |
None |
False |
certain_shift_amount_too_large |
Shift by the integer width or more (undefined behavior) |
None |
False |
certain_shift_right_negative |
Right shift with negative left-hand-side |
None |
False |
division_by_zero |
Division by zero |
None |
False |
double_free |
Dynamic memory released here was already released earlier |
None |
False |
float_division_by_zero |
Floating point division by floating point zero |
None |
False |
modulo_by_zero |
Modulo by zero |
None |
False |
null_deref |
Pointer is NULL at dereference |
None |
False |
null_this_arg |
Pointer passed in as argument for this is NULL |
None |
False |
out_of_bounds |
Access into array is out of bounds |
None |
False |
pass_as_pointer_to_const_param |
Passing uninitialized variable by pointer as function parameter with pointer-to-const type |
None |
False |
possible_division_by_zero |
Possible division by zero |
None |
False |
possible_double_free |
Dynamic memory released here possibly already released earlier |
None |
False |
possible_float_division_by_zero |
Possible floating point division by zero |
None |
False |
possible_indirect_out_of_bounds |
Pointer-indirect access through {node0} might be out of bounds accessing {name0} |
None |
False |
possible_modulo_by_zero |
Possible modulo by zero |
None |
False |
possible_null_deref |
Pointer may be NULL at dereference |
None |
False |
possible_null_deref_improbable |
Pointer may be NULL at dereference (improbable) |
None |
False |
possible_null_this_arg |
Pointer passed in as argument for this may be NULL |
None |
False |
possible_out_of_bounds |
Access into array might be out of bounds |
None |
False |
possible_return_value_uninit |
Function return value is potentially not initialized |
None |
False |
possible_stack_free |
{name0} possibly released by call to {node0} is a stack or static object |
None |
False |
possible_uninit |
Use of possibly uninitialized variable |
None |
False |
possible_unrelated_ptr_comparison |
Comparing possibly unrelated pointers |
None |
False |
possible_unrelated_ptr_subtraction |
Subtracting possibly unrelated pointers |
None |
False |
possible_use_after_free |
Dynamic memory possibly used after it was previously released |
None |
False |
possible_wrong_release |
Resource possibly released using wrong function (allocation used {node0}) |
None |
False |
possibly_initialized |
Use of possibly uninitialized variable (previous call {node0} might have initialized the variable) |
None |
False |
return_value_uninit |
Function return value is not initialized |
None |
False |
shift_amount_negative |
Possible shift by a negative bit count (undefined behavior) |
None |
False |
shift_amount_too_large |
Possible shift by the integer width or more (undefined behavior) |
None |
False |
shift_right_negative |
Possible right shift with negative left-hand-side |
None |
False |
signed_overflow_negative |
Arithmetic computation may cause negative overflow |
None |
False |
signed_overflow_positive |
Arithmetic computation may cause positive overflow |
None |
False |
stack_free |
{name0} released by call to {node0} is a stack or static object |
None |
False |
static_signed_overflow_negative |
Arithmetic computation may cause negative overflow |
None |
False |
static_signed_overflow_positive |
Arithmetic computation may cause positive overflow |
None |
False |
static_unsigned_wraparound_negative |
Arithmetic computation may cause negative wrap-around |
None |
False |
static_unsigned_wraparound_positive |
Arithmetic computation may cause positive wrap-around |
None |
False |
undefined_behaviour |
Undefined behaviour: {} |
None |
False |
undereferenced_arithmetic_out_of_bounds |
Pointer arithmetic on {node0} might create pointer one past the end of {name0} (but not dereferenced) |
None |
False |
undereferenced_out_of_bounds |
Access is one past the end of the array (but not dereferenced) |
None |
False |
undereferenced_possible_indirect_out_of_bounds |
Pointer-indirect access through {node0} might be one past the end accessing {name0} (but not dereferenced) |
None |
False |
undereferenced_possible_out_of_bounds |
Access might be one past the end of the array (but not dereferenced) |
None |
False |
uninit |
Use of uninitialized variable |
None |
False |
unrelated_ptr_comparison |
Comparing unrelated pointers |
None |
False |
unrelated_ptr_subtraction |
Subtracting unrelated pointers |
None |
False |
use_after_free |
Dynamic memory used after it was previously released |
None |
False |
wrong_release |
Resource released using wrong function (allocation used {node0}) |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
abstract_interpretation_div_by_zero¶
abstract_interpretation_div_by_zero : bool = True
abstract_interpretation_maximal_tracked_array_index¶
abstract_interpretation_maximal_tracked_array_index : int = 10
The number of explicit indices in array expressions per routine tracked by the "symbolic expression analysis". For example, consider the following program.
extern signed char a[6];
int main()
{
if (a[2] < 0)
{
a[2]++;
}
if (a[3] < 0)
{
a[3]++;
}
if (a[4] < 0)
{
a[4]++;
}
return 0;
}
If the value of this option is set to 2, the first two array index expressions
encountered in the routine are tracked. Hence, the analysis can use the facts
a[2] < 0 and a[3] < 0 to infer that a[2]++
and a[3]++ do not overflow, but it will not track the third array
access in this routine.
A higher value of the option can cause more consumption of memory and time for the analysis.
abstract_interpretation_out_of_bounds¶
abstract_interpretation_out_of_bounds : bool = False
abstract_interpretation_overflow¶
abstract_interpretation_overflow : bool = False
abstract_interpretation_overflow_unrolling_level¶
abstract_interpretation_overflow_unrolling_level : int = 0
additional_local_array_check¶
additional_local_array_check : bool = True
int example()
{
int a[10];
int b[20];
int uninit_var;
for (int i = 0; i < 10; ++i)
{
L1: a[i] = uninit_var; // use of uninit_var reported
b[i] = i;
}
int result = a[3]; // not reported, since already reported at L1
result += b[15]; // reported; c[] is not (completely) initialized
return result;
}
assume_globals_are_initialized¶
assume_globals_are_initialized : bool = True
check_array_access_with_unknown_index¶
check_array_access_with_unknown_index : bool = False
a[i] with non-literal index
i should be checked as well.
check_non_array_pointers¶
check_non_array_pointers : bool = False
check_signed¶
check_signed : bool = True
check_unsigned¶
check_unsigned : bool = True
compiler_messages_on_undefined¶
compiler_messages_on_undefined
Compiler messages of these types are reported.Type: set[int]
Default:
{1, 1037, 120, 1282, 137, 138, 157, 1665, 167, 171, 172, 1816, 1817, 1818, 192, 2, 28, 2903, 31, 40, 549, 57, 59, 7, 70, 8, 968}
exclude_from_pointer_to_const_param_check¶
exclude_from_pointer_to_const_param_check : set[bauhaus.analysis.config.QualifiedName] = {'__builtin_object_size'}
exclude_very_high_indices¶
exclude_very_high_indices : bool = True
execute_checks_covered_in_other_rules¶
execute_checks_covered_in_other_rules : bool = False
filter_multiple_instances¶
filter_multiple_instances : bool = False
functions_with_ignored_deallocators¶
functions_with_ignored_deallocators : set[str] = set()
maximum_number_of_threads¶
maximum_number_of_threads : int = 0
relevant_expressions¶
relevant_expressions
Which (const / constant) expressions should be considered.Type: RelevantExpressions
Default:
'const_and_compile_time_constant'
Note: this is only relevant for the purely static parts of the analysis. The StaticSemanticAnalysis-based checks for runtime errors will be performed independently.
report_empty_points_to_sets¶
report_empty_points_to_sets : bool = False
report_freed_this_at_call¶
report_freed_this_at_call : bool = False
report_null_this¶
report_null_this : bool = False
report_read_pointer_args_in_calls_to_undefined¶
report_read_pointer_args_in_calls_to_undefined : bool = True
report_unbounded_arrays¶
report_unbounded_arrays : bool = False
extern char buf[];.
report_undereferenced_one_past_the_end¶
report_undereferenced_one_past_the_end : bool = False
report_unknown_index¶
report_unknown_index : bool = False
resources¶
resources
Set of resources to be checked (selection of rules in the Resources group).Type: set[str]
Default:
{'C++ArrayHeapMemory', 'C++HeapMemory', 'CudaAsyncMemory', 'CudaDeviceMemory', 'CudaDriverAsyncMemory', 'CudaHostMemory', 'CudaManagedMemory', 'FileHandle', 'HeapMemory', 'UniquePtrHeapMemory'}
suppress_well_defined_findings¶
suppress_well_defined_findings
Type: SuppressionMode
Default:
'NONE'
Some overflows have well-defined semantics in all C/C++ standard
versions. The typical example is UINT_MAX+1 which is
well-defined as 0 via wraparound. This differs from
INT_MAX+1 which is either undefined or implementation-defined
depending on the considered standard version. Most CPUs will compute
INT_MIN but this wraparound is not guaranteed by any C/C++
standard.
Both cases are overflows and are reported by this rule. However, one might want to suppress messages for the well-defined cases. To suppress these activate this option.
Different C and C++ standard versions differ in what is well-defined, implementation-defined, or undefined. Luckily, if we only consider well-defined and do not discern between implementation-defined and undefined, we end up with only two groups: pre-C++20 and since-C++20.
track_conditional_initialization¶
track_conditional_initialization : bool = True
undefined_in_languages¶
undefined_in_languages
Restricts entries of :attr:`compiler_messages_on_undefined` to the languages and language dialects in which they really are undefined behaviour. A message is reported for a file only if that file was compiled as one of the languages or dialects listed for it. Messages without an entry here are reported regardless of the language.Type: dict[int, set[bauhaus.ir.Language_Type | bauhaus.ir.Language_Dialect_Type]]
Default:
{ 1: {'C', 'CPP98'}, 2: {'C', 'CPP98'} }
use_semantic_analysis¶
use_semantic_analysis : bool = True
witness_paths¶
witness_paths : bool = True
writing_into_pointer_to_const¶
writing_into_pointer_to_const
Names of routines (mapping to parameter index, starting at 0) having a parameter declared as pointer-to-const yet they are still writing into the pointee.Type: dict[bauhaus.analysis.config.QualifiedName, int]
Default:
{ 'cudaMemcpyToSymbol': 0 }
Option Types¶
These types are used by options listed above:
Language_Dialect_Type¶
C90
C99
C11
C18
C23
EMBEDDED_C
CPP98
CPP11
CPP14
CPP17
CPP20
CPP23
CPP26
EMBEDDED_CPP
ASM
CPP_CLI
CPP_CX
Language_Type¶
C
CPLUSPLUS
CPP_CLI
CPP_CX
CSHARP
CUDA
PYTHON
JAVA
ASM
QML
RUST
RESPONSE_FILE
IGNORE_FILE
UNKNOWN
AUTO
RelevantExpressions¶
none
No (additional) checks for overflows in const-expressions or compile time constant expressions.const_expressions_only
Whether the analysis should statically check const-expressions (i.e., const variables and literals) that might have been reduced to a literal during compilation.const_and_compile_time_constant
Whether the analysis should statically check const-expressions (i.e., const variables and literals) as well as compile-time constant expressions (i.e., preprocessor defines, constexprs or literals) that might have been reduced to a literal during compilation.SuppressionMode¶
NONE
Suppress nothing.
PRE_CPP2020
Suppress findings that are well-defined before C++20. These are:
- Positive and negative wrap-arounds of unsigned integers during addition, subtraction, and multiplication
- Conversions from unsigned to unsigned integers
- Wrap-around caused by left-shifting of unsigned integer
CPP2020
Suppress findings that are well-defined since C++20. These are:
- Positive and negative wrap-arounds of unsigned integers during addition, subtraction, and multiplication
- Conversions between signed and unsigned integers
- Wrap-around caused by left-shifting
- Shifting negative integers
Surprising mechanics of C++20 signed narrow integers
Since C++20, casts between signed and unsigned are defined as two-complement wrap-around. Overflows of signed integers are still undefined behavior and are reported by this rule. But, due to integer promotion rules, certain expressions are computed using wider integer types, which can lead to the false impression that this is no longer the case, because no overflow findings are reported there.
Suppose, that the code is compiled on a platform where short
is smaller than or equal to half the size of an int. Very
commonly the sizes are 2 and 4. This assumption is thus true for many
platforms.
In this case, narrow signed integer types such as short or
signed char are first implicitly promoted to int
before the arithmetic operation is executed. Because of this promotion, the
actual operation does not overflow and is thus well-defined. After the
operation, an implicit cast is performed to the narrower type. This cast is
well-defined in C++20 as wrapping around.
Consider the following snippet:
static_assert(sizeof(short) == 2);
static_assert(sizeof(int) == 4);
short a = 0x1000;
short b = 0x1001;
short c = a*b;
C++20 defines c as 0x1000. The reason is that
a*b is implicitly promoted to static_cast<int>
(a)*static_cast<int>(b). After the promotion, the
multiplication does not overflow and yields a well-defined
0x1001000. This number is then implicitly cast to
0x1000 which is also a well-defined operation.
An analogous effect can be observed for signed short addition and
multiplication. Another effect is that it is well-defined to shift by up to
as many bits as int has even if the shifted integer has fewer
bits.
DERIVE_FROM_IR
Derive the language version from the IR compilation flags and suppress findings accordingly.