Cake - C23 and Beyond
- Conventions and Contracts in C
Conventions and Contracts in C
Ownership, nullability and initialization, written down and checked
The examples were checked with Cake 0.15.28.
Preface
C trusts the programmer. That trust is the source of its power and of most of its bugs: a pointer that was null, a buffer that was freed twice, a value that was never set. Every C program already follows conventions: this pointer is never null, that function frees what it receives, this struct is filled in by the callee. They live in comments, in documentation, or only in the programmer's head. The rules in this text define those conventions precisely and give each one an annotation, so that a declaration states a contract between a function and its callers. A flow analysis checks both sides of every contract.
This matters more as more C is written by AI tools. A model reads the contracts in the declarations it is given, and when it breaks one, the analysis reports it in a single line it can act on. The model writes, the analysis checks, the model fixes, until nothing is reported. Verified contracts turn "looks plausible" into "agrees with the declarations".
The annotations do not change what a program does. Remove them and the program still compiles with any C compiler, and it means exactly the same thing. They exist only to be checked.
The idea is not new to C. _Noreturn ([[noreturn]] in C23) already says something about a function that its type cannot: the call never returns. It does not change what the function does, and it is read by the flow analysis: the path that calls it does not continue. If C did not have it yet, it would be one of the annotations described here. [[nodiscard]] is another: a contract that asks the caller to use the result. An _Owner result asks the same, for a stronger reason.
The rules are presented first as a tutorial, not as a reference manual. The rules follow the traditions of C, and so does this text: its style is deliberately modeled on The C Programming Language by Kernighan and Ritchie: a quick tour first, the details after, and a reference manual at the end. Chapter 1 is a quick tour; the chapters after it go over the same ground more carefully. The precise rules are in Appendix A, numbered so that a warning can be traced back to the rule that produced it. A reader who wants to implement the analysis should read Appendix A; a reader who wants to use it should start with Chapter 1 and write programs.
The only way to learn a new set of rules is to write programs with them. Every example here can be compiled with cake, or run online in the playground. Most sections end with an experiment: a small change to an example, ready to open in the playground, where the reader observes the result.
Chapter 1 - A Tutorial Introduction
Let us begin with a quick introduction. Our aim is to show the essential ideas through real programs, without getting bogged down in details, rules and exceptions.
1.1 Getting Started
The checks are off by default. A file turns them on with this line at its beginning:
#pragma safety enable
In that file, the compiler reads the annotations _Opt, _Owner, _Out, _Dtor, _Clear, _Uninitialized and _View, and warns when the code does not agree with them.
The first thing to know is that a pointer, in this world, is never null unless it says so.
#pragma safety enable
struct person {
const char* name; /* never null */
const char* _Opt nickname; /* may be null */
};
void print(const char* s);
void f(const struct person* p)
{
print(p->name); /* ok */
}
void g(struct person* p)
{
p->name = 0; /* warning 35 null assigned to non-nullable */
}
A pointer declared with _Opt is nullable: it may be null. A pointer declared without it is non-nullable: it is never null. That is the whole idea, and it is surprisingly far-reaching. f can use p->name without a test because the declaration of struct person promises it is there; g breaks that promise, and is told so.
1.2 Testing Before Use
A nullable pointer must be tested before it is used.
#pragma safety enable
struct point { int x; int y; };
struct point* _Opt find_point(int id);
int main()
{
struct point* _Opt p = find_point(1);
p->x = 1; /* warning 33 possible null dereference */
if (p)
p->x = 1; /* ok, narrowed to non-null */
}
Inside the if, the analysis knows p is not null. We say the condition narrows p. Nothing special has to be written for this; the test the programmer would write anyway is enough.
1.3 Owners
Some pointers are responsible for what they point to. A file returned by fopen must reach fclose exactly once. Such a pointer is an owner, and it is declared with _Owner.
#pragma safety enable
typedef struct _FILE FILE;
FILE* _Owner _Opt fopen(const char* name, const char* mode);
int fclose(FILE* _Owner p);
void f(void)
{
FILE* _Owner _Opt f = fopen("a.txt", "r");
if (f == 0) return;
FILE* _Owner g = f; /* g is the owner now */
fclose(g);
}
Assignment between owners moves the responsibility: after g = f, it is g that must be closed, and f must not be. Passing an argument to an _Owner parameter, as in fclose(g), is also a move. After fclose the file no longer exists, so using f again is a mistake:
#pragma safety enable
typedef struct _FILE FILE;
FILE* _Owner _Opt fopen(const char* name, const char* mode);
int fclose(FILE* _Owner p);
void f(void)
{
FILE* _Owner _Opt f = fopen("a.txt", "r");
if (f == 0) return;
fclose(f);
fclose(f); /* warning 32 'f' was moved */
}
Experiment 1-1. In the example above, the first fclose(f) is removed. Open it in the playground and observe the result.
So is forgetting to move it at all:
#pragma safety enable
typedef struct _FILE FILE;
FILE* _Owner _Opt fopen(const char* name, const char* mode);
int fclose(FILE* _Owner p);
void f(void)
{
FILE* _Owner _Opt f = fopen("a.txt", "r");
if (f == 0) return;
} /* warning 29 'f' still owns its resource */
1.4 Uninitialized Local Variables
A local variable that was not initialized has no value. Reading it is a mistake:
#pragma safety enable
int main()
{
int i;
int j = i; /* warning 30 assigning a possibly uninitialized object 'i' */
}
Often a variable is left uninitialized on purpose, because a function will fill it. That function declares its parameter with _Out:
void point_init(_Out struct point* p);
This declaration is a contract between point_init and its callers. Each side is checked separately.
The caller. It may pass an object that holds nothing yet, and after the call it may read every member:
#pragma safety enable
struct point { int x; int y; };
void point_init(_Out struct point* p);
int main()
{
struct point pt; /* uninitialized */
point_init(&pt); /* ok */
int x = pt.x; /* ok, point_init wrote it */
}
The implementation. It may not read *p, and it must write every member before it returns. Forgetting one is reported here, in point_init, not at the call:
#pragma safety enable
struct point { int x; int y; };
void point_init(_Out struct point* p)
{
p->x = 0;
} /* warning 71 _Out parameter 'p->y' is not initialized at exit */
Every annotation works this way: the caller is checked against what the declaration requires, and the implementation against what it promises.
1.5 One Function at a Time
The analysis never looks inside a function that is called. It reads the declaration and believes it. That is why the annotations matter: they are the contract between the function and its callers, and each side is checked against it separately.
When a declaration says nothing, the caller must assume the worst. Here g might have released x.text, so p may point to memory that no longer exists:
#pragma safety enable
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; };
struct X f();
void g(struct X* p);
int main()
{
struct X x = f();
char* _Opt p = x.text;
g(&x);
if (p)
{
char c = *p; /* warning 31 lifetime of '*p' has ended */
}
free(x.text);
}
Experiment 1-2. In the example above, the declaration of g is changed to void g(const struct X* p). Open it in the playground and observe the result.
If g is declared void g(const struct X* p), it promises not to touch x, and the warning goes away. We will come back to this in Chapter 4.
A file-scope object is treated the same way. To each function it is a parameter that does not appear in the list: the function knows only what its declaration says, and must leave it valid when it returns.
Chapter 2 - Pointers and Nullability
2.1 Where _Opt Goes
_Opt applies to the pointer itself, so it goes after the *, where const would go for a constant pointer. Like const, it may be used on any pointer: local and file-scope variables, members, parameters and results.
struct X* _Opt p; /* p may be null */
struct X* const _Opt q; /* q may be null and cannot be changed */
2.2 Leaving the Path
Any way of leaving a path narrows what comes after it, not only an if around the code. An early return is the most common:
#pragma safety enable
struct point { int x; int y; };
void point_print(const struct point* _Opt p)
{
if (p == 0) return;
int x = p->x; /* ok, p is non-null here */
}
break, continue, goto and throw work the same way.
2.3 What a Call Forgets
A test holds only until something may change the object. A function that receives a non-const pointer may change every object reachable from it, so after the call a nullable member must be tested again.
#pragma safety enable
struct person {
const char* name;
const char* _Opt nickname;
};
void print(const char* s);
void update(struct person* p);
void f(struct person* p)
{
if (p->nickname)
{
update(p);
print(p->nickname); /* warning 35 may be null */
}
}
With void update(const struct person* p) the test would still hold. The analysis assumes that nothing reachable from *p changes (Section 6.3).
Because of this, const improves the static analysis: the caller keeps what it knew. That is why the implementation of a function is warned when a pointer parameter could be const:
#pragma safety enable
struct point { int x; int y; };
int point_sum(struct point* p) /* warning 82 'p' could be const */
{
return p->x + p->y;
}
2.4 Objects Under Construction
There is one moment when a non-nullable member may be null: while the object is being built. struct person p = {} sets every member to zero, name included; so does calloc for an object on the heap. That is allowed, but the object may not be used until name is set.
#pragma safety enable
struct person {
const char* name;
const char* _Opt nickname;
};
void use(const struct person* p);
void f1(void)
{
struct person p = {}; /* ok, p.name is null for now */
p.name = "Ana";
use(&p); /* ok */
}
void f2(void)
{
struct person p = {};
use(&p); /* warning 35 'p.name' may be null */
}
Experiment 2-1. In f2, p.name is set before use(&p). Open it in the playground and observe the result.
Chapter 3 - Ownership
3.1 Two Kinds of Pointers
An owner is an object that holds a link to another object. That link is the principal one: ownership of the object is transferred only through it. Other pointers to the same object are views; they can look at it, but cannot move it.
If the principal link is broken, by overwriting the owner or by letting it go out of scope, nothing is left that can release the object. Its control is lost.
At run time an owner and a view are the same plain pointer. The difference is only in what the program promises to do with them.
The rules are short:
- an owner must be moved exactly once before it goes out of scope;
- an owner must not be overwritten before it is moved;
- a non-owner may not be made into an owner.
3.2 Assignment
Assigning one owner to another transfers the ownership. Assigning an owner to a non-owner does not: the non-owner becomes a view, and the original owner still has to be moved. When the owner is released, the view is no longer valid, and the analysis follows it.
#pragma safety enable
void free(void* _Owner _Opt p);
struct X { int i; };
void f(struct X* _Owner p)
{
struct X* view = p;
free(p);
view->i = 1; /* warning 31 lifetime of 'view->i' has ended */
}
After a move between owners, the source can still be used to read the object. A move only changes who must release the object, not whether it is alive. When the move is visible in the same function, the analysis knows the object is still alive and accepts the use. When the owner is moved into a function, the analysis cannot see what the function did with it, so it assumes the lifetime may have ended:
#pragma safety enable
void destroy(char* _Owner p);
char* _Owner _Opt strdup(const char* s);
int puts(const char* s);
void f(void)
{
char* _Owner _Opt s1 = strdup("hello");
if (s1 == 0) return;
char* _Owner s2 = s1;
puts(s1); /* ok, the object is alive */
destroy(s2);
puts(s1); /* warning 31 lifetime of '*s1' has ended */
}
3.3 Owner Members
A struct with an _Owner member owns what that member points to. Overwriting the member without releasing it first loses the object:
#pragma safety enable
char* _Owner _Opt strdup(const char* s);
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; };
void f(struct X* p)
{
p->text = strdup("a"); /* warning 26 'p->text' discarded without releasing it first */
}
void x_destroy(_Dtor struct X* p)
{
} /* warning 29 'p->text' still owns its resource */
3.4 Two Resources
A pointer to a struct owns two things: the memory, and the object stored in it. The object may own other objects through its _Owner members, and those may own others. Owners and the objects they point to form a chain, and the owner at the top is responsible for the whole chain. free takes a void*; it knows nothing about the members and releases only the memory. Everything below it in the chain must be released first. If a link of the chain is lost, everything that hangs from it is lost too.
#pragma safety enable
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; };
void x_delete_bad(struct X* _Owner p)
{
free(p); /* warning 29 'p->text' still owns its resource */
}
void x_delete(struct X* _Owner p)
{
free(p->text); /* the object */
free(p); /* the memory */
}
Experiment 3-1. In x_delete, the two calls to free are swapped. Open it in the playground and observe the result.
3.5 Heap Objects Must Have an Owner
A function that returns an owner hands the object to its caller. Ignoring the result loses it.
#pragma safety enable
char* _Owner _Opt make(void);
void f(void)
{
make(); /* warning 9 ignoring the result of _Owner type */
}
Chapter 4 - Functions and Their Contracts
4.1 The Plain Pointer Parameter
The most common parameter in C is struct X* p. With no annotation, it means:
pis not null, and*pis a complete, valid object;- the function may change
*p, but must leave it valid; *pstill belongs to the caller.
The function may release an owner member, but it must put something back before it returns:
#pragma safety enable
char* _Owner _Opt strdup(const char* s);
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; };
void f(struct X* p)
{
free(p->text);
} /* warning 72 'p->text' was moved but never reassigned */
void g(struct X* p)
{
free(p->text);
p->text = 0; /* ok */
}
void h(struct X* p)
{
free(p->text);
p->text = strdup("b"); /* ok */
}
A const pointer promises more: nothing reachable from *p changes, so the caller may keep using what it knew before the call (Section 6.3).
4.2 Output Parameters: _Out
_Out says the function initializes *p and does not read it. The function must write every member on every path, including the paths that fail.
#pragma safety enable
struct point { int x; int y; };
void point_init(_Out struct point* p)
{
p->x = 0;
} /* warning 71 _Out parameter 'p->y' is not initialized at exit */
Reading *p before writing it is reading nothing:
#pragma safety enable
struct point { int x; int y; };
void point_init(_Out struct point* p)
{
int i = p->x; /* warning 30 assigning a possibly uninitialized object 'p->x' */
p->x = 0;
p->y = 0;
}
4.3 Destructors: _Dtor
A destructor releases everything the object owns and leaves its memory to the caller. _Dtor says exactly that: on every path, every owner member is moved; after the call, the object holds nothing.
#pragma safety enable
char* _Owner _Opt strdup(const char* s);
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; };
void x_destroy(_Dtor struct X* p);
void f(void)
{
struct X x = {};
x.text = strdup("a");
x_destroy(&x);
free(x.text); /* warning 30 possibly uninitialized 'x.text' */
}
A destructor must also accept an object that was only half built. If a constructor fails halfway, some members are still null, even members that are declared non-nullable. Inside a _Dtor function every pointer member may be null.
#pragma safety enable
_Clear void* _Owner _Opt calloc(unsigned long n, unsigned long size);
char* _Owner _Opt strdup(const char* s);
void free(void* _Owner _Opt p);
struct X {
char* _Owner name;
char* _Owner email;
};
void x_destroy(_Dtor struct X* p)
{
free(p->name); /* ok, may be null */
free(p->email); /* ok, may be null */
}
struct X* _Owner _Opt x_create(const char* name, const char* email)
{
struct X* _Owner _Opt p = calloc(1, sizeof * p);
if (p == 0)
return 0;
char* _Owner _Opt s = strdup(name);
if (s == 0)
{
free(p);
return 0;
}
p->name = s;
s = strdup(email);
if (s == 0)
{
x_destroy(p); /* ok, p->email is still null */
free(p);
return 0;
}
p->email = s;
return p;
}
Experiment 4-1. In the example above, x_destroy(p); is removed from the second error path. Open it in the playground and observe the result.
Experiment 4-2. In the same example, x_destroy takes a plain struct X* p instead of _Dtor struct X* p. Open it in the playground and observe the result.
4.4 Reset: _Clear
_Clear is a destructor that leaves the object zeroed and ready to be used again.
#pragma safety enable
char* _Owner _Opt strdup(const char* s);
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; int n; };
void x_clear(_Clear struct X* p);
void f(void)
{
struct X x = {};
x.text = strdup("a");
x_clear(&x); /* x.text released, x is all zero */
x.text = strdup("b"); /* ok, x.text is zero */
free(x.text);
}
On a result, _Clear describes memory like calloc gives: every member is zero. _Uninitialized describes memory like malloc gives: nothing is set.
#pragma safety enable
void free(void* _Owner _Opt p);
void use(int i);
struct X { int a; int b; };
_Uninitialized struct X* _Owner _Opt x_alloc(void);
void f(void)
{
struct X* _Owner _Opt p = x_alloc();
if (p)
{
p->a = 1;
use(p->a); /* ok, written first */
use(p->b); /* warning 30 'p->b' is uninitialized */
free(p);
}
}
4.5 Passing by Value Without Moving: _View
A struct passed by value moves its owner members into the function. With _View nothing is moved: the function may only look at them, and the caller still owns them.
#pragma safety enable
void free(void* _Owner _Opt p);
struct X { char* _Owner _Opt text; };
void show(_View struct X x);
void f(void)
{
struct X x = {};
show(x); /* not moved */
free(x.text); /* ok, x is still the owner */
}
4.6 Putting Annotations Together
Annotations combine, and each keeps its own meaning. _Uninitialized struct X* _Owner _Opt F(void) returns a pointer that may be null, that the caller must free, and whose object holds nothing yet. That is a precise description of malloc.
Chapter 5 - How the Analysis Sees a Program
5.1 Paths
The analysis reads a function the way the machine would run it, but it follows every path at once. At each point it knows the set of things each object may be: null or not, which value, owned or moved. A warning is a question asked of that set. "Can p be null here?" If any path says yes, the warning is reported.
Where paths meet, after an if, at a label, after a loop, the sets are joined:
#pragma safety enable
void f(int x)
{
int a = 1;
if (x)
goto L;
a = 2;
L:
compile_assert(a == 1 || a == 2);
}
compile_assert fails to compile unless its condition holds on every path. It is the most direct way to ask the analysis what it knows.
5.2 Paths That End
A path that returns does not arrive anywhere. Code after it in the same block is never reached, and the analysis says so.
#pragma safety enable
void f(int x)
{
int a = 1;
if (x)
{
return;
a = 99; /* warning 68 */
}
compile_assert(a == 1);
}
5.3 Loops
A loop that may run zero times may leave a variable unset. When the first test of the condition is known to be true, the loop runs at least once, and the analysis knows it.
#pragma safety enable
void f(const char* s);
void g(int n)
{
char* p;
for (int h = 0; h < 1; h++) p = "";
f(p);
}
void h(int n)
{
char* p;
for (int h = 0; h < n; h++) p = "";
f(p); /* warning 30 */
}
5.4 One Report per Fact
When the same mistake is reachable from many paths, it is reported once. The message says how many other paths lead to it.
#pragma safety enable
void use(int* p);
int g;
void f(int a, int b)
{
int* _Opt p = &g;
if (a) p = 0;
else if (b) p = 0;
use(p); /* warning 35 */
}
Experiment 5-1. Three more else if branches set p to null. Open it in the playground and observe the result.
Chapter 6 - Limitations
The rules describe what a declaration can say today. Some programs are correct but cannot be described, and some bugs cannot be seen. This chapter lists the ones a programmer will meet first.
6.1 Contracts That Cannot Be Written
Some contracts cannot be written yet. The best known is realloc: ownership of its argument moves only if the call succeeds. What is missing is only a syntax to state it: the flow analysis already tracks states that depend on the result of a call, and would follow such a contract as it follows the existing ones. Where the analysis cannot follow, the programmer marks the line with /* lint N */, which says "warning N is expected here", silences it, and complains if it does not happen.
#pragma safety enable
void* _Owner _Opt realloc(void* _Opt p, unsigned long size);
void free(void* _Owner _Opt p);
void f(int* _Owner _Opt p)
{
int* _Owner _Opt q = realloc(p, 10 * sizeof(int));
if (q == 0)
{
free(p); /* failed: p still owns the memory */
return;
}
p = q; /* lint 26 (realloc) */
free(p);
}
Experiment 6-1. In the example above, the /* lint 26 (realloc) */ comment is removed. Open it in the playground and observe the result.
6.2 Contracts That Are Not Written
The analysis knows only what a declaration says. Here id returns its argument, but its declaration does not say so. The analysis cannot tell that q points to the object released through p, and the use after free is not reported.
#pragma safety enable
void* _Owner _Opt malloc(unsigned long n);
void free(void* _Owner _Opt p);
int* id(int* q) { return q; }
int f(void)
{
int* _Owner _Opt p = malloc(sizeof(int));
if (!p) return 0;
int* q = id(p);
free(p);
return *q; /* use after free, not reported */
}
A contract saying "the result points to the same object as the argument" would let the analysis follow the pointer through the call. No such annotation exists yet, but nothing new is needed in the analysis: it already follows a pointer to the same object through assignments, and a contract would let it do the same through the call. Only the syntax is missing.
realloc and id are two examples of a larger need. The annotations describe a fixed set of contracts, and more of them are still needed, or a more general way to write a contract.
6.3 What the Analysis Assumes About const
In C a const struct X* p protects only *p: p->m cannot be written, but p->m->x can. The analysis assumes more: after a call through const, the caller keeps what it knew about everything reachable from *p.
Where a function's implementation does not agree with that, warning 120 reports it: writing p->m->x (or ++, +=...) through a const pointer p, or letting p->m out as a pointer that is not const: passed to such a parameter, copied to such a pointer (struct m* q = p->m;, int* q = &p->m->x;) or returned as one. Once out, the copy could change what const promised. A void* parameter follows the same rule: a non-const void* says it may write (memset), one that only reads takes const void* (the source of memcpy). A struct copied by value (struct X y = *p;, return *p;, f(*p)) carries its pointer members without the const, so it is reported too when it has pointers to non-const. Passing it to a const parameter is fine: that function assumes the same and is checked the same way. An explicit cast is taken as intended. The same is reported through any const pointer (a local, a member), not only a parameter: it may not be what the programmer meant.
A move is also a write: it does not change any byte, but it changes the owner's state to "moved". So const applies to it. Moving p->head from a const struct list* p is warning 99 (C does not see a move as a write), and moving p->head->next is warning 120. Someone may be pointing to the const object and still expect it to own what it owns.
This applies only to const reached through a pointer, an object that belongs to someone else. A const object of our own (a local, or a parameter by value as in void f(const struct X x)) still has to move its owners at the end of its lifetime, like any other object: destroying it is not changing it.
For the same reason, a parameter whose owner is moved is not suggested const (warning 82): void f(struct list* p) { free(p->head); ... } would no longer compile cleanly with const.
A function that receives const and hands out something reachable from it as non-const (a lookup, like strchr) breaks the promise for its callers. Provide two versions: T* find(const C*) for callers that change the result, and const T* find_const(const C*) for callers that only read it.
6.4 Functions That Are Too Large
The analysis follows every path, and in a very large function the number of objects and paths can grow too much. When that happens the analysis stops, reports warning 97 once, and reports nothing else for that function. The next function is analysed normally. Splitting the function brings the analysis back.
6.5 Backward goto
A while or for loop is analysed as a loop: what one iteration does reaches the next. A label is not. A goto that jumps back to a label above it has no effect on what the analysis knows, so the result is too optimistic:
#pragma safety enable
void f(int n)
{
int a = 0;
L:
a = a + 1;
if (n > 0)
{
n = n - 1;
goto L;
}
compile_assert(a == 1); /* passes, but a may be any positive value */
}
Write the loop with while or for instead.
6.6 Comparing Two Pointers
Two pointers to different objects are taken to be always different, so p == q is seen as false and its branch as unreachable. At run time the two pointers may be equal, for example when both are null.
#pragma safety enable
void f(int* _Opt p, int* _Opt q)
{
if (p == q)
{
/* reachable at run time, but not analysed */
}
}
Comparisons with 0 or nullptr are not affected.
6.7 Arrays Whose Size Is Not Known
Indexes are checked only against arrays whose size is a constant. A variable length array, or a pointer to n items, has a size known only at run time, and an index past its end is not reported.
#pragma safety enable
void f(int n, int* p)
{
int a[n];
a[n] = 0; /* out of bounds, not reported */
p[n] = 0; /* p points to n items: out of bounds, not reported */
}
Appendix A - Reference Manual
This appendix states the rules more precisely.
A1. Definitions
- A1.1 Valid: the object and every object reachable from it are fully initialized, their non-nullable pointer members are non-null, and no owner among them is moved. For example, "
*pis valid" is a statement about*pand everything that can be reached throughp: its members, the objects they point to, and so on. - A1.2 Uninitialized: the object holds no value and no resources.
- A1.3 Nullable / non-nullable: a pointer declared with
_Optis nullable; without it, non-nullable. - A1.4 Empty: uninitialized, null or moved.
A2. Plain parameters: struct X* p
- A2.1 The implementation assumes
pis not null,*pis valid, andpdoes not own*p. - A2.2 At every exit
*pis valid. - A2.3 The caller must pass a non-null pointer to a valid object. After the call it must assume every object reachable from
*pmay have changed, and that its pointers into them are no longer valid. - A2.4 With
const, the analysis assumes that nothing reachable from*pis written or moved, so what the caller knew still holds (6.3). C protects only*p, so the implementation is checked for writes that break this assumption, and for pointers reachable from*pthat leave as non-const(passed,void*included; copied, also as&p->m->x; returned; or inside a struct copied by value) (warning 120).
A3. Results: struct X* F(void)
- A3.1 The result is not null and
*resultis valid. The caller does not own it. - A3.2 The implementation must return a value on every path: reaching the closing
}of a non-void function leaves the result uninitialized (warning 98).mainis the exception, its end returns 0.
A4. _Opt
- A4.1 On a parameter or result, null may be passed or returned, and the receiver must test before use.
- A4.2 On a member, readers must test before use and writers may store null.
- A4.3
_Optmay be used wherever a pointer is declared: local and file-scope variables, members, parameters and results.
A5. Assignment a = b
- A5.1
aand its owner members must be empty. - A5.2
bmust be valid (A1.1). - A5.3 When
ais an owner,bmust be an owner too (or a null pointer constant); a view cannot be assigned to an owner. Owner to owner movesb. Owner to non-owner makesaa view of the objectbstill owns. - A5.4
= {}may leave non-nullable members null until they are set and before the object is used. - A5.5 Passing an argument and returning a value follow the same rules, with the parameter or the result as
a. Thereais a new object, uninitialized, so A5.1 always holds. - A5.6 A move changes only which owner must release the object. After
a = bbetween owners, the object is still alive and may be read throughb. Afterbis passed to an_Ownerparameter, the lifetime of the object may have ended and it must not be used throughb.
A6. _Out
- A6.1
*pis uninitialized at entry and must be fully initialized on every exit. Owner members not created are null. - A6.2 The caller must pass
*pempty (A1.4).
A7. _Dtor
- A7.1 The caller must pass a valid object (A1.1), with one exception: its non-nullable pointer members may be null, so a partially constructed object is accepted. The implementation assumes the same.
- A7.2 At every exit every owner member of
*pis moved.- A7.3 After the call*pis uninitialized and its memory is still the caller's. - A7.4
_Dtorcannot be combined withconst. - A7.5
_Dtormay be used only on the pointed type of a parameter.
A8. _Clear
- A8.1 On a parameter, the caller must pass a valid object (A1.1), without the exception of A7.1. At every exit every owner member is moved and every member is zero.
- A8.2 On a result, every member of
*resultis zero. - A8.3
_Clearmay be used only on the pointed type of a parameter or of a result (as incalloc). - A8.4
_Clearcannot be combined withconst.
A9. _Uninitialized
- A9.1
_Uninitializedmay be used only on the pointed type of a result:*resultis uninitialized.
A10. _View
- A10.1 An object declared
_Viewdoes not own its owner members: assigning to it, or passing it by value, moves nothing, and the source still owns them. Without_View, they are moved. - A10.2
_Viewcannot be used on a pointer: a pointer without_Owneris already a view. - A10.3
_Viewmay be used wherever an object is declared: parameters, local and file-scope variables, and members (for example_View struct X x2 = x;).
A11. _Owner
- A11.1 An
_Ownerparameter must be moved on every exit; the argument is moved. - A11.2 An
_Ownerresult must be moved by the caller. - A11.3 An object owns what its
_Ownermembers point to; they must be moved before the object is destroyed. - A11.4
_Ownermay be used wherever an object is declared: local and file-scope variables, members, parameters and results. It is not limited to pointers (_Owner intfor a file descriptor). - A11.5 A move changes the owner's state, so it is a write: an owner that is
constthrough a pointer cannot be moved (warning 99), nor an owner reachable from aconstobject (warning 120, 6.3). Aconstobject of our own (local, parameter by value) still moves its owners at the end of its lifetime.
A12. Combination
- A12.1 Annotations combine; each adds its own contract and does not change the others.
A13. Casts
- A13.1 Casts are not yet defined: whether a cast may add or remove an annotation (for example from
T* _OpttoT*, or fromT* _OwnertoT*) is an open question.
A14. Flow analysis
- A14.1 The analysis runs on one function at a time. A call is described only by the declaration of the callee.
- A14.2 A file-scope object is not a parameter, but to each function it behaves as if it were one that does not appear in the parameter list. At entry it holds any value allowed by its type, and at every exit its contract must hold again.
- A14.3 At each point, every object has a set of possible states. Each state comes from at least one path. A diagnostic must be reported when some state supports it and must not be reported when none does.
- A14.4 Where paths meet, the set is the union of the arriving sets. A path that left by
return,break,continue,goto,throwor a noreturn call does not arrive. - A14.5 In the true branch of a condition only the states where it can be true remain; in the false branch, only those where it can be false.
- A14.6 Code no path reaches must be reported with warning 68, and its effects must not reach any later point.
- A14.7 When the first test of a loop condition is true in every state, the zero-iteration path must not exist. A
dobody runs at least once. - A14.8 A fact supported by several paths is reported once.
- A14.9 An implementation that stops analysing a function must report warning 97 once and nothing else in that function.
A15. Compatibility of annotated types
_Opt is checked in two places. The flow analysis checks the value (whether it can be null at that point, branch by branch). The type checks the pointed objects, because writes through a pointer happen later, where the flow analysis does not see them.
- A15.1 The value copied by an assignment, argument or return (the top level) may drop
_Opt(T* _OpttoT*); whether it is null there is checked by the flow analysis (A4.1). It may drop_Owner(A5.3), but it cannot gain_Owner. - A15.2 Through a pointer, the pointed object is shared, so its annotations must allow every access the destination can make:
- when the destination pointee is mutable,
_Optand_Ownermust match exactly at every level; - when the destination pointee is
const(read only, as inint * _Opt const *), it may add_Optbut not remove it; - when the destination pointee is
_Out(write only), it may remove_Optbut not add it:char * _Out _Opt *cannot receive&swhensischar *, because null may be stored ins(issue #523).
- when the destination pointee is mutable,
- A15.3 A function pointer may point to a function that accepts more and promises more: each parameter of the function may add
_Opt(void (*pf)(int *p)may point tovoid f(int * _Opt p), but not the opposite), and its result may remove_Opt._Owneron parameters and results must match exactly. - A15.4 A
[[nodiscard]]function pointer may point to a function that is not[[nodiscard]]; a pointer without[[nodiscard]]cannot point to a[[nodiscard]]function. This is only between function types: the result of a call is a value, sostruct X * _Owner _Opt p = malloc(sizeof *p);is fine even thoughmallocis[[nodiscard]]. - A15.5
[[noreturn]]/_Noreturnmust match exactly. - A15.6 Only
_Optand_Owner(and, between functions,[[nodiscard]]and[[noreturn]]) are compared._Clear,_Uninitialized,_Dtorand_Viewdescribe the state of an object and are not part of compatibility:struct X * _Owner _Opt p = calloc(1, sizeof *p);is fine with_Clear void * _Owner _Opt calloc(...).constand_Outonly select the A15.2 rule. - A15.7 These rules apply only when the extensions are on (
#pragma safety enable); otherwise compatibility is the one in C23 6.2.7. - A15.8 In
c ? a : bthe_Optof the result value is decided by the flow analysis, per branch (p ? p : 0may be null,p ? p : qis not), and_Ownerstays in the type. Below the value,aandbpoint to shared objects, so_Optand_Ownermust match at every pointee level:c ? (int * _Opt *) pp1 : (int **) pp2is incompatible.
Examples. Each line says what could go wrong if it were accepted.
#pragma safety enable
void f_ptr(int * p);
void f_opt(int * _Opt p);
int * _Opt g_opt(void);
int * g_nonnull(void);
void get(char * _Out _Owner _Opt * p);
void free(void * _Owner _Opt p);
void examples(int * p, int * _Opt q, int * _Owner o, int c)
{
/* A15.1 the copied value */
int * a = q; /* flow: warning 35, q may be null here */
int * b = o; /* ok: b is a view of what o owns */
/* A15.2 through a pointer: *pp is shared with the source */
int * _Opt * pp1 = &p; /* error: *pp1 = NULL would make p null */
int ** pp2 = &q; /* error: *pp2 is read as non-null, q may be null */
int * _Opt const * pp3 = &p; /* ok: read only, a non-null p is a valid _Opt */
int * const * pp4 = &q; /* error: read as non-null, q may be null */
char * _Owner s;
get(&s); /* error: get may store null in s */
free(s);
/* A15.3 function pointers: calls through pf go to the function */
void (*pf1)(int * p) = f_opt; /* ok: f_opt accepts more than pf1 passes */
void (*pf2)(int * _Opt p) = f_ptr; /* error: pf2(NULL) would reach f_ptr */
int * _Opt (*pg1)(void) = g_nonnull; /* ok: g_nonnull promises more */
int * (*pg2)(void) = g_opt; /* error: g_opt may return null */
/* A15.8 ?: the value is decided by flow, branch by branch */
int * r1 = q ? q : p; /* ok: q is not null in the first branch */
int * r2 = q ? q : 0; /* flow: warning 35, the second branch is null */
int * _Opt * r3 = c ? pp1 : &p; /* error: int * _Opt * and int ** share *r3 */
free(o);
}
#pragma safety enable
[[nodiscard]] int h_nd(void);
int h(void);
void attributes(void)
{
/* A15.4 the caller through the pointer must keep every promise of the function */
[[nodiscard]] int (*pn1)(void) = h; /* ok: the result is used, h does not care */
int (*pn2)(void) = h_nd; /* error: pn2() would discard h_nd's result */
}