INVARIANT_CONDITION.UNREACH
Invariant expression in a condition, which causes unreachable code
The INVARIANT_CONDITION.UNREACH checker searches for true/false conditions in selection or iteration statements that cause unreachable code issues in their branches. This differs from unreachable code checkers, such as UNREACH.GEN or UNREACH.RETURN which report the unreachable code itself regardless of what caused it. The INVARIANT_CONDITION.UNREACH checker reports only the condition which caused an unreachable code. Since these checkers detect similar issues (though in a slightly different way) it makes sense to turn on INVARIANT_CONDITION.UNREACH only when unreachable code checkers are turned off.
Vulnerability and risk
Invariant conditions can cause unintended program behavior due to a mismatch between the code as written and the intended design. Invariant conditions can also cause confusion during code maintenance or code review.
Code example
enum status_codes {
ST_UNKNOWN = -1,
ST_SUCCESS,
ST_INVALIDARG,
ST_NOTFOUND,
ST_FATAL,
};
extern void report_warn();
extern void report_err();
void report_status(int code)
{
if (code < 0) {
exit(1);
}
if (code >= ST_FATAL) {
report_err();
} else {
report_warn();
if (code == ST_UNKNOWN) { // <== invariant condition
exit(2); // ( <== unreachable code )
}
}
}
Klocwork reports the 'code == ST_UNKNOWN' condition at line 22 as an INVARIANT_CONDITION.UNREACH issue, since the value of the variable 'code' is guarded by a non-negative value at this path by a previous check at line 15. The code branch controlled by this condition at line 13 is unreachable.
To fix this issue, change the order in which the conditions are checked.
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.