Overview of the project
My project aimed to implement checkers in GCC’s static analyzer that are already offered by the clang static analyzer. The project was not on the list of selected project ideas but rather proposed by me. GCC’s analyzer is based on the same techniques and papers as the clang static analyzer. I used that fact as a guide to what is possible and realistic to implement.
Initially, I proposed to implement four warnings: cast size, malloc sizeof, null termination tracking and buffer overlap warning. After discussion of those with my mentor David Malcolm, we agreed to proceed in an agile manner, doing one checker at a time and then choosing the next checker. Also, we have decided to not do null termination tracking as this checker would probably be a GSoC project on its own. In the end, I implemented the cast size diagnostic as -Wanalyzer-allocation-size and the buffer overlap diagnostic in -Wanalyzer-restrict. Instead of the other two, I contributed -Wanalyzer-out-of-bounds.
My Contributions
-Wanalyzer-allocation-size
This checker warns on code paths in which a pointer to a buffer is assigned to point to a buffer with a size that is not a multiple of sizeof (*pointer).
For example, in the following snippet, alloc_me does allocate 6 bytes. Viewing the buffer as an int32_t * is dubious because one can only access a multiple of 4 bytes. The diagnostic warns at the cause of trailing bytes, considering only accessing the first element, or an overflow, considering accessing trying to access index 1 on view. Such bugs are classified as CWE-131: Incorrect Calculation of Buffer Size.
int16_t *alloc_me (unsigned n)
{
return malloc (n * sizeof (int16_t));
}
void foo (void)
{
void *buf = alloc_me (3);
int32_t *view = (int32_t *) buf;
free (buf);
}Compiling the previous example yields the output:
<source>:12:12: warning: allocated buffer size is not a multiple of the pointee's size [CWE-131] [-Wanalyzer-allocation-size]
12 | int32_t *view = (int32_t *) buf;
| ^~~~
‘foo’: events 1-2
|
| 9 | void foo (void)
| | ^~~
| | |
| | (1) entry to ‘foo’
| 10 | {
| 11 | void *buf = alloc_me (3);
| | ~~~~~~~~~~~~
| | |
| | (2) calling ‘alloc_me’ from ‘foo’
|
+--> ‘alloc_me’: events 3-4
|
| 4 | int16_t *alloc_me (unsigned n)
| | ^~~~~~~~
| | |
| | (3) entry to ‘alloc_me’
| 5 | {
| 6 | return malloc (n * sizeof (int16_t));
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) allocated 6 bytes here
|
<------+
|
‘foo’: events 5-6
|
| 11 | void *buf = alloc_me (3);
| | ^~~~~~~~~~~~
| | |
| | (5) returning to ‘foo’ from ‘alloc_me’
| 12 | int32_t *view = (int32_t *) buf;
| | ~~~~
| | |
| | (6) assigned to ‘int32_t *’ {aka ‘int *’} here; ‘sizeof (int32_t {aka int})’ is ‘4’
|The checker can also detect when the programmer only passed the number of elements rather than the bytes to be allocated:
At the time the analyzer runs, the sizeof operator is already resolved to a constant integer. Thus, thus it can’t detect cases where the allocation size is a multiple of the pointee’s size but the pointee type does not match the type passed to sizeofConsider int *buf = malloc (2 * sizeof (short));. When the analyzer runs, the corresponding line in GIMPLE, GCC’s intermediate representation in the middle-end, looks like this: buf = malloc (4);. A warning corresponding to malloc sizeof of the CSA could be implemented in the frontend of GCC.
.
The patch was pushed in commit e6c3bb379f5.
-Wanalyzer-restrict
This checker warns on code paths in which an argument that is passed to a restrict-qualified parameter aliases with another argument. Further, it does warn on overlapping source and destination buffers for memcpy and mempcpy.
The restrict qualifier gives the compiler a hint that for the lifetime of the restrict-qualified pointer, it is the only pointer used to access the region it is pointing to. For example, this allows the compiler to only emit one load instruction if the pointer is not written because it knows there can not be any aliases. Disregarding the restrict qualifier is undefined behavior, as the compiler might apply optimizations that break the program.
For any arbitrary function with restrict-qualified parameters, the diagnostic checks for aliases to restrict-qualified parameters…
extern void bar (void * restrict a, void * restrict b);
void foo (int n)
{
char buf = malloc(n);
char *alias = buf;
bar (buf, alias);
free (buf);
}…and complains about them with following output:
<source>: In function ‘foo’:
<source>:7:5: warning: argument 1 passed to ‘restrict’-qualified parameter aliases with argument 2 [-Wanalyzer-restrict]
7 | bar (buf, alias);
| ^~~~~~~~~~~~~~~~
‘foo’: event 1
|
| 7 | bar (buf, alias);
| | ^~~~~~~~~~~~~~~~
| | |
| | (1) ‘buf’ and ‘alias’ point to the same memory location
|
<source>:1:13: note: declared here
1 | extern void bar (void * restrict a, void * restrict b);
| ^~~memcpy also has an extra argument to provide the number of bytes that are accessed. In that case, the accessed byte ranges on the source and destination parameter shall not overlap. The diagnostic handles this special case:
Output:
<source>: In function ‘foo’:
<source>:7:3: warning: calling ‘memcpy’ with overlapping buffers results in undefined behavior [-Wanalyzer-restrict]
7 | memcpy (&buf[1], &buf[0], sz);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘foo’: event 1
|
| 7 | memcpy (&buf[1], &buf[0], sz);
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (1) copying 8 bytes from ‘&buf[0]’ to ‘&buf[1]’ overlaps by 4 bytes
|Some might ask why do this again because -Wrestrict is already part of GCC for a long time. The advantage of re-doing it in the analyzer is that the analyzer also finds interprocedural flows and resolves aliases more precisely. Both examples above are missed by -Wrestrict but found by -Wanalyzer-restrict. Further, while testing this diagnostic on coreutils, it complained on touch.c and the emitted warning was promptly confirmed as a bug and fixed.
During the discussion about the found bug in touch, it came up that the working draft of the C standard added new examples to clarify the definition of restrict. One of the examples is especially interesting:
void h(int n, int * restrict p, int * restrict q, int * restrict r)
{
int i;
for (i = 0; i < n; i++)
p[i] = q[i] + r[i];
}The draft states that h(100, a, b, b) is defined behavior because q and r are only read but never written. To stop the diagnostic from emitting false-positives, the body needs to be traversed to check whether there is any write to a restrict-qualified parameter. But due to the per-file compilation nature of C, the body of functions is often only available at the linking stage, which happens later than the analyzer pass. Thus, the patch is not yet pushed. We hope to come to a conclusion how GCC should handle that case-Wrestrict is also affected by this.
and then adapt the patch accordingly.
-Wanalyzer-out-of-bounds
This diagnostic warns on code paths in which a buffer is read or written out-of-bounds.
Buffer overflows are one of the classical errors in C. Because C does not check the bounds on an array access and allows arbitrary pointer arithmetic, it is possible to access any memory location inside the virtual address space. Such an access might yield undefined behavior, result in a segfault or, if controlled by an attacker, can be used to alter the control-flow or read the memory contents. The corresponding CWE is CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer.
For constant offsets and buffer sizes, this diagnostic warns on underflows and underreads as well as on overflows and overreads. The example below is a classical off-by-one error…
size_t get_size ()
{
return 42;
}
void foo (void)
{
size_t n = get_size ();
char *buf = (char *) malloc (n);
// [...]
buf[n] = '\0';
free (buf);
}…which results in following output:
<source>: In function 'void foo()':
<source>:13:10: warning: heap-based buffer overflow [CWE-122] [-Wanalyzer-out-of-bounds]
13 | buf[n] = '\0';
| ~~~~~~~^~~~~~
'void foo()': events 1-2
|
| 11 | char *buf = (char *) malloc (n);
| | ~~~~~~~^~~
| | |
| | (1) capacity is 42 bytes
| 12 | // [...]
| 13 | buf[n] = '\0';
| | ~~~~~~~~~~~~~
| | |
| | (2) out-of-bounds write at byte 42 but region ends at byte 42
|
<source>:13:10: note: write is 1 bytes past the end of the region
13 | buf[n] = '\0';
| ~~~~~~~^~~~~~This patch was pushed in commit 7e3b45befdb.
As a follow-up to my initial commit, I worked on the detection of out-of-bounds with symbolic expressions Symbolic expressions are expressions where at least the value of one operand is not known.
. The challenge here is that the analyzer has to reason about the inequality of two symbolic expressions, a problem often solved by SMT solvers While there is the idea to optionally plug in an SMT solver in the analyzer, that is not yet possible.
. I decided to implement my own small check for inequalities, which does use the fact that the inequalities are always in the form of offset + num_bytes > buffer_size as well as does not try to handle commutativity and more complex nesting of positive offsets and factors. Even with those limitations, the diagnostic is able to detect many off-by-one mistakes with symbolic values. Below are examples that are caught by the symbolic out-of-bounds past the end diagnostic.
void foo (size_t size)
{
char *buf = __builtin_malloc (size);
if (!buf) return;
buf[size] = '\0';
free (buf);
}
void bar (size_t size, size_t offset)
{
char src[size];
char dst[size];
memcpy (dst, src, size + offset);
}<source>: In function ‘foo’:
<source>:9:13: warning: heap-based buffer overflow [CWE-122] [-Wanalyzer-out-of-bounds]
9 | buf[size] = '\0'; /* { dg-warning "overflow" } */
| ~~~~~~~~~~^~~~~~
‘foo’: events 1-4
|
| 6 | char *buf = __builtin_malloc (size);
| | ^~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (1) capacity is ‘size’ bytes
| 7 | if (!buf) return;
| | ~
| | |
| | (2) following ‘false’ branch (when ‘buf’ is non-NULL)...
| 8 |
| 9 | buf[size] = '\0'; /* { dg-warning "overflow" } */
| | ~~~~~~~~~~~~~~~~
| | | |
| | | (4) write of 1 byte at offset ‘size’ exceeds the buffer
| | (3) ...to here
|
<source>: In function ‘bar’:
<source>:17:3: warning: stack-based buffer overflow [CWE-121] [-Wanalyzer-out-of-bounds]
17 | memcpy (dst, src, size + offset);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘bar’: events 1-2
|
| 16 | char dst[size];
| | ^~~
| | |
| | (1) capacity is ‘size’ bytes
| 17 | memcpy (dst, src, size + offset);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) write of ‘size + offset’ bytes at offset ‘0’ exceeds the buffer
|
<source>:17:3: warning: buffer overread [CWE-126] [-Wanalyzer-out-of-bounds]
17 | memcpy (dst, src, size + offset);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘bar’: events 1-2
|
| 15 | char src[size];
| | ^~~
| | |
| | (1) capacity is ‘size’ bytes
| 16 | char dst[size];
| 17 | memcpy (dst, src, size + offset);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) read of ‘size + offset’ bytes at offset ‘0’ exceeds the buffer
|The follow-up patch was pushed in commit 7a6564c9b27.
Note that for this diagnostic, the diagnostic messages are not final and will probably change until the release of GCC 13.
Other commits by me
- Found and fixed a bug where the
reallocmodelled didn’t consider that the buffer could shrink. Pushed in commit 2b75b3b6a4d. - Fixed a bug where the analyzer didn’t fold a byte access on a string correctly to a char if the index was 0. Pushed in commit 1cc7e31c41a.
- I’ve implemented a modelling of the
strcpysemantics. This patch enabled the out-of-bounds diagnostic to also detect overflows caused bystrcpy. Pushed in commit 0a9c0d4ae55. - Added
-Wanalyzer-impreicse-fp-arithmetic, which warns about the use of floating-point arithmetic inside the allocation size argument ofmallocand others. That diagnostic was created because my allocation size checker introduced an ICEInternal Compiler Error, e.g. on a segfault or failed assertion.
if the allocation size had a non-integer constant operand and can’t properly reason about floating-point values, but we still wanted to warn about them. Pushed in commit c83e97317ef. - Fixed the regressions and a bug I introduced.
Patches that won’t be merged
Before the patch for support of symbolic values in the out-of-bounds diagnostic, I worked on a more sophisticated inequality comparison that also handles commutativity and is less dependent on the structure of the symbolic values. But that feature added around ~30% of runtime to the compilation with not too much benefit, as the calculation of allocation sizes are often not too complicated.
Further, I also had another improvement prepared for the out-of-bounds checker. The analyzer, by design to ensure termination, does not explore all paths. In the example below, the analyzer only explores the paths where i == 0 or i == 1. But the analyzer also tracks constraints on values such that it provides that i <= 4. I had implemented a function that replaces all symbolic operands in an expression with available constraints to fold the expression into a constant value, which then could be passed to the out-of-bounds logic. While that worked fineIt detected various problems where the offset or number of bytes accessed depended on for or if. I’m planning to do a slimmed down version.
, it also suffered from severe inefficiency. I tried caching the folded values such that the folding occurs only once per symbolic value, but that didn’t help much either.
Final Thoughts
GSoC was a fun experience working on such a large codebase and I learned many new things, especially about the semantics of C. At first, it was quite challenging for meProbably because my C++ knowledge was rudimentary at best in the beginning :D
. I also struggled a bit with the old school development process and codebase with a mixed space/tab indentation, use of many macrosSupport for the indentation style is limited in modern editors and the codebase is huge, so sometimes jump to definition didn’t work well.
and sending patches via email. On the other hand, it was also rewarding to see the patches getting merged and the relevance of thoseSometimes it didn’t take long for someone to find a bug in my code. That also means people are interested in what I’m doing. By the way, thanks to all people who tested my code and reported bugs!
. All in all, I think GSoC did help me to develop new skills, and I would definitely do it again.