Safe C

Overview

The long version of the README: what the code looks like, the results, the standard library, how to adopt it, and the limits.

A fork of Clang with one flag, -fsafe-c, opted into one file at a time. What it cannot show is safe does not compile, or stops at run time instead of corrupting memory. The annotations come from one header, safec.h, and mean nothing to other compilers: the same file is C99, and the ABI does not change.

It does not make every C program safe. Its rules are proved sound in Lean; the compiler is tested against them, not proved: see Limits.

Try it: in the browser, or brew install safe-c-project/tap/safe-c and then safecc file.c (more).

The same bug in C, Rust and Safe C

A small text editor (Safe C), written three times, with the same mistake in each: on Enter, keep the old line's indent by reading the document through a view taken before the insert. The insert can move the text.

C compiles it with no warning, and it edits the wrong bytes:

struct str doc = text_str(&e->doc);
...
case '\n':
  replace(e, e->cursor, 0, STR("\n"));
  size_t was = line_start(doc, e->cursor - 1);
  if (doc.len > 0 && doc.p[was] == '\t')
    replace(e, e->cursor, 0, STR("\t"));
$ clang -Wall -Wextra edit.c        # no output
$ clang -fsanitize=address edit.c && ./a.out
ERROR: AddressSanitizer: heap-use-after-free

Rust rejects it:

let doc = &e.doc;
replace(e, e.cursor, 0, b"\n");
if !doc.is_empty() && doc[line_start(doc, e.cursor - 1)] == b'\t' {
error[E0502]: cannot borrow `*e` as mutable because it is also borrowed as immutable
420 |     let doc = &e.doc;
    |               ------ immutable borrow occurs here
421 |     replace(e, e.cursor, 0, b"\n");
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
422 |     if !doc.is_empty() && doc[line_start(doc, e.cursor - 1)] == b'\t' {
    |         --- immutable borrow later used here

Safe C rejects the C code as it is, for the same reason Rust does:

$ safecc edit.c
edit.c:336:18: error: 'doc.p' is passed to 'line_start' after the call to 'replace' on line 335
  336 |     size_t was = line_start(doc, e->cursor - 1);
edit.c:287:20: note: 'doc.p' points into what 'e' owns from here
  287 |   struct str doc = text_str(&e->doc);
edit.c:335:5: note: 'replace' may change what 'e' owns, which can move or free what 'doc.p' points to
  335 |     replace(e, e->cursor, 0, STR("\n"));
edit.c:336:18: note: get 'doc.p' again from 'e' after the call

The Safe C editor is 361 lines, the C one 465, the Rust one 454. No lifetimes are written: replace takes struct editor *e, and that is enough to know it may change what e owns.

What it looks like

#include "json.h"
#include "file.h"

int main(void) {
  struct text in = {0};
  struct json j = {0};
  if (file_read("people.json", &in) != 0 || !json_parse(&j, text_str(&in), NULL)) {
    json_free(&j);
    text_free(&in);
    return 1;
  }
  for (size_t p = json_first(&j, 0); p; p = json_at(&j, p).next) {
    struct str name = json_text(&j, json_get(&j, p, STR("name")));
    str_write(name, "\n", stdout);
  }
  json_free(&j);
  text_free(&in);
}

No annotations at all: they are in the headers. What goes wrong is an error:

struct str name = json_text(j, 1);
(void)json_parse(j, text, NULL);
return name.p[0];
// error: 'name.p' is used after the call to 'json_parse' on line 4

struct json_value v = json_at(j, json_get(j, person, STR("age")));
return v.number;
// error: reading 'number' needs the tag 'kind' known to be JSON_NUMBER here, or the
// union's bytes could be another member's; check it first (as in 'if (x.kind == JSON_NUMBER)'
// or 'case JSON_NUMBER:')

Real bugs

Bugs from Magma, a benchmark of real CVEs in libpng, libtiff, libsndfile, libxml2, sqlite and OpenSSL, picked by rule and rewritten in Safe C by hand (how):

Kind Blocked When Stock Clang -Wall -Wextra
Use after free (every one in the sample) 4 of 4 compile time no warning
Out of bounds, null, type confusion, divide by zero 17 of 17 3 at compile time, 14 stop at run time no warning

The fixed version of each is accepted and runs. They are reductions of a few lines, not the libraries.

The style

Seven programs were written this way: wc, uniq, comm, sort and tsort from sbase, a JSON parser and a text editor (all of them). The tools print what the originals print on 4,200 random inputs, the JSON parser agrees with JavaScript's on 3,987 documents, and the editor with a model on 17,467 keys. Only the editor has unsafe code: three small functions around the terminal.

Instead of Write
hoping every malloc is freed nothing: an owner never freed, returned or handed on is an error, and so is freeing a struct before what its fields own
a *_free function that might miss a field _Empties on its parameter: the compiler checks it leaves every owning field empty
a pointer per node, freed one by one one array of nodes and indexes into it (VEC): one thing to free
char * with a length somewhere else struct str to look at text, struct text to own it
setting a pointer and then its length _Set(p, n, new_p, new_n), both at once
a union and a comment saying which member _Tagged_by(kind) and _When(...) on each member
a pointer that may be null, and hoping _Nullable, and the compiler makes you check
a parameter you only read const: then nothing it points to changes in the call
returning int for success and hoping it is checked the same int, marked __attribute__((warn_unused_result)): dropping it is an error

The standard library

Not rewritten. The compiler knows what each C function frees, keeps and returns. Of 118 C99 functions, 98 are checked as they are and 20 are errors that name a replacement (clang/utils/safe-c/libc/check.sh).

The 47 functions that are errors, and what to use instead.

Where C has no safe way to do something, small headers in safe-c-std do it, with no unsafe code inside:

Header For Instead of
text.h str and text: split, trim, compare, numbers, lines strtok, strchr, atoi, getline
vec.h a growing array, once per type (#define VEC_NAME, VEC_TYPE); of owners too (VEC_OWNED), such as strings from strdup realloc by hand
map.h text to plain data hash tables by hand
file.h read a whole file; replace one all at once fread loops, half-written files
args.h options in argv indexing argv
json.h JSON, kept by index trees of pointers
pool.h handles that know when they are stale pointers between nodes of a graph
result.h optional, if you want Rust-style results: RESULT, OK, ERR, TRY; the value cannot be read before ok is checked an int code and an out-pointer (the other headers use those)

Get started

Install the prebuilt compiler (macOS arm64, Linux x86_64), or try it in the browser:

brew install safe-c-project/tap/safe-c
# or, without Homebrew:
curl -fsSL https://raw.githubusercontent.com/safe-c-project/safe-c/main/clang/utils/safe-c/install.sh | sh
safecc hello.c    # clang -fsafe-c, with safe-c-std and (on macOS) the SDK set up

To see it first: try/ has small programs with one bug each, and the command to compile them.

  1. Install or build the compiler (building), then compile one file: safecc parser.c. Start with the file that reads untrusted input.

  2. Fix what it reports. Errors say what is wrong and what to write.

  3. The annotations you meet first:

    Write When
    _Nullable the pointer may be null
    __counted_by(n) the pointer has a length, n
    _Owned whoever holds it must free it
    _Take(place) move an owner out of a field, leaving null; (void)_Take(p) lets it go on purpose
    _View a struct that borrows, kept on the stack
  4. Not ready to fix a spot? __unsafe { } around it, or #pragma clang safe_c legacy at the top of a header. A plain C library is called from a small __unsafe function, which answers for what it passes.

  5. Still building with gcc, MSVC or plain clang? Copy safe-c-std/safec.h into the project and #include "safec.h" in each file. Other compilers see the annotations as nothing. Under -fsafe-c the compiler's own copy comes first, so an outdated copy in the project changes nothing.

Every annotation: annotations. Every rule: rules (frozen; ideas wait in later).

Limits

Rules proved, compiler tested the rules are proved sound in Lean 4 (safe-c-lean): pointer kinds and bounds, ownership (owned, borrowed, free, realloc, stack scopes, views) and out arguments; that clang follows them is tested, not proved
Attacked four times blind attacks found 34, 32, 33, then 19 root causes, all fixed; the fixes and the later rules have not been attacked
Threads data races are checked only for data marked _Guarded_by a lock
Containers vec.h holds owners (VEC_OWNED); map.h holds plain data
Heap contents malloc and realloc return zeroed bytes; a block another library allocated (strdup in libc) can still bring a few stale bytes of slack through a realloc
Platform macOS (arm64) with Apple's SDK; Linux builds, but glibc's headers have no annotations
Cost 0% to 7% run time on the programs above, against the same code in plain Clang; ported libraries from 0.58x to 1.28x

Ported libraries: jsmn, inih, parson, puff (zlib's reference inflate) and cJSON with ownership on (cJSON's references are not sound), lz4 without. Every open item: open issues, and clang/utils/safe-c/holes.

Juliet

None missed. On a ported copy of NIST's Juliet suite, 6,773 of 11,522 cases in 10 bug classes (those whose fixed version builds after porting):

Bugs Caught When
Null, double free, use after free 608 of 608 compile time, as in Rust
Out of bounds, divide by zero, that the harness can make happen 5,545 of 5,545 at the bad access

Not counted: 394 need an input the harness does not give (a random value, a file, a socket), and 226 are not bugs on this target (32-bit-only overflows, floating-point division, buffers that stay terminated). 4,749 cases do not build after porting. For 3,221 of the traps the harness could not rule out one raised by the platform, and the run predates the current ownership checker.

A case counts only when Safe C gives a compile error or traps at the bug. Full table, the port and the exclusions.

View the source of this page on GitHub