Safe C

Library types

A C library's header says what its functions take and return, but not who frees what or how much memory a pointer reaches. Safe C needs both, so out of the box it rejects most calls into a library it knows nothing about. A types file supplies them without changing the library or your code, like a TypeScript .d.ts file.

// safe-c-types/zlib.h
#include_next <zlib.h>            // the library's own header, unchanged

const char *_Static zlibVersion(void);
int compress(Bytef *__counted_by(*destLen) dest, uLongf *destLen,
             const Bytef *__counted_by(sourceLen) source, uLong sourceLen);

Your program still writes #include <zlib.h>. safecc searches the types directories before the system headers, so it finds the types file, which includes the real header and then declares each function again with the annotations it lacks. That second declaration is what calls are checked against.

Where safecc looks

  1. ~/.safe-c/types/: your own, searched first, so it can add a library or replace a bundled file.
  2. share/safe-c-types/ in the installed package: the ones in this repo's safe-c-types.

A project can pass its own with -I path/to/types.

Writing one

Declare again every function your programs call. Each declaration says:

Write Meaning
the declaration as it is frees nothing, keeps no pointer past the call, returns a borrow of its first pointer argument (or a number)
T *_Owned result the caller owns the result and frees it with free()
T *_Owned parameter the function takes ownership (frees it, or keeps it until another call frees it)
T *_Static result the result points at storage that lives as long as the program, such as a version string
__counted_by(n) on a pointer the function reads or writes n elements there; Safe C checks the buffer is that big before the call
_Nullable may be null (otherwise never null)

A function the compiler already has a contract for (malloc, fopen, the rest of the C library it knows) cannot be declared again with different annotations.

A types file is trusted, like a _Trusted function: if it says a function frees nothing and the function does free, a use after free compiles. Write each declaration from the library's documentation, and add a test program.

Testing one

Each library has programs in safe-c-types/tests: zlib.c builds against the system's own zlib.h, links with -lz and runs; a program whose first line is // stops: must stop at a Safe C check (here, a length larger than the buffer). bash safe-c-types/check.sh runs them; it is the types gate in check-all.sh.

Limits

View the source of this page on GitHub