\chapter{Verifying C Programs with SATABS}\label{chap:verifying}

\section{Supported Language Features}\label{sec:features}

Following table gives an overview over the language features of ANSI-C
that \satabs supports. Furthermore, the rightmost column lists the
properties that are automatically checked for the corresponding language
feature.

\begin{maxipage}
\begin{center}
\begin{tabular}{p{0.3\textwidth}p{0.3\textwidth}p{0.3\textwidth}}
\multicolumn{2}{c}{Supported Language Features} & 
\multicolumn{1}{c}{Properties checked}\\\hline
\textbf{Basic Data Types} & All scalar data types float and double 
using fixed-point arithmetic. The bit-width can be adjusted using a command
line option. & \\
\textbf{Integer Operators} & All integer operators, including division and
bit-wise operators. Only the basic floating-point operators. 
& Division by zero, Overflow for signed data types\\
\textbf{Type casts} & All type casts, including conversion between integer and 
floating-point types & Overflow for signed data types\\
\textbf{Side effects} & \satabs allows all compound operators & 
Side effects are checked not to affect variables that are evaluated elsewhere, 
and thus, that the ordering of evaluation does not affect the result.\\
\textbf{Function calls} & Supported by inlining. The locality of parameters 
and non-static local variables is preserved. & 
Functions with a non-void return type must return a value by 
means of the return statement. \\


\textbf{Control flow statements} & \texttt{goto}, \texttt{return}, 
\texttt{break}, \texttt{continue}, \texttt{switch} & \\ 	 
\textbf{Non-Determinism} & User-input is modeled by means of non-deterministic 
choice functions & \\	 
\textbf{Assumptions and Assertions} & Only standard ANSI-C expressions are 
allowed as assertions. & Assertions are verified to be true for all possible 
non-deterministic choices given that any assumption executed prior to the 
assertion is true.\\
\end{tabular}
\end{center}
\end{maxipage}


\newpage
\begin{maxipage}
\begin{center}
\begin{tabular}{p{0.3\textwidth}p{0.3\textwidth}p{0.3\textwidth}}
\textbf{Arrays} & Multi-dimensional arrays and dynamically-sized arrays are 
supported & Lower and upper bound of arrays, even for arrays with 
dynamic size\\
\textbf{Structures} & Arbitrary, nested structure types; may be recursive by 
means of pointers; incomplete arrays as last element of structure are allowed\\
\textbf{Unions} & Support for named unions, anonymous union members are 
currently not supported & \satabs checks that unions are not used for type 
conversion, i.e., that the member used for reading is the same as used for 
writing last time.\\
\textbf{Pointers} & Dereferencing & When a pointer is dereferenced, \satabs 
checks that the object pointed to is still alive and of matching type. 
If the object is an array, the array bounds are checked.\\
& Pointer arithmetic & \\
& Relational operators on pointers &
\satabs checks that the two operands point to the same object.\\
& Pointer Type Casts & Upon dereferencing, the type of the object and 
the expression are checked to match\\
& Pointers to Functions & The offset within the object is checked to be zero\\
\textbf{Dynamic Memory} & \texttt{malloc} and \texttt{free} are supported. 
The argument of \texttt{malloc} may be a nondeterministically chosen, 
arbitrarily large value. & Upon dereferencing, the object pointed to must 
still be alive. The pointer passed to \texttt{free} is checked to point to 
an object that is still alive. \satabs can check that all dynamically 
allocated memory is deallocated before exiting the program 
(''memory leaks'').\\
\textbf{Concurrency} &
\texttt{pthread\_create}, \texttt{pthread\_\-mu\-tex\_\-lock}, and
\texttt{pthread\_\-mu\-tex\_\-un\-lock} are supported. Depending
on the model checker for the Boolean program, unbounded
thread creation is permitted. &
Optionally, \satabs can check for data races.
Assertions are checked for arbitrary thread
interleavings.
\end{tabular}
\end{center}
\end{maxipage}

\newpage
\section{Using the Command Line Interface}
\label{sec:usage}

This section explains the usage of the command line version of \satabs.
The executable \texttt{satabs} is called with a set of (optional) parameters,
which are described below, followed by the file(s) that shall be verified.
Currently, \satabs cannot verify the files of the program under 
test separately. If a program comprises more than one file, then all these
files have to be verified in one step by providing all file names in one
single command line.

\emph{Example}:

\texttt{satabs --show-claims file1.c file2.c}

This call instructs \satabs to generate and display a list of claims for
the program that is contained in \texttt{file1.c} and \texttt{file1.c}.
If, for instance, you wanted to verify the 2$^{nd}$ claim in this list, you
could do this by calling 

\texttt{satabs --claim 2 file1.c file2.c}

Verifying claims separately is highly recommended for reasons of
scalability.

\subsection{\satabs Parameters}
\label{sec:parameters}

There are several command line parameters that allow you to control
the behaviour of \satabs. We divide them into two groups: The
switches in the first group have an impact on how \satabs actually
behaves. The remaining switches tell \satabs to provide more
information and are therefore useful for debugging or inspecting the
verification results. Calling \texttt{satabs --help} lists the
switches described below.

\noindent
\textbf{Parameters to modify behavior}

\begin{tabular}{p{0.3\textwidth}p{0.64\textwidth}}
  \texttt{--16, --32} & The \texttt{int} type of the system you run
  your program on is assumed to have a size of 16 bits (and 32 bits,
  respectively). This
  information is necessary in order to model overflows accurately.\\
  \texttt{--function} name & Set the name of the main function (i.e.,
  the entry point of the program). By
  default, \texttt{main} will be considered to be the main function.\\
  \texttt{--claims <n>} & Verify only a single claim. \texttt{<n>}
  denotes an index into the list of claims that \satabs prints
  when called with the parameter \texttt{--show-claims}. 
  \emph{It is recommended
  to verify claims separately in order to avoid scalability problems.}\\
  \texttt{--modelchecker} name & Specify the model checker that \satabs
  shall use. Currently the values \texttt{boppo}, \texttt{cadence-smv},
  \texttt{nusmv}, \texttt{cmu-smv}, \texttt{spin}, and \texttt{satmc} are
  supported.\\
  \texttt{--iterations} \# & Allows you to specify the maximum number
  of refinement iterations. \emph{By default, the number of iterations
  is 50.}\\
\end{tabular}

\noindent
\textbf{Parameters to increase verbosity}

\begin{tabular}{p{0.3\textwidth}p{0.64\textwidth}}
  \texttt{--show-claims} & Lists the claims (see Section~\ref{sec:properties})
  that \satabs will try to verify for the given program.\\
  \texttt{--show-goto-program} & Allows you to inspect the ``goto-program''
  that corresponds to your input program. Goto-programs correspond to
  the original input program, but the function calls have been inlined,
  and control flow statements have been replaced by conditional jumps
  (``guareded \texttt{goto}s'') to basic blocks.\\
  \texttt{--show-value-sets} & Show the data used for pointer analysis
\end{tabular}

\section{Model Checking C Programs}

Similar to unit testing, the model checking approach requires 
the user to clearly define what parts of the program should
be tested. This requirement has following reasons:
\begin{itemize}
  \item Despite recent advances, the size of the programs that
    model checkers can cope with is still restricted.
  \item Typically, you want to verify \emph{your} program and
    not the libraries that it uses (these are usually assumed
    to be correct).
  \item \satabs cannot verify binary libraries. 
  \item \satabs does not provide a model for the hardware
    (e.g., hard disk, input/output devices) the tested program
    runs on. Since \satabs is supposed to examine the
    behaviour of the tested program for \emph{all} possible inputs
    and outputs, it is reasonable to model input and output
    by non-deterministic choice.
\end{itemize}

This section provides an introduction to model checking ``real''
C programs with \satabs. It starts with a small example
that is based on Linux device drivers.

\subsection{Example: Reference Counting in Linux Device Drivers}
\label{example:driver}

Microsoft's \textsc{Slam}\footnote{\url{http://research.microsoft.com/SLAM}}
toolkit has been successfully used to find bugs in Windows
device drivers. \textsc{Slam} automatically verifies device driver
whether a device driver adheres to a specifications. 
\textsc{Slam} provides a test harness for
device drivers that calls the device driver dispatch routines
in a non-deterministic order. Therefore, the model checker  
examines all combinations of calls. Motivated by the success
this approach, we provide an example based on Linux device 
drivers.

Dynamically loadable modules enable the Linux Kernel to load
device drivers on demand and to release them when they are not
needed anymore. When a device driver is registered, the kernel
provides a major number that is used to uniquely identify the
device driver. The corresponding device can be accessed through
special files in the filesystem; they are conventionally located
in the \texttt{/dev} directory. If a process accesses a device 
file the kernel calls the corresponding \texttt{open}, \texttt{read}
and \texttt{write} functions of the device driver. Since a driver
must not be released by the kernel as long as it is used by
at least one process, the device driver must maintain a usage counter
(in modern Linux kernels, this is done automatically, however, drivers
that must maintain backward compatibility have to adjust this count).

We provide a skeleton of such a driver. The driver contains following
functions:
\begin{enumerate}
  \item \texttt{register\_chrdev}: (in \texttt{spec.c}, 
    Figure~\ref{fig:spec_c}) 
    Registers a character device. In
    our implementation, the function sets the variable \texttt{usecount}
    to zero and returns a major number for this device (a constant, if
    the user provides 0 as argument for the major number, and the value
    specified by the user otherwise).
  \item \texttt{unregister\_chrdev}: (in \texttt{spec.c},
    Figure~\ref{fig:spec_c})
    Unregisters a character device.
    This function asserts that the device is not used by any process
    anymore (we use the macro \texttt{MOD\_IN\_USE} to check this).
  \item \texttt{dummy\_open}: (in \texttt{driver.c}, 
    Figure~\ref{fig:driver_c}) This function
    increases the \texttt{usecount}. If the device is locked by
    some other process \texttt{dummy\_open} returns -1. Otherwise
    it locks the device for the caller.     
  \item \texttt{dummy\_read}: (in \texttt{driver.c}, 
    Figure~\ref{fig:driver_c}) This function
    ``simulates'' a read access to the device. In fact it does 
    nothing, since we are currently not interested in the potential buffer
    overflow that may result from a call to this function.
    Note the usage of
    the function \texttt{nondet\_int} (in line~\ref{line:nondet}): 
    This is an internal \textsc{SatAbs}
    function that nondeterministically returns an arbitrary integer
    value. The function \texttt{assume} (line~\ref{line:assume})
    tells \textsc{SatAbs} to ignore
    all traces that do not adhere to the given assumption. Therefore,
    whenever the lock is held, \texttt{dummy\_read} will 
    return a value between 0 and  \texttt{max}. If the lock is not held
    then \texttt{dummy\_read} returns -1.
  \item \texttt{dummy\_release}: (in \texttt{driver.c}) If the lock
    is held, then \texttt{dummy\_release} decreases
    the \texttt{usecount}, releases the lock, and returns 0. Otherwise,
    the function returns -1.
\end{enumerate}

\begin{figure}[t]
\codebox{%
\li\texttt{int usecount;}\\
\li\texttt{int dummy\_major;}\\
\li\texttt{extern int locked;}\\
\\
\li\texttt{int register\_chrdev (unsigned int major, const char* name)}\\
\li\texttt{\{}\\
\li\>\texttt{usecount = 0;}\\
\li\>\texttt{if (major == 0)}\\
\li\>\>\texttt{return MAJOR\_NUMBER;}\\
\li\>\texttt{return major;}\\
\li\texttt{\}}\\
\\
\li\texttt{int}\\ 
\texttt{unregister\_chrdev (unsigned int major, const char* name)}\\
\li\texttt{\{}\\
\li\>\texttt{if (MOD\_IN\_USE) \{}\\
\li\texttt{ERROR:}\>\>\texttt{assert (0);}\label{line:assert}\\
\li\>\texttt{\}}\\
\li\>\texttt{else}\\
\li\>\>\texttt{return 0;}\\
\li\texttt{\}}\\
}
\caption{Sources (\texttt{spec.c}) for the (un)registering
  of device drivers\label{fig:spec_c}}
\end{figure}

\begin{figure}[t]
\codebox{%
\li \texttt{extern int dummy\_major;}\\
\li \texttt{int locked;}\\
\li \texttt{int init\_module (void) \{}\\
\li \>\texttt{locked = FALSE;}\\
\li \texttt{\}}\\
\\
\li \texttt{int dummy\_open (struct inode *inode, struct file *filp) \{}\\
\li \>\texttt{assert (MAJOR (inode->i\_rdev) == dummy\_major);}
\label{line:claim1}\\
\li \>\texttt{MOD\_INC\_USE\_COUNT;}\\
\li \>\texttt{if (locked)}\\
\li \>\>\texttt{return -1;}\\
\li \>\texttt{locked = TRUE;}\\
\li\>\texttt{return 0; /* success */}\\
\li \texttt{\}}\\
\\
\li \texttt{unsigned int dummy\_read (struct file *filp,}\\
\>\>\>\>\>\texttt{char *buf, int max) \{}\\
\li\>\texttt{int n;}\\
\li\>\texttt{if (locked) \{}\\
\li\>\>\texttt{n = nondet\_int ();}\label{line:nondet}\\
\li\>\>\texttt{assume ((n >= 0) \&\& (n <= max));}\label{line:assume}\\
\li\>\>\texttt{/* writing to the buffer is not modeled here */}\\
\li\>\>\texttt{return n;}\\
\li\>\texttt{\}}\\
\li\>\texttt{return -1;}\\
\li\texttt{\}}\\
\\
\li\texttt{int dummy\_release (struct inode *inode, }\\
\>\>\>\>\>\texttt{struct file *filp) \{}\\
\li\>\texttt{if (locked) \{}\\
\li\>\>\texttt{MOD\_DEC\_USE\_COUNT;}\\
\li\>\>\texttt{locked = FALSE;}\\
\li\>\>\texttt{return 0;}\\
\li\>\texttt{\}}\\
\li\>\texttt{return -1;}\\
\li\texttt{\}}\\
}%
  \caption{Sources (\texttt{driver.c}) for the ``dummy'' device driver
    \label{fig:driver_c}}
\end{figure}

We now want to check if any \emph{valid} sequence of calls of the 
dispatch functions (Figure~\ref{fig:driver_c}) can lead to the violation 
of the assertion in line~\ref{line:assert} in Figure~\ref{fig:spec_c}.
Obviously, a call to \texttt{dummy\_open} that is immediately followed
by a call to \texttt{unregister\_chrdev} violates the assertion.
Therefore, we rule out this invalid sequence of calls by ensuring
(see line~\ref{line:while} in Figure~\ref{fig:harness})
that no device is unregistered while still being locked.

The model checking harness that calls the dispatching functions is 
shown in Figure~\ref{fig:harness}. 

\begin{figure}[t]
\codebox{%
\li\texttt{int main (int argc, char** argv) \{}\\
\li\>\texttt{int rval, size;}\\
\li\>\texttt{struct file my\_file;}\\
\li\>\texttt{char *buffer; /* we do not model this buffer */}\\
\li\>\texttt{struct inode inode;}\\
\li\>\texttt{unsigned char random;}\\
\\
\li\>\texttt{dummy\_major = register\_chrdev (0, "dummy");}\\
\li\>\texttt{inode.i\_rdev = dummy\_major $<<$ MINORBITS;}\\
\\
\li\>\texttt{init\_module ();}\\
\li\>\texttt{/* assign arbitrary values */}\\
\li\>\texttt{my\_file.f\_mode = nondet\_uint ();}\\
\li\>\texttt{my\_file.f\_pos  = nondet\_uint ();}\\
\\
\li\>\texttt{do \{}\\
\li\>\>\texttt{random = nondet\_uchar ();}\label{line:random}\\
\li\>\>\texttt{assume (0 <= random \&\& random <= 3);}\label{line:assm_rand}\\
\\
\li\>\>\texttt{switch (random) \{}\\
\li\>\>\texttt{case 1:}\\
\li\>\>\>\texttt{rval = dummy\_open (\&inode, \&my\_file);}\\
\li\>\>\>\texttt{break;}\\
\li\>\>\texttt{case 2:}\\
\li\>\>\>\texttt{count = dummy\_read (\&my\_file, buffer,}\\
\>\>\>\>\>\>\>\texttt{BUF\_SIZE);}\\
\li\>\>\>\texttt{break;}\\
\li\>\>\texttt{default:}\\
\li\>\>\>\texttt{dummy\_release (\&inode, \&my\_file);}\\
\li\>\>\texttt{\}}\\
\li\>\texttt{\} while (random $\vert\vert$ locked);}\label{line:while}\\
\\
\li\>\texttt{cleanup\_module ();}\\
\li\>\texttt{unregister\_chrdev (dummy\_major, "dummy");}\label{line:unreg}\\
\\
\li\>\texttt{return 0;}\\
\li\texttt{\}}\\
}
\caption{Sources for the model checking harness\label{fig:harness}}
\end{figure}

The function \texttt{main} in \texttt{spec.c} gives an example of how these functions are
called. First, a character device ``\texttt{dummy}'' is registered.
The major number is stored in the \texttt{inode} structure of the
device. The values for the file structure are assigned non-deterministically.
In line~\ref{line:random} 
the variable \texttt{random} is assigned non-deterministically.
Subsequently, in line~\ref{line:assm_rand}, the value of \texttt{random}
is restricted to be $0\leq$\texttt{random}$\leq 3$ by a call to
\texttt{assume}. Whenever the value of \texttt{random} is
not in this interval, the corresponding execution trace is simply 
pruned by \satabs. Depending on the value of \texttt{random}, the
harness calls either \texttt{dummy\_open}, \texttt{dummy\_read} or
\texttt{dummy\_close}. Therefore, 
if there is a sequence of calls to these three
functions that leads to a violation of the assertion in 
\texttt{unregister\_chrdev} in line~\ref{line:unreg}, then \satabs
will eventually consider it.

If we ask \texttt{satabs} to show us the verification claims 
(\texttt{--show-claims}) 
for our example, we obtain 
\begin{enumerate}
  \item \emph{Claim 1}: In File \texttt{driver.c}
    (Figure~\ref{fig:driver_c}), line~\ref{line:claim1}:
    assertion\\ 
    \texttt{(*inode).i\_rdev $>>$ 8 == dummy\_major}
  \item \emph{Claim 2}: In File \texttt{spec.c} (Figure~\ref{fig:spec_c}), 
    line~\ref{line:assert}: assertion\\
    \texttt{FALSE}
\end{enumerate}

It seems obvious that claim 1 can never be violated. \satabs confirms
this assumption: We call

\texttt{satabs --claim 1 driver.c spec.c}

and \satabs reports \texttt{VERIFICATION SUCCESSFUL} after a few iterations.
However, if we try to verify claim 2, \satabs reports that
the property in line~\ref{line:assert} in file \texttt{spec.c} 
(Figure~\ref{fig:spec_c}), function \texttt{unregister\_chrdev} is violated
(i.e., the assertion is \texttt{FALSE}, therefore the 
\texttt{VERIFICATION FAILED}). Furthermore, \satabs provides a detailed
description of the counterexample (i.e., the execution trace that violates
the property). On this trace, \texttt{dummy\_open} is called \emph{twice},
leading to a \texttt{usecount} of 2 (the second call of course fails with
\texttt{rval=-1}, but the counter is increased nevertheless). Then,
\texttt{dummy\_release} is called to release the lock on the device.
Finally, the loop is left and the call to \texttt{unregister\_chrdev}
results in a violation of the assertion (since \texttt{usecount} is still 1,
even though \texttt{locked=0}).

\subsection{The Eclipse User Interface of SATABS}
\label{sec:eclipse}
Many readers will agree that command line interfaces are a bit archaic
nowadays. Therefore, we provide a user interface for \satabs that
integrates the command line tool seamlessly into 
Eclipse\footnote{Eclipse is an open-sourced integrated development 
environment and can be downloaded from \url{http://www.eclipse.org}.}. 
We assume that you have already installed Eclipse as well as the
\satabs plugin. The  installation of the plugin is covered by chapter
\ref{chap:installation}, and installation instructions for Eclipse can
be found on the Eclipse homepage. This section provides a short, step by step
introduction to the user interface and is based on the same example
as the previous section.

\begin{enumerate}

\item Start Eclipse.
\item Create a new \satabs project as shown in 
Figure~\ref{fig:eclipse_create_new}. Name your project \texttt{DummyDriver}.

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{0.5\textwidth}{!}{\includegraphics{eclipse_satabs_newproject}}
\end{center}
\end{maxipage}
\caption{Creating a new \satabs project.
\label{fig:eclipse_create_new}}
\end{figure}

\item Once you have created a \satabs project, right click on the
element \texttt{DummyDriver} in the Eclipse Navigator (or, alternatively,
click on the File menu) and select \emph{New} $\rightarrow$ \emph{New Task}
to create a new \satabs task. Name the task \texttt{usecount}.

\item Double click the element \texttt{usecount.tsk} in the Navigator
to show the Eclipse view that provides the settings for this task.
Figure~\ref{fig:eclipse_select_file} shows the \emph{Files Selection}
tab, which allows you to select the source files you want to run \satabs on.
Click on the \emph{Change} button to select the directory where the source
files you want to verify are located. Choose the driver example described
in the previous section.

\item Select the source files \texttt{spec.c} and \texttt{driver.c}
(see Figure~\ref{fig:eclipse_select_file}). Do not
select the header files, as the C preprocessor already includes
the files.

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{\textwidth}{!}{\includegraphics{eclipse_select_file}}
\end{center}
\end{maxipage}
\caption{Selecting source files using the Eclipse plugin for SATABS
\label{fig:eclipse_select_file}}
\end{figure}

\item The \emph{Includes and Defines} tab can be used to specify
include paths and add definitions. This is useful if you want to
replace the standard header files by a specific, \satabs enhanced
version. (Due to the GNU extensions to C, \satabs fails to parse
some of the GCC header files.) In a later section, we provide
a more complex example where this is necessary.

\item The \emph{Options} tab (see Figure~\ref{fig:eclipse_satabs_options})
allows you to specify the command line options for \satabs. This
tab reflects exactly the parameters presented in Section~\ref{sec:usage}.
Make sure that checking of assertions is activated.

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{\textwidth}{!}{\includegraphics{eclipse_satabs_options}}
\end{center}
\end{maxipage}
\caption{Specifying the command line options for SATABS
\label{fig:eclipse_satabs_options}}
\end{figure}

\item Create a launch configuration by clicking 
  the green run button 
  (\resizebox{0.7cm}{!}{\includegraphics{eclipse_satabs_launch}}).
  Figure~\ref{fig:eclipse_satabs_run} shows the dialog that allows
  you to create a new run configuration for \satabs. Name
  the new configuration \texttt{Satabs} and make sure that
  the \texttt{satabs} executable is selected (not \texttt{cbmc}).

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{\textwidth}{!}{\includegraphics{eclipse_satabs_run}}
\end{center}
\end{maxipage}
\caption{Running SATABS in Eclipse
\label{fig:eclipse_satabs_run}}
\end{figure}

\item Now run \satabs on \texttt{usecount.tsk} by clicking 
  \resizebox{0.7cm}{!}{\includegraphics{eclipse_satabs_launch}}
  again. \satabs generates two claims for the driver example, one
  for each assertion.

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{\textwidth}{!}{\includegraphics{eclipse_satabs_assertion}}
\end{center}
\end{maxipage}
\caption{Using SATABS to verify an assertion
\label{fig:eclipse_satabs_assert1}}
\end{figure}

\item Verify the first assertion\footnote{In the source file view,
  the assertion is highlighted yellow, indicating that it has not
  been checked so far.} by clicking on \texttt{driver.c}
  with the right mouse button
  and selecting \emph{Check Selection}. As in the previous section,
  \satabs takes a few seconds the verify that the assertion cannot
  be violated. This is indicated by the symbol 
  \resizebox{0.5cm}{!}{\includegraphics{eclipse_satabs_ok}} that
  is displayed in the left-most column of the claim. Furthermore, assertions that
  have already been verified are highlighted in green in 
  the source file.

\item Repeat the same step for the second assertion. This time, 
  \satabs takes a bit longer to come to a conclusion.
  The log view in Figure~\ref{fig:eclipse_satabs_running} shows that 
  \satabs needs several refinement abstraction iterations.
  After some time, \satabs should report that the claim can be
  violated (see Figure~\ref{fig:eclipse_satabs_stepping}).

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{\textwidth}{!}{\includegraphics{eclipse_satabs_running}}
\end{center}
\end{maxipage}
\caption{SATABS is checking an assertion (iterations shown in log)
\label{fig:eclipse_satabs_running}}
\end{figure}

\item \satabs provides a detailed execution trace that explains
  how the assertion can be violated. The Trace view shown in
  Figure~\ref{fig:eclipse_satabs_stepping} can be used to step
  through the counterexample and provides the values of the
  variables in each step. Since the program is not actually 
  executed,\footnote{Therefore, you cannot change the
    values of the variables, as you can do in a debugger.} 
  you can step forwards as well as backwards, a feature
  which makes it much easier to understand the counterexample and
  find the error in the program.

\begin{figure}[h]
\begin{maxipage}
\begin{center}
  \resizebox{\textwidth}{!}{\includegraphics{eclipse_satabs_stepping}}
\end{center}
\end{maxipage}
\caption{Stepping through a counterexample in Eclipse
\label{fig:eclipse_satabs_stepping}}
\end{figure}

\end{enumerate}

\subsection{Example: Buffer Overflow in a Mail Transfer Agent}
\label{example:aeon}

The example presented in Section~\ref{example:driver} is obviously
a toy example and can hardly be used to convince your project
manager to use static verification in your next project. Even though
we recommend to use formal verification and specification already in
the early phases of your project, 
the sad truth is that in most projects verification (of any kind) 
is still pushed to the very end of the development
cycle. Therefore, this section is dedicated to the verification of
legacy code. However, the techniques presented here can also be used
for unit testing.

We explain how to model check \textsc{Aeon}\footnote{(available for 
download on the \satabs{} homepage and on
\url{http://freshmeat.net/projects/aeon/})} version 0.2a, 
a small mail transfer agent written by Piotr Benetkiewicz. 
freshmeat.net claims that \textsc{Aeon} is
a ``good choice for \emph{hardened} or minimalistic boxes''.

Our first naive attempt to verify \textsc{Aeon} using 

\texttt{satabs --show-claims aeon.c base64.c lib\_aeon.c}

fails due to the following reasons:
\begin{enumerate}
  \item \emph{Parsing errors}. On some of the architectures that
    \satabs{} supports, the frontend of \satabs{} fails to parse
    the ANSI-C standard header files that are distributed with your 
    compiler of choice (e.g., GCC makes use of extensions of the
    C programming language that cannot be handled by \satabs{}).
  \item \emph{Missing library functions}. As already stated on
    page~\pageref{lbl:library_functions}, \satabs{} is unable
    to find the source code for library functions like \texttt{strcmp},
    \texttt{getenv} and \texttt{strtok}.
\end{enumerate}

To solve the first of these problems, we provide a set of header
files that are suitable for the \satabs{} C parser. The header
files can be downloaded from the \satabs{} homepage. Assuming
that you have unpacked these files to the directory 
\texttt{../include} (relative to the source files of \textsc{Aeon})
you can now instruct \satabs{} to use these header files as follows:

\texttt{satabs --show-claims -I ../include aeon.c base64.c lib\_aeon.c}

After complaining that the bodies of approximately 30 library functions are
missing, \satabs{} will provide more than 150 claims for \textsc{Aeon}.

Now, do you have to provide a body for all missing library functions?
There is no easy answer to this question, but a viable answer would
be ``most likely not''. It is necessary to understand how \satabs{} 
handles functions without bodies: It simply assumes that such a function
returns an arbitrary value, but that no other
locations than the one on the left hand side of the assignment are
changed. Obviously, there are cases in which this assumption is
unsound, since the function potentially modifies all memory locations
that it can somehow address. 
Consider the first few lines of the \texttt{main} function 
of \textsc{Aeon} in Figure~\ref{fig:aeon_main_c} and the
function \texttt{getConfig} in Figure~\ref{fig:aeon_getconfig_c}.
The function \texttt{getConfig} makes calls to 
\texttt{strcpy}, \texttt{strcat}, \texttt{getenv}, \texttt{fopen},
\texttt{fgets}, and \texttt{fclose}. 
It is very easy to provide an implementation for the functions from
the string library (\texttt{string.h}), and we do so in
Figure~\ref{fig:aeon_str_stubs_c}. 

\begin{figure}[h]
\codebox{%
\li\texttt{int main(int argc, char **argv)}\\
\li\texttt{\{}\\
\li\>\texttt{char settings[MAX\_SETTINGS][MAX\_LEN];}\\
\li\>\ldots\\
\li\>\texttt{numSet = getConfig(settings);}\\
\li\>\texttt{if (numSet == -1) \{}\\
\li\>\>\texttt{logEntry(\"Missing config file!\");}\\
\li\>\>\texttt{exit(1);}\\
\li\>\texttt{\}}\\
\li\>\ldots

}%
\caption{First few lines of \texttt{main} of \textsc{Aeon}
  (\texttt{aeon.c})\label{fig:aeon_main_c}}
\end{figure}


\begin{figure}[h]
\codebox{%
\li\texttt{/* reading rc file, handling missing options */}\\
\li\texttt{int getConfig(char settings[MAX\_SETTINGS][MAX\_LEN])}\\
\li\texttt{\{}\\
\li\>\texttt{char home[MAX\_LEN];}\\
\li\>\texttt{FILE *fp;				/* .rc file handler */}\\
\li\>\texttt{int numSet = 0;			/* number of settings */}\\
\li\>\label{line:home}\texttt{strcpy(home, getenv("HOME"));	/* get home path */}\\
\li\>\texttt{strcat(home, "/.aeonrc");		/* full path to rc file */}\\
\li\>\texttt{fp = fopen(home, "r");}\\
\li\>\texttt{if (fp == NULL) return -1; 	/* no cfg - ERROR */}\\
\li\>\>\texttt{while (fgets(settings[numSet], MAX\_LEN-1, fp)}\\
\li\>\>\>\texttt{\&\& (numSet < MAX\_SETTINGS)) numSet++;}\\
\li\>\texttt{fclose(fp);}\\
\li\>\texttt{return numSet;}\\
\li\texttt{\}}\\
}%
\caption{Function \texttt{getConfig} of \textsc{Aeon}
  (\texttt{lib\_aeon.c})\label{fig:aeon_getconfig_c}}
\end{figure}


\begin{figure}[t]
\codebox{%
\li\texttt{char *strcpy (char *dest, const char *src)}\\
\li\texttt{\{}\\
\li\>\texttt{int i;}\\
\li\>\texttt{for (i = 0 ;; i++) \{}\\
\li\>\>\texttt{dest[i] = src[i];}\\
\li\>\>\texttt{if (src[i] == '$\backslash$0')}\\
\li\>\>\>\texttt{break;}\\
\li\>\texttt{\}}\\
\li\texttt{\}}\\
\\
\li\texttt{char *strcat(char *dest, const char *src)}\\
\li\texttt{\{}\\
\li\>\texttt{int i, j;}\\
\li\>\texttt{i = 0; j = 0;}\\
\li\>\texttt{while (dest[i] != '$\backslash$0')}\\
\li\>\>\texttt{i++;}\\
\li\>\texttt{do \{}\\
\li\>\>\texttt{dest[i] = src[j];}\\
\li\>\>\texttt{i++; j++;}\\
\li\>\texttt{\} while (src[j] != '$\backslash$0');}\\
\li\>\texttt{return dest;}\\
\li\texttt{\}}\\
}
\caption{Functions \texttt{strcpy} and \texttt{strcat}
  (\texttt{stubs.c})\label{fig:aeon_str_stubs_c}}
\end{figure}

The implementation of \texttt{getenv} is not so straight forward.
The man-page of \texttt{getenv} (which we obtain by entering
\texttt{man 3 getenv} in a Unix or cygwin command prompt) tells us:

\texttt{`getenv'}  searches  the  list  of environment 
variable names and values
(using the global pointer \texttt{"`char **environ'" }) 
for a variable whose name
matches  the  string  at \texttt{NAME}. If a variable name matches, 
\texttt{`getenv'} returns a pointer to the associated value.

\satabs{} has no information whatsoever about the content of
\texttt{environ}. Even if \satabs{} could access the
environment variables on your computer, a successful verification
of \textsc{Aeon} would then only guarantee that the claims for
this program hold on your computer with a specific set of
environment variables. We have to assume that \texttt{environ}
contains environment variables that have an arbitrary content
of arbitrary length. The content of environment
variables is not only arbitrary but could be malefic, since it
can be modified by the user.

\satabs{} provides several functions to model user input, one
of which, namely \texttt{nondet\_uint}, is used in
the implementation of \texttt{getenv} in Figure~\ref{fig:aeon_getenv_c}.
The prototype declaration of the function \texttt{nondet\_uint} tells
us that \texttt{nondet\_uint} will return an unsigned integer.
Since we do not provide a body to this function, \satabs{} will
consider all possible return values. In Figure~\ref{fig:aeon_getenv_c}
we use \texttt{nondet\_uint} to determine the length of the the
string that \texttt{getenv} returns. The subsequent call to
\texttt{assume} guarantees that \texttt{buf\_size} is at least
one (since we need to zero-terminate the string) and is bounded
by \texttt{SATABS\_MAX\_BUF\_LEN}. In our first approximation
of the behaviour of \texttt{getenv} we completely ignore the 
content of the string.

\begin{figure}[t]
\codebox{%
\li\texttt{unsigned int nondet\_uint (void);}\\
\li\texttt{\#define SATABS\_MAX\_BUF\_LEN (65535)}\\
\\
\li\texttt{char *getenv(const char *name)}\\
\li\texttt{\{}\\
\li\>\texttt{char* buffer;}\\
\li\>\texttt{size\_t buf\_size = nondet\_uint ();}\\
\li\>\texttt{assume (buf\_size > 1}\\
\li\>\>\texttt{\&\& buf\_size <= SATABS\_MAX\_BUF\_LEN+1);}\\
\li\>\texttt{buffer = (char*)malloc (buf\_size*sizeof(char));}\\
\li\>\texttt{buffer[buf\_size-1]=0;}\\
\li\>\texttt{return buffer;}\\
\li\texttt{\}}
}%
\caption{Function \texttt{getenv}
  (\texttt{stubs.c})\label{fig:aeon_getenv_c}}
\end{figure}

We could model the function \texttt{fgets} in a similar manner, but
before we do this, let us have another look at the claims that 
\texttt{Satabs} generates if we provide the implementations from
the string library and for \texttt{getenv}. (The file \texttt{stubs.c}
can be downloaded from the \satabs{} homepage.)

\texttt{satabs --show-claims -I ../include aeon.c base64.c $\backslash$}\\
\texttt{lib\_aeon.c ../stubs/stubs.c}

Now \satabs{} will generate approximately 700 claims. Most of these
claims require that we verify that the upper and lower bounds of
buffers or arrays are not violated. Let us look at the first few
claims that \satabs{} generates:

\begin{itemize}
\item Claim 4:\\
  file stubs.c line 8 column 10 function c::strcpy\\
  dereference failure: array `home' lower bound\\
  \texttt{!(i $<$ 0) $\vert\vert$ !(dest == \&home[0])}\\
\item Claim 5:\\
  file stubs.c line 8 column 10 function c::strcpy\\
  dereference failure: array `home' upper bound\\
  \texttt{!(dest == \&home[0]) $\vert\vert$ !(i >= 512)}\\
\end{itemize}

The variable \texttt{home}
looks familiar; We encountered it line~\ref{line:home}
of the function \texttt{getConfig} in Figure~\ref{fig:aeon_getconfig_c}.
The function \texttt{getenv} in combination with functions
\texttt{strcpy}, \texttt{strcat} or \texttt{sprintf} is indeed
often the source for buffer overflows. Therefore, we try to use \satabs{}
to check if the upper bound of the array \texttt{home}:

\texttt{satabs --claim 5 -I ../include aeon.c base64.c $\backslash$}\\
\texttt{lib\_aeon.c ../stubs/stubs.c}

\satabs{} runs for quite a while and will eventually give up,
telling us that it's upper bound for abstraction refinement iterations
has been exceeded. This is not exactly the result we were hoping for,
and we could now increase the bound for iterations with help of the
\texttt{--iterations} command line switch of \satabs{}.

Before we do this, let us investigate why \satabs{} failed to provide
a satisfying result. The function \texttt{strcpy} contains a loop
that counts from 1 to the length of the input string. Predicate
abstraction, the mechanism \satabs{} is based on, is unable to detect
such loops and will therefore unroll the loop body as often as necessary.
The array \texttt{home} has \texttt{MAX\_LEN} elements, and 
\texttt{MAX\_LEN} is defined to be 512 in \texttt{aeon.h}. 
Therefore, \satabs{} would have to run through at least 512 iterations, only to
verify (or reject) one of the more than 700 claims! Does this fact
defeat the purpose of static verification?

\satabs{} provides a mechanism to bypass this problem by
providing a detection for deep loops. For this purpose, \satabs{}
has to rely on a close cooperation with the abstract model checker.
Currently, the only model checker that provides loop detection 
is BOPPO (please refer to Chapter~\ref{chap:installation} to find
out where to obtain and how to install BOPPO).

The switch \texttt{--loop-detection} tells \satabs{} to activate
the detection of deep loops. Furthermore, we tell \satabs{} to
use BOPPO instead of the default model checker SMV:

\texttt{satabs --claim 5 --modelchecker boppo --loop-detection $\backslash$}\\
\texttt{-I ../include aeon.c base64.c lib\_aeon.c ../stubs/stubs.c}

This time, \satabs{} will tell us that it found a potential buffer
overflow:

\begin{itemize}
\item Violated property:\\
  file stubs.c line 8 column 10 function c::strcpy\\
  dereference failure: array `home' upper bound\\
  \texttt{!(dest == \&home[0]) $\vert\vert$ !(i $>$= 512)}
\end{itemize}

Furthermore, \satabs{} provides a counterexample trace that 
demonstrates how the buffer overflow be reproduced.
If you use the Eclipse plugin (as described in Section~\ref{sec:eclipse}),
you can step through this counterexample, although it might be a bit
tedious to step through 512 iterations of the loop in \texttt{strcpy}.

\subsection{Unit Testing with SATABS}

As mentioned in Section~\ref{example:aeon}, it is highly recommendable
to use formal verificat as early as possible in your development
cycle. Unit testing is used in most software development projects, and
static verification with \satabs{} can be very well combined with
this task. Unit testing relies on a number test cases that yield the
desired code coverage. Such test cases are imlemented by a
software testing engineer in terms of
a test harness (aka test driver) and a set of function stubs.
Typically, a slight modification to the test harness allows it to
be used with \satabs{}. Replacing the explicit input values
with non-deterministic inputs (as explained in sections~\ref{example:driver}
and~\ref{example:aeon} guarantees that \satabs{} will try to achieve
\emph{full} path and state coverage (due to the fact that predicate 
abstraction implicitely detects equivalence classes). However, it is
not guaranteed that \satabs{} terminates in all cases. Keep in mind
that you must not make any assumptions about the validity of the claims
if \satabs{} did not run to completion! 

