This manual was written by David Evans, except for Section 9 and Appendix B which were written by David Larochelle and David Evans.
Splint is developed and maintained by the Secure Programming Group at the University of Virginia Department of Computer Science. David Evans is the project leader and the primary developer of Splint. David Larochelle developed the memory bounds checking. University of Virginia students Chris Barker, David Friedman, Mike Lanouette and Hien Phan all contributed significantly to the development of Splint.
Splint is the successor to LCLint, a tool originally developed as a joint research project between the Massachusetts Institute of Technology and Digital Equipment Corporation’s System Research Center. David Evans was the primary designed and developer of LCLint. John Guttag and Jim Horning had the original idea for a static checking tool for detecting inconsistencies between LCL specifications and their C implementations. They provided valuable advice on its functionality and design and were instrumental in its development.
Splint incorporates the original LCL checker developed by Yang Meng Tan. This was built on the DECspec Project (Joe Wild, Gary Feldman, Steve Garland, and Bill McKeeman). The LSL checker used by LCLint was developed by Steve Garland. The original C grammar for LCLint was provided by Nate Osgood. This work has also benefited greatly from discussions with Mike Burrows, David Friedman, Stephen Garland, Colin Godfrey, Steve Harrison, Yanlin Huang, Daniel Jackson, John Knight, David Larochelle, Angelika Leeb, Ulana Legedza, Gary McGraw, Anya Pogosyants, Avneesh Saxena, Seejo Sebastine, Navneet Singh, Raymie Stata, Yang Meng Tan, and Mark Vandevoorde. I especially thank Angelika Leeb for many constructive comments on improving an early version of this document, Raymie Stata and Mark Vandevoorde for technical assistance, and Dorothy Curtis, Paco Hope, Scott Ruffner, Christina Jackson, David Ladd, and Jessica Greer for systems assistance.
Much of Splint’s development has been driven by feedback from users in academia and industry. Many more people than I can mention here have made contributions by suggesting improvements, reporting bugs, porting early versions of Splint to other platforms. Particularly heroic contributions have been made by Nelson Beebe, Eric Bloodworth, Jutta Degener, Rick Farnbach, Chris Flatters, Huver Hu, Alexander Mai, John Gerard Malecki, Thomas G. McWilliams, Michael Meskes, Richard O’Keefe, Jens Schweikhardt, Albert L. Ting and Jim Zelenka. Martin “Herbert” Dietze and Mike Smith performed valiantly in producing the original Win32 and OS2 ports. Tim Van Holder produced the automake and autoconf distribution.
Splint research at the University of Virginia is currently funded in part by an NSF CAREER Award and an NSF CCLI Award for using analysis to teach software engineering. Splint has been previously supported by a grant from NASA and David Larochelle was funded by a USENIX student research grant.
Contents
1 Operation................................................................................................................ 11
1.1 Warnings............................................................................................................. 11
1.2 Flags.................................................................................................................... 12
1.3 Stylized Comments............................................................................................... 12
1.3.1 Annotations................................................................................................... 13
1.3.2 Setting Flags.................................................................................................. 13
2 Null Dereferences................................................................................................... 14
2.1.1 Predicate Functions........................................................................................ 14
2.1.2 Notnull Annotations........................................................................................ 15
2.1.3 Relaxing Null Checking.................................................................................. 15
3 Undefined Values.................................................................................................... 17
3.1.1 Undefined Parameters................................................................................... 17
3.1.2 Relaxing Checking......................................................................................... 18
3.1.3 Partially Defined Structures............................................................................ 18
4 Types....................................................................................................................... 19
4.1 Built in C Types.................................................................................................... 19
4.1.1 Characters.................................................................................................... 19
4.1.2 Enumerators.................................................................................................. 19
4.1.3 Numeric Types.............................................................................................. 19
4.1.4 Arbitrary Integral Types................................................................................. 19
4.2 Boolean Types..................................................................................................... 20
4.3 Abstract Types..................................................................................................... 21
4.3.1 Controlling Access......................................................................................... 22
4.3.2 Mutability...................................................................................................... 23
4.4 Polymorphism....................................................................................................... 24
5 Memory Management............................................................................................ 25
5.1 Storage Model...................................................................................................... 25
5.2 Deallocation Errors............................................................................................... 26
5.2.1 Unshared References.................................................................................... 26
5.2.2 Temporary Parameters.................................................................................. 27
5.2.3 Owned and Dependent References................................................................. 27
5.2.4 Keep Parameters........................................................................................... 28
5.2.5 Shared References........................................................................................ 28
5.2.6 Stack References.......................................................................................... 28
5.2.7 Inner Storage................................................................................................. 28
5.3 Implicit Memory Annotations................................................................................. 29
5.4 Reference Counting.............................................................................................. 30
6 Sharing.................................................................................................................... 31
6.1 Aliasing................................................................................................................ 31
6.1.1 Unique Parameters........................................................................................ 31
6.1.2 Returned Parameters..................................................................................... 31
6.2 Exposure.............................................................................................................. 32
6.2.1 Read-Only Storage........................................................................................ 32
6.2.2 Exposed Storage............................................................................................ 33
7 Function Interfaces................................................................................................. 35
7.1 Modifications........................................................................................................ 35
7.1.1 State Modifications........................................................................................ 36
7.1.2 Missing Modifies Clauses............................................................................... 36
7.2 Global Variables................................................................................................... 37
7.2.1 Controlling Globals Checking.......................................................................... 37
7.2.2 Definition State.............................................................................................. 38
7.3 Declaration Consistency........................................................................................ 38
7.4 State Clauses....................................................................................................... 39
7.5 Requires and Ensures Clauses............................................................................... 41
8 Control Flow........................................................................................................... 43
8.1 Execution............................................................................................................. 43
8.2 Undefined Behavior.............................................................................................. 44
8.3 Problematic Control Structures.............................................................................. 45
8.3.1 Likely Infinite Loops...................................................................................... 45
8.3.2 Switches....................................................................................................... 46
8.3.3 Deep Breaks................................................................................................. 46
8.3.4 Loop and If Bodies........................................................................................ 47
8.3.5 Complete Logic............................................................................................. 47
8.4 Suspicious Statements........................................................................................... 47
8.4.1 Statements with No Effects............................................................................ 47
8.4.2 Ignored Return Values................................................................................... 48
9 Buffer Sizes............................................................................................................. 49
9.1 Checking Accesses.............................................................................................. 49
9.2 Annotating Buffer Sizes........................................................................................ 49
9.3 Warnings............................................................................................................. 50
10 Extensible Checking............................................................................................ 52
10.1 Defining Attributes............................................................................................ 52
10.2 Annotations...................................................................................................... 54
10.3 Example........................................................................................................... 54
11 Macros.................................................................................................................. 55
11.1 Constant Macros............................................................................................... 55
11.2 Function-like Macros......................................................................................... 55
11.2.1 Side Effect Free Parameters....................................................................... 56
11.3 Controlling Macro Checking............................................................................... 57
11.4 Iterators........................................................................................................... 58
11.4.1 Defining Iterators....................................................................................... 58
11.4.2 Using Iterators........................................................................................... 58
12 Naming Conventions............................................................................................ 60
12.1 Type-Based Naming Conventions...................................................................... 60
12.1.1 Czech Names............................................................................................. 60
12.1.2 Slovak Names............................................................................................ 61
12.1.3 Czechoslovak Names.................................................................................. 61
12.2 Namespace Prefixes......................................................................................... 61
12.3 Naming Restrictions.......................................................................................... 63
12.3.1 Reserved Names........................................................................................ 63
12.3.2 Distinct Names........................................................................................... 63
13 Completeness....................................................................................................... 65
13.1 Unused Declarations......................................................................................... 65
13.2 Complete Programs........................................................................................... 65
13.2.1 Unnecessarily External Names.................................................................... 65
13.2.2 Declarations Missing from Headers............................................................. 65
14 Libraries and Header File Inclusion.................................................................... 66
14.1 Standard Libraries............................................................................................. 66
14.1.1 ISO Standard Library.................................................................................. 66
14.1.2 POSIX Library........................................................................................... 66
14.1.3 UNIX Library............................................................................................ 66
14.1.4 Strict Libraries............................................................................................ 66
14.2 Generating Libraries.......................................................................................... 67
14.2.1 Generating the Standard Libraries................................................................ 67
14.3 Header File Inclusion......................................................................................... 68
14.3.1 Preprocessing Constants............................................................................. 68
Appendix A Availability............................................................................................... 71
Appendix B Flags........................................................................................................ 72
Global Flags................................................................................................................... 72
Help.......................................................................................................................... 72
Initialization................................................................................................................ 72
Pre-processor............................................................................................................ 73
Libraries.................................................................................................................... 73
Output....................................................................................................................... 74
Expected Errors......................................................................................................... 75
Message Format............................................................................................................ 75
Mode Selector Flags....................................................................................................... 75
Checking Flags............................................................................................................... 76
Key........................................................................................................................... 76
Types........................................................................................................................ 76
Function Interfaces..................................................................................................... 79
Memory Management................................................................................................ 81
Sharing...................................................................................................................... 84
Use Before Definition (Section 3)............................................................................... 85
Null Dereferences (Section 2).................................................................................... 85
Macros (Section 7).................................................................................................... 85
Iterators..................................................................................................................... 86
Naming Conventions................................................................................................... 86
Other Checks............................................................................................................. 90
Flag Name Abbreviations................................................................................................ 95
Appendix C Annotations............................................................................................. 97
Suppressing Warnings................................................................................................. 97
Syntactic Annotations..................................................................................................... 97
Functions................................................................................................................... 97
Iterators (Section 11.4)............................................................................................... 98
Constants (Section 11.1)............................................................................................. 98
Alternate Types (Section 4.4)...................................................................................... 98
Declarator Annotations............................................................................................... 98
Type Access.............................................................................................................. 98
Macro Expansion...................................................................................................... 101
Arbitrary Integral Types............................................................................................ 102
Traditional Lint Comments........................................................................................ 102
Metastate Definitions.................................................................................................... 103
Appendix D Specifications......................................................................................... 104
Specification Flags.................................................................................................... 104
Appendix E Annotated Bibliography........................................................................ 107
Splint User’s Manual
Version 3.1.1
7 27 April 2003
Splint[1] is a tool for statically checking C programs for security vulnerabilities and programming mistakes. Splint does many of the traditional lint checks including unused declarations, type inconsistencies, use before definition, unreachable code, ignored return values, execution paths with no return, likely infinite loops, and fall through cases. More powerful checks are made possible by additional information given in source code annotations. Annotations are stylized comments that document assumptions about functions, variables, parameters and types. In addition to the checks specifically enabled by annotations, many of the traditional lint checks are improved by exploiting this additional information.
As more effort is put into annotating programs, better checking results. A representational effort-benefit curve for using Splint is shown in Figure 1. Splint is designed to be flexible and allow programmers to select appropriate points on the effort-benefit curve for particular projects. As different checks are turned on and more information is given in code annotations the number of bugs that can be detected increases dramatically.
Problems detected by Splint include:
· Dereferencing a possibly null pointer (Section 2);
· Using possibly undefined storage or returning storage that is not properly defined (Section 3);
· Type mismatches, with greater precision and flexibility than provided by C compilers (Section 4.1–4.2);
· Violations of information hiding (Section 4.3);
· Memory management errors including uses of dangling references and memory leaks (Section 5);
· Dangerous aliasing (Section 6);
· Modifications and global variable uses that are inconsistent with specified interfaces (Section 7);
· Problematic control flow such as likely infinite loops (Section 8.3.1), fall through cases or incomplete switches (Section 8.3.2), and suspicious statements (Section 8.4);
· Buffer overflow vulnerabilities (Section 9);
· Dangerous macro implementations or invocations (Section 11); and
· Violations of customized naming conventions. (Section 12).
Figure 1. Typical Effort-Benefit Curve
Splint checking can be customized to select what classes of errors are reported using command line flags and stylized comments in the code. In addition, users can define new annotations and associated checks to extend Splint’s checking or to enforce application specific properties (Section 10).
About This Document
This document is a guide to using Splint. Section 1 explains how to run Splint, interpret messages and control checking. Sections 2–13 describe particular checks done by Splint. There are some minor dependencies between sections, but in general they can be read in any order. Section 14 covers issues involving libraries and header file inclusion important for running Splint on large systems.
This document does not describe technical details of the checking. For technical background and analysis of Splint’s effectiveness in practice, see the papers available at http://www.splint.org.
|
Since human beings themselves are not fully debugged yet, there will be bugs in your code no matter what you do. Chris Mason,Zero-defects memo (quoted in Microsoft Secrets, Cusumano and Selby) |
Splint is invoked by listing files to be checked. Initialization files, command line flags, and stylized comments may be used to customize checking globally and locally.
The best way to learn to use Splint, of course, is to actually use it (if you don’t already have Splint installed on your system, see Appendix A). Before you read much further in this document, I recommend finding a small C program. Then, try running:
splint *.c
For the most C programs, this will produce a large number of warnings. To turn off reporting for some of the warnings, try:
splint -weak *.c
The -weak flag is a mode flag that sets many checking parameters to select weaker checking than is done in the default mode. Other Splint flags will be introduced in the following sections; a complete list is given in Appendix B.
A typical warning message is:
sample.c: (in function faucet)
sample.c:11:12 : Fresh storage x not released before return
A memory leak has been detected. Storage allocated locally is not released
before the last reference to it is lost. (Use -mustfreefresh to inhibit
warning)
sample.c:5:47: Fresh storage x allocated
The first line gives the name of the function in which the error is found. This is printed before the first message reported for a function. The second line is the text of the message. This message reports a memory leak—storage allocated in a function is not deallocated before the function returns. The file name, line and column number where the error is located precedes the text.
The next line is a hint giving more information about the suspected error, including information on how the warning message may be suppressed. For this message, using the ‑mustfreefresh flag would prevent this warning from being reported. This flag can be set at the command line, or more precisely just around the code point in question by using annotations (see Section 1.3.2).
The final line of the message gives additional location information. For this message, it tells where the leaking storage was allocated.
The generic message format is (parts enclosed in square brackets are optional):
[<file>:<line> (in <context>)]
<file>:<line>[,<column>]: message
[hint]
<file>:<line>,<column>: extra location information, if appropriate
Users can customize the format and content of messages printed by Splint. The function context is not printed if -showfunc is used. Column numbers are not printed if ‑showcol is used. The +parenfileformat flag can be used to generate file locations in the format recognized by Microsoft Visual Studio. If +parenfileformat is set, the line number follows the file name in parentheses (e.g., sample.c(11).) Messages are split into lines of length less than the value set using -linelen <number>. The default line length is 80 characters. Splint attempts to split lines in a sensible place as near to the line length limit as possible.
The ‑hints prevents any hints from being printed. Normally, a hint is given only the first time a class of error is reported. To have Splint print a hint for every message regardless, use +forcehints.
So that many programming styles can be supported, Splint provides several hundred flags for controlling checking and message reporting. Some of the flags are introduced in the body of this document. Appendix B describes every flag. Modes and shortcut flags are provided for setting many flags at once. Individual flags can override the mode settings.
Flags are preceded by + or -. When a flag is preceded by + we say it is on; when it is preceded by - it is off. The precise meaning of on and off depends on the type of flag.
The +/- flag settings are used for consistency and clarity, but contradict standard UNIX usage and it is easy to accidentally use the wrong one. To reduce the likelihood of using the wrong flag, Splint issues warnings when a flag is set in an unusual way. Warnings are issued when a flag is redundantly set to the value it already had (these errors are not reported if the flag is set using a stylized comment), if a mode flag or special flag is set after a more specific flag that will be set by the general flag was already set, if value flags are given unreasonable values, of if flags are set in an inconsistent way. The -warnflags flag suppresses these warnings.
Default flag settings will be read from ~/.splintrc if it is readable. If there is a .splintrc file in the working directory, settings in this file will be read next and its settings will override those in ~/.splintrc. Command-line flags override settings in either file. The syntax of the .splintrc file is the same as that of command-line flags, except that flags may be on separate lines and the # character may be used to indicate that the remainder of the line is a comment. The -nof flag prevents the ~/.splintrc file from being loaded. The -f <filename> flag loads options from filename.
To make flag names more readable, hyphens (-), underscores (_) and spaces in flags at the command line are ignored. Hence, warnflags, warn-flags and warn_flags all select the warnflags option.
Stylized comments are used to provide extra information about a type, variable or function interface to improve checking, or to control flag settings locally.
All stylized comments begin with /*@ and are closed by the end of the comment. The role of the @ may be played by any printable character. Use -commentchar <char> to select a different stylized comment marker.
Annotations are stylized comments that follow a definite syntax. Although they are comments, they may only be used in fixed grammatical contexts (e.g., like a type qualifier).
Sections 2–6 describe annotations for expressing assumptions about variables, parameters, return values, structure fields and type definitions. For example, /*@null@*/ is used to express an assumption that a parameter may be NULL. Section 7 describes annotations for describing function interfaces. Other annotations are described in later sections and Section 10 describes mechanisms users can employ to define new annotations. A summary of annotations is found in Appendix C.
Some annotations, known as control comments, may appear between any two tokens in a C program (unlike regular C comments, control comments should not be used within a single token as they introduce new separators in the code). Syntactically, they are no different from standard comments. Control comments are used to provide source-level control of Splint checking. They may be used to suppress spurious messages, set flags, and control checking locally in other ways.
Most flags (all except those characterized as “global” in Appendix B) can be set locally using control comments. A control comment can set flags locally to override the command line settings. The original flag settings are restored before processing the next file. The syntax for setting flags in control comments is the same as that of the command line, except that flags may also be preceded by = to restore their setting to the original command-line value. For instance,
/*@+charint -modifies=showfunc@*/
sets charint on (this makes char and int indistinguishable types), sets modifies off (this prevents reporting of modification errors), and sets showfunc to its original setting (this controls whether or not the name of a function is displayed before a message).
A common cause of program failures is when a null pointer is dereferenced. Splint detects these errors by distinguishing possibly NULL pointers at interface boundaries.
The null annotation is used to indicate that a pointer value may be NULL. A pointer declared with no null annotation, may not be NULL. If null checking is turned on (controlled by null), Splint will report an error when a possibly null pointer is passed as a parameter, returned as a result, or assigned to an external reference with no null qualifier.
If a pointer is declared with the null annotation, the code must check that it is not NULL on all paths leading to a dereference of the pointer (or the pointer being returned or passed as a value with no null annotation). Dereferences of possibly null pointers may be protected by conditional statements or assertions (to see how assert is declared see Section 8.1) that check the pointer is not NULL.
Consider two implementations of firstChar in Figure 2. For firstChar1, Splint reports an error since the pointer that is dereferenced is declared with a null annotation. For firstChar2, no error is reported since the true branch of the s == NULL if statement returns, so the dereference of s is only reached if s is not NULL.
|
null.c |
Running Splint |
|
char firstChar1 (/*@null@*/ char *s) { }
char firstChar2 (/*@null@*/ char *s) { if
(s == NULL) return ‘\0’; } |
> splint null.c Splint 3.0.1
null.c: (in function firstChar1) null.c:3:11: Dereference of possibly null pointer s: *s null.c:1:35: Storage s may become null
Finished checking --- 1 code warning found
|
|
Figure 2. Null Checking Output from running Splint is displayed in sans-serif font. The command line is preceded by >, the rest is output from Splint. Explanations added to the code or splint output are shown in italics. Code shown in the figures in this document is available from the splint web site, http://www.splint.org . No error is reported for line 9, since the dereference is reached only if s is non-null. For most of the figures, the options -linelen 55 -hints –showcol were used to produce condensed output, and –exportlocal to inhibit warnings about exported declarations. |
Another way to protect null dereference, is to declare a function using nullwhentrue or falsewhennull(these annotations where originally falsenull and truenull, but were renamed to clarify the logical asymmetry; falsenull and truenull may still be used) and call the function in a conditional statement before the null-annotated pointer is dereferenced.
If a function annotated with nullwhentrue returns true it means its first passed parameter is NULL. If it returns false, the parameter is not NULL. Note that it may return true for a parameter that is not NULL. A more descriptive name for nullwhentrue would be “if the result is false, the parameter was not null”. For example, if isNull is declared as,
/*@nullwhentrue@*/ bool isNull (/*@null@*/ char *x);
we could write firstChar2:
char firstChar2 (/*@null@*/ char *s)
{
if (isNull (s)) return
'\0';
return *s;
}
No error is reported since the dereference of s is only reached if isNull(s) is false, and since isNull is declared with the nullwhentrue annotation this means s must not be null.
The falsewhennull annotation is not quite the logical opposite of nullwhentrue. If a function declared with falsewhennull returns true, it means its parameter is definitely not NULL. If it returns false, the parameter may or may not be NULL. That is a falsewhennull always returns false when passed a NULL parameter; it may sometimes return false when passed a non-NULL parameter.
For example, we could define isNonEmpty to return true if its parameter is not NULL and has least one character before the NUL terminator:
/*@falsewhennull@*/ bool isNonEmpty (/*@null@*/ char *x)
{
return (x != NULL && *x != ‘\0’);
}
Splint does not check that the implementation of a function declared with nullwhentrue or falsewhennull is consistent with its annotation, but assumes the annotation is correct when code that calls the function is checked.
The notnull annotation specifies that a declarator is definitely not NULL. By default, this is assumed, but it may be necessary to use notnull to override a null in a type definition. The null annotation may be used in a type definition to indicate that all instances of the type may be NULL. For declarations of a type declared using null, the null annotation in the type definition may be overridden with notnull. This is particularly useful for parameters to hidden static operations of abstract types (see Section 4.3) where the null test has already been done before the function is called, or function results known to never be NULL. For an abstract type, notnull may not be used for parameters to external functions, since clients should not be aware of when the concrete representation may by NULL. Parameters to static functions in the implementation module, however, may be declared using notnull, since they may only be called from places where the representation is accessible. Return values for static or external functions may be declared using notnull.
An additional annotation, relnull may be used to relax null checking. No error is reported when a relnull value is dereferenced, or when a possibly null value is assigned to an identifier declared using relnull.
This is generally used for structure fields that may or may not be null depending on some other constraint. Splint does not report and error when NULL is assigned to a relnull reference, or when a relnull reference is dereferenced. It is up to the programmer to ensure that this constraint is satisfied before the pointer is dereferenced.
Like many static checkers, Splint detects instances where the value of a location is used before it is defined. This analysis is done at the procedural level. If there is a path through the procedure that uses a local variable before it is defined, a use before definition error is reported. The usedef flag controls use before definition checking.
Splint can do more checking than standard checkers though, because the annotations can be used to describe what storage must be defined and what storage may be undefined at interface points. Unannotated references are expected to be completely defined at interface points. This means all storage reachable from a global variable, parameter to a function, or function return value is defined before and after a function call.
Sometimes, function parameters or return values are expected to reference undefined or partially defined storage. For example, a pointer parameter may be intended only as an address to store a result, or a memory allocator may return allocated but undefined storage. The out annotation denotes a pointer to storage that may be undefined.
Splint does not report an error when a pointer to allocated but undefined storage is passed as an out parameter. Within the body of a function, Splint will assume an out parameter is allocated but not necessarily bound to a value, so an error is reported if its value is used before it is defined.
Splint reports an error if storage reachable by the caller after the call is not defined when the function returns. This can be suppressed by -must-define. After a call returns, an actual parameter corresponding to an out parameter is assumed to be completely defined.
When checking unannotated programs, many spurious use before definition errors may be reported If impouts is on, no error is reported when an incompletely-defined parameter is passed to a formal parameter with no definition annotation, and the actual parameter is assumed to be defined after the call. The /*@in@*/ annotation can be used to denote a parameter that must be completely defined, even if imp-outs is on. If imp-outs is off, there is an implicit in annotation on every parameter with no definition annotation.
|
usedef.c |
Running Splint |
|
extern void setVal (/*@out@*/ int *x); extern int getVal (/*@in@*/ int *x); extern int mysteryVal (int *x);
int dumbfunc (/*@out@*/ int *x, int i) { if (i > 3) 11 return *x; else if (i > 1) 13 return getVal (x); else if (i == 0) 15 return mysteryVal (x); else { 18 setVal (x); 19 return *x; } } |
> splint usedef.c usedef.c:11: Value *x used before definition usedef.c:13: Passed storage x not completely defined (*x is undefined): getVal (x) usedef.c:15: Passed storage x not completely defined (*x is undefined): mysteryVal (x)
Finished checking --- 3 code warnings
No error is reported for line 18, since the incompletely defined storage x is passed as an out parameter. After the call, x may be dereferenced, since setVal is assumed to completely define its out parameter. The warning for line 15 would not appear if +impouts were used since there is no in annotation on the parameter to mysteryVal. |
The reldef annotation relaxes definition checking for a particular declaration. Storage declared with a reldef annotation is assumed to be defined when it is used, but no error is reported if it is not defined before it is returned or passed as a parameter.
It is up to the programmer to check reldef fields are used correctly. They should be avoided in most cases, but may be useful for fields of structures that may or may not be defined depending on other constraints.
The partial annotation can be used to relax checking of structure fields. A structure with undefined fields may be passed as a partial parameter or returned as a partial result. Inside a function body, no error is reported when the field of a partial structure is used. After a call, all fields of a structure that is passed as a partial parameter are assumed to be completely defined.
Strong type checking often reveals programming errors. Splint can check primitive C types more strictly and flexibly than typical compilers (4.1) and provides support a Boolean type (4.2). In addition, users can define abstract types that provide information hiding (0).
Two types have compatible type if their types are the same.
ANSI C, <IP_ADDRESS>.
Splint supports stricter checking of built in C types. The char and enum types can be checked as distinct types, and the different numeric types can be type-checked strictly.
The primitive char type can be type-checked as a distinct type. If char is used as a distinct type, common errors involving assigning ints to chars are detected.
The +charint flag can be used for checking legacy programs where char and int are used interchangeably. If charint is on, char types indistinguishable from ints. To keep char and int as distinct types, but allow chars to be used to index arrays, use +charindex.
Standard C treats user-declared enum types just like integers. An arbitrary integral value may be assigned to an enum type, whether or not it was listed as an enumerator member. Splint checks each user-defined enum type as distinct type. An error is reported if a value that is not an enumerator member is assigned to the enum type, or if an enum type is used as an operand to an arithmetic operator. If the enumint flag is on, enum and int types may be used interchangeably. Like charindex, if the enumindex flag is on, enum types may be used to index arrays.
Splint reports where numeric types are used in dangerous or inconsistent ways. With the strictest checking, Splint will report an error anytime numeric types do not match exactly. If the relax-quals flag is on, only those inconsistencies that may corrupt values are reported. For example, if an int is assigned to a variable of type long (or passed as a long formal parameter), Splint will not report an error if relax-quals is on since a long must have at least enough bits to store an int without data loss. On the other hand, an error would be reported if the long were assigned to an int, since the int type may not have enough bits to store the long value.
Similarly, if a signed value is assigned to an unsigned, Splint will report an error since an unsigned type cannot represent all signed values correctly. If the +ignore-signs flag is on, checking is relaxed to ignore all sign qualifiers in type comparisons (this is not recommended, since it will suppress reporting of real bugs, but may be necessary for quickly checking certain legacy code).
Some types are declared to be integral types, but the concrete type may be implementation dependent. For example, the standard library declares the types size_t, ptr_diff and wchar_t, but does not constrain their types other than limiting them to integral types. Programs may rely on them being integral types (e.g., can use + operator on two size_t operands), but should not rely on a particular representation (e.g., long unsigned).
Splint supports three different kinds of arbitrary integral types:
/*@integraltype@*/
An arbitrary integral type. The actual type may be any one of short, int, long, unsigned short, unsigned, or unsigned long.
/*@unsignedintegraltype@*/
An arbitrary unsigned integral type. The actual type may be any one of unsigned short, unsigned, or unsigned long.
/*@signedintegraltype@*/
An arbitrary signed integral type. The actual type may be any one of short, int, or long.
Splint reports an error if the code depends on the actual representation of a type declared as an arbitrary integral. The match-any-integral flag relaxes checking and allows an arbitrary integral type is allowed to match any integral type.
Other flags set the arbitrary integral types to a concrete type. These should only be used if portability to platforms that may use different representations is not important. The long-integral and long-unsigned-integral flags set the type corresponding to /*@integraltype@*/ to be unsigned long and long respectively. The long-unsigned-unsigned-integral flag sets the type corresponding to /*@unsignedintegraltype@*/ to be unsigned long. The long-signed-integral flag sets the type corresponding to /*@signedintegraltype@*/ to be long.
Pre-ISO99 C had no Boolean representation – the result of a comparison operator was an integer, and no type checking is done for test expressions. C99 introduced a Boolean type (_Bool and bool, true and false macros in stdbool.h), but did not strengthen the type checking. Splint supports a Boolean type that can be checked distinctly from integral types. Many common errors can be detected by introducing a distinct Boolean type and stronger type checking.
Splint checks that the test expression in an if, while, or for statement or an operand of a &&, || or !operator is a Boolean. If the type of a test expression is not a Boolean, Splint will produce a warning depending on the type of the test expression and flag settings. If the test expression has pointer type, the warning is inhibited by –predboolptr (this can be used to prevent messages for the idiom of testing if a pointer is not null without a comparison). If it is type int, the warnings is inhibited by -pred-bool-int. For all other types, Splint warns unless -pred-bool-others is set. Relations, comparisons and certain standard library functions are declared to return Booleans.
Since using = instead of == is such a common bug, reporting of test expressions that are assignments is controlled by the separate pred-assign flag. The message can be suppressed by adding extra parentheses around the test expression.
Use the –booltype <name> flag to select the type name is used to represent Boolean values. There is no default Boolean type, although bool is used by convention. The names TRUE and FALSE are assumed to represent true and false Boolean values. To change the names of true and false, use -booltrue and -boolfalse. (The Splint distribution includes an implementation of bool, in lib/bool.h. However, it isn’t necessary to use this implementation to get the benefits of Boolean checking.)
Figure 4 illustrates some of the Boolean checking done by Splint.
|
bool.c |
Running Splint |
|
# include "bool.h" int f (int i, char *s, bool b1, bool b2) { 6 if (i = 3) 7 return b1; 8 if (!i || s) 9 return i; 10 if (s) 11 return 7; 12 if (b1 == b2) 13 return 3; 14 return 2; } |
> splint bool.c +predboolptr –booltype bool
bool.c:6: Test expression for if is assignment expression: i = 3 bool.c:6: Test expression for if not bool, type int: i = 3 bool.c:7: Return value type bool does not match declared type int: b1 bool.c:8: Operand of ! is non-boolean (int): !i bool.c:8: Right operand of || is non-boolean (char *): !i || s bool.c:10: Test expression for if not bool, type char *: s bool.c:12: Use of == with bool variables (risks inconsistency because of multiple true values): b1 == b2
Finished checking --- 7 code warnings found |
|
Figure 4. Boolean Checking |
Information hiding is a technique for handling complexity. By hiding implementation details, programs can be understood and developed in distinct modules and the effects of a change can be localized. One technique for information hiding is data abstraction. An abstract type is used to represent some natural program abstraction. It provides functions for manipulating instances of the type. The module that implements these functions is called the implementation module. We call the functions that are part of the implementation of an abstract type the operations of the type. Other modules that use the abstract type are called clients.
Clients may use the type name and operations, but should not manipulate or rely on the actual representation of the type. Only the implementation module may manipulate the representation of an abstract type. This hides information, since implementers and maintainers of client modules should not need to know anything about how the abstract type is implemented. It provides modularity, since the representation of an abstract type can be changed without having to change any client code.
Splint supports abstract types by detecting places where client code depends on the concrete representation of an abstract type. Some examples of abstraction violations detected by Splint are shown in Figure 5.
To declare an abstract type, the abstract annotation is added to a typedef. For example (in mstring.h),
typedef /*@abstract@*/ char *mstring;
declares mstring as an abstract type. It is implemented using a char *, but clients of the type should not depend on or need to be aware of this. If it later becomes apparent that a better representation such as a string table should be used, we should be able to change the implementation of mstring without having to change or inspect any client code.
In a client module, abstract types are checked by name, not structure. Splint reports an error if an instance of mstring is passed as a char * (for instance, as an argument to strlen), since the correctness of this call depends on the representation of the abstract type. Splint also reports errors if any C operator except assignment (=) or sizeof is used on an abstract type. The assignment operator is allowed since its semantics do not depend on the representation of the type (for abstract types whose instances can change value, a client does need to know if assignment has copy or sharing semantics as discussed in Section 4.3.2). The use of sizeof is also permitted, since this is the only way for clients to allocate pointers to the abstract type. Type casting objects to or from abstract types in a client module is an abstraction violation and will generate a warning message.
Normally, Splint will assume a type definition is not abstract unless the /*@abstract@*/ qualifier is used. If instead you want all user-defined types to be abstract types unless they are marked as concrete, the +imp-abstract flag can be used. This adds an implicit abstract annotation to any typedef that is not marked with /*@concrete@*/.
|
palindrome.c |
Running Splint |
|
# include "bool.h" # include "mstring.h"
bool isPalindrome (mstring s) { 6 char *current = (char *) s; 7 int i, len = (int) strlen (s);
for (i = 0; i <= (len+1) / 2; i++) { 11 if (current[i] != s[len-i-1]) return FALSE; } return TRUE; }
bool callPal (void) { 19 return (isPalindrome ("bob")); } |
> splint palindrome.c
palindrome.c:6: Cast from underlying abstract type mstring: (char *)s palindrome.c:7: Function strlen expects arg 1 to be char * gets mstring: s palindrome.c:11: Array fetch from non-array (mstring): s[len - i - 1] palindrome.c:19: Function isPalindrome expects arg 1 to be mstring gets char *: "bob"
Finished checking --- 4 code warnings
|
|
Figure 5. Information Hiding Violations |
Traditionally, programming books wax
mathematical when they arrive at the topic of abstract data
types…
Such books make it seem as if you’d never actually use an
abstract data type except as a sleep aid.
Steve McConnell
Where code may manipulate the representation of an abstract type, we say the code has access to that type. If code has access to an abstract type, the representation of the type and the abstract type are indistinguishable. Usually, a single program module that is the only code that has access to the type representation implements an abstract type. Sometimes, more complicated access control is desired if the implementation of an abstract type is split across program files, or particular client code needs to access the representation.
There are a several ways of selecting what code has access the representation of an abstract type:
· Modules. An abstract type defined in M .h is accessible in M.c. Controlled by the accessmodule flag. This means when accessmodule is on, as it is by default, the module access rule is in effect. If accessmodule is off (when -access-module is used), the module access rule is not in effect and an abstract type defined in M.h is not necessarily accessible in M .c.
· File names. An abstract type named type is accessible in files named type.<extension>. For example, the representation of mstring is accessible in mstring.h and mstring.c. Controlled by the access-file flag.
· Function names. An abstract type named type may be accessible in a function named type_name or typeName. For example, mstring_length and mstringLength would have access to the mstring abstract type. Controlled by accessfunction and the naming convention (see Section 12).
· Access control comments. The syntax /*@access type,+@*/[2] allows the following code to access the representation of type. Similarly, /*@noaccess type,+@*/ restricts access to the representation of type. The type in a noaccess comment must have been declared as an abstract type.
We can view types as being mutable or immutable. A type is mutable if passing it as a parameter to a function call can change the value of an instance of the type. For example, the primitive type int is immutable. If i is a local variable of type int and no variables point to the location where i is stored, the value of i must be the same before and after the call f (i). Structure and union types are also immutable, since they are copied when they are passed as arguments. On the other hand, pointer types are mutable. If x is a local variable of type int *, the value of *x (and hence, the value of the object x) can be changed by the function call g(x).
The mutability of a concrete type is determined by its type definition. For abstract types, mutability does not depend on the type representation but on what operations the type provides. If an abstract type has operations that may change the value of instances of the type, the type is mutable. If not, it is immutable. The value of an instance of an immutable type never changes. Since object sharing is noticeable only for mutable types, they are checked differently from immutable types.
The /*@mutable@*/ and /*@immutable@*/ annotations are used to declare an abstract type as mutable or immutable. (If neither is used, the abstract type is assumed to be mutable.) For example,
typedef /*@abstract@*/ /*@mutable@*/ char *mstring;
typedef /*@abstract@*/ /*@immutable@*/ int weekDay;
declares mstring as a mutable abstract type and weekDay as an immutable abstract type.
Clients of a mutable abstract type need to know the semantics of assignment. After the assignment expression s = t, do s and t refer to the same object (that is, will changes to the value of s also change the value of t).
Splint prescribes that all abstract types have sharing semantics, so s and t would indeed be the same object. Splint will produce a warning if a mutable type is implemented with a representation (e.g., a struct) that does not provide sharing semantics (controlled by mutrep flag).
The mutability of an abstract type is not necessarily the same as the mutability of its representation. We could use the immutable concrete type int to represent mutable strings using an index into a string table, or declare mstring as immutable as long as no operations are provided that modify the value of an mstring.
Sometimes it is useful to have a type that is abstract in some ways, but can be used with the standard numerical operators. Splint supports numabstract types for this purpose. The /*@numabstract@*/ annotation denotes a numabstract type. Splint will report warnings when numabstract types are used inconsistently, but allow binary numeric operators to operate on two values of the same numabstract type. Several flags control the strictness of type checking for numabstract types: numabstract, numabstractcast, numabstractlit, numabstractindex, and numabstractprint .
In C, all declarators must be declared to have exactly one type. This makes it impossible to write functions that operate on more than one type of parameter – for example, we cannot use the same square function for ints and floats. Because of the stricter type checking made possible by Splint, it is often useful to declare a parameter that has more than one possible type.
Splint provides alternate types to indicate that a declaration may be one of several possible types. The /*@alt type,+@*/ annotation creates a union type. For example, int /*@altchar, unsigned char@*/c declares c such that either an int, char or unsigned char value may be assigned to it without warning.
One use of alternate types is to specify the type of a macro that operates on multiple types of operands (see Section 11.2.1). Alternate types are also useful for declaring functions for which the return value may be safely ignored (see Section 8.4.2). A function can be declared to return t /*@altvoid@*/ to indicate that it returns a value of type t, but there should be not warning if that value is ignored.
About half the bugs in typical C programs can be attributed to memory management problems. Memory management bugs are notoriously difficult to detect through traditional techniques. Often, the symptom of the bug is far removed from its actual source. Memory management bugs often only appear sporadically and some bugs may only be apparent when compiler optimizations are turned on or the code is compiled on a different platform. Run-time tools offer some help, but are cumbersome to use and limited to detecting errors that occur when test cases are run. By detecting these errors statically, we can be confident that certain types of errors will never occur and provide verified documentation on the memory management behavior of a program.
Splint can detect many memory management errors at compile time including using storage that may have been deallocated (Section 5.2), memory leaks (Section 5.2), or returning a pointer to stack-allocated storage (Section 5.2.6).
Yea, from the
table of my memory I'll wipe away all trivial fond records, all
saws of books,
all forms, all pressures past, that youth and observation copied
there.
 Act I, Scene
v)
Most of these checks depend on annotations added to programs to document assumptions related to memory management and pointer values. By documenting these assumptions for function interfaces, variables, type definitions and structure fields, memory management bugs can be detected at their source — where an assumption is violated. In addition, precise documentation about memory management decisions makes it easier to change code.
This section describes execution-time concepts for describing the state of storage more precisely than can be done using standard C terminology. Certain uses of storage are likely to indicate program bugs, and are reported as anomalies.[3]
Splint assumes a CLU-like object storage model.[4] An object is a typed region of storage. Some objects use a fixed amount of storage that is allocated and deallocated automatically by the compiler. Other objects use dynamic storage that must be managed by the program.
Storage is undefined if it has not been assigned a value, and defined after it has been assigned a value. An object is completely defined if all storage that may be reached from it is defined. What storage is reachable from an object depends on the type and value of the object. For example, if p is a pointer to a structure, p is completely defined if the value of p is NULL, or if every field of the structure p points to is completely defined.
When an expression is used as the left side of an assignment expression we say it is used as an lvalue. Its location in memory is used, but not its value. Undefined storage may be used as an lvalue since only its location is needed. When storage is used in any other way, such as on the right side of an assignment, as an operand to a primitive operator (including the indirection operator, *),[5] or as a function parameter, we say it is used as an rvalue. It is an anomaly to use undefined storage as an rvalue.
A pointer is a typed memory address. A pointer is either live or dead. A live pointer is either NULL or an address within allocated storage. A pointer that points to an object is an object pointer. A pointer that points inside an object (e.g., to the third element of an allocated block) is an offset pointer. A pointer that points to allocated storage that is not defined is an allocated pointer. The result of dereferencing an allocated pointer is undefined storage. Hence, it is an anomaly to use it as an rvalue. A dead (or “dangling”) pointer does not point to allocated storage. A pointer becomes dead if the storage it points to is deallocated (e.g., the pointer is passed to the free library function.) It is an anomaly to use a dead pointer as an rvalue.
There is a special object null corresponding to the NULLpointer in a C program. A pointer that may have the value NULL is a possibly-null pointer. It is an anomaly to use a possibly-null pointer where a non-null pointer is expected (e.g., certain function arguments or the indirection operator).
There are two kinds of deallocation errors with which we are concerned: deallocating storage when there are other live references to the same storage, or failing to deallocate storage before the last reference to it is lost. To handle these deallocation errors, we introduce a concept of an obligation to release storage. Every time storage is allocated, it creates an obligation to release the storage. This obligation is attached to the reference to which the storage is assigned.[6] Before the scope of the reference is exited or it is assigned to a new value, the storage to which it points must be released. Annotations can be used to indicate that this obligation is transferred through a return value, function parameter or assignment to an external reference.
‘Tis in my
memory lock’d, and you yourself shall keep the key of
it.
Ophelia prefers explicit
deallocation (Hamlet. Act I, Scene iii)
The only annotation is used to indicate a reference is the only pointer to the object it points to. We can view the reference as having an obligation to release this storage. This obligation is satisfied by transferring it to some other reference in one of three ways:
· pass it as an actual parameter corresponding to a formal parameter declared with an only annotation
· assign it to an external reference declared with an only annotation
· return it as a result declared with an only annotation
After the release obligation is transferred, the original reference is a dead pointer and the storage it points to may not be used.
All obligations to release storage stem from primitive allocation routines (e.g., malloc), and are ultimately satisfied by calls to free. The standard library declared the primitive allocation and deallocation routines.
The basic memory allocator, malloc, is declared:
/*@only@*/ /*@null@*/ void *malloc (size_t size);
It returns an object that is referenced only by the function return value.
The deallocator, free, is declared:[7]
void free (/*@only@*/ /*@out@*/ /*@null@*/ void *ptr);
|
Running Splint | |
|
1 extern /*@only@*/ int *glob;
/*@only@*/ int * f (/*@only@*/ int *x, int *y, int *z) /*@globals glob;@*/ { 8 int *m = (int *) 9 malloc (sizeof (int));
11 glob = y; Memory leak 12 free (x); 13 *m = *x; Use after free 14 return z; Memory leak detected } |
> splint only.c only.c:11: Only storage glob (type int *) not released before assignment: glob = y only.c:1: Storage glob becomes only only.c:11: Implicitly temp storage y assigned to only: glob = y only.c:13: Dereference of possibly null pointer m: *m only.c:8: Storage m may become null only.c:13: Variable x used after being released only.c:12: Storage x released only.c:14: Implicitly temp storage z returned as only: z only.c:14: Fresh storage m not released before return only.c:9: Fresh storage m allocated |
The parameter to free must reference an unshared object. Since the parameter is declared using only, the caller may not use the referenced object after the call, and may not pass in a reference to a shared object. There is nothing special about malloc and free — their behavior can be described entirely in terms of the provided annotations.
The temp annotation is used to declare a function parameter that is used temporarily by the function. An error is reported if the function releases the storage associated with a temp formal parameter or creates new aliases to it that are visible after the function returns. Any storage may be passed as a temp parameter, and it satisfies its original memory constraints after the function returns.
In real programs it is sometimes necessary to have storage that is shared between several possibly references. The owned and dependent annotations provide a more flexible way of managing storage, at the cost of less checking. The owned annotation denotes a reference with an obligation to release storage. Unlike only, however, other external references marked with dependent annotations may share this object. It is up to the programmer to ensure that the lifetime of a dependent reference is contained within the lifetime of the corresponding owned reference.
The keep annotation is similar to only, except the caller may use the reference after the call. The called function must assign the keep parameter to an only reference, or pass it as a keep parameter to another function. It is up to the programmer to make sure that the calling function does not use this reference after it is released. The keep annotation is useful for adding an object to a collection (e.g., a symbol table), where it is known that it will not be deallocated until the collection is.
If Splint is used to check a program designed to be used in a garbage-collected environment, there may be storage that is shared by one or more references and never explicitly released. The shared annotation declares storage that may be shared arbitrarily, but never released.
Local variables that are not allocated dynamically are stored on a call stack. When a function returns, its stack frame is deallocated, destroying the storage associated with the function’s local variables. A memory error occurs if a pointer into this storage is live after the function returns. Splint detects errors involving stack references exported from a function through return values or assignments to references reachable from global variables or actual parameters. No annotations are needed to detect stack reference errors, since it is clear from a declaration if storage is allocated on the function stack. Figure 7 gives and example of errors reported involving stack-allocated storage.
|
stack.c |
Running Splint |
|
int *glob;
/*@dependent@*/ int * f (int **x) { int sa[2] = { 0, 1 }; int loc = 3;
9 glob = &loc; 10 *x = &sa[0];
12 return &loc; } |
> splint stack.c stack.c:12: Stack-allocated storage &loc reachable from return value: &loc stack.c:12: Stack-allocated storage *x reachable from parameter x stack.c:10: Storage *x becomes stack stack.c:12: Stack-allocated storage glob reachable from global glob stack.c:9: Storage glob becomes stack
A dependent annotation is used on the return value. Without this, other warnings would be reported, since the result would have an implicit only annotation. |
|
Figure 7. Stack-Allocated Storage |
An annotation always applies to the outermost level of storage. For example,
/*@only@*/ int **x;
declares x as an unshared pointer to a pointer to an int. The only annotation applies to x, but not to *x. To apply annotations to inner storage a type definition may be used:
typedef /*@only@*/ int *oip;
/*@only@*/ oip *x;
Now, x is an only pointer to an oip, which is an only pointer to an int.
When annotations are used in type definitions, they may be overridden in instance declarations. For example,
/*@dependent@*/ oip x;
makes x a dependent pointer to an int. Another way to apply annotations to inner storage is to use a state clause (see Section 7.4).
Since it is important that Splint can check unannotated programs effectively, the meaning of declarations with no memory annotations is chosen to minimize the number of annotations needed to get useful checking on an unannotated program.
An implicit memory management annotation may be assumed for declarations with no explicit memory management annotation. Implicit annotations are checked identically to the corresponding explicit annotation, except error messages indicate that they result from an implicit annotation. Figure 8 illustrates some implicit annotations.
Unannotated function parameters are assumed to be temp. This means if memory checking is turned on for an unannotated program, all functions that release storage referenced by a parameter or assign a global variable to alias the storage will produce error messages. (Controlled by paramimptemp.)
|
implicit.c | |
|
typedef struct { only char *name; int val; } *rec;
extern only rec rec_last ;
extern only rec rec_create (temp char *name, int val) ; Annotations in italics are not present in the code, but may be implied depending on flag settings. |
Implicit only annotation on mutable structure field if structimponly is on.
Implicit only annotation on mutable global variables if globimponly is on.
Implicit only annotation on mutable function result if retimponly is set. Implicit temp annotation on mutable parameter if paramimptemp is set. |
|
Figure 8. Implicit Annotations |
Unannotated return values, structure fields and global variables are assumed to be only. With implicit annotations (on by default), turning on memory checking for an unannotated program will produce errors for any function that does not return unshared storage or assignment of shared storage to a global variable or structure field. If an exposure qualifier is used (see Section 6.2), the implied dependent annotation is used instead of the more generally implied only annotation. (Controlled by retimponly, structimponly and globimponly. The allimponly flag sets all of the implicit only flags.)
Another approach to memory management is to add a field to a type to explicitly keep track of the number of references to that storage. Every time a reference is added or lost the reference count is adjusted accordingly; if it would become zero, the storage is released. Reference counting it difficult to do without automatic checking since it is easy to forget to increment or decrement the reference count, and exceedingly difficult to track down these errors.
Splint supports reference counting by using annotations to constrain the use of reference counted storage in a manner similar to other memory management annotations.
A reference counted type is declared using the refcounted annotation. Only pointer to struct types may be declared as refcounted, since reference counted storage must have a field to count the references. One field in the structure (or integral type) is preceded by the refs annotation to indicate that the value of this field is the number of live references to the structure. For example (in rstring.h),
typedef /*@abstract@*/ /*@refcounted@*/ struct {
/*@refs@*/ int refs;
char *contents;
} *rstring;
declares rstring as an abstract, reference-counted type. The refs field counts the number of references and the contents field holds the contents of a string.
|
rstring.c |
Running Splint |
|
# include "rstring.h"
static rstring rstring_ref (rstring r) { r->refs++; 6 return r; }
rstring rstring_first (rstring r1, rstring r2) { if (strcmp (r1->contents, r2->contents) < 0) 12 return r1; else 14 return rstring_ref (r2); } |
> splint rstring.c rstring.c:12: Reference counted storage returned without modifying reference count: r1
No error is reported for line 6 since the reference count was incremented. No error is reported for line 14, since rstring_ref returns a new reference.
|
|
Figure 9. Reference Counting |
All functions that return refcounted storage must increase the reference count before returning. Splint cannot determine if the reference count was increased, so any function that directly returns a reference to refcounted storage will produce an error. This is avoided, by using a function to return a new reference (e.g., rstring_ref in Figure 9).
A reference counted type may be passed as a temp or dependent parameter. It may not be passed as an only parameter. Instead, the killref annotation is used to denote a parameter whose reference is eliminated by the function call. Like only parameters, an actual parameter corresponding to a killref formal parameter may not be used in the calling function after the call. Splint checks that the implementation of a function releases all killref parameters, either by passing them as killref parameters, or assigning or returning them without increasing the reference count.
Errors involving unexpected sharing of storage can cause serious problems. Undocumented sharing may lead to unpredictable modifications, and some library calls (e.g., strcpy) have undefined behavior if parameters share storage. Another class of sharing errors occurs when clients of an abstract type may obtain a reference to mutable storage that is part of the abstract representation. This exposes the representation of the abstract type, since clients may modify an instance of the abstract type indirectly through this shared storage.
Splint detects errors involving dangerous aliasing of parameters. Some of these errors are already detected through the standard memory annotations (e.g., only parameters may not be aliases.) Two additional annotations are provided for constraining aliasing of parameters and return values.
The unique annotation denotes a parameter that may not be aliased by any other storage reachable from the function implementation — that is, any storage reachable through the other parameters or global variables used by the function. The unique annotation places similar constraints on function parameters as the only annotation, but it does not transfer the obligation to release storage. Splint will report an error if a unique parameter may be aliased by another parameter or global variable.
Splint reports an error if a function returns a reference to storage reachable from one of its parameters (if retalias is on) since this may introduce unexpected aliases in the body of the calling function when the result is assigned.
Figure 10 illustrated sharing checks. An error is reported since the first parameter to the library function strcpy is declared with unique. If a unique qualifier were added to the parameter declaration for s or t, no error would be reported.
|
unique.c |
Running Splint |
|
# include <string.h>
void capitalize (/*@out@*/ char *s, char *t) { 7 strcpy (s, t); *s = toupper (*s); } |
> splint unique.c
unique.c: (in function capitalize) unique.c:7: Parameter 1 (s) to function strcpy is declared unique but may be aliased externally by parameter 2 (t)
|
|
Figure 10. Unique parameters |
The returned annotation denotes a parameter that may be aliased by the return value. Splint checks the call assuming the result may be an alias to the returned parameter.
Consider the following code excerpt:
extern intSet intSet_insert (/*@returned@*/ intSet s, int x);
intSet intSet_singleton (int x)
{
7 return (intSet_insert (intSet_new (), x));
}
Without the returned qualifier on the parameter to intSet_insert, a memory leak error would be reported for line 7, since the only storage returned by intSet_new is not released. Because of the returned qualifier, Splint assumes the result of intSet_insert is the same storage as its first parameter, in this case the storage returned by intSet_new. No error is reported, since the only storage is then transferred through the return value (which has an implicit only annotation, see Section 5.3).
Splint detects places where the representation of an abstract type is exposed. This occurs if a client has a pointer to storage that is part of the representation of an instance of the abstract type. The client can then modify or examine the storage this points to, and manipulate the value of the abstract type instance without using its operations.
There are three ways a representation may be exposed:
1. Returning (or assigning to a global variable) an object that includes a pointer to a mutable component of an abstract type representation. (Controlled by ret-expose).
2. Assigning a mutable component of an abstract object to storage reachable from an actual parameter or a global variable that may be used after the call. This means the client may manipulate the abstract object using the actual parameter after the call. Note that if the corresponding formal parameter is declared only, the caller may not use the actual parameter after the call so the representation is not exposed. (Controlled by assign-expose).
3. Casting mutable storage to or from an abstract type. (Controlled by cast-expose).
Annotations may be used to allow exposed storage to be returned safely by restricting how the caller may use the returned storage.
It is often useful for a function to return a pointer to internal storage (or an instance of a mutable abstract type) that is intended only as an observer. The caller may use the result, but should not modify the storage it points to. For example, consider a naïve implementation of the employee_getName operation for the abstract employee type:
typedef /*@abstract@*/ struct {
char *name;
int id;
} *employee;
…
char *employee_getName (employee e) { return e->name; }
Splint produces a message to indicate that the return value exposes the representation. One solution would be to return a fresh copy of e->name. This is expensive, though, especially if we expect employee_getName is used mainly just to get a string for searching or printing. Instead, we could change the declaration of employee_getName to:
extern /*@observer@*/ char *employee_getName (employee e);
Now, the original implementation is correct. The declaration indicates that the caller may not modify the result, so it is acceptable to return shared storage. (The program must also not use the returned observer storage after any other calls to the abstract type module using the same parameter. Splint does not attempt to check this, and in practice it is rarely a problem.) Splint checks that the caller does not modify the return value. An error is reported if observer storage is modified directly, passed as a function parameter that may be modified, assigned to a global variable or reference derivable from a global variable that is not declared with an observer annotation , or returned as a function result or a reference derivable from the function result that is not annotation with an observer annotation.
A program that attempts to modify a string literal has undefined behavior [ISO, 6.4.5]. This is not enforced by most C compilers, and can lead to particularly pernicious bugs that only appear when optimizations are turned on and the compiler attempts to minimize storage for string literals. Splint can be used to check that string literals are not modified, by treating them as -observer storage. If +read-only-strings is set (default in standard mode), Splint will report an error if a string literal is modified.
Sometimes it is necessary to expose the representation of an abstract type. This may be evidence of a design flaw, but in some cases is justified for efficiency reasons. The exposed annotation denotes storage that is exposed. It may be used on a return value for results that reference storage internal to an abstract representation, on a parameter value to indicate a parameter that may be assigned directly to part of an abstract representation (note that if the parameter is annotated with only, it is not an error to assign it to part of an abstract representation, since the caller may not use the storage after the call returns), or on a field of an abstract representation to indicate that external references to the storage may exist. An error is reported if exposed storage is released, but unlike an observer, no error is reported if it is modified. Figure 11 shows examples of exposure problems detected by Splint.
|
exposure.c |
Running Splint |
|
# include "employee.h"
char * employee_getName (employee e) { 6 return e->name; }
/*@observer@*/ char * employee_obsName (employee e) { return e->name; }
/*@exposed@*/ char * employee_exposeName (employee e) { return e->name; }
void employee_capName (employee e) { char *name;
name = employee_obsName (e); 23 *name = toupper (*name); } |
> splint exposure.c +checks
exposure.c:6: Function returns reference to parameter e: e->name exposure.c:6: Return value exposes rep of employee: e->name exposure.c:6: Released storage e->name reachable from parameter at return point exposure.c:6: Storage e->name is released exposure.c:23: Suspect modification of observer name: *name = toupper(*name)
Three messages are reported for line 6 where a mutable field of an abstract type is returned with no sharing qualifier (without +checksonly the third one would be reported.) The error for line 23 reports a modification of an observer. If the call in line 22 were changed to call employee_exposeName , no error would be reported. |
Functions communicate with their calling environment through an interface. The caller communicates the values of actual parameters and global variables to the function, and the function communicates to the caller through the return value, global variables and storage reachable from the actual parameters. By keeping interfaces narrow (restricting the amount of information visible across a function interface), we can understand and implement functions independently.
A function prototype documents the interface to a function. It serves as a contract between the function and its caller. In early versions of C, the function “prototype” was very limited. It described the type returned by the function but nothing about its parameters. ANSI C (1989) provided function prototypes with the ability to add information on the number and types of parameter to a function. Splint provides the means to express much more about a function interface such as what global variable the function may use and what values visible to the caller it may modify.
The extra interface information places constraints on both how the function may be called and how it may be implemented. Splint reports places where these constraints are not satisfied. Typically, these indicate bugs in the code or errors in the interface documentation.
This section describes annotations that may be added to a function declaration to document what global variables the function implementation may use and what values visible to its caller it may modify.
The modifies clause lists what values visible to the caller may be modified by a function. Modifies clauses limit what values a function may modify, but they do not require that listed values are always modified. The declaration,
int f (int *p, int *q) /*@modifies *p@*/;
declares a function f that may modify the value pointed to by its first argument but may not modify the value of its second argument or any global state.
Splint checks that a function does not modify any caller-visible value not encompassed by its modifies clause and does modify all values listed in its modifies clause on some possible execution of the function. Figure 12 shows an example of modifies checking done by Splint.
|
Running Splint | |
|
void setx (int *x, int *y) /*@modifies *x@*/ { 4 *y = *x; }
void sety (int *x, int *y) /*@modifies *y@*/ { setx (y, x); } |
> splint modify.c +checks modify.c:4: Undocumented modification of *y: *y = *x modify.c:5: Suspect object listed in modifies of setx not modified: *x modify.c:1: Declaration of setx
There are
no errors
for sety– the call to
setxmodifies the value |
|
Figure 12. Modification |
A few special names are provided for describing function modifications that effect state not identifiable through parameters or global variables:
internalState
The function modifies some internal state (that is, the value of a static variable). Even though a client cannot access the internal state directly, it is important to know that something may be modified by the function call both for clear documentation and for checking undefined order of evaluation (Section 8.2) and side effect free parameters (Section 11.2.1).
fileSystem
The function modifies the file system. Any modification that may change the system state is considered a file system modification. All functions that modify an object of type pointer to FILE also modify the file system. In addition, functions that do not modify a FILE pointer but modify some state that is visible outside this process also modify the file system (e.g., rename). The flag mod-file-system controls reporting of undocumented file system modifications.
nothing
The function modifies nothing (i.e., it is side effect free).
The annotation, /*@*/ in a function declaration or definition (after the parameter list, before the semi-colon or function body) denotes a function that modifies nothing and does not use any global variables (see Section 7.2).
Splint is designed so programs with many functions that are declared without modifies clauses can be checked effectively. Unless modnomods is in on, no modification errors are reported checking a function declared with no modifies clause.
A function with no modifies clause is an unconstrained function since there are no documented constraints on what it may modify. When an unconstrained function is called, it is checked differently from a function declared with a modifies clause. To prevent spurious errors, no modification error is reported at the call site unless the mod-uncon flag is on. Flags control whether errors involving unconstrained functions are reported for other checks that depend on modifications (side effect free macro parameters (Section 11.2.1), undefined evaluation order (Section 8.2), and likely infinite loops (Section 8.3.1).)
Another aspect of a function’s interface, is the global variables it uses. A globals list in a function declaration lists external variables that may be used in the function body. Splint checks that global variables used in a procedure match those listed in its globals list. A global is used in a function if it appears in the body directly, or it is in the globals list of a function called in the body. Splint reports if a global that is used in a procedure is not listed in its globals list, and if a listed global is not used in the function implementation. Figure 13 shows an example function definition with a globals list and associated checking done by Splint.
|
globals.c |
Running Splint |
|
int glob1, glob2;
3 int f (void) /*@globals glob1;@*/ { 5 return glob2; } |
> splint globals.c +checks
globals.c:5: Undocumented use of global glob2 globals.c:3: Global glob1 listed but not used
|
|
Figure 13. Global Variables |
Whether on not an error is reported for a use of a global variable in a given function depends on the scope of the variable (file static or external), the checking annotation used in the variable declaration or the implicit annotation if no checking annotation is used, whether or not the function is declared with a globals list, and flag settings.
A global or file static variable declaration may be preceded by an annotation to indicate how the variable should be checked. In order of decreasing checks, the annotations are:
/*@checkedstrict@*/
Strictest checking. Undocumented uses and modifications of the variable are reported in all functions whether or not they have a globals list (unless check-strict-globs is off).
/*@checked@*/
Undocumented use of the variable is reported in a function with a globals list, but not in a function declared with no globals (unless glob-noglobs is on).
/*@checkmod@*/
Undocumented uses of the variable are not reported, but undocumented modifications are reported. (If mod-globs-nomods is on, errors are reported even in functions declared with no modifies clause or globals list.)
/*@unchecked@*/
No messages are reported for undocumented use or modification of this global variable.
If a variable has none of these annotations, an implicit annotation is determined by the flag settings.
Different flags control the implicit annotation for variables declared with global scope and variables declared with file scope (i.e., using the static storage qualifier). To set the implicit annotation for global variables declared in context (globs for external variables or statics for file static variable) to be annotation (checked, checkmod, checkedstrict) use imp<annotation> <context>. For example, +imp-checked-strict-statics makes the implicit checking on unqualified file static variables checkedstrict. See Appendix B for a complete list of globals checking flags.
Annotations can be used in the globals list of a function declaration to describe the states of global variables before and after the call. If a global is preceded by undef, it is assumed to be undefined before the call. Thus, no error is reported if the global is not defined when the function is called, but an error is reported if the global is used in the function body before it is defined. The killed annotation denotes a global variable that may be undefined when the call returns. For globals that contain dynamically allocated storage, a killed global variable is similar to an only parameter (Section 5.2). An error is reported if it contains the only reference to storage that is not released before the call returns. Figure 14 illustrated killed and undef globals.
|
annotglobs.c |
Running Splint |
|
int globnum;
struct { char *firstname, *lastname; int id; } globname;
void initialize (/*@only@*/ char *name) /*@globals undef globnum, undef globname @*/ { 13 globname.id = globnum; globname.lastname = name; 15}
void finalize (void) /*@globals killed globname@*/ { free (globname.lastname); 21 } |
> splint annotglobs.c
annotglobs.c:13: Undef global globnum used before definition annotglobs.c:15: Global storage globname contains 1 undefined field when call returns: firstname annotglobs.c:21: Only storage globname.firstname (type char *) derived from killed global is not released (memory leak) |
|
Figure 14. Annotated Globals Lists |
Splint checks that function declarations and definitions are consistent. The general rule is that the first declaration of a function implies all later declarations and definitions. If a function is declared in a header file, the first declaration processed is its first declaration (if it is declared in more than one header file an error is reported if redecl is set) . Otherwise, the first declaration in the file defining the function is its first declaration.
Later declarations may not include variables in the globals list that were not included in the first declaration. The exception to this is when the first declaration is in a header file and the later declaration or definition includes file static variables. Since these are not visible in the header file, they can not be included in the header file declaration. Similarly, the modifies clause of a later declaration may not include objects that are not modifiable in the first declaration. The later declaration may be more specific. For example, if the header declaration is:
extern void setName (employee e, char *s) /*@modifies e@*/;
the later declaration could be,
void setName (employee e, char *) /*@modifies e->name@*/;
If employee is an abstract type, the declaration in the header should not refer to a particular implementation (i.e., it shouldn’t rely on there being a name field), but the implementation declaration can be more specific.
This rule also applies to file static variables. The header declaration for a function that modifies a file static variable should use modifies internalState since file static variables are not visible to clients. The implementation declaration should list the actual file static variables that may be modified.
Sometimes it is necessary to specify function interfaces at a lower level than is possible with the standard annotations. For example, if a function defines some fields of a returned structure but does not define all the fields. The /*@special@*/ annotation is used to mark a parameter, global variable, or return value that is described using state clauses.
State clauses may be used to constrain the state of a parameter or return value before or after a call. One or more state clauses may appear in a function declaration, before the modifies or globals clauses. State clauses may be listed in any order, but the same state clause should not be used more than once. In a state clause list, result is used to refer to the return value of the function.
The following state clauses are used to describe the definition state or parameters before and after the function is called and the return value after the function returns:
/*@uses <references>@*/
References in a uses clause must be completely defined before the function is called. They are assumed to be defined at function entrance when the function is checked.
/*@sets <references>@*/
References in a sets clause must be allocated before the function is called. They are completely defined after the function returns. They are assumed to be allocated but undefined storage at function entrance and an error is reported if there is a path on which they are not defined before the function returns.
/*@defines <references>@*/
References in a defines clause must not refer to unshared, allocated storage before the function is called. They are completely defined after the function returns. When the function is checked, they are assumed to be undefined at function entrance and an error is reported if there is a path on which they are not defined before the function returns.
/*@allocates <references>@*/
References in an allocates clause must be unallocated before the function is called. They are allocated but not necessarily defined after the function returns. An error is reported if there is a path through the function on which they are not allocated before the function returns.
/*@releases <references>@*/
References in the releases clause are deallocated by the function. They must be storage that could be passed as an only parameter before the function is called, and are dead pointers after the function returns. They are assumed to be defined at function entrance and an error is reported if they refer to live, allocated storage at any return point.
Some examples of state clauses are shown in Figure 15. The defines clause for record_new indicates that the id field of the structure pointed to by the result is defined, but the name field is not. So, record_create needs to call record_setName to define the name field. Similarly, the releases clause for record_clearName indicates that no storage is associated with the name field of its parameter after the return, so no failure to deallocate storage message is produced for the call to free in record_free. The ensures isnull clause is described in the next section.
|
clauses.c |
|
typedef struct { int id; /*@only@*/ char *name; } *record;
static /*@special@*/ record record_new (void) /*@defines result->id@*/ { record r = (record) malloc (sizeof (*r));
assert (r != NULL); r->id = 3; return r; }
static void record_setName (/*@special@*/ record r, /*@only@*/ char *name) /*@defines r->name@*/ { r->name = name; }
record record_create (/*@only@*/ char *name) { record r = record_new (); record_setName (r, name); return r; }
void record_clearName (/*@special@*/ record r) /*@releases r->name@*/ /*@ensures isnull r->name@*/ { free (r->name); r->name = NULL; }
void record_free (/*@only@*/ record r) { record_clearName (r); free (r); }
|
|
Figure 15. State Clauses |
More general assumptions about state of parameters and globals before and after a function is called can be described using requires and ensures clauses. A requires clause specifies a predicate that must be true at a call site; when checking a function implementation Splint assumes the constraints given in its requires clauses are true at function entry. An ensures clause specifies a predicate that is true at a call site after the call returns; when checking a function implementation Splint warns if there is an execution path that does not return with a state that satifies the constraints given in its ensures clauses. A function declaration can have many requires and ensures clauses as long as their meanings are not contradictory.
The following constraints can be stated using requires and ensures clauses:
/*@requires only<references>@*/; /*@ensures only<references>@*/
/*@requires shared<references>@*/; /*@ensures shared<references>@*/
/*@requires owned<references>@*/; /*@ensures owned<references>@*/
/*@requires dependent<references>@*/; /*@ensures dependent<references>@*/
References refer to only, shared, owned or dependent storage before (requires) or after (ensures) the call.
/*@requires observer<references>@*/; /*@ensures observer<references>@*/
/*@requires exposed<references>@*/; /*@ensures exposed <references>@*/
References refer to observer or exposed storage before (requires) or after (ensures) the call.
/*@requires isnull<references>@*/; /*@ensures isnull<references>@*/
References have the value NULL before (requires) or after (ensures) the call. Note, this is not the same name or meaning as the null annotation (which means the value may or may not be NULL.)
/*@requires notnull<references>@*/; /*@ensures notnull<references>@*/
References do not have the value NULL before (requires) or after (ensures) the call.
The section describes checking done by Splint related to control flow. Many of these checks are significantly improved because of the extra information that is known about the program when annotations are provided.
To detect certain errors and avoid spurious errors, it is important to know something about the control flow behavior of called functions. Without additional information, Splint assumes that all functions eventually return and execution continues normally at the call site.
The noreturn annotation is used to denote a function that never returns [8]. For example,
extern /*@noreturn@*/ void fatalerror (/*@observer@*/ char *s);
declares fatalerror to never return. This enables Splint to correctly analyze code like,
if (x == NULL) fatalerror ("Yikes!");
*x = 3;
Other functions may return, but sometimes (or usually) return normally. The maynotreturn annotation denotes a function that may or may not return. This may be useful for documentation, but does not help checking much, since Splint must assume that a function declared with maynotreturn returns normally when checking the code. The alwaysreturns annotation denotes a function that always returns (but Splint does no checking to verify this).
To describe non-returning functions more precisely, the noreturnwhentrue and noreturnwhenfalse annotations may be used. Similar to nullwhentrue and falsewhennull (see Section 2.1.1), noreturnwhentrue and noreturnwhenfalse mean that a function never returns if the value of its first argument is true (noreturnwhentrue) or false (noreturnwhenfalse). They may be used only on functions whose first argument is a Boolean.
Hence, a function declared with noreturnwhenwfalse must not return if the value of its argument is false. For example, the standard library declares assert as[9]:
/*@noreturnwhenfalse@*/ void
assert (/*@sef@*/ bool /*@alt int@*/ pred);
This way, code like,
assert (x != NULL);
*x = 3;
is checked without reporting a false warning, since the noreturnwhenwfalse annotation on assert means the deference of x is not reached is x != NULL is false.
The order in which side effects take place in a C program is not entirely defined by the code. Certain execution points are known as sequence points — a function call (after the arguments have been evaluated), the end of a full expression (an initializer, expression in an expression statement, the control expression of an if, switch, while or do statement, each expression of a for statement, and the expression in a return statement), and after the first operand or a &&, ||, ? or , operand.
All side effects before a sequence point must be complete before the sequence point, and no evaluations after the sequence point shall have taken place. Between sequence points, side effects and evaluations may take place in any order. Hence, the order in which expressions or arguments are evaluated is not specified. Compilers are free to evaluate function arguments and parts of expressions (that do not contain sequence points) in any order. The behavior of code is undefined if it uses a value that is modified by another expression that is not required to be evaluated before or after the other use.
Splint detects instances where undetermined order of evaluation produces undefined behavior. If modifies clauses and globals lists are used, this checking is enabled in expressions involving function calls. Evaluation order checking is controlled by the eval-order flag.
|
order.c |
Running Splint |
|
extern int glob;
extern int mystery (void);
extern int modglob (void) /*@globals glob@*/ /*@modifies glob@*/;
int f (int x, int y[]) { 11 int i = x++ * x;
13 y[i] = i++; 14 i += modglob() * glob; 15 i += mystery() * glob; 16 return i; } |
> splint order.c +evalorderuncon order.c:11: Expression has undefined behavior (value of right operand modified by left operand): x++ * x order.c:13: Expression has undefined behavior (left operand uses i, modified by right operand): y[i] = i++ order.c:14: Expression has undefined behavior (value of right operand modified by left operand): modglob() * glob order.c:15: Expression has undefined behavior (unconstrained function mystery used in left operand may set global variable glob used in right operand): mystery() * glob
The warning for line 14 is reported because the modifies clause of modglob indicated that it may modify glob. The behavior is undefined since we don’t know if glob is evaluated before, after or during the modification. The line 15 warning would not be reported without +evalorderuncon. |
|
Figure 16. Evaluation Order |
When checking systems without modifies and globals information (see Section 7), evaluation order checking may report errors when unconstrained functions are called in procedure arguments. Since Splint has no annotations to constrain what these functions may modify, it cannot be guaranteed that the evaluation order is defined if another argument calls an unconstrained function or uses a global variable or storage reachable from a parameter to the unconstrained function. Its best to add modifies and globals clauses to constrain the unconstrained functions in ways that eliminate the possibility of undefined behavior. For large legacy systems, this may require too much effort. Instead, the ‑eval-order-uncon flag may be used to prevent reporting of undefined behavior due to the order of evaluation of unconstrained functions. Figure 16 illustrates detection of undefined behavior.
|
loop.c |
Running Splint |
|
extern int glob1, glob2; extern int f (void) /*@globals glob1@*/ /*@modifies nothing@*/; extern void g (void) /*@modifies glob2@*/ ; extern void h (void) ;
void upto (int x) { 14 while (x > f ()) g(); 15 while (f () < 3) h(); } |
> splint loop.c +infloopsuncon loop.c:14: Suspected infinite loop. No value used in loop test (x, glob1) is modified by test or loop body. loop.c:15: Suspected infinite loop. No condition values modified. Modification possible through unconstrained calls: h An error
is reported for line 14 since the only value modified by |
|
Figure 17. Infinite Loops |
A number of control structures that are syntactically legal may indicate likely bugs in programs. Splint can detect errors involving likely infinite loops (Section 8.3.1), fall through cases and missing cases in switch statements (Section 8.3.2), break statements within deeply nested loops or switches (Section 8.3.3), clauses of if, while or for statements that are empty statements or unblocked single statements (Section 8.3.4) and incomplete if-else logic (Section 8.3.5). Although any of these may appear in a correct program, depending on the programming style used they may indicate likely bugs or style violations that should be detected and eliminated.
Splint reports an error if it detects a loop that appears to be infinite. An error is reported for a loop that does not modify any value used in its condition test inside the body of the loop or in the condition test itself. This checking is enhanced by modifies clauses and globals lists (see Section 7) since they provide more information about what global variable may be used in the condition test and what values may be modified by function calls in the loop body.
Figure 17 shows examples of infinite loops detected by Splint. An error is reported for the loop in line 14, since neither of the values used in the loop condition (x directly and glob1 through the call to f) is modified by the body of the loop. If the declaration of g is changed to include glob1 in the modifies clause no error is reported. (In this example, if we assume the annotations are correct, then the programmer has probably called the wrong function in the loop body. This isn’t surprising, given the horrible choices of function and variable names!)
If an unconstrained function is called within the loop body, Splint will assume that it modifies a value used in the condition test and not report an infinite loop error, unless infloopsuncon is on. If infloopsuncon is on, Splint will report infinite loop errors for loops where there is no explicit modification of a value used in the condition test, but where they may be an undetected modification through a call to an unconstrained function (e.g., line 12 in Figure 17).
The automatic fall through of C switch statements is almost never the intended behavior.[10] Splint detects case statements with code that may fall through to the next case. The casebreak flag controls reporting of fall through cases. A single fall through case may be marked by preceding the case keyword with /*@fallthrough@*/ to indicate explicitly that execution falls through to this case. See Figure 18 for an example.
For switches on enum types, Splint reports an error if a member of the enumerator does not appear as a case in the switch body (and there is no default case). (Controlled by misscase.)
|
switch.c |
Running Splint |
|
typedef enum { YES, NO, DEFINITELY, PROBABLY, MAYBE } ynm; void decide (ynm y) { switch (y) { case PROBABLY: case NO: printf ("No!"); 10 case MAYBE: printf ("Maybe"); /*@fallthrough@*/ case YES: printf ("Yes!"); 13 } } |
> splint switch.c switch.c:10: Fall through case (no preceding break) switch.c:13: Missing case in switch: DEFINITELY
No fall through error is
reported for the NO
case, The
/*@fallthrough@*/ comment
prevents |
|
Figure 18. Switch Cases |
There is no syntax provided by C (other than goto) for breaking out of a nested loop. All break and continue statements act only on the innermost surrounding loop or switch. This can lead to serious problems[11] when a programmer intends to break the outer loop or switch instead. Splint optionally reports warnings for break and continue statements in nested contexts.
Four types of break warnings are reported:
· break inside a loop (while or for) that is inside a loop. Controlled by looploopbreak. To indicate that a break is inside an inner loop, precede the break by /*@innerbreak@*/.
· break inside a loop that is inside a switch statement. Controlled by switchloopbreak. To mark the break as a loop break, precede the break by /*@loopbreak@*/.
· break inside a switch statement that is inside a loop. Controlled by loopswitchbreak. To mark the break as a switch break, precede the break by /*@switchbreak@*/.
· break inside a switch inside another switch. Controlled by switchswitchbreak. To indicate that the break is for the inner switch, use /*@innerbreak@*/.
Since continue only makes sense within loops, a warning (Controlled by looploopcontinue.) is reported only for continue statements within nested loops. A safe inner continue may be preceded by /*@innercontinue@*/ to suppress error messages locally. The deepbreak flag sets all nested break and continue checking flags.
Splint warns if the marker preceding a break is not consistent with its placement. A warning results if innerbreak precedes a break that is not breaking an inner loop, switchbreak precedes a break that is not breaking a switch, or loopbreak precedes a break that is not breaking a loop.
An empty statement after an if, while or for often indicates a potential bug. A single statement (i.e., not a compound block) after an if, while or for is not likely to indicate a bug, but make the code harder to read and edit. Splint can report errors for if or loop statements with empty bodies or bodies that are not compound statements. Separate flags control checking for statements following an if, while or for:
· [if,while, for]empty — report errors for empty bodies (e.g., if (x > 3) ; )
· [if,while, for]block — report errors for non-block bodies (e.g., if (x > 3) x++;)
The if statement checks also apply to the body of the else clause. No ifblock warning is reported if the body of the else clause is an if statement, to allow conventional else if chains.
Although it may be perfectly reasonable in many contexts, an if-else chain with no final else may indicate missing logic or forgetting to check error cases. If elseif-complete is on, Splint warns when an if statement that is the body of an else clause does not have a matching else clause. For example, the code,
if (x == 0) { return "nil"; }
else if (x == 1) { return "many"; }
results in a warning since the second if has no matching else branch.
Splint detects errors involving statements with no apparent effects (Section 8.4.1) and statements that ignore the result of a called function (Section 8.4.2).
Splint can report errors for statements that have no effect. (Controlled by no-effect.) Because of modifies clauses, Splint can detect more errors than traditional checkers. Unless the no-effect-uncon flag is on, errors are not reported for statements that involve calls to unconstrained functions since the unconstrained function may cause a modification. Figure 19 shows examples of Splint’s no effect checking.
|
Running Splint | |
|
extern void nomodcall (int *x) /*@*/; Recall /*@*/ is shorthand for extern void mysterycall (int *x);
int noeffect (int *x, int y) { y == *x; nomodcall (x); mysterycall (x); return *x; } |
> splint noeffect.c +noeffectuncon noeffect.c:6: Statement has no effect: y == *x noeffect.c:7: Statement has no effect: nomodcall(x) noeffect.c:8: Statement has no effect (possible undetected modification through call to unconstrained function mysterycall): mysterycall(x)
The warning
for line 8 would not be |
|
Figure 19. Statements with No Effect |
Splint reports an error when a return value is ignored. Checking may be controlled based on the type of the return value: ret-val-int controls reporting of ignored return values of type int, and ret-val-bool for return values of type bool, and ret-val-others for all other types. A function statement may be cast to void to prevent this error from being reported.
Alternate types (Section 4.4) can be used to declare functions that return values that may safely be ignored by declaring the result type to alternately be void. Several functions in the standard library are specified to alternately return void to prevent ignored return value errors for standard library functions (e.g., strcpy) where the result may be safely ignored (see Section 14.1). Figure 20 shows examples of ignored return value errors reported by Splint.
|
ignore.c |
Running Splint |
|
# include “bool.h” extern int fi (void); extern bool fb (void); extern int /*@alt void@*/ fv (void);
int ignore (void) { 8 fi (); 9 (void) fi (); 10 fb (); 11 fv (); 12 return fv (); } |
> splint ignore.c
ignore.c:8: Return value (type int) ignored: fi() ignore.c:10: Return value (type bool) ignored: fb()
The message for line 8 would not be reported
if ‑retvalint
is set;
No message is reported for line 9 because
the result is cast to void
,
|
|
Figure 20. Ignored Return Values |
Buffer overflow errors are a particularly dangerous type of bug in C programs. They are directly responsible for about half of all security attacks [Larochelle01]. For performance reasons, C does not perform run time bounds checking. Referencing storage outside allocated regions can cause memory corruption and lead to strange behavior. Moreover, buffer overflow bugs are particularly insidious because they can go undetected in testing or normal use, but usually result in security critical bugs. Reads beyond the end of a buffer can cause the program to leak information. Writes beyond the end a buffer (buffer overflows) can usually be exploited make the program run arbitrary code. Attackers can exploit these programming bugs to replace the return address on the stack and place arbitrary code in memory thereby gaining full access to the machine. Splint is able to detect many memory bounds errors. [12]
Splint models blocks of contiguous memory using two properties: maxSet and maxRead. Given a buffer b, maxSet(b) denotes the highest address beyond b that can be safely used as an lvalue. For the declaration char buf[MAXSIZE] we have maxSet(buf) = MAXSIZE - 1. Similarly, maxRead denotes the highest index of a buffer that can be safely used an rvalue. It is inappropriate to read an uninitialized element or beyond the NUL terminator of a null terminated buffer.
When a buffer is accessed as an lvalue, Splint generates a precondition constraint involving the maxSet property. When a buffer is accessed as an rvalue, Splint generates a precondition constraint involving the maxRead property. For the expression *ptr, Splint generates the constraints maxSet(ptr) >= 0 or maxRead(ptr) >= 0 depending on whether ptr is used as an lvalue or rvalue. Similarly, for accesses of the form ptr[i], splint generates the constraints maxSet(ptr) >= i or maxRead(ptr) >= i. If +boundswrite is set, Splint warns if it is unable to resolve a constraint involving maxSet. If +boundsread is set, Splint warns about unresolved maxRead constraints also.
Splint generates postconditions for statements to help resolve precondition constraints. When a buffer is written to we know that an element of a buffer is initialized and is safe to read. We generate the postcondition maxRead(ptr) >= 0 if the buffer is accessed using *ptr or maxRead(ptr) >= i if the buffer is accessed using ptr[i]. Splint generates additional postconditions for a variety of C constructs. For assignment statements, Splint generates a postcondition equating the two operands. Splint also generates post condition constraints for the maxSet value of fixed sized arrays.
Function declarations may include requires and ensures clauses that specify assumptions about buffer sizes for function preconditions. They are interpreted like requires and ensures clauses for simple memory states (see Section 7.5) but can be more expressive. When a function with a requires clause is called, the call site must be checked to satisfy the constraints implied by the requires clause. Similarly, an ensures clause can be used to specify function post conditions. If the +checkpost flag is set, Splint warns if it cannot verify that a function implementation satisfies its declared postconditions.
Constraints can contain function parameters as well as global variables and integer constants. The unary operators, maxSet and maxRead which correspond to the properties described above are also supported. Multiple predicates may be conjoined using /\.
For example, the standard library annotates strcpy:
void /*@alt char * @*/strcpy
(/*@unique@*/ /*@out@*/ /*@returned@*/ char *s1, char *s2)
/*@modifies *s1@*/
/*@requires maxSet(s1) >= maxRead(s2) @*/
/*@ensures maxRead(s1) == maxRead (s2) @*/;
The requires clause indicates that the buffer passed as s1 must be large enough to hold the string passed as s2. The ensures clause specifies that maxRead of s1 after the call is equal to maxRead of s2. In cases where the size of s2 is unknown, programs should use strncpy, annotated as:
void /*@alt char * @*/ strncpy
(/*@unique@*/ /*@out@*/ /*@returned@*/ char *s1, char *s2,
size_t n)
/*@modifies *s1@*/
/*@requires maxSet(s1) >= ( n - 1 ); @*/
/*@ensures maxRead (s2) >= maxRead(s1) /\ maxRead (s1) <= n;@*/;
The syntax for buffer size constraint clauses is:
constraint Þ (requires | ensures) consExpr relOp consExpr
relOp Þ == | > | >= | < | <=
consExpr Þ consExpression binOp consExpr | unaryOp (consExpr ) | term
binOp Þ + | -
unaryOp Þ maxSet | maxRead
term Þ identifier | literal | result
For some programs, Splint's standard bounds checking produces an unacceptably high number of warnings. Because of this, Splint now prioritizes warnings using a simple heuristic. The flags likely-bounds, likely-bounds-writes, and likely-bounds-read are similar to bounds,bounds-write, and bounds-read, but they only cause Splint to produce warnings for what it determines are likely bounds errors. Splint classifies an unresolved constraint as a likely bounds error if it can reduce the constraint to a numerical inconsistency such as 5 >= 10. Warnings for these constraints are more likely to be legitimate -- indicating real bugs or the lack of annotations. Additionally, when these warnings are false positives, it is easier for humans to recognize them as spurious. These flags generate significantly fewer errors (an order of magnitude in some cases), and the errors generated are easier to understand. However, this does not come without cost. The checking is significantly less precise and is likely to miss real errors.
Since bounds checking is more complex than other checks done by Splint, memory bounds warnings contain extensive information about the unresolved constraint. Warning messages for unresolved constraints contain both the original constraints and the simplified form of the constraint which cannot be resolved. If the constraint was derived from a function precondition, the original precondition is included in the error message. If the +showconstraintlocation flag is set, the message includes the expression that the constraint is derived from. The +showconstraintparens flag directs Splint to display fully parenthesized constraints in warnings to remove ambiguity.
Consider the code excerpt below containing a trivial out-of-bounds write:
int buf[10];
buf[10] = 3;
Splint warns:
setChar.c:5:4: Likely out-of-bounds store:
buf[10] = 3
Unable to resolve constraint: requires 9 >= 10
needed to satisfy precondition: requires maxSet(buf @ setChar.c:5:4) >= 10
Splint has simplified the constraint from the requires clause to 9 >= 10 by substituting for the known value of maxSet(buf) and generated a warning because 9(the highest index of buf that may be safely written to) is not greater than or equal to 10.
A more realistic example is shown Figure 21. The function updateEnv is a naïve implementation of a function to copy an environmental variable. There is no standard restriction on the length of the return value of getenv so this can cause a buffer overflow. A safe version of updateEnv (such as updateEnvSafe in Figure 21) would ensure that the buffer is large enough to hold the environment variable string before copying.
The requires clause means Splint will report a warning if a call to updateEnvSafe passed in a buffer as str that is not big enough to hold the value passed as strSize characters.
In many cases, functions will have multiple unresolved constraints which are similar. For example, if a subsequence statement writes to the next element of a buffer. Usually all these constraints represent all real problems or are all spurious. If the +redundantconstraints flag is set, Splint reports even apparently redundant warning messages. Otherwise, if satisfying one unresolved constraint would imply satisfying another, Splint only prints a warning message for the stronger constraint.
|
bounds.c |
Running Splint |
|
void updateEnv(char * str) { char * tmp; 7 tmp = getenv(“MYENV”); if (tmp != NULL) 9 strcpy (str, tmp); }
void updateEnvSafe (char * str, size_t strSize) /*@requires maxSet(str) >= strSize –1@*/ { char * tmp; tmp = getenv(“MYENV”); if (tmp != NULL) { strncpy (str, tmp, strSize -1); str[strSize -1] = ‘/0’; } } |
> splint bounds.c +bounds +showconstraintlocation
bounds.c:9: Possible out-of-bounds store: strcpy(str, tmp) Unable to resolve constraint: requires maxSet(str @ bounds.c:9) >= maxRead(getenv("MYENV") @ bounds.c:7) needed to satisfy precondition: requires maxSet(str @ bounds.c:9) >= maxRead(tmp @ bounds.c:9) derived from strcpy precondition: requires maxSet(<parameter 1>) >= maxRead(<parameter 2>) |
|
Figure 21. Memory Bounds |
The +functionpost flag is useful for determining if array bounds warnings are spurious. If this flag is set, Splint will print the constraints that it established at the end of the function. If the warnings are spurious, localized control comments can be used to suppress them.
Splint provides mechanisms for defining new checks and annotations using metastate definitions. User-defined checks can be used to check and document properties not supported by the provided checks. [13]
A large class of useful checks can be described as constraints on attributes associated with program objects or the global execution state. Unlike types, however, the values of these attributes can change along an execution path. Splint provides a general language that lets users define attributes associated with different kinds of program objects as well as rules that both constrain attributes’ values at interface points and specify how attributes change.
Because user-defined attribute checking is integrated with normal checking, Splint’s analysis of user-defined attributes can take advantage of other analyses, such as alias and nullness analysis.
To define an attribute, create a metastate file (.mts) that defined the possible values and transfer rules of the attribute. Attributes can either be associated with a particular kind of program object (for example, all char *’s) or with the global state (whether or not the network has been initialized). The –mts <file> flag is used to direct Splint to read a metastate file (which will be found on the LARCH_PATH with default extension .mts).
An example attribute definition is shown in Figure 22. It defines the taintedness attribute for recording whether or not a char * came from a possibly untrustworthy source. Knowing whether a value is possibly hostile is useful for preventing several security vulnerabilities including format string bugs.[14] (A simpler way to detect format vulnerabilities is to warn for any format string that is unknown at compile time. Splint provides this checking, issuing a warning if the +formatconst flag is set and finds any unknown format strings at compile time. This can produce spurious messages, however, because there might be unknown format strings that are not vulnerable to hostile input.)
The first three lines of the attribute definition define the taintedness attribute associated with char * objects, which can be in one of two states: untainted or tainted. The context clause gives a context selector for which objects have the attribute. In this case, reference char * means that every reference that is a char * has an associated taintedness attribute. Other contexts include parameter (only parameter declarations), literal (only string or number literals), and null (only known NULL values). Attribute can also be defined that are not associated with any particular object, but instead are associated with the global state of a program execution. The global keyword is used before attribute to define a global attribute.
The oneof clause introduces two identifiers for representing the taintedness value: untainted for references that are not derived from untrustworthy input, and tainted for references that may contain hostile data.
The annotations clause defines two new annotations that may be used to describe taintedness assumptions. In this case, the annotations match the names of the value choices, but they may be any identifier. The clause tainted reference ==> tainted defines the tainted annotation that may be used on a reference to indicate that it has tainted state.
|
attribute taintedness context reference char * oneof untainted, tainted annotations tainted reference ==> tainted untainted reference ==> untainted transfers tainted as untainted ==> error "Possibly tainted storage used where untainted required." merge tainted + untainted ==> tainted defaults reference ==> tainted literal ==> untainted null ==> untainted end Figure 22. Taintedness Attribute |
The transfers clause defines rules for state changes and warning when objects are passed as parameters, returned, or assigned to externally visible references. The rule, tainted as untainted ==> error "Possibly tainted storage used where untainted required.", means it is an error to pass a tainted value as a parameter that has untainted taintedness. All other transfers are implicitly permitted, and leave the passed storage in the same state as before the transfer. We may also use a transfers clause to indicate that the reference changes state after a transfer. A losereference clause (not used in taintedness) is similar to a transfers clause, except it is used to provide rules for when a reference to storage is lost, either by leaving the scope in which it was declared, returning from a function, or assigning it to a new value.
The merge clause defined rules for combining state along paths. The clausemerge tainted + untainted ==> tainted indicates that combining tainted and untainted objects produces a tainted object. Thus, if a reference is tainted along one control path and untainted along another control path, checking assumes that it is taintedafter the two branches merge. It is also used to merge taintedness states in function specifications (see the strcat example in the next section). We can also define error combinations so that a warning is reported if the states on different paths are incompatible.
The defaults clause specifies default values used for declarators without explicit attribute annotations. We choose default values to make it easy to start checking an unannotated program. Here we assume unannotated references are tainted and Splint will report a warning where unannotated references are passed to functions that require untainted parameters. The warnings indicate either a format bug in the code or a place where an untainted annotation should be added. Running Splint again after adding the annotation will propagate the newly documented assumption through the program.
The full grammar for metastate definitions is given in Appendix C.