CBMC
Loading...
Searching...
No Matches
Background Concepts
Author
Martin Brain, Peter Schrammel, Johannes Kloos

The purpose of this section is to explain several key concepts used throughout the CPROVER framework at a high level, ignoring the details of the actual implementation. In particular, we will discuss different ways to represent programs in memory, three important analysis methods and some commonly used terms.

Representations

One of the first questions we should be considering is how we represent programs in such a way that we can easily analyze and reason about them.

As it turns out, the best way to do this is to use a variety of different representations, each representing a different level of abstraction. These representations are designed in such a way that for each analysis we want to perform, there is an appropriate representation, and it is easy to go from representations that are close to the source code to representations that focus on specific semantic aspects of the program.

The representations that the CPROVER framework uses mirror those used in modern compilers such as LLVM and gcc. I will point out those places where the CPROVER framework does things differently, attempting to give rationales wherever possible.

One in-depth resource for most of this section is the classic compiler construction text book ''Compilers: Principles, Techniques and Tools'' by Aho, Lam, Sethi and Ullman.

To illustrate the different concepts, we will consider a small example program. While the program is in C, the general ideas apply to other languages as well - see later sections of this manual to understand how the specific features of those languages are handled. Our running example will be a program that calculates factorials.

/* factorial.c
*
* For simplicity's sake, we just give the forward
* declarations of atoi and printf.
*/
int atoi(const char *);
int printf(const char *, ...);
unsigned long factorial(unsigned n) {
unsigned long fac = 1;
for (unsigned int i = 1; i <= n; i++) {
fac *= i;
}
return fac;
}
/* Error handling elided - this is just for illustration. */
int main(int argc, const char **argv) {
unsigned n = atoi(argv[1]);
printf("%u! = %lu\n", n, factorial(n));
return 0;
}
int main()
Definition example.cpp:18
int printf(const char *format,...)
Definition stdio.c:1513
int atoi(const char *nptr)
Definition stdlib.c:1088

The question of this first section is: how do we represent this program in memory so that we can do something useful with it?

One possibility would be to just store the program as a string, but this is clearly impractical: even finding whether there is an assignment to a specific variable would require significant parsing effort. For this reason, the first step is to parse the program text into a more abstract representation.

AST

The first step in representing a program in memory is to parse the program, at the same time checking for syntax errors, and store the parsing result in memory.

The key data structure that stores the result of this step is known as an Abstract Syntax Tree, or AST for short (cf. Wikipedia). ASTs are still relatively close to the source code, and represent the structure of the source code while abstracting away from syntactic details, e.g., dropping parentheses, semicolons and braces as long as those are only used for grouping.

Considering the example of the C program given above, we first notice that the program describes (in C terms) a single translation unit, consisting of four top-level declarations (the two function forward declarations of atoi and printf, and the function definitions of factorial and main). Let us start considering the specification of atoi. This gives rise to a subtree modeling that we have a function called atoi whose return type is int, with an unnamed argument of type const char *. We can represent this using a tree that has, for instance, the following structure (this is a simplified version of the tree that the CPROVER framework uses internally):

AST for the `atoi` declaration

This graph shows the (simplified) AST structure for the atoi function. The top level says that this is a global entity, namely one that has code (i.e., a function), called atoi and yielding int. Furthermore, it has a child node initiating a parameter list, and there is a node in the parameter list for each parameter, giving its type and name, if a name is given.

Extending this idea, we can represent the structure of the factorial function using ASTs. The idea here is that the code itself has a hierarchical structure. In the case of C, this starts with the block structure of the code: at the top, we start with a block of code, having three children, each being a ''statement'' node:

  1. unsigned long fac = 1
  2. for (unsigned int i = 1; i <= n; i++) { fac *= i }
  3. return fac

The first statement is already a basic statement: we represent it as a local declaration (similar to the global declarations above) of a variable.

AST for `unsigned long fac = 1`

The second statement is a compound statement, which we can decompose further. At the top level, we have a node stating that this is a for statement, with four child nodes:

  1. Another declaration node, declaring variable i.
  2. An expression node, with operator <= and two children giving the LHS as variable i and the RHS as variable n.
  3. An expression node with post-fix operator ++ and a child giving the variable i as argument.
  4. A block node, starting a new code block. This node has one child:
    1. An expression node with top-level operator *= and two child nodes giving the LHS as variable fac and the RHS as variable i. All in all, the AST for this piece of code looks like this:
AST for the `for` loop

Finally, the third statement is again simple: it consists of a return statement node, with a child node for the variable expression fac. Since the AST is very similar to the first AST above, we omit it here. All in all, the AST for the function body looks like this:

AST for the body of `factorial`

Using the AST for the function body, we can easily produce the definition of the factorial function:

AST for `factorial` (full definition)

In the end, we produce a sequence of trees modeling each declaration in the translation unit (i.e., the file factorial.c).

This data structure is already useful: at this level, we can easily derive simple information such as ''which functions are being defined?'', ''what are the arguments to a given function'' and so on.

Symbol tables and variable disambiguation

Nevertheless, for many analyses, this representation needs to be transformed further. In general, the first step is to resolve variable names. This is done using an auxiliary data structure known as the symbol table.

The issue that this step addresses is that the meaning of a variable name depends on a given scope - for instance, in a C program, we can define the variable i as a local variable in two different functions, so that the name i refers to two different objects, depending on which function is being executed at a given point in time.

To resolve this problem, a first transformation step is performed, changing (short) variable names to some form of unique identifier. This ensures that each variable identifier is used only once, and all accesses to a given variable can be easily found by just looking for the variable identifier. For instance, we could change each variable name into a pair of the name and a serial number. The serial number gets increased whenever a variable of that name is declared. In the example, the ASTs for factorial and main after resolving variable names would look roughly like this:

ASTs with resolved variables

Note that the parameter n in factorial and the local variable n in main are now disambiguated as n.1 and n.2; furthermore, we leave the names of global objects as-is. In the CPROVER framework, a more elaborate system is used: local variables are prefixed with the function names, and further disambiguation is performed by adding indices. For brevity, we use indices only.

Further information on ASTs can be found in the Wikipedia page and the materials linked there. Additionally, there is an interesting discussion on StackOverflow about abstract versus concrete syntax trees.

At this level, we can already perform a number of interesting analyses, such as basic type checking. But for more advanced analyses, other representations are better: the AST contains many different kinds of nodes (essentially, one per type of program construct), and has a rather intricate structure.

Intermediate Representations (IR)

The ASTs in the previous section represent the syntax of a program, including all the features of a given programming language. But in practice, most programming languages have a large amount of ''syntactic sugar'': constructs that are, technically speaking, redundant, but make programming a lot easier. For analysis, this means that if we immediately try to work on the initial AST, we would have to handle all these various cases.

To simplify analysis, it pays off to bring the AST into simpler forms, known as intermediate representations (short IR). An IR is usually given as some form of AST, using a more restricted subset or a variant of the original language that is easier to analyze than the original version.

Taking the example from above, we rewrite the program into a simpler form of the C language: instead of allowing powerful control constructs such as while and for, we reduce everything to if and goto. In fact, we even restrict if statements: an if statement should always be of the form if (*condition*) goto *target* else goto *target*;. As it turns out, this is sufficient to represent every C program. The factorial function in our example program can then be rewritten as follows:

unsigned long factorial(unsigned n) {
unsigned long fac = 1;
// Replace the for loop with if and goto
unsigned int i = 1;
for_loop_start:
if (i <= n) goto for_loop_entry else goto for_loop_end;
for_loop_entry:
fac *= i;
i++;
goto for_loop_start;
for_loop_end:
return fac;
}

We leave it up to the reader to verify that both versions of the function behave the same way, and to draw the function as an AST.

In the CPROVER framework, a number of different IRs are employed to simplify the program under analysis into a simple core language step-by-step. In particular, expressions are brought into much simpler forms. This sequence of transformations is described in later chapters.

TODO: Link to corresponding sections.

Control Flow Graphs (CFG)

Another important representation of a program can be gained by transforming the program structure into a control flow graph, short CFG. While the AST focuses more on the syntactic structure of the program, keeping constructs like while loops and similar forms of structured control flow, the CFG uses a unified graph representation for control flow.

In general, for analyses based around Abstract Interpretation (see Abstract Interpretation), it is usually preferable to use a CFG representation, while other analyses, such as variable scope detection, may be easier to perform on ASTs.

The general idea is to present the program as a graph. The nodes of the graph are instructions or sequences of instructions. In general, the nodes are basic blocks: a basic block is a sequence of statements that is always executed in order from beginning to end. The edges of the graph describe how the program execution may move from one basic block to the next. Note that single statements are always basic blocks; this is the representation used inside the CPROVER framework. In the examples below, we try to use maximal basic blocks (i.e., basic blocks that are as large as possible); this can be advantageous for some analyses.

Let us consider the factorial function as an example. As a reminder, here is the code, in IR:

unsigned long fac = 1;
unsigned int i = 1;
for_loop_start:
if (i <= n) goto for_loop_entry else goto for_loop_end;
for_loop_entry:
fac *= i;
i++;
goto for_loop_start;
for_loop_end:
return fac;

We rewrite the code with disambiguated variables (building the AST from it is left as an exercise):

unsigned long fac.1 = 1;
unsigned int i.1 = 1;
for_loop_start:
if (i.1 <= n.1) goto for_loop_entry else goto for_loop_end;
for_loop_entry:
fac.1 *= i.1;
i.1++;
goto for_loop_start;
for_loop_end:
return fac.1;

This function consists of four basic blocks:

  1. unsigned long fac.1 = 1; unsigned int i.1 = 1;
  2. if (i.1 <= n.1) goto for_loop_entry else goto for_loop_end (this block has a label, for_loop_start).
  3. fac.1 *= i.1
    i.1 ++ goto for_loop_start (this block has a label, for_loop_entry).
  4. return fac.1 (this block has a label, for_loop_end).

One way to understand which functions form basic blocks is to consider the successors of each instruction. If we have two instructions A and B, we say that B is a successor of A if, after executing A, we can execute B without any intervening instructions. For instance, in the example above, the loop initialization statement unsigned int i.1 = 1 is a successor of unsigned long fac.1 = 1. On the other hand, return fac.1 is not a successor of unsigned long fac.1 = 1: we always have to execute some other intermediate statements to reach the return statement.

Now, consider the if statement, if (i.1 <= n.1) goto for_loop_entry else goto for_loop_end. This statement has two successors: fac.1 *= i.1 and return fac.1.

Similarly, we say that A is a predecessor of B if B is a successor of A. We find that the if statement has two predecessors, unsigned int i.1 = 1 and goto for_loop_start.

A basic block is a sequence of instructions with the following property:

  1. If B comes directly after A in the sequence, B must be the sole successor of A.
  2. If A comes directly before B in the sequence, A must be the sole predecessor of B.

In particular, each member of the sequence but the first must have exactly one predecessor, and each member of the sequence but the last must have exactly one successor. These criteria explain why we have the basic blocks described above.

Putting everything together, we get a control flow graph like this:

Control flow graph for factorial

The graph can be read as follows: each node corresponds to a basic block. The initial basic block (where the function is entered) is marked with a double border, while those basic blocks that leave the function have a gray background. An edge from a basic block B to a basic block B', means that if the execution reaches the end of B, execution may continue in B'. Some edges are labeled: the edge leaving the comparison basic block with the label true, for instance, can only be taken if the comparison did, in fact, return true.

Note that this representation makes it very easy to interpret the program, keeping just two pieces of state: the current position (which basic block and which line), and the values of all variables (in real software, this would also include parts of the heap and the call stack). Execution proceeds as follows: as long as there are still instructions to execute in the current basic block, run the next instruction and move the current position to right after that instruction. At the end of a basic block, take one of the available outgoing edges to another basic block.

In the CPROVER framework, we often do not construct CFGs explicitly, but instead use an IR that is constructed in a way very similar to CFGs, known as ''GOTO programs''. This IR is used to implement a number of static analyses, as described in sections Frameworks: and Specific analyses:.

SSA

While control flow graphs are already quite useful for static analysis, some techniques benefit from a further transformation to a representation known as static single assignment, short SSA. The point of this step is to ensure that we can talk about the entire history of assignments to a given variable. This is achieved by renaming variables again: whenever we assign to a variable, we clone this variable by giving it a new name. This ensures that each variable appearing in the resulting program is written to exactly once (but it may be read arbitrarily many times). In this way, we can refer to earlier values of the variable by just referencing the name of an older incarnation of the variable.

We illustrate this transformation by first showing how the body of the for loop of factorial is transformed. We currently have:

_
expression: fac.1 *= i.1
expression: i.1 ++

We now give a second number to each variable, counting the number of assignments so far. Thus, the SSA version of this code turns out to be

_
expression: fac.1.2 = fac1.1 * i.1.1
expression: i.1.2 = i.1.1 + 1

This representation now allows us to state facts such as ''i is increasing'' by writing i.1.1 < i.1.2.

At this point, we run into a complication. Consider the following piece of code for illustration:

// Given some integers a, b
int x = a;
if (a < b)
x = b;
return x;

The corresponding control flow graph looks like this:

CFG for maximum function

When we try to transform to SSA, we get:

CFG for maximum function - SSA, attempt

Depending on which path the execution takes, we have to return either x.1 or x.2! The way to make this work is to introduce a function Φ that selects the right instance of the variable; in the example, we would have

CFG for maximum function - SSA using Φ

In the CPROVER framework, we provide a precise implementation of Φ, using explicitly tracked information about which branches were taken by the program. There are also some differences in how loops are handled (finite unrolling in CPROVER, versus a Φ-based approach in compilers); this approach will be discussed in a later chapter.

For the time being, let us come back to factorial. We can now give an SSA using Φ functions:

Control flow graph in SSA for factorial

The details of SSA construction, plus some discussion of how it is used in compilers, can be found in the original paper.

The SSA is an extremely helpful representation when one wishes to perform model checking on the program (see next section), since it is much easier to extract the logic formulas used in this technique from an SSA compared to a CFG (or, even worse, an AST). That being said, the CPROVER framework takes a different route, opting to convert to intermediate representation known as GOTO programs instead.

Field Sensitivity

Control granularity of object accesses.

Field sensitivity is a transformation of the instructions goto-program which mainly replaces some expressions by symbols but can also add assignments to the target equations produced by symbolic execution. The main goal of this transformation is to allow more constants to be propagated during symbolic execution. Note that field sensitivity is not applied as a single pass over the whole goto program but instead applied as the symbolic execution unfolds.

On a high level, field sensitivity replaces member operators, and array accesses with atomic symbols representing a field when possible. In cases where this is not immediately possible, like struct assignments, some things need to be added. The possible cases are described below.

Member access

A member expression struct_expr.field_name is replaced by the symbol struct_expr..field_name; note the use of .. to visually distinguish the symbol from the member expression. This is valid for both lvalues and rvalues. See field_sensitivityt::apply.

Symbols representing structs

In an rvalue, a symbol struct_expr which has a struct type with fields field1, field2, etc, will be replaced by {struct_expr..field_name1; struct_expr..field_name2; …}. See field_sensitivityt::get_fields.

Assignment to a struct

When the symbol is on the left-hand-side, for instance for an assignment struct_expr = other_struct, the assignment is replaced by a sequence of assignments: struct_expr..field_name1 = other_struct..field_name1; struct_expr..field_name2 = other_struct..field_name2; etc. See field_sensitivityt::field_assignments.

Array access

An index expression array[index] when index is constant and array has constant size is replaced by the symbol array[[index]]; note the use of [[ and ]] to visually distinguish the symbol from the index expression. When index is not a constant, array[index] is replaced by {array[[0]]; array[[1]]; …index]. Note that this process does not apply to arrays whose size is not constant, and arrays whose size exceed the bound max_field_sensitivity_array_size. See field_sensitivityt::apply.

Symbols representing arrays

In an rvalue, a symbol array which has array type will be replaced by {array[[0]]; array[[1]]; …}[index]. See field_sensitivityt::get_fields.

Assignment to an array

When the array symbol is on the left-hand-side, for instance for an assignment array = other_array, the assignment is replaced by a sequence of assignments: array[[0]] = other_array[[0]]; array[[1]] = other_array[[1]]; etc. See field_sensitivityt::field_assignments.

Analysis techniques

Bounded model checking

One of the most important analysis techniques by the CPROVER framework, implemented using the CBMC (and JBMC) tools, is bounded model checking, a specific instance of a method known as Model Checking.

The basic question that model checking tries to answer is: given some system (in our case, a program) and some property, can we find an execution of the system such that it reaches a state where the property holds? If yes, we would like to know how the program reaches this state - at the very least, we want to see what inputs are required, but in general, we would prefer having a trace, which shows what statements are executed and in which order.

In general, a trace describes which statements of the program were executed, and which intermediate states were reached. Often, it is sufficient to only provide part of the intermediate states (omitting some entirely, and only mentioning parts that cannot be easily reconstructed in others).

As it turns out, model checking for programs is, in general, a hard problem. Part of the reason for this is that many model checking algorithms strive for a form of ''completeness'' where they either find a trace or return a proof that such a trace cannot possibly exist.

Since we are interested in generating test cases, we prefer a different approach: it may be that a certain target state is reachable only after a very long execution, or not at all, but this information does not help us in constructing test cases. For this reason, we introduce an execution bound that describes how deep we go when analyzing a program.

Model checking techniques using such execution bounds are known as bounded model checking; they will return either a trace, or a statement that says ''the target state could not be reached in n steps'', for a given bound n. Thus, for a given bound, we always get an underapproximation of all states that can be reached: we can certainly find those reachable within the given bound, but we may miss states that can be reached only with more steps. Conversely, we will never claim that a state is not reachable within a certain bound if there is, in fact, a way of reaching this state.

The bounded model checking techniques used by the CPROVER framework are based on symbolic model checking, a family of model checking techniques that work on sets of program states and use advanced tools such as SAT solvers (more on that below) to calculate the set of reachable states. The key step here is to encode both the program and the set of states using an appropriate logic, mostly propositional logic and (fragments of) first-order logic.

In the following, we will quickly discuss propositional logic, in combination with SAT solving, and show how to build a simple bounded model checker. Actual bounded model checking for software requires a number of additional steps and concepts, which will be introduced as required later on.

Propositional logic and SAT solving

Many of the concepts in this section can be found in more detail in the Wikipedia article on Propositional logic.

Let us start by looking at propositional formulas. A propositional formula consists of propositional variables, say x, y and z, that can take the Boolean values true and false, connected together with logical operators (often called junctors), namely and, or and not. Sometimes, one introduces additional junctors, such as xor or implies, but these can be defined in terms of the three basic junctors just described.

Examples of propositional formulas would be ''x and y'' or ''not x or y or z''. We can evaluate formulas by setting each variable to a Boolean value and reducing using the follows rules:

  • x and false = false and x = false or false = not true = false
  • x or true = true or x = true and true = not false = true

An important related question is: given a propositional formula, is there a variable assignment that makes it evaluate to true? This is known as the SAT problem. The most important things to know about SAT are:

  1. It forms the basis for bounded model checking algorithms;
  2. It is a very hard problem to solve in general: it is NP-complete, meaning that it is easy to check a solution, but (as far as we know) hard to find one;
  3. There has been impressive research in SAT solvers that work well in practice for the kinds of formulas that we encounter in model checking. A commonly-used SAT solver is minisat.
  4. SAT solvers use a specific input format for propositional formulas, known as the conjunctive normal form. For details, see the linked Wikipedia page; roughly, a conjunctive normal form formula is a propositional formula with a specific shape: at the lowest level are atoms, which are propositional variables ''x'' and negated propositional variables ''not x''; the next layer above are clauses, which are sequences of atoms connected with ''or'', e.g. ''not x or y or z''. The top layer consists sequences of clauses, connected with ''and''.

As an example in how to use a SAT solver, consider the following formula (in conjunctive normal form):

''(x or y) and (x or not y) and x and y''

We can represent this formula in the minisat input format as:

p cnf 2 3
1 2 0
1 -2 0
1 0
2 0

Compare the Minisat user guide. Try to run minisat on this example. What would you expect, and what result do you get?

Next, try running minisat on the following formula: ''(x or y) and (x or not y) and (not x) and y'' What changed? Why?

Using SAT to reason about data: Bit vectors

So far, we have seen how to reason about simple propositional formulas. This seems to be quite far from our goal of reasoning about the behavior of programs. As a first step, let us see how we can lift SAT-based reasoning to reasoning about data such as machine integers.

Remember the factorial function. It starts with the line

unsigned long fac = 1;