TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Compiler Warnings and Static Analysers

Compiler Warnings and Static Analysers

Sanitizers find bugs on the code paths that tests execute. Static analysis looks at code without running it, so it can reason about paths no test reaches, at the price of missing what it can't prove and reporting some things that aren't bugs. The cheapest static analyser is the compiler you already run: GCC and Clang warn about many memory-safety mistakes, but only if asked, and each compiler catches different ones. Dedicated analysers (GCC's -fanalyzer, the Clang Static Analyzer, clang-tidy, cppcheck, CodeQL, Semgrep, Coverity) go further. This lesson runs the ones in your sandbox over one file with six seeded bugs and shows who finds what.

The seeded file

Six bugs from the previous section in 30 lines: a malloc(strlen(s)) without room for the NUL, a missing NULL check, a variable uninitialised on one path, a sprintf overflow, a format-string bug and a double free. The session compiles it with each tool and prints only the warnings, prefixed with line:column. It runs in your sandbox:

bash · try it yourself
cat > bugs.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *dup_upper(const char *s) {
    char *p = malloc(strlen(s));             /* 1: no room for the NUL */
    strcpy(p, s);                            /* 2: p may be NULL */
    for (size_t i = 0; p[i]; i++) p[i] &= ~0x20;
    return p;
}

int parse_len(const char *s) {
    int n;
    if (s[0] == '#') n = atoi(s + 1);        /* 3: n uninitialised otherwise */
    return n;
}

void log_line(const char *user) {
    char buf[8];
    sprintf(buf, "user=%s", user);           /* 4: overflow for long names */
    printf(buf);                             /* 5: format string */
    puts("");
}

int main(int argc, char **argv) {
    char *u = dup_upper(argc > 1 ? argv[1] : "bob");
    log_line(u);
    free(u);
    free(u);                                 /* 6: double free */
    return parse_len(argc > 2 ? argv[2] : "7");
}
SRC
echo "== gcc -Wall -Wextra -O2"; gcc -Wall -Wextra -O2 -c bugs.c -o /dev/null 2>&1 | grep -E ': warning' | sed 's/^bugs.c://'
echo "== clang -Wall -Wextra";   clang -Wall -Wextra -c bugs.c -o /dev/null 2>&1 | grep -E ': warning' | sed 's/^bugs.c://'
echo "== gcc -fanalyzer";        gcc -fanalyzer -c bugs.c -o /dev/null 2>&1 | grep -E ': warning' | sed 's/^bugs.c://'
echo "== clang --analyze";       clang --analyze bugs.c -o /dev/null 2>&1 | grep -E ': warning' | sed 's/^bugs.c://'
== gcc -Wall -Wextra -O2
21:12: warning: format not a string literal and no format arguments [-Wformat-security]
29:5: warning: pointer ‘u’ used after ‘free’ [-Wuse-after-free]
7:5: warning: ‘__builtin___strcpy_chk’ writing one too many bytes into a region of a size that depends on ‘strlen’ [-Wstringop-overflow=]
15:12: warning: ‘n’ may be used uninitialized [-Wmaybe-uninitialized]
13:9: warning: ‘n’ may be used uninitialized [-Wmaybe-uninitialized]
== clang -Wall -Wextra
14:9: warning: variable 'n' is used uninitialized whenever 'if' condition is false [-Wsometimes-uninitialized]
21:12: warning: format string is not a string literal (potentially insecure) [-Wformat-security]
== gcc -fanalyzer
21:12: warning: format not a string literal and no format arguments [-Wformat-security]
7:5: warning: use of possibly-NULL ‘p’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]
15:12: warning: use of uninitialized value ‘n’ [CWE-457] [-Wanalyzer-use-of-uninitialized-value]
15:12: warning: use of uninitialized value ‘n’ [CWE-457] [-Wanalyzer-use-of-uninitialized-value]
29:5: warning: double-‘free’ of ‘u’ [CWE-415] [-Wanalyzer-double-free]
== clang --analyze
15:5: warning: Undefined or garbage value returned to caller [core.uninitialized.UndefReturn]
29:5: warning: Attempt to free released memory [unix.Malloc]

Who found what

Mapping each warning to its line and bug number gives a coverage table. The model below holds the table as data (read off the session output) and computes what the combination finds. It runs in your browser:

python · try it yourself
BUGS = {1: "malloc(strlen) no NUL (line 6-7)", 2: "NULL not checked (line 7)",
        3: "n uninitialised (line 13-15)", 4: "sprintf overflow (line 20)",
        5: "format string (line 21)", 6: "double free (line 29)"}
FOUND = {
    "gcc -Wall -Wextra -O2": {1, 3, 5, 6},     # stringop-overflow, maybe-uninitialized, format-security, use-after-free
    "clang -Wall -Wextra":   {3, 5},           # sometimes-uninitialized, format-security
    "gcc -fanalyzer":        {2, 3, 5, 6},     # possible-null-argument, uninitialized, double-free
    "clang --analyze":       {3, 6},           # UndefReturn, unix.Malloc
}
print(f"{'tool':23}" + "".join(f"{b:>3}" for b in BUGS))
for tool, found in FOUND.items():
    print(f"{tool:23}" + "".join(f"{'x' if b in found else '.':>3}" for b in BUGS))
union = set().union(*FOUND.values())
print("found by at least one tool:", sorted(union))
for b in sorted(set(BUGS) - union):
    print("missed by all:", BUGS[b])
tool                     1  2  3  4  5  6
gcc -Wall -Wextra -O2    x  .  x  .  x  x
clang -Wall -Wextra      .  .  x  .  x  .
gcc -fanalyzer           .  x  x  .  x  x
clang --analyze          .  .  x  .  .  x
found by at least one tool: [1, 2, 3, 5, 6]
missed by all: sprintf overflow (line 20)
  • No single tool found everything, and the two compilers disagree: GCC at -O2 found the missing NUL (its -Wstringop-overflow uses the same size tracking as FORTIFY) and the double free (-Wuse-after-free, new in GCC 12); Clang's -Wall found the uninitialised path more precisely and the format string.
  • The analysers add path reasoning: -fanalyzer alone saw that malloc may return NULL before strcpy (CWE-690), and both analysers tag findings with checker names (and GCC with CWE numbers), which makes triage easier.
  • The sprintf overflow was missed by every tool. The length of user is unknown at compile time, so nothing can prove the overflow. That bug is found by ASan in a test with a long name, by a fuzzer, or by a reviewer who knows that sprintf into a fixed buffer is always suspicious. Static analysis narrows the search; it doesn't end it.

The analysers that aren't in the sandbox

  • clang-tidy: checks for C and C++ style and bug patterns: bugprone-* (e.g. bugprone-not-null-terminated-result), cert-* (the SEI CERT C/C++ rules), cppcoreguidelines-* (bounds, ownership, casts), and clang-analyzer-* (the Clang Static Analyzer).
  • cppcheck: a standalone analyser with few false positives; good on buffer sizes it can compute and on resource leaks.
  • CodeQL: compiles the code into a database and runs queries in a Datalog-like language. Its taint tracking follows data from a source (a read(), recv(), argv) to a sink (a memcpy length, an allocation size, a format argument). GitHub runs it as "code scanning".
  • Semgrep: pattern rules that look like code (strcpy($DST, $SRC)), quick to write for a team's own banned functions.
  • Coverity, PVS-Studio, Klocwork: commercial analysers with deep inter-procedural analysis; Coverity Scan is free for many open-source projects.

A warning policy for C and C++

A practical baseline for new code: -Wall -Wextra -Wformat=2 -Wformat-security -Wconversion -Wsign-conversion -Wimplicit-fallthrough -Wshadow -Wvla -Werror=format-security, plus -Werror in CI so warnings can't accumulate. Build with both GCC and Clang if the project can, and run one analyser (-fanalyzer, clang --analyze or clang-tidy) on every change and CodeQL or similar on the main branch. For old code with thousands of warnings, turn them on one family at a time and fix size- and format-related ones first: they are the ones that become CVEs.

Pitfalls

  • Silencing instead of fixing. A cast that hides -Wsign-compare created the bug in Signedness and Truncation.
  • Optimisation-dependent warnings. GCC's -Wmaybe-uninitialized and -Wstringop-overflow depend on what the optimiser sees; a -O0 debug build shows fewer. Compile the warning job at -O2.
  • False positives fatigue. An analyser that reports 500 issues on day one gets ignored. Start with a baseline, fail CI only on new findings, and burn down the old ones.

Practice

1. Why did GCC report ‘__builtin___strcpy_chk’ writing one too many bytes for line 7 although the code calls strcpy?

At -O2 Ubuntu enables _FORTIFY_SOURCE=3, which rewrites strcpy into __builtin___strcpy_chk with the destination size. Because the size is strlen(s) and the copy is strlen(s) + 1, the compiler can prove one byte too many without knowing s.

2. Which single tool would you add to catch bug 4, and with what input?

ASan in a test (or a fuzzer) that calls log_line with a name of 3 or more characters: "user=" is 5 bytes, plus the name, plus the NUL, into 8 bytes.

3. Write a Semgrep-style pattern that flags bug 5 in general.

printf($X) where $X is not a string literal (Semgrep: pattern: printf($X) with metavariable-regex excluding "..."), and the same for fprintf($F, $X), syslog($P, $X), snprintf($B, $N, $X).

Test yourself

Which seeded bug did none of the four tools report?

  1. The double free
  2. The format string
  3. The sprintf overflow into char buf[8]
  4. The uninitialised n

Which tool alone reported that malloc might return NULL before strcpy?

  1. gcc -Wall
  2. clang -Wall
  3. gcc -fanalyzer
  4. clang --analyze

Why compile with both GCC and Clang warnings?

  1. One of them is always wrong
  2. They catch different bugs: here GCC found the missing NUL and the double free, Clang the uninitialised path precisely
  3. It's faster
  4. Clang can't compile C

What does CodeQL's taint tracking follow?

  1. Memory addresses at run time
  2. Data flowing from a source such as recv() to a sink such as a memcpy length
  3. Git history
  4. Compiler flags