In this lesson, you will learn how to distinguish between lexical, syntactic, and semantic static analysis to systematically identify vulnerabilities in your embedded C/C++ codebase.
Static analysis tools examine your source code without executing it. To choose the right tool for safety-critical reliability, you must understand the three levels at which these tools operate.
1. Lexical Analysis (Pattern Matching)
Lexical analysis treats your code as a stream of text. It looks for forbidden patterns or "bad" string sequences. It doesn't understand the structure of your program; it just flags character sequences.
- Use Case: Finding forbidden functions like
strcpyorgetsthat are prone to buffer overflows. - Example: A tool flagging the use of
printfbecause it is forbidden in your specific real-time kernel environment.
2. Syntactic Analysis (Abstract Syntax Trees)
Syntactic analysis checks whether your code adheres to the grammar rules of the C or C++ language. The tool builds an Abstract Syntax Tree (AST) to ensure the structure is valid.
- Use Case: Enforcing coding standards like MISRA C. It verifies if your code follows expected structural patterns, such as ensuring a
switchstatement always includes adefaultcase. - Example: Identifying a missing semicolon or an malformed
if-elseblock that could cause logic misinterpretation by the compiler.
3. Semantic Analysis (Logic and Data Flow)
This is the most advanced level. Semantic analysis tracks the meaning and intent of your code by tracing data flow and control flow across functions. It understands what the variables represent and how they are modified.
- Use Case: Detecting complex bugs like dangling pointers, uninitialized variables, or race conditions.
- Example:
void process_sensor(int* data) {
if (data != NULL) {
*data = 42;
}
*data = 0; // Semantic analysis detects potential NULL pointer dereference
}
While a syntactic tool sees valid C code, a semantic tool understands that the path taken if data is NULL results in an invalid memory access.
Key Takeaway: While lexical tools act like "find-in-files" filters and syntactic tools ensure structural compliance, semantic tools are essential for identifying deep, logic-based vulnerabilities that jeopardize system reliability.