Memory and ownership

This page says what cerastes proves about programs that use pointers. For every access through a pointer it proves that the access is defined: the pointer is not null, the object it points to still exists, and the function has the right to read or write it. A use of a pointer whose object has ended is an error too, even when nothing is read through it, as C and C++ say.

This version covers pointers to integers, bool and enumerations, and pointers to such pointers (Pointers to pointers): in local variables, as parameters and as results, with contracts that say which objects a function may read or write (Pointer parameters and contracts), in loops (Loops) and across jumps (Leaving a block); arrays of scalars as locals, globals, static locals, structure members and C compound literals (Arrays, [array-members]), and arrays of structures as locals, globals, static locals and structure members (Arrays of structures); global and static local variables (Global variables, static local variables); and memory from malloc, calloc and free (Allocated memory: malloc, calloc and free). What is not supported yet lists what is still rejected.

Objects whose address is taken

A local variable whose address is never taken is a plain value, as before. A local whose address is taken anywhere in the function (&x) is an object in memory: it exists from the moment its block is entered until the block ends, and it is reached by name or through any pointer to it. Reading or writing it through a pointer is the same as reading or writing it by name:

#include <cerastes.h>

int set_through(void)
    CERASTES_ENSURES(r, r == 2)
{
  int x = 1;
  int *p = &x;
  *p = 2;
  return x;
}

Each object starts without a value unless its declaration has an initializer, and reading it first is reported as uninitialized, whether the read is by name or through a pointer. Arithmetic through a pointer is checked like any other (Integer semantics): (*p)++ overflows exactly when x++ would.

Null pointers

A null pointer is written NULL, 0 or nullptr, in C and in C++. A pointer that may be null must not be dereferenced: such a read or write is reported as null-dereference. Testing the pointer first is enough, since cerastes follows the paths of the program:

#include <stddef.h>
#include <cerastes.h>

int store_if_set(int set)
    CERASTES_ENSURES(r, r == (set != 0 ? 5 : 0))
{
  int x = 0;
  int *p = NULL;
  if (set != 0) {
    p = &x;
  }
  if (p != NULL) {
    *p = 5;
  }
  return x;
}

A pointer used as a condition (if (p), !p, p && …) means p != NULL.

Comparing pointers

== and != compare pointers as C does: two pointers to different objects are never equal, and a pointer to an object is never null. CERASTES_CHECK and assert may use pointers like the code around them:

#include <cerastes.h>

int same_object(void)
    CERASTES_ENSURES(r, r == 1)
{
  int a = 1;
  int b = 2;
  int *p = &a;
  CERASTES_CHECK(&a != &b);
  return p == &a && p != &b;
}

Comparisons of order (<, >) and arithmetic on pointers are not supported yet, nor conversions between pointer types other than adding const to the object pointed to (Pointers to pointers).

A pointer may also point one past the end of an object, and C does not say whether such a pointer equals a pointer to another object that happens to follow it in memory. So when == or != compares two pointers that may point into different objects, one of them one past its end, cerastes reports pointer-comparison instead of choosing an answer. Inside one function this cannot happen; a pointer parameter can (Pointer parameters and contracts).

Lifetimes and dangling pointers

An object in memory ends when its block ends. After that, a pointer to it is dangling: reading or writing through it is reported as permission, and any other use of its value, even a test, a comparison or a copy, is reported as lifetime, because C and C++ make the value of such a pointer indeterminate:

#include <cerastes.h>

int use_after_block(int a)
{
  int found = 0;
  int *p;
  {
    int x = a;
    p = &x;
  }
  if (p) {
    found = 1;
  }
  return found;
}

Returning the address of a local variable or a parameter (return &x;, also through parentheses, a cast, either arm of ?: or the right operand of ,) is rejected, as clang’s -Wreturn-stack-address and GCC’s -Wreturn-local-addr warn about it: the object ends as the function returns (Shapes the compilers warn about). A copy of such an address returned through a variable (int *p = &x; return p;) is reported where the caller first uses it, as lifetime.

Pointers to pointers

A pointer variable whose address is taken is an object in memory like any other, so pointers to pointers (int **, and deeper) follow the same rules: *pp reads or writes the pointer that pp points to, **pp the object that pointer points to, and each step is checked:

#include <cerastes.h>

int retarget(void)
    CERASTES_ENSURES(r, r == 9)
{
  int x = 1;
  int y = 7;
  int *p = &x;
  int **pp = &p;
  **pp = 2;
  CERASTES_CHECK(x == 2);
  *pp = &y;
  CERASTES_CHECK(p == &y);
  return x + *p;
}

Writing *pp changes where p points. When the pointer stored in *pp is dangling, reading or writing **pp is reported as permission and any other use of *pp as lifetime, as for any pointer. In a loop, a write through a pointer to a pointer may change every pointer of that type, as a write through an int * may change every int (Loops).

A conversion may add const to the object a pointer points to (int ** to int *const *), but not further down. int ** to const int ** would let a const object be written through the original pointer, so it is rejected even when written as a cast, which compilers accept without a warning; int ** to const int *const *, which C++ allows and C does not, is rejected in both languages for now.

Two uses of one such object that C does not order, one of them a write (**pp + (**pp = 1), (*pp = &y) == *pp), are rejected, as GCC’s -Wsequence-point warns about them (Side effects in expressions).

A contract can name every object along the way. cerastes_owns(*pp) holds the pointer pp points to; cerastes_owns(**pp) (or cerastes_reads(**pp)) holds the object that pointer points to, and cerastes_live(*pp) says only that it points to a live object. An atom reached through a pointer read needs an earlier atom that holds that pointer: cerastes_owns(**pp) needs cerastes_owns(*pp) or cerastes_reads(*pp) before it, or the contract is reported as reading *pp without owning it:

#include <cerastes.h>

void set(int **pp)
    CERASTES_REQUIRES(cerastes_owns(*pp) && cerastes_owns(**pp))
    CERASTES_ENSURES(cerastes_owns(*pp) && *pp == cerastes_old(*pp) && cerastes_owns(**pp) && **pp == 5)
{
  **pp = 5;
}

int same(int **pp)
    CERASTES_REQUIRES(cerastes_owns(*pp) && cerastes_live(*pp))
    CERASTES_ENSURES(r, cerastes_owns(*pp) && *pp == cerastes_old(*pp) && cerastes_live(*pp) && r == 1)
{
  int *q = *pp;
  return q == *pp;
}

int use(void)
    CERASTES_ENSURES(r, r == 5)
{
  int x = 0;
  int *p = &x;
  set(&p);
  CERASTES_CHECK(x == 5);
  return x;
}

In a requires, **pp is the object *pp points to on entry; in an ensures, the one it points to on return. A function that may change *pp says whether it did: *pp == cerastes_old(*pp) when it does not, or names the new object. cerastes_old(**pp) is the value, on entry, of the object *pp pointed to on entry. A function may move *pp to another object it was given and promise cerastes_owns(**pp) for it; a function declared without a body must say which object its ensures names (*pp == cerastes_old(*pp), or *pp == q for an object it was given), since nothing checks such a contract against code. The same holds at any depth (***ppp) and through a pointer member (p->q->x, Structures) or a pointer global (*gp, Global variables).

Pointer parameters and contracts

A function that takes a pointer says in its contract what it may do with the object the pointer points to. Three specification functions, from <cerastes.h>, state it; in C they are spelled cerastes_owns, cerastes_reads and cerastes_live, in C++ also cerastes::owns, cerastes::reads and cerastes::live (the C spelling works in both, so a header shared by C and C++ writes one):

Written Means

cerastes_owns(*p)

p is not null and points to an object that exists, holds a value, and that the function may read and write; in ensures, the function gives it back

cerastes_reads(*p)

the same, but the function may only read the object; others may read it too

cerastes_live(p)

p is not null and points into an object that exists; the function may compare and copy p but not read through it

The caller must hold what the callee’s requires asks for, at the call, and the callee must hold what its ensures promises, at every return; either failure is reported as permission. Whatever the caller holds that the callee’s contract does not name keeps its value across the call. cerastes_old(*p) (in C++ also cerastes::old(*p)) in an ensures is the value *p had when the function was entered:

#include <cerastes.h>
#include <limits.h>

void inc(int *p)
    CERASTES_REQUIRES(cerastes_owns(*p) && *p < INT_MAX)
    CERASTES_ENSURES(cerastes_owns(*p) && *p == cerastes_old(*p) + 1)
{
  *p += 1;
}

int count_twice(void)
    CERASTES_ENSURES(r, r == 2)
{
  int x = 0;
  inc(&x);
  inc(&x);
  return x;
}

A function that only reads takes cerastes_reads: the caller lends it the right to read and can write the object again as soon as the call returns, and two reads of the same object may be passed to one call:

#include <cerastes.h>

int peek(const int *p)
    CERASTES_REQUIRES(cerastes_reads(*p))
    CERASTES_ENSURES(r, cerastes_reads(*p) && r == *p)
{
  return *p;
}

int read_then_write(void)
    CERASTES_ENSURES(r, r == 8)
{
  int x = 4;
  int a = peek(&x);
  x = a * 2;
  return x;
}

A pointer that may be null is described by a condition, p == NULL || cerastes_owns(*p), and the function tests it before it dereferences p:

#include <cerastes.h>
#include <stddef.h>

void reset(int *p)
    CERASTES_REQUIRES(p == NULL || cerastes_owns(*p))
    CERASTES_ENSURES(p == NULL || (cerastes_owns(*p) && *p == 0))
{
  if (p != NULL) {
    *p = 0;
  }
}

The attribute cerastes::owning on a pointer parameter (or CERASTES_OWNING, a macro that other compilers read as nothing) says the same in one word: the parameter may be null, and when it is not, the function owns its object and gives it back, exactly as p == NULL || cerastes_owns(*p) in both the requires and the ensures would. The attribute goes before the parameter’s declaration or after its name, and the contract’s other clauses may read *p where p != NULL:

#include <cerastes.h>
#include <stddef.h>

void bump(CERASTES_OWNING int *p)
    CERASTES_REQUIRES(p == NULL || *p < 100)
    CERASTES_ENSURES(p == NULL || *p == cerastes_old(*p) + 1)
{
  if (p != NULL) {
    *p += 1;
  }
}

int use_bump(void)
    CERASTES_ENSURES(r, r == 6)
{
  int x = 5;
  bump(&x);
  bump(NULL);
  return x;
}

Beside the attribute, an explicit cerastes_owns(*p) (which also says that p is not null) or p == NULL || cerastes_owns(*p) takes the attribute’s place in its clause list; cerastes_reads(*p), cerastes_live(p) or an owns under another condition is rejected. Every declaration of the function carries the same owning attributes, on the same parameters.

A few more rules:

  • A contract may read *p only where an owns or reads of *p comes before it, on that path; otherwise the contract itself is reported as permission ("the contract of f reads *p without owning it"). In an ensures, *p is the value when the function returns, so the ensures needs its own owns or reads of *p; cerastes_old(*p) needs the one in requires.

  • Returning or comparing a pointer parameter uses its value, so the contract must say that its object exists: cerastes_live(p), or an owns or reads of *p. A pointer result may be related to the parameters (ensures(r, r == p || r == q)), and its object read as *r where an owns or reads of that object comes before it (ensures(r, r == p && cerastes_owns(*p) && *r == 0)).

  • A parameter of type int ** may own the pointer it points to (cerastes_owns(*pp)), say where that pointer points (*pp == q, cerastes_old(*pp)), and own, read or require the liveness of the object behind it (cerastes_owns(**pp), cerastes_live(*pp); Pointers to pointers). A guard may read through a pointer too: *pp == NULL || cerastes_owns(**pp), after an atom that holds *pp.

  • A contract may not compare pointers whose objects differ in const (r == v for int *r and const int *v, or *pp == v), nor convert a pointer to one whose object differs in const ((const int *)r), nor own an object it reaches through a pointer to const (cerastes_owns(*v) for const int *v; a function that only reads it takes cerastes_reads(*v)). Otherwise a function whose body is elsewhere could hand its caller a pointer through which a const object is written, or write one itself, which C leaves undefined. Each is rejected.

  • A function that takes cerastes_owns(*p) in its requires and does not give it back in its ensures keeps the object. If that object is a local variable of the caller, the caller cannot end its lifetime: the closing brace of the variable’s block is reported as lifetime.

  • A restrict pointer parameter is rejected (unsupported_annotation, reported at the head of the function’s definition, in a message that names each such parameter; in C++, where compilers spell the keyword __restrict, as a type, unsupported_type): cerastes does not model restrict. The keyword promises that an object modified through the parameter is reached only through pointers based on it, and a compiler may reorder accesses on that promise. Owning the object does not keep the promise, because ownership belongs to the object and not to the pointer: a function may hold the permission it needs and still reach the same object by another name (a global, a second parameter, a pointer that a called function hands back), and C leaves such a function undefined although each of its accesses is one its contract allows. Drop the keyword to verify the function: for a program with defined behaviour restrict changes what a compiler may assume, not what the program does. The proof is then of the program without the keyword, so the program that is compiled must not have it either: hiding it from cerastes alone proves nothing about the compiled one. A function that the file only declares (no body) is rejected the same way where cerastes first reads its signature: at the first call of it in the file, or, for some signatures (a pointer to a structure among them), at the declaration itself whether or not it is called. A declaration that is neither called nor read in that way is not reported; nothing is verified against it. One declaration with the keyword is enough, whatever the function’s other declarations say. restrict written only on a declaration, before or after the definition, of a function that the file defines without it is accepted: C attaches the promise to the definition, and that definition makes none.

  • The address of a parameter may be taken (int *q = &a;): the parameter is then an object in memory, like a local.

  • A contract may own an object on one path and only read it on another (c ? cerastes_owns(*p) : cerastes_reads(*p)), but not do both on one path, and its ensures may give back only what its requires took on the same path; either mistake is reported at the contract as permission, even for a function whose body is elsewhere:

    #include <cerastes.h>
    #include <stddef.h>
    
    int step(int c, int *p)
        CERASTES_REQUIRES((c ? cerastes_owns(*p) : cerastes_reads(*p)) && *p >= 0 && *p < 100)
        CERASTES_ENSURES(r, (c ? cerastes_owns(*p) : cerastes_reads(*p)) && r == *p && r == cerastes_old(*p) + (c != 0 ? 1 : 0))
    {
      if (c) {
        *p += 1;
      }
      return *p;
    }
    
    int use_step(int c)
        CERASTES_ENSURES(r, r == (c != 0 ? 2 : 1))
    {
      int x = 1;
      return step(c, &x);
    }
  • A function’s decreases may read an object its requires owns or reads; it is compared, as for integers, between the function’s entry and each recursive call:

    #include <cerastes.h>
    #include <stddef.h>
    
    int down(int *p)
        CERASTES_REQUIRES(cerastes_owns(*p) && *p >= 0 && *p < 100)
        CERASTES_DECREASES(*p)
        CERASTES_ENSURES(r, cerastes_owns(*p))
    {
      if (*p == 0) {
        return 0;
      }
      *p -= 1;
      return down(p);
    }
  • Verification time grows quickly with the number of pointer parameters of one type that only reads or live describe, since any of them may point to the same object: four take a few seconds, five tens of seconds, and six or more may reach the time limit (an error, never a wrong answer).

Initialization through pointers

A pointer parameter whose contract owns its object (cerastes_owns(*p)) expects an object that has a value: the caller gives it one, and the function returns it with one. An argument whose object may not have a value yet is reported at the call as uninitialized ("passes &x to set, whose parameter p needs *p to have a value; it may not have one here"); the same holds for cerastes_reads(*p).

Two attributes from the C++ initialization profile (P4222), in the cerastes:: spelling, let a function receive an object that has no value yet:

  • cerastes::must_init (the macro CERASTES_MUST_INIT): the object may have no value on entry, and the function gives it one before it returns. A path that returns without writing *p is reported as postcondition ("returns without initializing *p, which cerastes::must_init on p promises"). After the call the caller may read the object, and the ensures may say what it holds.

  • cerastes::ref_to_uninit (the macro CERASTES_REF_TO_UNINIT): the object may have no value on entry, and the function promises nothing about it on return, except that an object that had a value still has one (its value may have changed).

#include <cerastes.h>

void init(int *p CERASTES_MUST_INIT)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p) && *p == 0)
{
  *p = 0;
}

int use_init(void)
    CERASTES_ENSURES(r, r == 0)
{
  int x;
  init(&x);
  return x;
}
#include <cerastes.h>

int fill(int *p CERASTES_REF_TO_UNINIT)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(r, cerastes_owns(*p) && r == 7)
{
  *p = 7;
  return *p;
}

void maybe(int *p CERASTES_REF_TO_UNINIT, int c)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p))
{
  if (c != 0) {
    *p = 5;
  }
}

int use_both(int c)
    CERASTES_ENSURES(r, r == 7)
{
  int x;
  int y = fill(&x);
  int z = 1;
  maybe(&z, c);
  return y;
}

int keep(int c)
{
  int z = 1;
  maybe(&z, c);
  return z;  // z still has a value: 1 or 5
}

The rules:

  • The attribute goes before the parameter’s declaration or after its name, on a pointer to an object that is not const (a int ** parameter’s object is the pointer it points to). Its contract owns the object: cerastes_owns(*p) in the requires, or cerastes::owning, and for must_init in the ensures too. cerastes_reads(*p) beside either attribute is rejected, and so are both attributes on one parameter. Every declaration of the function carries the same attributes on the same parameters.

  • Inside the function, *p is read only after it is written, on every path, as a local without an initializer is (Locals without an initializer).

  • The contract may not read the object where it may have no value: *p in the requires, cerastes_old(*p), *p in a decreases, and *p in the ensures of a ref_to_uninit parameter are rejected; the ensures of a must_init parameter may read it (*p == 0 above). A read through another pointer that may equal p is reported at the contract as permission.

  • A must_init parameter that the function writes only inside a loop is reported, even when the loop always runs: give it a value before the loop.

  • The attributes are rejected on a function that never returns (must_init), on a pure or predicate function, and on a redeclaration of a function a system header declares.

cerastes::uninit (the macro CERASTES_UNINIT) on a local without an initializer states that it starts without a value, and the option --strict-init asks for it on every such local and for these attributes wherever an object without a value is passed (The strict initialization mode).

Structures

A structure whose members are integers, bool, enumerations, pointers and other such structures can be a local, the object a pointer points to, and the subject of a contract. Each member is an object of its own: pt.x and pt.y are different objects, and &pt.x points to pt.x only. A structure local is created without a value when it has no initializer; a braced initializer gives every member a value, zero for the members it does not name. A member is read, written, and passed by address like any other object:

#include <cerastes.h>
#include <limits.h>

struct point {
  int x;
  int y;
};

void inc(int *p)
    CERASTES_REQUIRES(cerastes_owns(*p) && *p < INT_MAX)
    CERASTES_ENSURES(cerastes_owns(*p) && *p == cerastes_old(*p) + 1)
{
  *p += 1;
}

int moved(void)
    CERASTES_ENSURES(r, r == 7)
{
  struct point pt = {.x = 1, .y = 0};
  pt.y = 5;
  inc(&pt.x);
  return pt.x + pt.y;
}

cerastes_owns(*p) of a pointer to a structure owns every member, and cerastes_old(p->x) is the value a member had on entry. A function that swaps two members passes their addresses on, which is VeriFast’s point_mirror:

#include <cerastes.h>

struct point {
  int x;
  int y;
};

void mirror(struct point *p)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p) && p->x == cerastes_old(p->y) && p->y == cerastes_old(p->x))
{
  int t = p->x;
  p->x = p->y;
  p->y = t;
}

int use_mirror(void)
    CERASTES_ENSURES(r, r == 2)
{
  struct point pt = {1, 2};
  mirror(&pt);
  return pt.x;
}

A contract may also name one member, cerastes_owns(p->count) or cerastes_reads(p->count): the callee then may touch that member only, and the caller keeps the others with their values:

#include <cerastes.h>

struct counter {
  int count;
  int limit;
};

void reset(struct counter *p)
    CERASTES_REQUIRES(cerastes_owns(p->count))
    CERASTES_ENSURES(cerastes_owns(p->count) && p->count == 0)
{
  p->count = 0;
}

int limit_after_reset(void)
    CERASTES_ENSURES(r, r == 10)
{
  struct counter c = {.count = 3, .limit = 10};
  reset(&c);
  return c.count + c.limit;
}

Separation is decided by the objects two parameters can reach, whatever their types: a pointer to a structure and a pointer to an int reach one object when the int is one of the structure’s members. Passing &pt and &pt.x to two owning parameters is reported as permission at the call:

#include <cerastes.h>

struct point {
  int x;
  int y;
};

void place(struct point *s, int *q)
    CERASTES_REQUIRES(cerastes_owns(*s) && cerastes_owns(*q))
    CERASTES_ENSURES(cerastes_owns(*s) && cerastes_owns(*q))
{
  s->x = 1;
  *q = 2;
}

void trap(void)
{
  struct point pt = {0, 0};
  place(&pt, &pt.x);
}

Copying a structure (t = s;, *p = *q;, struct point t = s;) reads every member: a member without a value is reported as uninitialized at the copy, even though C lets a partly initialized structure be copied. A copy is a statement or an initializer; its value cannot be used ((t = s).x is rejected). In C a structure’s initializer is evaluated before the object has a value, so struct point pt = {1, pt.x}; reads pt.x without a value; in C++ the members are initialized in order.

The markers of Initialization through pointers work on structures: cerastes::uninit on a structure local, and cerastes::ref_to_uninit and cerastes::must_init on a pointer to a structure, where must_init promises every member. cerastes::ref_to_uninit also applies to a pointer member (Marked members); with owning it lets a buffer that has no value be handed to a function (Marked owning members).

Passing and returning structures. A structure can be passed and returned by value. In a contract a parameter’s members (p.x) are their values on entry, like any parameter, and a result’s members are named through the result (r.x); a member of a call’s result is read directly (make(4, 0).y):

#include <cerastes.h>

struct point {
  int x;
  int y;
};

struct point make(int x, int y)
    CERASTES_ENSURES(r, r.x == x && r.y == y)
{
  struct point p = {x, y};
  return p;
}

struct point mirror(struct point p)
    CERASTES_ENSURES(r, r.x == p.y && r.y == p.x)
{
  int t = p.x;
  p.x = p.y;
  p.y = t;
  return p;
}

int sum(struct point p)
    CERASTES_REQUIRES(p.x >= 0 && p.x <= 100 && p.y >= 0 && p.y <= 100)
    CERASTES_ENSURES(r, r == p.x + p.y)
{
  return p.x + p.y;
}

int use(void)
    CERASTES_ENSURES(r, r == 3)
{
  struct point a = make(1, 2);
  struct point b = mirror(a);
  return sum(b) + make(4, 0).y;
}

Passing or returning a structure copies it, so every member must have a value: a member without one is reported as uninitialized at the call or the return, as at a copy. A contract reads a structure value only member by member (p == q and cerastes_old(p) are rejected: C has no == on structures).

A contract can follow a pointer member: cerastes_owns(p->q->x) names the member x of the object p→q points to (after an atom that holds p→q, such as cerastes_owns(*p)), cerastes_owns(*s.q) and cerastes_live(s.q) the object a by-value parameter’s pointer member points to, and in an ensures *r.q the object a returned structure’s pointer member points to, after an atom on that object (r.q == p && cerastes_owns(*p) && *r.q == 1). Without cerastes_live(s.q) a function cannot use the member’s value (return s.q; is reported as lifetime):

#include <cerastes.h>

struct L {
  struct L *q;
  int x;
};

struct P {
  int *q;
};

void inc(struct L *p)
    CERASTES_REQUIRES(cerastes_owns(*p) && cerastes_owns(p->q->x) && p->q->x < 100)
    CERASTES_ENSURES(cerastes_owns(*p) && p->q == cerastes_old(p->q) && cerastes_owns(p->q->x) && p->q->x == cerastes_old(p->q->x) + 1)
{
  p->q->x += 1;
}

int deref(struct P s)
    CERASTES_REQUIRES(cerastes_owns(*s.q))
    CERASTES_ENSURES(r, cerastes_owns(*s.q) && *s.q == cerastes_old(*s.q) && r == *s.q)
{
  return *s.q;
}

int use(void)
    CERASTES_ENSURES(r, r == 4)
{
  struct L t = {0, 3};
  struct L s = {&t, 0};
  inc(&s);
  CERASTES_CHECK(t.x == 4);
  int v = 4;
  struct P w = {&v};
  return deref(w);
}

cerastes_live(r.q) and cerastes_owns(*r.q) of a returned structure are not supported yet: they hand the caller something the function’s requires did not take.

Compound literals. In C, (struct point){1, 2} is a value wherever a structure value is: an initializer, an assignment, an argument, a returned value. &(struct point){1, 2} (and &(int){5}) is the address of an object that lives until the end of the block the literal is in, like a local declared there: after the block a pointer to it is dangling (Lifetimes and dangling pointers):

#include <cerastes.h>

struct point {
  int x;
  int y;
};

void shift(struct point *p)
    CERASTES_REQUIRES(cerastes_owns(*p) && p->x < 100)
    CERASTES_ENSURES(cerastes_owns(*p) && p->x == cerastes_old(p->x) + 1 && p->y == cerastes_old(p->y))
{
  p->x += 1;
}

int first(struct point p)
    CERASTES_ENSURES(r, r == p.x)
{
  return p.x;
}

int use(void)
    CERASTES_ENSURES(r, r == 11)
{
  struct point a = (struct point){.y = 2};
  int *n = &(int){5};
  struct point *q = &(struct point){1, 2};
  shift(q);
  *n += q->x;
  return *n + first((struct point){4, a.y}) + a.x;
}

The elements of a compound literal are evaluated before any member is stored, in no particular order, as the elements of an initializer are. In C an array literal ((int[]){1, 2, 3}) is an object of its block too, and its value is a pointer to its first element. A compound literal used as an object whose element writes (x = (int[]){x++}[0];) is rejected unless it is a whole statement, a declaration’s initializer or a whole element of a braced list (in C, beside elements without side effects): C does not order that write with the rest of the expression. In C++, where compound literals are a compiler extension creating temporaries, they are accepted as values only, and so are S{1, 2} and S(); array literals are not supported there.

Array members. A member may be an array of scalars (struct buffer { int data[8]; int len; };). Its elements are reached as an array’s are (b.data[i], p→data[i], &b.data[i]), with the same out-of-bounds, permission and uninitialized checks, and p→data[i] checks that p is not null as p→len does. In a braced initializer the member takes a list of its own ({{1, 2}, 2}); the elements it does not list are zero, as are those of a member the initializer does not name. Leaving out the inner braces ({1, 2, 3}) is rejected, as the compilers warn about it, except {}, C’s {0}, and C++'s {0} for a structure whose only member is the array. cerastes_owns(*p) and cerastes_reads(*p) give every element with the other members; cerastes_owns(p→data) and cerastes_reads(p→data) give the array member alone; after either a contract may read p→data[i]. The elements are objects apart from every other member, so passing &b and &b.data[1] to a function that owns both is reported as permission. Loops carry array members as they carry a local array (Loops), and a structure global or static local may have one:

#include <cerastes.h>

struct buffer {
  int data[8];
  int len;
};

void put(struct buffer *b, int i, int v)
    CERASTES_REQUIRES(cerastes_owns(*b) && 0 <= i && i < 8)
    CERASTES_ENSURES(cerastes_owns(*b) && b->data[i] == v && b->len == i + 1)
{
  b->data[i] = v;
  b->len = i + 1;
}

void zero_first(struct buffer *b)
    CERASTES_REQUIRES(cerastes_owns(b->data))
    CERASTES_ENSURES(cerastes_owns(b->data) && b->data[0] == 0)
{
  b->data[0] = 0;
}

int main(void)
{
  struct buffer b = {{1, 2, 3}, 3};
  CERASTES_CHECK(b.data[2] == 3 && b.data[3] == 0 && b.len == 3);
  put(&b, 5, 9);
  CERASTES_CHECK(b.data[5] == 9 && b.len == 6);
  zero_first(&b);
  CERASTES_CHECK(b.data[0] == 0 && b.len == 6);
  return 0;
}

Passing the structure and one of its elements to a function that owns both:

#include <cerastes.h>

struct buffer {
  int data[8];
  int len;
};

void both(struct buffer *b, int *x)
    CERASTES_REQUIRES(cerastes_owns(*b) && cerastes_owns(*x))
    CERASTES_ENSURES(cerastes_owns(*b) && cerastes_owns(*x))
{
  b->len = 0;
  *x = 0;
}

int main(void)
{
  struct buffer b = {{1, 2, 3}, 3};
  both(&b, &b.data[1]);
  return b.len;
}

A structure with an array member is copied as a whole (t = s;, *p = *q;, struct buffer c = b;): every element of the source must have a value, as every member must (copying a partly written buffer is reported as uninitialized, stricter than C), and the destination must be owned whole. It may also be passed and returned by value, and f().data[i] reads an element of a returned value, with the same out-of-bounds check, as long as the structure holds at most 7 array elements in all: a larger one is rejected as a parameter, a result or an argument passed by value, and in C as a compound literal used as a value (a copy has no such limit). In C++, a temporary of such a structure (S{{1, 2}, 3}) inside the initializer of a variable that is not the whole initializer is not supported yet. A copy and a call by value:

#include <cerastes.h>

struct buffer {
  int data[8];
  int len;
};

struct small {
  int data[2];
  int len;
};

int zero_first(struct small s)
    CERASTES_REQUIRES(s.data[0] == 1 && s.len == 2)
    CERASTES_ENSURES(r, r == 0)
{
  s.data[0] = 0;
  return s.data[0];
}

int main(void)
{
  struct buffer a = {{1, 2, 3}, 3};
  struct buffer b;
  b = a;
  CERASTES_CHECK(b.data[2] == 3 && b.data[7] == 0 && b.len == 3);
  b.data[2] = 9;
  CERASTES_CHECK(a.data[2] == 3);
  struct small m = {{1, 2}, 2};
  int t = zero_first(m);
  CERASTES_CHECK(m.data[0] == 1 && t == 0);
  return b.len - 3 + t;
}

The copy is an object of its own: writing an element of it leaves the source as it was, so a check that the source changed fails:

#include <cerastes.h>

struct buffer {
  int data[8];
  int len;
};

struct small {
  int data[2];
  int len;
};

int zero_first(struct small s)
    CERASTES_REQUIRES(s.data[0] == 1 && s.len == 2)
    CERASTES_ENSURES(r, r == 0)
{
  s.data[0] = 0;
  return s.data[0];
}

int main(void)
{
  struct buffer a = {{1, 2, 3}, 3};
  struct buffer b;
  b = a;
  CERASTES_CHECK(b.data[2] == 3 && b.data[7] == 0 && b.len == 3);
  b.data[2] = 9;
  CERASTES_CHECK(a.data[2] == 9);
  struct small m = {{1, 2}, 2};
  int t = zero_first(m);
  CERASTES_CHECK(m.data[0] == 1 && t == 0);
  return b.len - 3 + t;
}

A member may also be an array of structures (struct path { struct point v[2]; int n; };). Its elements' members are reached as those of any array of structures (t.v[i].x, p→v[i].x, Arrays of structures), its initializer takes one list per element ({{{1, 2}, {3}}, 5}, with zero for what a list leaves out), cerastes_owns(*p) holds every member of every element with the other members, cerastes_owns(p→v) the array member alone, and a contract may then read p→v[i].x. Passing a pointer to the structure and a pointer to one of its elements to a function that owns both (f(&t, &t.v[1])) is reported at the call, as for any object named twice. For a global structure gt, cerastes_owns(gt.v) and cerastes_reads(gt.v) likewise name the array member alone. Such a structure is copied whole when the members of its elements number at most 7 in all, and passed and returned by value when those members and the elements of its other array members number at most 7 together. Not supported yet, each rejected with a diagnostic: reading an element of a structure passed by value in a contract (t.v[1].y of a parameter struct path t), in C passing an element of a global structure’s array member by value (f(gt.v[1]); copy it to a local first), and cerastes_old(gt.v[1].x) for a global structure. Each such structure that one function holds as a local adds much to the time its proof takes, and a function that holds a global structure with such a member and calls another function that holds it may run into the time limit.

A structure with an array member of scalars may be allocated (Allocated memory: malloc, calloc and free). malloc(sizeof(struct buffer)) gives the whole object with every element uninitialized, calloc(1, sizeof(struct buffer)) gives every element zero, free ends the object with its elements, and cerastes_owns_block(p) holds every element with the other members:

#include <cerastes.h>
#include <stdlib.h>

struct buffer {
  int data[4];
  int len;
};

int main(void)
{
  struct buffer *b = (struct buffer *)malloc(sizeof(struct buffer));
  if (b == NULL) {
    return 1;
  }
  b->data[0] = 10;
  b->data[1] = 20;
  b->data[2] = 30;
  b->data[3] = 40;
  b->len = 4;
  CERASTES_CHECK(b->data[2] == 30 && b->len == 4);
  int sum = b->data[0] + b->data[3];
  free(b);
  return sum == 50 ? 0 : 1;
}

Reading an element that nothing wrote:

#include <cerastes.h>
#include <stdlib.h>

struct buffer {
  int data[4];
  int len;
};

int main(void)
{
  struct buffer *b = (struct buffer *)malloc(sizeof(struct buffer));
  if (b == NULL) {
    return 1;
  }
  int first = b->data[1];
  free(b);
  return first;
}

calloc of a structure with an array member is accepted when the structure holds at most 24 values in all, counting each element of its array members and each of its other members (int data[23]; int len; is accepted, int data[24]; int len; is not): the proof that every element is zero grows with their number, and a larger structure is rejected at the call. Allocate a larger one with malloc and write its elements; elements written one by one can be read back, while a read of an element that only a loop wrote is reported as uninitialized in this version (see the false alarms below).

Such a structure may also have an owning or ref_to_uninit member beside the array (Owning fields), and a pointer to it may be owning, ref_to_uninit or must_init: a must_init function has to write every element (one left unwritten is reported as postcondition at its closing brace), and a caller that reads an element nobody wrote is told uninitialized. A contract may reach it through a pointer read from memory (cerastes_owns(*p->q), after which it may read p→q→data[i]), and may give it back with an ensures atom that has no requires partner on the result (cerastes_owns(*r)). A loop carries the elements of an allocated structure as it carries a local array’s (Loops), and a loop invariant may name it with a written cerastes_owns(*p) or cerastes_owns(p→data), p a pointer variable, which asks for the whole structure or the whole array member when the loop starts (not supported yet, each rejected: a written cerastes_reads of such a structure, a pointer read from memory in the atom, and an atom whose condition reads memory through a pointer or reads a global variable).

Listed false alarms: after a loop that fills the elements of a structure allocated with malloc, reading an element is still reported as uninitialized (the loop’s automatic invariant does not say which elements it wrote; calloc avoids it); after a loop that may give an owner a new block (the owner may be null when the loop starts, or the loop frees its block and allocates another), a read of that block is reported as uninitialized until it is written again; a loop over the elements of a structure that a called function gave back with cerastes_owns(*r) reports permission, and so does a loop invariant that reads an element of an allocated structure (p→data[0] in the invariant).

None of this paragraph’s forms is supported yet for a structure whose array member holds structures (struct path above) or arrays (int m[2][3]): allocating it, an owning or marked member beside that member, owning, ref_to_uninit or must_init on a pointer to it, a place of it reached through a pointer read from memory, an ensures atom without a requires partner, and an atom in a loop invariant on the structure or on one of its array members are each rejected with a diagnostic. A contract cannot yet name part of an array member (cerastes_owns_range(p→data, n)) or pass it to a quantifier or a pure function.

Not supported yet, each rejected with a diagnostic: unions, bit-fields, arrays of arrays as members, const, volatile and _Atomic members, anonymous members, members that are void * or pointers to functions, packed structures, structures from system headers (such as FILE), structures defined inside a function, and in C++ every class feature beyond a C structure (member functions, constructors, base classes, access control, static members, default member initializers). Initializers that elide the braces of an inner structure (struct line l = {1, 2, 3, 4};) and, in C, designators out of declaration order are rejected too, and so are const structure parameters and globals, a structure ?:, comma or assignment used as a value (t = c ? a : b;), the address of a const compound literal, a compound literal in a loop’s condition or step, and a compound literal used as an object without & ((struct point){1, 2}.x = 3;).

Arrays

A local array (int a[4];, of integers, bool, an enumeration or pointers) is an object in memory with one element per index, from the moment its block is entered until the block ends, as any object whose address is taken. Its elements are read and written by index, and every access is checked: the index is inside the array (out-of-bounds), and an element read has been given a value (uninitialized). Arithmetic on an element is checked like any other: a[i] += 1 overflows exactly when x += 1 would.

#include <cerastes.h>

int score(int i)
    CERASTES_REQUIRES(0 <= i && i < 4)
    CERASTES_ENSURES(r, 0 <= r && r <= 30)
{
  int table[4] = {10, 20};
  table[3] = 30;
  CERASTES_CHECK(table[2] == 0);
  return table[i];
}

A braced initializer gives every element a value: the elements it names, and zero (false, a null pointer) for the rest, as C says, so table[2] above is 0. int a[] = {1, 2, 3}; takes its length from the list and {} sets every element to zero. Without an initializer no element has a value until it is written. An index that is a constant outside the array (a[4] of int a[4]), a truth test of an array (if (a)) or of the address of an element (if (&a[1]), &a[1] == NULL: the address is never null) and, in C, a list longer than its array are rejected, as the compilers warn about them (Shapes the compilers warn about).

&a[i] is a pointer to one element, and a function that owns one object (cerastes_owns(*p)) can be given an element. Two elements are two objects, so a function that owns two can be given two different elements of one array:

#include <cerastes.h>

void swap(int *p, int *q)
    CERASTES_REQUIRES(cerastes_owns(*p) && cerastes_owns(*q))
    CERASTES_ENSURES(cerastes_owns(*p) && cerastes_owns(*q))
    CERASTES_ENSURES(*p == cerastes_old(*q) && *q == cerastes_old(*p))
{
  int t = *p;
  *p = *q;
  *q = t;
}

int first_after_swap(void)
    CERASTES_ENSURES(r, r == 2)
{
  int pair[2] = {1, 2};
  swap(&pair[0], &pair[1]);
  return pair[0];
}

An array used as a value is a pointer to its first element: int *p = a;, or a as an argument, which a function that owns one object can take. p[i] indexes any pointer, with the checks of a[i] against the object the pointer points into, so a pointer to a[1] reaches a[2] as q[1]. A function that receives a pointer with cerastes_owns(*p) owns one object, p[0]: p[1] there is reported as out-of-bounds (the object may end at p) and as permission (or it goes on, and the function does not own the rest).

#include <cerastes.h>

void set_first(int *p, int v)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p) && *p == v)
{
  p[0] = v;
}

int second_after(void)
    CERASTES_ENSURES(r, r == 9)
{
  int a[3] = {1, 2, 3};
  set_first(a, 7);
  int *q = &a[1];
  q[1] = 9;
  return a[2] + a[0] - 7;
}

&a[n] of an array of n elements is a pointer one past the end: it can be formed and compared, and reading or writing through it is reported as permission (no element is there). return a; and return &a[1]; are rejected, as return &x; is. When the array’s block ends, a function that kept an element is reported as lifetime, as for any object.

In a loop, every array in scope is carried like the other objects in memory (Loops): its elements keep their values when no write in the loop can reach the array (no assignment to one of its elements, no write through a pointer to its element type, no call of a function whose contract owns an object of that type), and an element that has a value keeps one. A loop invariant or measure may read an element, with the checks code has: the index is inside the array, and the element has a value.

#include <cerastes.h>

int total(void)
    CERASTES_ENSURES(r, 0 <= r && r <= 40)
{
  int marks[4] = {10, 0, 10, 10};
  int s = 0;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= 4 && 0 <= s && s <= 10 * i)
  CERASTES_INVARIANT(marks[1] == 0)
  CERASTES_DECREASES(4 - i)
  while (i < 4) {
    s += marks[i];
    i += 1;
  }
  return s;
}

Arrays of structures

The elements of a local array may be structures (struct point v[3];, of a structure Structures describes whose members are scalars or nested structures). Each element is a structure object of its own, and each member of each element is an object: v[0].x and v[1].x are two objects, and so are v[i].x and v[i].y.

v[i].x and, through a nested member, v[i].t.x are read and written like a[i]: the index is checked first (out-of-bounds: the index of v[i] may be outside v), then the member like any member (a read needs it to have a value, uninitialized). p[i].x indexes any pointer to a structure with the checks of p[i] and then the member’s, and v used as a value is a pointer to its first element (struct point *p = v;).

A braced initializer holds one braced list per element, each read like a structure’s own initializer: struct point v[3] = {{1, 2}, {3, 4}};. Elements the list does not reach and members an element’s list leaves out are zero, and {} sets every member of every element to zero. Without an initializer no member of any element has a value until it is written. A list that leaves out the inner braces ({1, 2, 3, 4}) is rejected, as the compilers warn about it; Shapes the compilers warn about has the exact rule for {0}.

An element as a whole is a structure value. It can be copied out and in (t = v[i];, v[i] = t;, v[i] = v[j];, struct point t = v[i];) and passed by value (f(v[i])), with the checks of a structure copy after the index’s own: every member of the source must have a value. &v[i] is a pointer to one structure, which a function that owns one structure can take (cerastes_owns(*p)), and &v[i].x is a pointer to one member. A function that keeps the element it was given is reported when the array’s block ends (lifetime), as for any object.

In a loop, every member of every element is carried like the other objects in memory (Loops). A write to a member of an element (v[i].x = 0;) can reach every member of the same type in the function’s arrays of structures and structure locals, so the loop does not keep by itself what was known about v[k].y when x and y are both int; a member of another type is not reached. A loop invariant or measure may read a member of an element of a local array (v[i].x, v[i].t.x), with the checks code has: the index is inside the array and the member has a value. Two accesses to the same member of the same element in one expression, one of them a write, are rejected or reported as unsequenced as for the elements of any array (Writes and calls inside expressions).

An element structure may have array members of scalars (struct row { int n; int a[3]; } v[2];). v[i].a[j] has one check per index, the first against v and the second against the member (out-of-bounds: the message reads v[i], whose index may be outside v, for the first, and names a[j], whose index may be outside v[i].a, for the second), then the cell’s own. Such an array may be a local, a global or a static local (its initializer read element by element, with C’s zero fill for what a list leaves out) or a member of a structure (t.v[i].a[j], p->v[i].a[j] under an atom that holds the structure), and a pointer parameter may own or read a range of such structures (Ranges of structures), with p[i].a[j] in the body and in the contract. An element is copied as a whole like any other (v[i] = v[j];, t = v[i];), the array member with it; the source needs a value in every cell. Two accesses to one cell of one element in one expression, one of them a write, are rejected as for any array (v[0].a[1] assigned and incremented in one expression). In a loop invariant v[e].a[e2] of a local or of a global array may be read; under a parameter’s range only p[e].x may.

Not supported yet, each rejected with a diagnostic: a structure value stored into an element (v[i] = f();, v[i] = (struct point){1, 2};: copy from a structure local instead); an element structure with an owning or marked member, with an array member that holds structures or arrays, or with a nested structure that has an array member (struct outer { struct row r; int k; } v[2];); an element’s array member read in a loop invariant through a parameter’s range (p[e].a[e2]); cerastes_old of a cell of an element’s array member in a global array (cerastes_old(g[1].a[2])); cerastes_owns or cerastes_reads of a global array of such structures, or of a structure whose member is one, after a condition and || or as an arm of ?:; cerastes::uninit, cerastes::owning and cerastes::ref_to_uninit on an array of structures; p[i].x through a pointer in a loop invariant or measure of a function whose contract holds no range on p (Ranges of structures); and a truth test or a comparison with NULL of &v[i], &v[i].x or &p[i] (array_address_null_test: the address is never null, and GCC warns).

Arrays of arrays

The elements of a local array may be arrays: int m[2][3]; is two rows of three int each. Every cell m[i][j] is an object, and each row m[i] is an array object of its own. The cells may be of any type a one-dimensional array’s elements may have (integers, bool, enumerations, pointers).

m[i][j] is read and written like a[i], with one check per index, in order: the first index must be inside m (out-of-bounds: the message names m[i][j], whose first index may be outside m), then the second inside the row (whose second index may be outside m[i]), then the cell’s own checks (a read needs it to have a value, uninitialized). A second index that runs past its row is an error even where C’s layout would put a cell of the next row there: m[0][3] is not m[1][0].

A braced initializer holds one braced list per row: int m[2][3] = {{1, 2, 3}, {4}};. Cells a row’s list leaves out and rows the list does not reach are zero, and {} sets every cell to zero. A list without the inner braces ({1, 2, 3, 4, 5, 6}) is rejected, as the compilers warn about it; Shapes the compilers warn about has the exact rule for {0}. Without an initializer no cell has a value until it is written.

A row used as a value is a pointer to its first cell: int *r = m[1];, or m[1] passed to a function that owns or reads a range of three int (cerastes_owns_range(q, 3)). The row index is checked, and the function gets the cells of that row and no others: a count of four is reported at the call (permission). &m[i][j] is a pointer to one cell, and may point one past the end of its row but no further. As for any local, a function that returns a pointer into its own matrix (return m[1];, return &m[1][2];) is rejected (cerastes-return_local_address), and one that keeps a pointer it was lent is reported when the matrix’s block ends (lifetime).

In a loop, the cells of a matrix are carried like the elements of an array (Loops), and a loop invariant or measure may read m[i][j] with the checks code has. Two accesses to one cell in one expression, one of them a write, are rejected or reported as unsequenced as for the elements of any array (Writes and calls inside expressions).

Parameters that take a matrix

A parameter written int a[][3], int a[2][3] or int (*a)[3] is a pointer to rows of three int. The three spellings mean the same, and so do the spellings through a typedef of the row (typedef int row[3]; with row *a, row a[] or row a[2]). Its contract owns or reads n rows with a range atom:

#include <cerastes.h>

void put(int a[][3], [[maybe_unused]] int n, int i, int j, int v)
    CERASTES_REQUIRES(cerastes_owns_range(a, n) && 0 <= i && i < n && 0 <= j && j < 3)
    CERASTES_ENSURES(cerastes_owns_range(a, n) && a[i][j] == v)
{
  a[i][j] = v;
}

int get(int a[][3], [[maybe_unused]] int n, int i, int j)
    CERASTES_REQUIRES(cerastes_reads_range(a, n) && 0 <= i && i < n && 0 <= j && j < 3)
    CERASTES_ENSURES(r, cerastes_reads_range(a, n) && r == a[i][j])
{
  return a[i][j];
}

int demo(void)
    CERASTES_ENSURES(r, r == 9)
{
  int m[2][3] = {{0, 0, 0}, {0, 0, 0}};
  put(m, 2, 1, 2, 9);
  return get(m, 2, 1, 2);
}

cerastes_owns_range(a, n) holds every cell of rows 0 to n - 1, and cerastes_reads_range(a, n) lets the function read them. a[i][j] is read and written in the body and read in the contract (in requires, ensures, a measure and under cerastes_old), with the first index checked against the range and the second against the row:

#include <cerastes.h>

int get(int a[][3], int n, int i, int j)
    CERASTES_REQUIRES(cerastes_reads_range(a, n) && 0 <= i && i < n && 0 <= j && j <= 3)
{
  return a[i][j];
}
matrix_index_error.c:11: error: out-of-bounds: reads `a[i][j]`, whose second index may be outside `a[i]`

A matrix is passed by its name (put(m, 2, 1, 2, 9)), a function may pass its own parameter on (g(a, n)), and a row of the parameter is a pointer to its first cell (a[i]), as a row of a matrix is. A loop may run over the rows and cells, with a[i][j] in its invariant. After a call to a function that owns the range, the caller knows of the cells only what that function’s ensures states, as for any range.

Ownership is of objects, whatever reaches them. A call that passes a matrix to a function that owns its rows and, beside it, a pointer to one of its cells, one of its rows, or the matrix again, to a parameter the function also owns, asks for the same cells twice and is reported at the call (permission: "passes m[0..2) and m[1][2] to f1, which may be one object, once to own it"); passing rows that do not overlap (f(m, 1, &m[1][2])) verifies.

Such a parameter can only be subscripted, named in a range atom, or passed whole. Comparing it, testing it for null, assigning to it and writing *a are rejected with a diagnostic, so a contract cannot say a == NULL || …​: write the range atom unguarded. The outer bound of int a[2][3] is checked as a constant and then ignored, as for int a[4]; the inner bound is part of the type. sizeof(a) is rejected for the array spellings, as the compilers warn (cerastes-sizeof_array_argument), and is the size of a pointer for int (*a)[3]; sizeof(a[0]) is the size of a row, in code.

Global, static and member matrices

An array of arrays may also be a global, a static local, or a member of a structure, and it may be named through a typedef (typedef int grid[2][3];).

A global or static local one (static int table[2][3] = {{1, 2, 3}, {4}};) starts as a global array does ([global-arrays]): the listed cells have their values, the rest are zero, or every cell is unknown where a global’s initial values are not known. cerastes_owns(table) and cerastes_reads(table) name every cell, a contract may then read table[i][j], main and the loops of a function that holds it carry it, and it is passed by name to a function that takes rows (Parameters that take a matrix). The atom is written unguarded: after a condition and ||, or as an arm of ?:, it is rejected for now.

A member (struct board { int n; int m[2][3]; };) is read and written as b.m[i][j], and p→m[i][j] through a pointer, with the two index checks. An atom on the structure (cerastes_owns(*p)) holds every cell of the member, and cerastes_owns(p→m) holds the member alone; a contract may then read p→m[i][j]. These atoms are written unguarded: an atom on such a structure after a condition and ||, or as an arm of ?:, is rejected for now. A structure with such a member is passed, returned and copied as a whole value (f(b), return b;, c = b;, *p = *q;) cell by cell, with every cell of the source needing a value, as long as its array members hold at most 7 cells in all (a whole copy counts only the cells of the matrix); a larger one is rejected with a diagnostic. A contract cannot yet read a cell of such a value (v.m[i][j] of a by-value parameter), nor code a cell of a returned one (f().m[1][2]): copy the value into a local first. [array-members] lists what a structure whose array member holds arrays cannot do yet (the heap, owners, markers).

Not supported yet, each rejected with a diagnostic: a matrix whose cells are structures (struct point m[2][2];); a pointer to an array anywhere but a parameter (int (*p)[3] = m;, &m[i]); a const matrix and a const row parameter; a row as the base of a range in a contract (cerastes_owns_range(m[i], 3)); cerastes::owning, cerastes::ref_to_uninit and cerastes::must_init on a row parameter, and cerastes::uninit on a matrix; sizeof(a[0]) of a row parameter inside a contract; cerastes_old of a cell of a global structure’s matrix member (cerastes_old(g.m[1][1])); in C, a pointer INITIALIZED with the address of a cell of a global structure’s matrix member (int *q = &g.m[1][0];: assign it after the declaration instead); and a truth test or a comparison with NULL of a row or of &m[i][j] (array_address_null_test).

Ranges in contracts

A function states that it owns the elements p[0] to p[n - 1] with cerastes_owns_range(p, n) (in C++ also cerastes::owns_range(p, n)), and that it only reads them with cerastes_reads_range(p, n) (cerastes::reads_range). Each is a clause of a contract, like cerastes_owns(*p): p is a pointer parameter and n a count over the parameters and constants that reads no memory. A range implies p != NULL, so a function that also accepts a null pointer or an empty range writes n == 0 || cerastes_owns_range(p, n). Every element of a range has a value on entry and on return, unless the parameter is marked (below). The contract reads an element as code does, p[i], and cerastes_old(p[i]) is its value on entry. Each such read must lie inside a range (or an object) that an earlier clause of the contract holds; otherwise it is reported as permission ("the contract of f reads p[i] without owning it").

#include <cerastes.h>

void set(int *p, int n, int i, int v)
    CERASTES_REQUIRES(cerastes_owns_range(p, n) && 0 <= i && i < n)
    CERASTES_ENSURES(cerastes_owns_range(p, n) && p[i] == v)
{
  (void)n;
  p[i] = v;
}

int caller(void)
    CERASTES_ENSURES(r, r == 7)
{
  int a[4] = {1, 2, 3, 4};
  set(&a[1], 2, 0, 9);  // a[1..3)
  set(a, 4, 2, 7);      // all of a
  return a[2];
}

A caller passes a whole array (set(a, 4, …)), a part of one (&a[1] and a count), or a range it holds itself, and the call is checked as a call that owns one object is: the range lies inside the object the pointer points into, the caller holds every element of it, and every element has a value (uninitialized otherwise). Two ranges, or a range and an object, passed to one call must not overlap where one of them is owned. After a call that owns a range, the caller knows of its elements only what the callee’s ensures says; after a call that reads one, every element keeps its value:

#include <cerastes.h>

int larger(const int *p, int n)
    CERASTES_REQUIRES(cerastes_reads_range(p, n) && n >= 2)
    CERASTES_ENSURES(cerastes_reads_range(p, n))
    CERASTES_ENSURES(r, (r == p[0] || r == p[1]) && r >= p[0] && r >= p[1])
{
  (void)n;
  return p[0] > p[1] ? p[0] : p[1];
}

int caller(void)
    CERASTES_ENSURES(r, r == 9)
{
  int a[3] = {4, 9, 2};
  int m = larger(a, 3);
  CERASTES_CHECK(a[0] == 4 && a[2] == 2);
  return m;
}

A range one element too long for its array is reported at the call as permission ("calls set, which needs to own a[0..5), without owning it"), and so are a null pointer with a positive count and a negative count ("… the range the pointer points to …"):

#include <cerastes.h>

void set(int *p, int n, int i, int v)
    CERASTES_REQUIRES(cerastes_owns_range(p, n) && 0 <= i && i < n)
    CERASTES_ENSURES(cerastes_owns_range(p, n) && p[i] == v)
{
  (void)n;
  p[i] = v;
}

void caller(void)
{
  int a[4] = {1, 2, 3, 4};
  set(a, 5, 0, 7);
}

An index the contract does not keep inside the range (p[i] with only i ⇐ n) is reported twice at the access, as for p[1] under cerastes_owns(*p): out-of-bounds (the object may end at p
n
) and permission (it may go on, and the function does not hold the rest).

A function that only reads a range lends each callee the same share of every element, computed from the range’s first element, since a share of a whole range cannot be measured at once. A caller whose shares of a range’s elements differ (a function it called kept part of one element’s share and gave the rest of the object back) can therefore be told at a later call that it does not hold the range, though it holds part of every element: a known limit.

In a loop, the ranges of a function’s parameters are carried as its arrays are (Loops): the loop holds every element of each range the requires gives a parameter the function never assigns, and the elements keep their values when nothing in the loop can write them (the range is only read, or nothing writes its element type). A loop invariant or measure may read an element of such a range, of a local array through a pointer to it, or of a pointer the loop holds, and a read outside all of them is reported as permission ("this loop invariant reads p[i], which this loop does not hold"):

#include <cerastes.h>

void fill(int *p, int n, int v)
    CERASTES_REQUIRES(cerastes_owns_range(p, n))
    CERASTES_ENSURES(cerastes_owns_range(p, n))
    CERASTES_ENSURES(n == 0 || p[0] == v)
{
  int i;
  CERASTES_INVARIANT(0 <= i && i <= n && (i == 0 || p[0] == v)) CERASTES_DECREASES(n - i) for (i = 0; i < n; i++) {
    p[i] = v;
  }
}

int caller(void)
    CERASTES_ENSURES(r, r == 5)
{
  int a[3] = {0};
  fill(a, 3, 5);
  return a[0];
}

A function that assigns its range parameter (p = &p[1];) gives its loops no range to carry, so a read through that parameter inside a loop is reported as lifetime although the program is correct: a known limit, lifted with pointer arithmetic. A range written in a loop invariant (CERASTES_INVARIANT(cerastes_owns_range(q, m))) is not supported yet.

The markers of Initialization through pointers apply to a range as to one object: cerastes::must_init on p with cerastes_owns_range(p, n) lets the elements have no value on entry and promises every one a value on return (postcondition otherwise: "returns without initializing every element of p[0..n), which cerastes::must_init on p promises"), so a caller may pass an array declared without an initializer; cerastes::ref_to_uninit lets the elements have no value on entry and keeps every element that had one. A function that gives the elements their values in a loop says which ones the loop has written with an invariant over every element (Facts about every element), and its must_init then holds; without one it is reported as not kept. cerastes::owning(n) on a parameter is p == NULL || cerastes_owns_range(p, n) (Owning parameters).

Ranges of structures

cerastes_owns_range(p, n) and cerastes_reads_range(p, n) also take a pointer parameter to a structure. The function then holds every member of each of the n elements p[0] to p[n - 1] (for a structure inside the element, its members in turn), and a caller passes an array of structures:

#include <cerastes.h>

struct point {
  int x;
  int y;
};

void fill(struct point *p, int n)
    CERASTES_REQUIRES(cerastes_owns_range(p, n) && n >= 2)
    CERASTES_ENSURES(cerastes_owns_range(p, n) && p[0].x == 1 && p[1].x == 3)
{
  (void)n;
  p[0].x = 1;
  p[0].y = 2;
  p[1].x = 3;
  p[1].y = 4;
}

long long sum_x(struct point *p, int n)
    CERASTES_REQUIRES(cerastes_reads_range(p, n) && n >= 2)
    CERASTES_ENSURES(r, cerastes_reads_range(p, n) && r == (long long)p[0].x + p[1].x)
{
  (void)n;
  return (long long)p[0].x + p[1].x;
}

int demo(void)
    CERASTES_ENSURES(r, r == 4)
{
  struct point v[3] = {{0, 0}, {0, 0}, {0, 0}};
  fill(v, 3);
  return (int)sum_x(v, 3);
}

The contract may read a member of an element (p[0].x, p[i].t.y), also under cerastes_old and in a decreases, where the element lies in a range the contract holds; a read of an element outside it is reported in the contract as permission, as for a range of integers. At a call the caller must hold every member of every element it passes. An array one element too short is reported at the call ("calls fill, which needs to own v[0..3), without owning it"), and so is a member that a called function kept, where the message names the member ("…​ (the member x of every element)").

A range of structures and another pointer may not name the same object twice. A function that owns the range and also owns one member of one element, a whole element, or a second range that overlaps the first asks for the same object two times, and the call is reported:

#include <cerastes.h>

struct point {
  int x;
  int y;
};

void tally(struct point *p, int n, int *count)
    CERASTES_REQUIRES(cerastes_owns_range(p, n) && cerastes_owns(*count))
    CERASTES_ENSURES(cerastes_owns_range(p, n) && cerastes_owns(*count))
{
  (void)p;
  (void)n;
  *count = 0;
}

int demo(void)
{
  struct point v[3] = {{1, 2}, {3, 4}, {5, 6}};
  tally(v, 3, &v[1].x); // <- error
  return v[0].x;
}
array_of_structs_alias_error.c:25: error: permission: passes `v[0..3)` and `v[1].x` to `tally`, which may be one object, once to own it

A loop in such a function carries each member of every element of the range as it carries a range of integers, and its invariant and measure may read p[i].x. A write to a member reaches every member of that type in the ranges and structures the function holds, so the loop does not keep by itself what was known about another int member; a member of another type is kept. cerastes::owning(n) and the markers of Initialization through pointers apply to a range of structures member by member: cerastes::must_init promises every member of every element a value on return, and the message names the member a path leaves out ("returns without initializing the member y of every element of p[0..n), which cerastes::must_init on p promises").

The structure of a range may have array members of scalars ([element-array-members]): the range holds every cell of every element’s array member, and the contract reads p[e].a[e2] with the first index checked against the range and the second against the member.

Not supported yet, each rejected with a diagnostic unless said otherwise: a range of structures that have an owning or marked member, or an array member that holds structures or arrays; cerastes::ref_to_uninit or cerastes::must_init on a range of structures that have an array member; a range on part of an array (cerastes_owns_range(&v[1], n)) and an atom on one element (cerastes_owns(p[1]), cerastes_owns(p[1].x)); &p[i] in a contract; a read through a pointer member of an element in a contract or a loop invariant (*p[0].q, p[0].q→x). Two known limits: a function marked cerastes::must_init that gives the elements their values in a loop is reported as not keeping its promise, because a loop cannot say yet which members it has written; and a pointer to an element that the contract does not cover, &p[n] one past the range or &p[1] under cerastes_owns(*p), may be formed, but passing it to a function that neither owns nor reads what it points to, or returning it, stops cerastes verify with an internal error instead of a diagnostic. Nothing is reported as verified in either case. A function that reads two ranges of the same structure type and has a loop is slow to verify, and may run into the time limit.

Array parameters

A parameter written as an array, int a[] or int a[4], is a pointer parameter, as C says: its contract owns or reads what it points to (cerastes_owns(*a), cerastes_owns_range(a, 4)), and a bound written there is checked as a constant and then ignored. sizeof(a) of such a parameter is the size of a pointer, not of an array, so it is rejected, as the compilers warn (cerastes-sizeof_array_argument), and so are two declarations of one function whose array parameters disagree on the bound, give a bound in one and none in the other, or write a bounded array in one and a pointer in the other (int a[] against int *a is accepted) (cerastes-array_parameter_mismatch; Shapes the compilers warn about). A variable length (int a[n], int a[*]) and int a[static 4] are not supported yet. A parameter that takes an array of arrays (int a[][3]) is a pointer to rows: Parameters that take a matrix.

Facts about every element

cerastes_forall(f, a, n) states a fact about every element: f is a pure function whose one return says it for the element at the quantified index, and the quantifier means that for every value of the index (forall gives the rules for f and its arguments). It may stand in a function’s requires and ensures, in a loop invariant and in a check.

A loop that fills an array declared without an initializer states which elements it has written, and what they hold; after the loop every element has a value:

#include <cerastes.h>

CERASTES_PURE bool filled(int k, const int *a, int m)
{
  return !(0 <= k && k < m) || a[k] == k;
}

int fill_and_read(void)
    CERASTES_ENSURES(r, r == 3)
{
  int a[4];
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= 4 && cerastes_forall(filled, a, i))
  CERASTES_DECREASES(4 - i)
  while (i < 4) {
    a[i] = i;
    i = i + 1;
  }
  return a[0] + a[3];
}

An invariant that reads elements under the quantifier states that they hold values, at every iteration and after the loop: if the loop may not have written an element, the invariant is reported as uninitialized ("this loop invariant reads a[i] before it is given a value"). A loop body that skips the write is reported twice at the invariant, as uninitialized and as invariant-preserved: the element has no value, and not the one stated. The loop must hold every element the invariant reads ("this loop invariant reads a[i], which this loop does not hold" is permission), and an index outside a local array is out-of-bounds.

In a contract, the elements the quantifier reads must be framed by the function’s range atoms, as a single element read is (Ranges in contracts); a caller proves a quantified requires at the call, and learns a quantified ensures after it. A maximum states its result against every element:

#include <cerastes.h>

CERASTES_PURE bool at_most(int k, const int *a, int n, int m)
{
  return !(0 <= k && k < n) || a[k] <= m;
}

int max_of(const int *a, int n)
    CERASTES_REQUIRES(cerastes_reads_range(a, n) && n > 0)
    CERASTES_ENSURES(r, cerastes_reads_range(a, n) && cerastes_forall(at_most, a, n, r))
{
  int m = a[0];
  int i = 1;
  CERASTES_INVARIANT(1 <= i && i <= n && cerastes_forall(at_most, a, i, m))
  CERASTES_DECREASES(n - i)
  while (i < n) {
    if (a[i] > m) {
      m = a[i];
    }
    i = i + 1;
  }
  return m;
}

Under ensures, cerastes_old(a[i]) in the body of f reads each element’s value on entry, so a function can say which elements it leaves alone:

#include <cerastes.h>

CERASTES_PURE bool kept(int i, const int *a, int n, int j)
{
  return !(0 <= i && i < n && i != j) || a[i] == cerastes_old(a[i]);
}

void set_one(int *a, int n, int j, int v)
    CERASTES_REQUIRES(cerastes_owns_range(a, n) && 0 <= j && j < n)
    CERASTES_ENSURES(cerastes_owns_range(a, n) && a[j] == v && cerastes_forall(kept, a, n, j))
{
  (void)n;
  a[j] = v;
}

int caller(void)
    CERASTES_ENSURES(r, r == 5)
{
  int a[4] = {1, 2, 3, 4};
  set_one(a, 4, 2, 9);
  return a[0] + a[3];
}

A fact may relate two elements of one array (a[i] ⇐ a[i + 1]) or the elements of two arrays at one index (p[i] == q[i]):

#include <cerastes.h>

CERASTES_PURE bool same_at(int i, const int *p, const int *q, int n)
{
  return !(0 <= i && i < n) || p[i] == q[i];
}

void copy(int *dst, const int *src, int n)
    CERASTES_REQUIRES(cerastes_owns_range(dst, n) && cerastes_reads_range(src, n))
    CERASTES_ENSURES(cerastes_owns_range(dst, n) && cerastes_reads_range(src, n) && cerastes_forall(same_at, dst, src, n))
{
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n && cerastes_forall(same_at, dst, src, i))
  CERASTES_DECREASES(n - i)
  while (i < n) {
    dst[i] = src[i];
    i = i + 1;
  }
}

int use(void)
    CERASTES_ENSURES(r, r == 6)
{
  int a[2] = {0, 0};
  int b[2] = {5, 6};
  copy(a, b, 2);
  CERASTES_CHECK(a[1] == b[1]);
  return a[1];
}

Such a fact over two reads is used where the program mentions an element of each: after p[i] == q[i] and q[i] >= 0, p[2] >= 0 follows once the program also reads q[2], and is reported as not proved otherwise (a known limit, lifted with pointer arithmetic). In a check, a quantifier over a local array or a range is checked element by element: every element must be readable (permission), within a local array’s bound, and have a value, before the fact itself (check). In a loop invariant and a check a quantifier stands as a conjunct of the clause, it does not dereference an array argument or compare pointer arguments, and over two reads it computes only with the first; in a check it reads only elements at the quantified index, of a type that is not a pointer (known limits; the positions in a later milestone, the rest with pointer arithmetic).

Every check of the body of f (an overflow, a division, an element read without permission) is made for every value of the index and reported at the forall, with a note at the line of f; an argument’s own checks (n + 1) are made once, at the forall.

Not supported yet, each rejected with a diagnostic: designators in an array’s initializer ({[2] = 5}: the front end keeps only the index’s computed value, which cerastes cannot check as written); an element of the initializer that reads, writes or takes the address of the array itself; arrays of more than one dimension and of owning pointers; const arrays; a variable length; one element as a contract’s object (cerastes_owns(p[i])), a range of elements in a loop invariant, a range whose pointer is not a parameter; pointer arithmetic (p + 1); and in a forall, an index other than i, i + c and i - c, arithmetic on reads of two arrays or two offsets (and, in loops and checks, on the second of two reads), a pointer argument other than a parameter (in a contract) or a pointer variable, local array or global array (in a loop or a check), the shapes a loop invariant or a check does not accept yet (above), structure members and array members under the quantifier, and the positions forall lists.

A value computed from an array

A quantifier states a fact about each element; a value computed from all of them, such as their sum, is a pure function that cerastes verify reads (Pure functions). Its requires reads the range with cerastes_reads_range, its body is one return, and a recursive one carries a measure:

#include <cerastes.h>

CERASTES_PURE long long sum_to(const int *a, int n)
    CERASTES_REQUIRES(0 <= n && cerastes_reads_range(a, n))
    CERASTES_ENSURES(r, -2147483648LL * n <= r && r <= 2147483647LL * n)
    CERASTES_DECREASES(n)
{
  return n == 0 ? 0 : sum_to(a, n - 1) + a[n - 1];
}

A loop that computes the sum states, in its invariant, that the running total is the function’s value over the prefix it has read. cerastes verify proves that the invariant holds on entry, that one iteration keeps it (the function’s definition, unfolded once, relates sum_to(a, i + 1) to sum_to(a, i)), and that on exit it gives the ensures:

long long sum(const int *a, int n)
    CERASTES_REQUIRES(0 <= n && cerastes_reads_range(a, n))
    CERASTES_ENSURES(r, cerastes_reads_range(a, n) && r == sum_to(a, n))
{
  long long s = 0;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n && s == sum_to(a, i))
  CERASTES_DECREASES(n - i)
  while (i < n) {
    s = s + a[i];
    i = i + 1;
  }
  return s;
}

Each call of a pure function in an annotation is checked where it stands. In a loop invariant, the loop must hold every element the function reads (here the loop holds a[0] to a[n - 1], which the function’s requires reads from a[0] to a[i - 1]); an element it does not hold, or one that has no value yet, is an error at the invariant. A write inside the summed prefix changes the function’s value, and the invariant is then not kept.

What cerastes verify does not compute by itself:

  • Where it checks a contract on its own, it knows a call’s value only through the callee’s ensures and the range of the result’s type (here all of long long): the tighter bound in the ensures of sum_to is what lets the caller’s arithmetic be checked, and what makes the loop’s s + a[i] safe. Without it, the function’s own addition and the loop’s are reported as overflow.

  • It unfolds a recursive definition one step at a time: a check at known arguments may need one written step per element (check(sum_to(a, 1) == a[0]) before check(sum_to(a, 2) == a[0] + a[1])).

  • One range of the caller must hold every element a call reads: a call over elements held by two different ranges is reported as permission.

  • A pointer argument of a call, for a parameter that the callee reads through, is a parameter (in a contract) or a pointer variable or a local array (in a loop invariant or a check); &a[1] or p + 1 there is rejected.

  • A call in a loop invariant or a check of a function that reads elements which are themselves pointers (int **, with cerastes_reads_range(pp, n)) is rejected; the same call in a contract is accepted. A pointer argument that C++ converts below its first level (an int ** for a const int *const * parameter) is rejected, as the same conversion is elsewhere (Pointers to pointers).

  • A call over the range of a parameter marked CERASTES_MUST_INIT or CERASTES_REF_TO_UNINIT is reported as permission, even where the function has given every element a value: a call does not read a marked range yet.

Global variables

A global variable that is not const is an object in memory that exists for the whole run of the program. main starts with every global of the file, each holding its initial value; any other function reaches a global only through its contract, which names it the way it names *p: cerastes_owns(count) to read and write it, cerastes_reads(count) to read it. A function whose contract does not name a global cannot change it, so its caller keeps the global’s value across the call. A function that reads or writes a global its contract does not name is reported as permission:

#include <cerastes.h>

static int count = 0;

void record(void)
    CERASTES_REQUIRES(cerastes_owns(count) && count < 1000)
    CERASTES_ENSURES(cerastes_owns(count) && count == cerastes_old(count) + 1)
{
  count += 1;
}

int total(void)
    CERASTES_REQUIRES(cerastes_reads(count))
    CERASTES_ENSURES(r, cerastes_reads(count) && r == count)
{
  return count;
}

int twice(int a)
    CERASTES_REQUIRES(a >= 0 && a <= 1000)
    CERASTES_ENSURES(r, r == 2 * a)
{
  return 2 * a;
}

int main(void)
{
  record();
  record();
  int t = twice(total());
  CERASTES_CHECK(count == 2 && t == 4);
  (void)t;
  return 0;
}

cerastes_old(count) in an ensures is the global’s value when the function was entered, and a contract may compare a pointer with its address (r == &count). The address of a global can be taken, stored and passed like the address of a local (int *p = &count;); it never dangles.

Initial values. main knows a global’s initial value when the file is the only one that can set it:

  • a global declared static (or, in C++, in an unnamed namespace) starts with its initializer’s value, 0 or a null pointer without one;

  • in C, so does any global with an initializer;

  • a C global without an initializer and not static (int count;) starts with an unknown value, since another file may define it with a value (compilers that merge such definitions, -fcommon, are the default on macOS);

  • in C++, a global that is not static starts with an unknown value, since another file’s initialization may change it before main runs, and so does a global whose address is the initial value of such a global (or of one of its elements or members), and an array whose first element’s address is.

The rest of the program is assumed to keep to this file’s contracts: code that runs before main in another file calls none of this file’s functions, and a function of another file declared here changes only what its contract names (one translation unit). A structure global follows the same rules member by member: each member starts with the initializer’s value, zero (or null) for the members it does not name, and a contract names the whole object (cerastes_owns(stats)) or one member (cerastes_owns(stats.hits)):

#include <cerastes.h>

struct counter {
  int hits;
  int misses;
};

static struct counter stats = {.hits = 0, .misses = 2};

void hit(void)
    CERASTES_REQUIRES(cerastes_owns(stats.hits) && stats.hits < 1000)
    CERASTES_ENSURES(cerastes_owns(stats.hits) && stats.hits == cerastes_old(stats.hits) + 1)
{
  stats.hits += 1;
}

int total(void)
    CERASTES_REQUIRES(cerastes_reads(stats) && 0 <= stats.hits && stats.hits <= 1000 && 0 <= stats.misses && stats.misses <= 1000)
    CERASTES_ENSURES(r, cerastes_reads(stats) && r == stats.hits + stats.misses)
{
  return stats.hits + stats.misses;
}

int main(void)
{
  hit();
  CERASTES_CHECK(stats.hits == 1 && stats.misses == 2);
  return total() == 3 ? 0 : 1;
}

A contract can name the object a pointer global points to, cerastes_owns(*gp), after an atom that holds the global itself (cerastes_owns(gp) or cerastes_reads(gp)):

#include <cerastes.h>

static int h = 7;
static int *gp = &h;

void bump(void)
    CERASTES_REQUIRES(cerastes_owns(gp) && cerastes_owns(*gp) && *gp < 100)
    CERASTES_ENSURES(cerastes_owns(gp) && gp == cerastes_old(gp) && cerastes_owns(*gp) && *gp == cerastes_old(*gp) + 1)
{
  *gp += 1;
}

int main(void)
{
  bump();
  CERASTES_CHECK(h == 8);
  return 0;
}

Global arrays. A global array (int table[8];), or a static local one, is an object of all its elements that exists for the whole run. main starts with every element: the values its braced initializer lists, zero (false, a null pointer) for the elements it does not list, or unknown values by the rules above. Each listed value is checked as written, like a global’s initializer, and so is the bound. A contract names the whole array, cerastes_owns(table) to read and write every element or cerastes_reads(table) to read them, and after such an atom it may read an element (table[i], cerastes_old(table[i])). A loop in a function that holds the array carries it, as it carries a local array (Loops); table passed where a callee takes a range (cerastes_owns_range(p, n)) gives it the elements it names:

#include <cerastes.h>

static int table[4] = {10, 20};

void store(int i, int v)
    CERASTES_REQUIRES(cerastes_owns(table) && 0 <= i && i < 4)
    CERASTES_ENSURES(cerastes_owns(table) && table[i] == v)
{
  table[i] = v;
}

int load(int i)
    CERASTES_REQUIRES(cerastes_reads(table) && 0 <= i && i < 4)
    CERASTES_ENSURES(r, cerastes_reads(table) && r == table[i])
{
  return table[i];
}

void clear(int *p, int n)
    CERASTES_REQUIRES(cerastes_owns_range(p, n) && n > 0)
    CERASTES_ENSURES(cerastes_owns_range(p, n) && p[0] == 0)
{
  (void)n;
  p[0] = 0;
}

int main(void)
{
  CERASTES_CHECK(table[1] == 20 && table[2] == 0);
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= 4)
  CERASTES_DECREASES(4 - i)
  while (i < 4) {
    table[i] = i;
    i += 1;
  }
  store(3, 7);
  int t = load(3);
  CERASTES_CHECK(t == 7);
  (void)t;
  clear(table, 4);
  CERASTES_CHECK(table[0] == 0);
  return 0;
}

An index outside the array is reported as out-of-bounds, an element read before the function holds the array as permission:

#include <cerastes.h>

static int table[4] = {10, 20};

void store(int i, int v)
    CERASTES_REQUIRES(cerastes_owns(table) && 0 <= i && i <= 4)
{
  table[i] = v;
}

int main(void)
{
  return table[0] - 10;
}

A contract cannot yet name part of a global array or one of its elements (cerastes_owns_range(table, n), &table[2]), take its address plus an offset (table + i), or pass it to a quantifier or a pure function (a loop invariant and a check can). A const global array and a global initialized with &table[2] are not supported yet; a global array declared without a bound or a braced initializer (int table[];) is rejected, as the compilers warn about it.

A global or static local array may hold structures (static struct point grid[3] = {{1, 2}, {3}};). Each element takes a list of its own, and what the lists leave out is zero, as for any object with static storage, so grid[1].y and every member of grid[2] are 0 here; where the initial values of a global are not known (Global variables), none of its elements' members is. cerastes_owns(grid) and cerastes_reads(grid) name every member of every element, a contract may then read grid[i].x, and main and the loops of a function that holds the array carry it member by member, as they carry a local array of structures.

Globals of other files (extern int count; with no definition here) are not supported yet, nor is a structure global initialized with the address of another global’s member (&h.x).

static local variables

A static local variable is a global whose name only its function sees, so no contract can name it. cerastes gives the function the right to it implicitly, and the same right to every function that calls it, directly or not; main holds it from the start. Its initializer runs once, before main, and nothing is known about its value when the function is entered, since another call may have changed it:

#include <cerastes.h>
#include <limits.h>

int next_id(void)
    CERASTES_ENSURES(r, r > 0)
{
  static int last = 0;
  if (last < 0 || last == INT_MAX)
    last = 0;
  last += 1;
  return last;
}

int main(void)
{
  int a = next_id();
  int b = next_id();
  CERASTES_CHECK(a > 0 && b > 0);
  (void)a;
  (void)b;
  return 0;
}

Since every caller holds the variable across the call, two calls that both reach the function and that C does not order (next_id() + next_id()) are reported as unsequenced: the result depends on which runs first. A static local may be a structure or an array (Global arrays); the function and its callers then hold every member or element. A function may return the address of its static local; its caller can use the pointer when the contract says what it points to (Results that give a place), and otherwise a use of it is reported as lifetime. A static const local is not supported yet.

Results that give a place

An ensures that names a pointer parameter’s object normally gives back what the requires took (Pointer parameters and contracts). A function can also promise something about the object its pointer result points to, or about a member of a returned structure’s pointer (cerastes_owns(*r), cerastes_reads(*r), cerastes_live(r), cerastes_live(r.q), cerastes_owns(**r)), though no requires atom names it. The promise is one of two kinds, and cerastes decides which at each return.

Covered. The function already holds the object through a right it does not list: the implicit right to its static local (static local variables), or the object of an owning parameter. The atom then adds nothing the caller does not get anyway: the caller learns that the result is that object and uses the right it holds. With live(r) the caller may use the pointer: copy it, compare it, pass it on.

#include <cerastes.h>
#include <stddef.h>

int *where(void)
    CERASTES_ENSURES(r, cerastes_live(r))
{
  static int s = 5;
  return &s;
}

int use_where(void)
{
  int *p = where();
  if (p == NULL) {
    return 1;
  }
  return 0;
}

A covered live gives the equality of the objects and nothing more. It never gives access, so the caller may not read *p through it:

#include <cerastes.h>
#include <stddef.h>

int *where(void)
    CERASTES_ENSURES(r, cerastes_live(r))
{
  static int s = 5;
  return &s;
}

int main(void)
{
  int *p = where();
  int v = *p;
  return v;
}

With owns(*r) the caller reads and writes the object through its own right to the static local:

#include <cerastes.h>

int *where(void)
    CERASTES_ENSURES(r, cerastes_owns(*r))
{
  static int s = 6;
  return &s;
}

int main(void)
{
  int *w = where();
  *w = 3;
  int v = *w;
  CERASTES_CHECK(v == 3);
  return v - 3;
}

An owning parameter’s object is covered the same way:

#include <cerastes.h>
#include <stddef.h>

int *identity(CERASTES_OWNING int *p)
    CERASTES_ENSURES(r, r == NULL || cerastes_owns(*r))
{
  return p;
}

int use_identity(void)
    CERASTES_ENSURES(r, r == 0 || r == 2)
{
  int x = 1;
  int *q = identity(&x);
  int w = 0;
  if (q != NULL) {
    *q = 2;
    w = *q;
  }
  return w;
}

Given. The function holds the object beyond what it gives back for its other atoms, and hands the right over. take_cell takes a global’s cell and gives it to its caller through the result; its own ensures does not give g back, since the caller now has it as *r:

#include <cerastes.h>

static int g = 3;

int *take_cell(void)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(r, cerastes_owns(*r) && r == &g && *r == cerastes_old(g))
{
  return &g;
}

int main(void)
{
  int *p = take_cell();
  int v = *p;
  CERASTES_CHECK(v == 3);
  *p = 5;
  CERASTES_CHECK(g == 5);
  return v - 3;
}

A function can give only what it holds. If take_cell held nothing of g, it would promise a place it does not have, and cerastes reports it at the return:

#include <cerastes.h>

static int g = 3;

int *take_cell(void)
    CERASTES_ENSURES(r, cerastes_owns(*r) && r == &g)
{
  return &g;
}

Only the implicit rights cover; a written atom never does. Two atoms joined by && stay two objects, so the caller of pick concludes that the result is not *p, and may write through it without changing x (the contract says *p is unchanged, which the caller needs to know x still holds 1):

#include <cerastes.h>

static int g = 0;

int *pick(int *p)
    CERASTES_REQUIRES(cerastes_owns(*p) && cerastes_owns(g))
    CERASTES_ENSURES(r, cerastes_owns(*p) && *p == cerastes_old(*p) && cerastes_owns(*r) && r == &g)
{
  (void)p;
  return &g;
}

int main(void)
{
  int x = 1;
  int *q = pick(&x);
  *q = 2;
  CERASTES_CHECK(x == 1);
  return x - 1;
}

A place that lies inside or around one the requires takes cannot be promised again as a new one (owns(*p) taken, a new owns(p→x) promised, or live(p) beside a new owns(*p)): write one atom on the whole place. A reach through the result (owns(**r)) needs an atom on *r before it, as every contract read of an object does.

Contracts without a body. A function declared without a body is trusted, and a contract nothing verifies must not promise a right its caller may already hold, or the caller’s state would be impossible and everything after the call would verify. Such a contract may therefore promise a place only on its result, and only when no clause equates the result, or a pointer read through it, with anything but a null pointer: a function that returns a fresh object is such a contract. Any other promise (a place on a parameter, a result tied to a parameter) is cerastes-unsupported_annotation, until the contract manifest (planned with the concepts) lets a unit state what it relies on:

#include <cerastes.h>
#include <stddef.h>

int *fresh(void)
    CERASTES_ENSURES(r, r == NULL || cerastes_owns(*r));

int use_fresh(void)
    CERASTES_ENSURES(r, r == 0 || r == 2)
{
  int *p = fresh();
  int w = 0;
  if (p != NULL) {
    *p = 2;
    w = *p;
  }
  return w;
}
#include <cerastes.h>

void give(int *p)
    CERASTES_REQUIRES(cerastes_live(p))
    CERASTES_ENSURES(cerastes_owns(*p));

void caller(int *q)
    CERASTES_REQUIRES(cerastes_live(q))
{
  give(q);
}

Writes and calls inside expressions

An object in memory may be written inside an expression, as a variable can (Side effects in expressions): y = x++, f(*p = 1) and (*p)++ + 1 are fine, and so is a call of a function whose contract owns or reads an object, next to other uses of objects in memory:

#include <cerastes.h>

int take(int v)
    CERASTES_ENSURES(r, r == v)
{
  return v;
}

int in_expression(void)
    CERASTES_ENSURES(r, r == 11)
{
  int x = 0;
  int y = 0;
  int *px = &x;
  int *p = &y;
  int a = take(x = 1);
  int b = (*p = 3) + 1;
  int c = x++;
  return a + b + c + *px + y;
}

C does not say in which order the operands of most operators are evaluated. Two accesses to one object without a sequence point between them, one of them a write, are undefined behaviour, and a call next to an access to an object that the call may change gives a result that depends on an order C leaves open. When the source names the object twice (x++ + x, *p = (*p)++), the compilers warn and cerastes rejects the expression (unsequenced_modification). When it names it in two ways that may meet (*p = (*q)++, x + bump(&x), bump(p) + peek(q)), cerastes checks, on each path, that they are different objects, and reports unsequenced where they may not be:

#include <cerastes.h>
#include <stddef.h>

int bump(int *p)
    CERASTES_REQUIRES(cerastes_owns(*p) && *p < 100)
    CERASTES_ENSURES(r, cerastes_owns(*p) && *p == cerastes_old(*p) + 1 && r == *p)
{
  *p += 1;
  return *p;
}

int beside(void)
    CERASTES_ENSURES(r, r == 11)
{
  int x = 1;
  int y = 2;
  int s = x + bump(&y);
  x = bump(&x);
  int t = bump(&x) + bump(&y);
  return s + t;
}

A call and the accesses written in its own arguments, a statement’s own assignment of the call’s result (x = bump(&x);), and accesses separated by ,, &&, || or the condition of ?: have a fixed order, and are not reported.

Loops

A loop may use pointers and objects in memory like any other code. Its body gets, without any annotation, every object in memory the function holds when the loop starts: the local variables whose address is taken (in every block that is open there, including those declared later in it), the parameters whose address is taken, the object each pointer parameter points to, when the function never assigns that parameter, and every object the contract names through a pointer read (**pp, *gp, p->q->x, *s.q): the object the requires named, and, when the function may change the pointer before the loop, also the object the pointer points to when the loop starts. As for a local variable that the loop assigns, the loop’s invariant states what the loop does to their values:

#include <cerastes.h>

int count_up(int n)
    CERASTES_REQUIRES(0 <= n && n <= 100)
    CERASTES_ENSURES(r, r == n)
{
  int x = 0;
  int *p = &x;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n && x == i)
  CERASTES_DECREASES(n - i)
  while (i < n) {
    *p += 1;
    i += 1;
  }
  return x;
}

What the invariant does not state is known in two cases only:

  • An object keeps its value across the loop when no write in the loop can reach it: no assignment to it by name, no write through a pointer to its type, and no call of a function whose contract owns an object of its type. A write through a pointer counts against every object of that type, since cerastes does not follow where each pointer points:

    #include <cerastes.h>
    
    int havoc(int n)
        CERASTES_REQUIRES(0 <= n && n <= 100)
        CERASTES_ENSURES(r, r == 7)
    {
      int keep = 7;
      int last = 0;
      int *pk = &keep;
      int *pl = &last;
      int i = 0;
      CERASTES_INVARIANT(0 <= i && i <= n)
      CERASTES_DECREASES(n - i)
      while (i < n) {
        *pl = i;
        i += 1;
      }
      return *pk;
    }

    cerastes reports the ensures of havoc: the write through pl may have changed keep. Stating the value in the invariant is enough:

    #include <cerastes.h>
    
    int havoc(int n)
        CERASTES_REQUIRES(0 <= n && n <= 100)
        CERASTES_ENSURES(r, r == 7)
    {
      int keep = 7;
      int last = 0;
      int *pk = &keep;
      int *pl = &last;
      int i = 0;
      CERASTES_INVARIANT(0 <= i && i <= n && keep == 7)
      CERASTES_DECREASES(n - i)
      while (i < n) {
        *pl = i;
        i += 1;
      }
      return *pk;
    }
  • An object that held a value when the loop started still holds one. An object that the loop gives its first value is known to hold one after the loop only when the invariant states its value (i == 0 || x == i); an invariant that reads an object that holds no value yet is reported as uninitialized.

Every iteration must end holding what the loop started with: a function called in the loop that keeps one of these objects is reported as permission at the closing brace of the loop’s body. An invariant or a measure may read objects in memory (CERASTES_INVARIANT(x == i), CERASTES_DECREASES(*p)), compare pointers and take addresses; it reads only what the loop holds, and an invariant that reads an object the loop does not hold is reported as permission. A pointer that the loop assigns needs an invariant saying where it points (p == &x || p == &y). The address of a variable in an annotation (p == &x) is accepted only when the code takes that address too.

A pointer that the function assigns (a pointer local, or a parameter it reassigns) takes nothing into a loop by itself. The invariant says what the loop holds through it, with cerastes_owns(*q), cerastes_reads(*q) or cerastes_live(q) as in a contract, also through a pointer read (cerastes_owns(**pp), cerastes_owns(*p->q), cerastes_owns(*gp), and cerastes_owns(*q) where the address of q itself is taken): the loop must hold it when it starts and at the end of every iteration, and gives it back after the loop. Without it, an access inside the loop is reported as permission:

#include <cerastes.h>
#include <stddef.h>

int count(int *p, int n)
    CERASTES_REQUIRES(cerastes_owns(*p) && *p == 1 && 0 <= n && n <= 100)
    CERASTES_ENSURES(r, cerastes_owns(*p) && r == n)
{
  int *q = p;
  p = NULL;
  int s = 0;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n && s == i && cerastes_owns(*q) && *q == 1)
  CERASTES_DECREASES(n - i)
  while (i < n) {
    s += *q;
    i += 1;
  }
  return s;
}

Ownership that the loop lacks is reported as permission, at the invariant when the loop starts without it, and at the closing brace of the body when an iteration ends without it. When the loop moves such a pointer (q = &y;), the invariant must also say where it may point (q == &x || q == &y), and what the loop held comes back after the loop only for the object q points to then. Two owns of objects that may be one are reported too. For a pointer to a structure, cerastes_owns(*q) and cerastes_reads(*q) hold every member of the structure q points to, and cerastes_owns(q->x) one member:

#include <cerastes.h>

struct S {
  int a;
  int b;
};

int walk(int n)
    CERASTES_REQUIRES(0 <= n && n <= 100)
    CERASTES_ENSURES(r, r == 1)
{
  struct S s1 = {1, 2};
  struct S s2 = {1, 3};
  struct S *q = &s1;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n && s1.a == 1 && s2.a == 1 && (q == &s1 || q == &s2) && cerastes_owns(*q) && q->a == 1)
  CERASTES_DECREASES(n - i)
  while (i < n) {
    q = (q == &s1) ? &s2 : &s1;
    i += 1;
  }
  return q->a;
}

A loop that moves an owned pointer from the object of one pointer parameter to the object of another may be reported at the end of an iteration even when it is correct, since the share of each object’s lifetime that the caller lends may differ; keep one pointer per parameter in such loops. An owns, reads or live in a do … while (0) invariant, which is checked once like a CERASTES_CHECK, or in a measure, is rejected.

Leaving a block

break, continue, goto and return end the lifetime of every object in memory whose block they leave, as the closing brace does. A function that kept such an object is reported at the jump as lifetime:

#include <cerastes.h>

int first_special(int n)
    CERASTES_REQUIRES(0 <= n && n <= 100)
    CERASTES_ENSURES(r, 0 <= r && r <= n)
{
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n)
  CERASTES_DECREASES(n - i)
  while (i < n) {
    int x = i;
    int *p = &x;
    if (*p == 3) {
      i += 1;
      continue;
    }
    if (*p == 50) {
      break;
    }
    if (*p == 60) {
      goto done;
    }
    if (*p == 70) {
      return i;
    }
    i += 1;
  }
done:
  return i;
}

Allocated memory: malloc, calloc and free

malloc, calloc and free come with contracts in vlibc, cerastes’s C library headers. An allocation is a new object that the function now owns entirely; free ends it. cerastes proves that every allocation is tested against null before it is used, that only what was allocated is freed, and only once, and that nothing allocated is forgotten (a leak).

One object per allocation. In this version an allocation holds one object: its size must be sizeof(T) (sizeof *p is the same), and its result must be converted at once to T *: in an initializer or assignment (int *p = malloc(sizeof *p);, C), a return, an argument, or a cast ((int *)malloc(sizeof(int)), which C++ needs). The object then has type T for its whole life. calloc(1, sizeof(T)) gives an object whose members are all zero, null for a pointer member; the object from malloc has no value until the program gives it one (reading it first is uninitialized). Arrays of objects (n * sizeof(T)) and realloc are planned with pointer arithmetic.

#include <cerastes.h>
#include <stdlib.h>

struct point {
  int x;
  int y;
};

int main(void)
{
  struct point *p = (struct point *)calloc(1, sizeof(struct point));
  if (p == NULL) {
    return 1;
  }
  CERASTES_CHECK(p->x == 0 && p->y == 0);
  p->x = 3;
  p->y = 4;
  int sum = p->x + p->y;
  free(p);
  return sum == 7 ? 0 : 1;
}

Freeing. free(p) needs the whole allocation that p points to the start of. Freeing it twice, freeing a local or global object or a structure’s member, freeing an object the function only borrows, or freeing while a function it called may still hold a pointer to it is invalid-free. After free(p), any use of p is lifetime and any access through it permission. free(NULL) does nothing, but it must be written with a typed pointer: a bare free(NULL) is rejected.

Leaks. A function that ends while it still owns an allocation it does not hand to its caller is reported at its closing brace as leak, and so is main (as VeriFast does): free everything before main returns. A path that ends in exit, abort or _Exit is not checked, since it does not return. An iteration of a loop that ends while it owns an allocation the loop does not carry to the next iteration is a leak too, reported at the end of the loop’s body.

Loops. A loop may use an allocation made before it, through a pointer variable declared before the loop: the loop keeps the allocation as it found it, and may read, write or free it. When the loop moves allocations between pointers (two pointers swapped, a pointer given a new allocation), the allocation is no longer the one it found, and the loop’s invariant says which pointer holds one: CERASTES_INVARIANT(p == NULL || cerastes_owns_block(p)) keeps the whole allocation p points to, whichever it is, at the start of every iteration. Two such pointers in one invariant name two different allocations.

#include <cerastes.h>
#include <stdlib.h>

int swap_many(int n)
    CERASTES_REQUIRES(0 <= n && n <= 100)
{
  int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  int *q = (int *)malloc(sizeof(int));
  if (q == NULL) {
    free(p);
    return -1;
  }
  *p = 0;
  *q = 1;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n && (p == NULL || cerastes_owns_block(p)) && (q == NULL || cerastes_owns_block(q)))
  CERASTES_DECREASES(n - i)
  while (i < n) {
    int *t = p;
    p = q;
    q = t;
    i += 1;
  }
  free(p);
  free(q);
  return 0;
}

Without the invariant, the swap is reported: after the loop nothing says which variable holds which allocation. An owning local (below) needs no such invariant, since the loop keeps its block by its value.

Handing an allocation over. cerastes_owns_block(p) (cerastes::owns_block in C++) in a contract is ownership of the whole allocation p points to the start of, everything free needs. In a requires alone, the function takes the allocation (it frees it, or hands it on); in an ensures about the result, the caller receives it; in both, about a parameter, the function borrows it and gives it back. cerastes::owning written on a function means the same as ensures(r == NULL || owns_block(r)), and cerastes::ref_to_uninit on such a function says the caller receives an object without a value, as from malloc:

#include <cerastes.h>
#include <stdlib.h>

int *make_cell(int v)
    CERASTES_ENSURES(r, r == NULL || (cerastes_owns_block(r) && *r == v))
{
  int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return NULL;
  }
  *p = v;
  return p;
}

void drop_cell(int *p)
    CERASTES_REQUIRES(p == NULL || cerastes_owns_block(p))
{
  free(p);
}

int main(void)
{
  int *p = make_cell(7);
  if (p == NULL) {
    return 1;
  }
  int v = *p;
  drop_cell(p);
  return v == 7 ? 0 : 1;
}

Through a pointer or a global. The pointer that cerastes_owns_block takes may also be read from memory:

  • cerastes_owns_block(*pp) is the allocation *pp points to the start of;

  • cerastes_owns_block(p→next) is the one a member points to;

  • cerastes_owns_block(g) is the one a global pointer points to.

The pointer itself must be owned or read earlier in the same clause list (cerastes_owns(*pp) && cerastes_owns_block(*pp)), as every read in a contract must. In a requires it names the allocation the pointer holds when the function is called; in an ensures, the one it holds when the function returns. So a function can allocate into *pp and hand the allocation to its caller:

#include <cerastes.h>
#include <stdlib.h>

int make(int **pp)
    CERASTES_REQUIRES(cerastes_owns(*pp))
    CERASTES_ENSURES(r, cerastes_owns(*pp) && (r != 0 || cerastes_owns_block(*pp)))
{
  *pp = (int *)malloc(sizeof(int));
  if (*pp == NULL) {
    return 1;
  }
  **pp = 5;
  return 0;
}

int main(void)
{
  int *p = NULL;
  if (make(&p) != 0) {
    return 1;
  }
  *p = 6;
  free(p);
  return 0;
}

Nothing checks what a function without a body in the program returns. So when such a function borrows an allocation through a pointer or a global, its contract must say that it gives back the same one (*pp == cerastes_old(*pp)). A function without a body that takes or hands over an allocation through a pointer or a global is rejected: that needs the contracts of other translation units, which are planned. A local that owns an allocation is an owning local, and a global that does is an owning global.

vlibc’s allocator. vlibc also has an allocator of its own, vlibc_malloc, vlibc_calloc and vlibc_free (with vlibc_realloc, vlibc_aligned_alloc, vlibc_free_sized and vlibc_free_aligned_sized), in the library libvlibc (vlibc). The first three have the contracts of malloc, calloc and free, and cerastes checks their calls the same way. Its blocks are a heap of their own: a block from vlibc_malloc or vlibc_calloc is freed with vlibc_free, a block from malloc or calloc with free, and freeing a block with the other allocator’s function is invalid-free:

#include <cerastes.h>
#include <vlibc/stdlib.h>

int main(void)
{
  int *p = (int *)vlibc_malloc(sizeof(int));   // vlibc's heap
  int *q = (int *)malloc(sizeof(int));         // the platform's heap
  if (p == NULL || q == NULL) {
    vlibc_free(p);
    free(q);
    return 1;
  }
  *p = 1;
  *q = 2;
  int sum = *p + *q;
  vlibc_free(p);   // each block is freed by its own allocator
  free(q);
  return sum == 3 ? 0 : 1;
}

A function can borrow the objects of a block of either allocator through owns(*p), reads(*p) and live(p). vlibc’s allocator is for C: in C++ a call of vlibc_malloc or vlibc_calloc is rejected, since C++ creates objects only in the storage std::malloc and its family return (placement new comes with classes).

A vlibc block in a contract. cerastes_owns_block and cerastes::owning name a block of malloc or calloc: handing a block of vlibc’s over through them is reported as permission. cerastes_owns_vlibc_block(p) is cerastes_owns_block(p) for a block of vlibc’s allocator. It is declared by <cerastes.h> under that C name only, in C programs (in C++ it is cerastes-unsupported_annotation, like the allocation itself), and everything said of cerastes_owns_block applies: a requires alone takes the block, an ensures alone about the result hands it over, both on one parameter borrow it. A contract does not name both spellings for one pointer. A program that names it is checked as one that uses vlibc’s allocator: each block’s allocator is checked wherever it is handed over or freed.

#include <cerastes.h>
#include <vlibc/stdlib.h>

void touch(int *p)
    CERASTES_REQUIRES(cerastes_owns_vlibc_block(p))
    CERASTES_ENSURES(cerastes_owns_vlibc_block(p))
{
  *p = 2;
}

void dispose(int *p)
    CERASTES_REQUIRES(cerastes_owns_vlibc_block(p))
{
  vlibc_free(p);
}

int use(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  int *p = (int *)vlibc_malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 1;
  touch(p);
  dispose(p);
  return 0;
}

A block of the other allocator is reported where it is passed:

#include <cerastes.h>
#include <stdlib.h>

void dispose(int *p)
    CERASTES_REQUIRES(cerastes_owns_vlibc_block(p));

int use(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 1;
  dispose(p);
  return 0;
}

Owning locals

A pointer local marked cerastes::owning (CERASTES_OWNING) owns the allocation it points to. cerastes then reports a forgotten allocation where it happens, at the end of the variable’s scope or when the variable is assigned another value, instead of only at the end of the function (the attribute).

The value rule. An owner is given the start of an allocation the function holds whole, or null. Anything else (the address of a local, a pointer into the middle of a block, a block the function does not own) is permission at the initialization or the assignment:

#include <cerastes.h>

void g(void)
{
  int x = 0;
  CERASTES_OWNING int *q = &x;
  *q = 1;
}

Lifetime end. At each way out of the variable’s scope (the end of its block, a break, a continue or a goto that leaves it, a return) the owner must no longer hold its block: it was freed, handed to a function that takes it, or passed to another owner or returned. One that still holds it is leak, reported at the way out:

#include <cerastes.h>
#include <stdlib.h>

int use_and_free(void)
    CERASTES_ENSURES(r, r == 7 || r == -1)
{
  CERASTES_OWNING int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 7;
  int v = *p;
  free(p);
  return v;
}

int block_scope(int c)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  {
    CERASTES_OWNING int *q = (int *)malloc(sizeof(int));
    if (q == NULL) {
      return -1;
    }
    *q = c;
    free(q);
  }
  return 0;
}
#include <cerastes.h>
#include <stdlib.h>

int use_and_forget(void)
    CERASTES_ENSURES(r, r == 7 || r == -1)
{
  CERASTES_OWNING int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 7;
  int v = *p;
  return v;
}

Reassignment. Assigning to an owner that holds a block drops the block, and is leak at the assignment, unless another owner or the value being assigned holds it (p = p is fine):

#include <cerastes.h>
#include <stdlib.h>

int overwrite(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  CERASTES_OWNING int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 1;
  p = (int *)malloc(sizeof(int));
  free(p);
  return 0;
}

Owners. At a point, the owners are the owning locals in scope that hold their block. A block is also held by an owner that outlives the way out: a variable of an enclosing scope, the value a function returns when the function is owning or its ensures hands over the result, and the entry value of a parameter that the function borrows (cerastes_owns_block in both lists), so that a function can park a borrowed block in an owning local:

#include <cerastes.h>
#include <stdlib.h>

CERASTES_OWNING int *second(void)
{
  CERASTES_OWNING int *a = (int *)malloc(sizeof(int));
  if (a == NULL) {
    return NULL;
  }
  *a = 1;
  CERASTES_OWNING int *b = (int *)malloc(sizeof(int));
  if (b == NULL) {
    free(a);
    return NULL;
  }
  *b = 2;
  free(a);
  return b;
}
#include <cerastes.h>
#include <stdlib.h>

CERASTES_OWNING int *second(void)
{
  CERASTES_OWNING int *a = (int *)malloc(sizeof(int));
  if (a == NULL) {
    return NULL;
  }
  *a = 1;
  CERASTES_OWNING int *b = (int *)malloc(sizeof(int));
  if (b == NULL) {
    free(a);
    return NULL;
  }
  *b = 2;
  return b;
}
#include <cerastes.h>

void park(int *p)
    CERASTES_REQUIRES(cerastes_owns_block(p))
    CERASTES_ENSURES(cerastes_owns_block(p))
{
  CERASTES_OWNING int *v = p;
  *v = 1;
}

Handing a block on. Passing the pointer to a function whose requires takes the block (cerastes_owns_block(p) without a matching ensures, or free) ends the obligation, and so does assigning it to another owner:

#include <cerastes.h>
#include <stdlib.h>

void dispose(int *p)
    CERASTES_REQUIRES(cerastes_owns_block(p))
{
  free(p);
}

int make_and_dispose(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  CERASTES_OWNING int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 5;
  dispose(p);
  return 0;
}
#include <cerastes.h>
#include <stdlib.h>

int handoff(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  CERASTES_OWNING int *keeper = NULL;
  {
    CERASTES_OWNING int *t = (int *)malloc(sizeof(int));
    if (t == NULL) {
      return -1;
    }
    *t = 3;
    keeper = t;
  }
  free(keeper);
  return 0;
}

A dangling owner. After the block is freed or taken by a call, the owner holds nothing, even if a later allocation returns the same address. A use of the pointer after the free is still lifetime. A copy in a plain pointer does not take the obligation: the owner still holds the block when its scope ends, whatever the copy does later, so a block moved to a plain pointer is reported at the owner’s scope:

#include <cerastes.h>
#include <stdlib.h>

int copy_to_plain(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  int *keeper = NULL;
  {
    CERASTES_OWNING int *t = (int *)malloc(sizeof(int));
    if (t == NULL) {
      return -1;
    }
    *t = 3;
    keeper = t;
  }
  free(keeper);
  return 0;
}

Unannotated pointers. Nothing changes for a pointer that is not marked: the rule at the end of the function (every allocation the function still holds and does not hand back is a leak) stays, and it reports blocks that no owner holds.

Loops. An owning local declared outside a loop that the loop assigns is kept across iterations by its value: at the start of the loop, and at the end of each iteration, an owner that is not null must hold the whole block it points to, and after the loop it is null or holds its block. A loop that frees the block of such an owner sets the variable to NULL after the free, and its invariant says so: the loop cannot carry "freed" otherwise. A loop that allocates into the variable every iteration, without freeing the previous block, drops a block in the second iteration (the reassignment rule above). So an owner that the loop allocates into must be NULL at the head of each iteration: say so in the invariant (v == NULL), or free it and set it to NULL in the body; otherwise the assignment at the head is reported as a leak, since the invariant does not say that the owner holds nothing there.

#include <cerastes.h>
#include <stdlib.h>

int last_frees(int n)
    CERASTES_REQUIRES(1 <= n && n <= 100)
{
  CERASTES_OWNING int *v = (int *)malloc(sizeof(int));
  if (v == NULL) {
    return -1;
  }
  *v = 1;
  int k = n;
  CERASTES_INVARIANT(0 <= k && k <= n && (k > 0 || v == NULL))
  CERASTES_DECREASES(k)
  while (k > 0) {
    k -= 1;
    if (k == 0) {
      free(v);
      v = NULL;
    }
  }
  return 0;
}

A violation is reported at the loop, as permission, at the start or at the end of an iteration:

#include <cerastes.h>
#include <stdlib.h>

int last_frees(int n)
    CERASTES_REQUIRES(1 <= n && n <= 100)
{
  CERASTES_OWNING int *v = (int *)malloc(sizeof(int));
  if (v == NULL) {
    return -1;
  }
  *v = 1;
  int k = n;
  CERASTES_INVARIANT(0 <= k && k <= n && (k > 0 || v == NULL))
  CERASTES_DECREASES(k)
  while (k > 0) {
    k -= 1;
    if (k == 0) {
      free(v);
    }
  }
  return 0;
}

A loop’s invariant may read the owner’s object (*v); the loop holds it through the owning local, so an owns(*v) or reads(*v) written for it in the invariant is permission ("which the loop already owns through its owning local"): drop the atom. A pointer that only copies the owner’s block (int *alias = v;) is an ordinary pointer in the loop, as before. When every assignment to the owner in the loop comes from one allocator (malloc or vlibc_malloc), the loop keeps the allocator, so a vlibc loop may start from a NULL owner; an owner that enters the loop with a block of the other allocator is permission at the loop’s entry, even when the loop would free it before the first assignment.

Owners that change hands inside a loop. Two owning locals may share a block for a while inside a loop (b = a;, then a = NULL;), and a plain pointer’s block may be handed to an owner (v = w;). The loop tracks which variable holds each block at the end of every iteration. An owner that takes its block on only some iterations needs an invariant that says when, since after the loop it could otherwise still be null:

#include <cerastes.h>
#include <stdlib.h>

int main(void)
{
  int *w = (int *)malloc(sizeof(int));
  if (w == NULL) {
    return 1;
  }
  *w = 0;
  CERASTES_OWNING int *v = NULL;
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= 3 && (i < 3 || v != NULL))
  CERASTES_DECREASES(3 - i)
  while (i < 3) {
    if (i == 2 && v == NULL) {
      v = w;
    }
    *w = i;
    i += 1;
  }
  free(v);
  return 0;
}

An owner can also be a structure’s member (Owning fields).

Owning globals and static locals

A global or a static local marked cerastes::owning holds the block it points to across calls. It starts null. An owning global with external linkage in C++, or a C global declared without an initializer, starts with a value cerastes cannot know: another translation unit may set it. So main must assign such a global before it hands it on. Its initializer, when it has one, must be a null pointer.

Who holds it. A function that names cerastes_owns(g) of an owning global in its contract also receives and returns the block g points to, when g is not null. It is as if the contract said cerastes_owns(g) && (g == NULL || cerastes_owns_block(g)). So when the function returns, g is null or holds a whole block the function holds. cerastes_reads(g) gives only the pointer’s value. A static local’s block travels the same way, through the implicit owns of the static local that its function and every caller already have:

#include <cerastes.h>
#include <stdlib.h>

static int *g CERASTES_OWNING = NULL;

void install(int v)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g))
{
  free(g);
  g = (int *)malloc(sizeof(int));
  if (g != NULL) {
    *g = v;
  }
}

int current(void)
    CERASTES_REQUIRES(cerastes_reads(g) && (g == NULL || cerastes_reads(*g)))
    CERASTES_ENSURES(cerastes_reads(g) && (g == NULL || cerastes_reads(*g)))
{
  return g == NULL ? -1 : *g;
}

int main(void)
{
  install(3);
  install(4);
  return current() < 0;
}

Assigning it. As for an owning local, a block that the global already holds must be freed or handed on before the global is assigned another value (leak at the assignment). The value it receives must be null or the start of a block the function holds whole (permission). A function that frees the block and returns while g still points to it is permission at the return: set g to NULL after freeing it.

#include <cerastes.h>
#include <stdlib.h>

static int *g CERASTES_OWNING = NULL;

void discard(void)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g))
{
  free(g);
}

int main(void)
{
  discard();
  return 0;
}

A marked owning global. An owning global that is also cerastes::ref_to_uninit holds a block that may have no value. A function whose contract takes the global (cerastes_owns(g)) is given the block without a value, and a function that returns it claims a value for it only when its ensures ties the global (g == cerastes_old(g), the same pointer): the caller’s value then survives the call. Without the tie the callee may have replaced the block with a fresh one, which has no value, so the caller cannot read what it wrote before the call (uninitialized, at the read). The same rule holds for an owning, marked member (Marked owning members).

#include <cerastes.h>
#include <stdlib.h>

int *g CERASTES_OWNING CERASTES_REF_TO_UNINIT;

void touch(void)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g) && g == cerastes_old(g))
{
}

void use(void)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g))
{
  if (g != NULL) {
    *g = 1;
  }
  touch();
  if (g != NULL) {
    int y = *g;
    *g = y;
  }
}
#include <cerastes.h>
#include <stdlib.h>

int *g CERASTES_OWNING CERASTES_REF_TO_UNINIT;

void touch(void)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g))
{
}

void use(void)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g))
{
  if (g != NULL) {
    *g = 1;
  }
  touch();
  if (g != NULL) {
    int y = *g;
    *g = y;
  }
}

The end of main. main may return while an owning global or static local still holds its block. An owner with static storage keeps its object for the whole program, as P4417R0 allows. A block that only a global without cerastes::owning points to is still a leak when main returns.

Owning locals whose address is taken. An owning local whose address is taken is an owner like any other. A write through a pointer to it is a write to the owner, checked like an assignment. A function that receives its address decides by its contract what happens to the block: with cerastes_owns(*pp) alone it may change the pointer, and with cerastes_owns(*pp) && (*pp == NULL || cerastes_owns_block(*pp)) in both lists it borrows the block too.

Owning fields

A pointer member of a structure marked cerastes::owning owns the block it points to, for as long as the structure does: a structure that owns its buffer. Whoever owns the structure owns the buffer too, so a contract that says cerastes_owns(*b) of a struct buf *b gives and takes the block b→data points to whenever it is not null, as if it also said b→data == NULL || cerastes_owns_block(b→data). You do not write that clause; cerastes adds it after every owns that covers the member (cerastes_owns(*b), an owns of an enclosing member, of the member itself, or of a structure global), after an owning parameter’s and result’s block, and after cerastes_owns_block(b). A member whose pointee is itself a structure with owning members adds their blocks too, to any depth, as long as no structure owns itself:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

void buf_init(struct buf *b CERASTES_MUST_INIT)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  b->data = NULL;
  b->len = 0;
}

void buf_put(struct buf *b, int v)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  free(b->data);
  b->data = (int *)malloc(sizeof(int));
  if (b->data != NULL) {
    *b->data = v;
  }
}

void buf_destroy(struct buf *b)
    CERASTES_REQUIRES(b == NULL || cerastes_owns_block(b))
{
  if (b != NULL) {
    free(b->data);
    free(b);
  }
}

int main(void)
{
  struct buf *b = (struct buf *)malloc(sizeof(struct buf));
  if (b == NULL) {
    return 1;
  }
  buf_init(b);
  buf_put(b, 1);
  buf_put(b, 2);
  buf_destroy(b);
  return 0;
}

buf_init is the initializer: its requires gives the structure without values (CERASTES_MUST_INIT), which owns nothing yet, and its ensures gives back a structure whose member is null or holds a whole block. buf_put borrows the structure and its block, and may replace the block. buf_destroy takes the structure’s block and, through its member, the buffer: it must free both. cerastes_reads(*b) gives the member’s value and nothing it owns; a function that reads the buffer writes cerastes_reads(*b→data) beside it. The attribute goes on a pointer to an object, in either position (int *data CERASTES_OWNING; or int *data;), on each declarator that owns.

Storing into the member. The value stored must be null or the start of a block the function holds whole, or the store is permission:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

void buf_put(struct buf *b, int v)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  int x = v;
  free(b->data);
  b->data = &x;
}

A block the member held when it is overwritten, or when the structure is freed, is not reported at that line: cerastes cannot tell, for a structure reached through a pointer, whether another owner took the block first. The function still holds it, so it is a leak at the function’s last line ("may return while it still owns an allocation that its ensures does not hand back"), or at a loop’s back edge if it happens in a loop:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

void buf_clear(struct buf *b)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  b->data = NULL;
  b->len = 0;
}

A structure in a variable. An owning member of a local structure, of a global structure or of a static local structure is an owner like an owning variable (Owning locals, Owning globals and static locals). Assigning to it while it holds a block is a leak at the assignment, and a local structure whose member still holds a block when its lifetime ends is a leak there ("owning field s.data still holds its block"). A function given &s decides by its contract, as for &v: with cerastes_owns(*b) it borrows the structure and the block, and may replace it.

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

void buf_init(struct buf *b CERASTES_MUST_INIT)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  b->data = NULL;
  b->len = 0;
}

void buf_put(struct buf *b, int v)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  free(b->data);
  b->data = (int *)malloc(sizeof(int));
  if (b->data != NULL) {
    *b->data = v;
  }
}

int main(void)
{
  struct buf s;
  buf_init(&s);
  buf_put(&s, 1);
  free(s.data);
  return 0;
}
#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

void buf_init(struct buf *b CERASTES_MUST_INIT)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  b->data = NULL;
  b->len = 0;
}

void buf_put(struct buf *b, int v)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  free(b->data);
  b->data = (int *)malloc(sizeof(int));
  if (b->data != NULL) {
    *b->data = v;
  }
}

int main(void)
{
  struct buf s;
  buf_init(&s);
  buf_put(&s, 1);
  return 0;
}

main may end while a structure global or a static local structure still holds blocks through its owning members, and through theirs: as for an owning global, an owner with static storage keeps its object for the whole program.

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

static struct buf g = { NULL, 0 };

void g_put(int v)
    CERASTES_REQUIRES(cerastes_owns(g))
    CERASTES_ENSURES(cerastes_owns(g))
{
  free(g.data);
  g.data = (int *)malloc(sizeof(int));
  if (g.data != NULL) {
    *g.data = v;
  }
}

int main(void)
{
  g_put(1);
  g_put(2);
  return 0;
}

Copies. Copying a structure (t = s;, *q = *p;, struct buf t = *p;) copies its members, and each owning member of the copy is a store to an owner: the copy and the original then hold the same block, as two owning variables do after b = a;. One of them must be set to NULL before both are handed to a function or returned, and a function that only reads the original (cerastes_reads(*p)) cannot copy it into an owner. A structure passed or returned by value owns nothing unless its contract says so (s.data == NULL || cerastes_owns_block(s.data)).

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

int main(void)
{
  struct buf s = { NULL, 0 };
  s.data = (int *)malloc(sizeof(int));
  if (s.data == NULL) {
    return 1;
  }
  *s.data = 1;
  struct buf t = s;
  s.data = NULL;
  free(t.data);
  return 0;
}

Loops. A loop invariant cerastes_owns(*b) carries the member’s block too, so a loop may free and replace it on every iteration:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int len;
};

void buf_churn(struct buf *b, int n)
    CERASTES_REQUIRES(cerastes_owns(*b) && 0 <= n && n <= 100)
    CERASTES_ENSURES(cerastes_owns(*b))
{
  int i = 0;
  CERASTES_INVARIANT(0 <= i && i <= n)
  CERASTES_INVARIANT(cerastes_owns(*b))
  CERASTES_DECREASES(n - i)
  while (i < n) {
    free(b->data);
    b->data = (int *)malloc(sizeof(int));
    if (b->data != NULL) {
      *b->data = i;
    }
    i += 1;
  }
}

Each owning member’s block in a loop invariant costs time, and two of them in one loop take minutes; a loop that replaces two members' blocks verifies, but slowly.

When a loop needs its invariant written. cerastes carries an owning member’s block through a loop by itself when the loop works on the structure through what holds it: a local or global structure, an owning pointer, or a parameter whose structure the invariant owns. Two kinds of loop need a fact that only the program knows, and the invariant states it:

  • a loop that replaces the member’s block through a second, non-owning pointer to a structure the function borrows (v = p). The invariant owns the structure through the parameter, cerastes_owns(*p); owning it through the second pointer, cerastes_owns(*v), is reported (v→data may be p->data), and without the invariant the loop’s frees are reported:

    #include <cerastes.h>
    #include <stdlib.h>
    
    struct buf {
      int *data CERASTES_OWNING;
      int len;
    };
    
    void buf_churn_alias(struct buf *p, int n)
        CERASTES_REQUIRES(cerastes_owns(*p) && 0 <= n && n <= 5)
        CERASTES_ENSURES(cerastes_owns(*p))
    {
      struct buf *v = p;
      int i = 0;
      CERASTES_INVARIANT(0 <= i && i <= n)
      CERASTES_INVARIANT(cerastes_owns(*p))
      CERASTES_DECREASES(n - i)
      while (i < n) {
        free(v->data);
        v->data = (int *)malloc(sizeof(int));
        if (v->data != NULL) {
          *v->data = i;
        }
        i += 1;
      }
    }
  • a loop that frees an owning pointer and gives it a new structure on every iteration, but frees the member’s block only in its first iteration. That is a fact of one iteration, which only a written invariant can state: CERASTES_INVARIANT(v == NULL || i != 0 || v→data == NULL || cerastes_owns_block(v→data)). Where the owning pointer’s address is taken (pv = &v), this invariant cannot be written yet, and the loop is reported although it is correct.

A function whose contract consumes the structure’s cells (requires owns **pp, ensures owns only *pp) leaves the caller without the structure, inside a loop or not: a second call, or a free of what *pp points to, is reported.

The buffer must hold values. Where a contract owns the structure, the member’s block must hold values, as every block a contract owns must: a structure whose buffer was allocated but not yet written cannot be passed to buf_put (an uninitialized error at the call). Write the buffer first, or mark the member (Marked owning members).

Marked owning members

A member that is cerastes::owning and also cerastes::ref_to_uninit (Marked members) owns a block that may hold no value. Its closure is not plain: a structure whose buffer was allocated and not yet written can be passed to a function that borrows it with cerastes_owns(*b), which is the use P4222’s ref_to_uninit is for. Without the marker the call is reported, as Owning fields says:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int n;
};

void buf_fill(struct buf *b)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  if (b->data != NULL) {
    *b->data = 1;
  }
}

int main(void)
{
  struct buf s = { NULL, 0 };
  s.data = (int *)malloc(sizeof(int));
  buf_fill(&s);
  free(s.data);
  return 0;
}

With the marker on the member, the same program verifies; the function receives the block without a value, and writes it:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING CERASTES_REF_TO_UNINIT;
  int n;
};

void buf_fill(struct buf *b)
    CERASTES_REQUIRES(cerastes_owns(*b))
    CERASTES_ENSURES(cerastes_owns(*b))
{
  if (b->data != NULL) {
    *b->data = 1;
  }
}

int main(void)
{
  struct buf s = { NULL, 0 };
  s.data = (int *)malloc(sizeof(int));
  buf_fill(&s);
  free(s.data);
  return 0;
}

The marker moves the checks to where the buffer is read:

  • A function that borrows the structure may write through the member but not read the buffer before it is written; the read is reported as uninitialized, at the read:

    #include <cerastes.h>
    #include <stdlib.h>
    
    struct buf {
      int *data CERASTES_OWNING CERASTES_REF_TO_UNINIT;
      int n;
    };
    
    void buf_sum(struct buf *b)
        CERASTES_REQUIRES(cerastes_owns(*b))
        CERASTES_ENSURES(cerastes_owns(*b))
    {
      if (b->data != NULL) {
        b->n = *b->data;
      }
    }
    
    int main(void)
    {
      struct buf s = { NULL, 0 };
      s.data = (int *)malloc(sizeof(int));
      buf_sum(&s);
      free(s.data);
      return 0;
    }
  • After the call, the caller still has a value in the buffer only if the function says it returns the same buffer: an equality b->data == cerastes_old(b->data) in its ensures (the tie; cerastes::not_invalidating on the parameter writes it for you, The not_invalidating marker):

    #include <cerastes.h>
    #include <stdlib.h>
    
    struct buf {
      int *data CERASTES_OWNING CERASTES_REF_TO_UNINIT;
      int n;
    };
    
    void buf_touch(struct buf *b)
        CERASTES_REQUIRES(cerastes_owns(*b))
        CERASTES_ENSURES(cerastes_owns(*b) && b->data == cerastes_old(b->data))
    {
      b->n = 0;
    }
    
    int main(void)
    {
      struct buf s = { NULL, 0 };
      s.data = (int *)malloc(sizeof(int));
      if (s.data == NULL) {
        return 1;
      }
      *s.data = 7;
      buf_touch(&s);
      if (s.data != NULL) {
        int y = *s.data;
        *s.data = y;
      }
      free(s.data);
      return 0;
    }

    Without the equality the function may have replaced the buffer, and a freshly allocated block has no value, so the caller’s read is reported, at the read:

    #include <cerastes.h>
    #include <stdlib.h>
    
    struct buf {
      int *data CERASTES_OWNING CERASTES_REF_TO_UNINIT;
      int n;
    };
    
    void buf_touch(struct buf *b)
        CERASTES_REQUIRES(cerastes_owns(*b))
        CERASTES_ENSURES(cerastes_owns(*b))
    {
      b->n = 0;
    }
    
    int main(void)
    {
      struct buf s = { NULL, 0 };
      s.data = (int *)malloc(sizeof(int));
      if (s.data == NULL) {
        return 1;
      }
      *s.data = 7;
      buf_touch(&s);
      if (s.data != NULL) {
        int y = *s.data;
        *s.data = y;
      }
      free(s.data);
      return 0;
    }

A function whose ensures has the tie and whose body replaces the buffer is reported as postcondition, since the equality is then false. When the equality is in the same ensures clause as the atom that gives the buffer (and when cerastes::not_invalidating splices it there), that is one error; an equality written as a separate ensures clause is reported on its own as well, so a replacing body gets two. A requires that gives the structure claims no value for the buffer, and an ensures that gives a structure the caller did not give (a result, for instance) claims none either. The closure of a marked member is closed no further: if the buffer is a structure with owning members of its own, theirs are not part of it, since the buffer may hold no value. A marked member that is not owning changes nothing in the default mode.

A function cannot promise to have filled the buffer: a caller that passes a marked member’s buffer to a function that writes it, and reads it after the call, is reported (uninitialized) even when the function’s ensures ties the buffer. The tie says that the buffer is the same one and keeps a value that the caller already had; it does not say that the function wrote one. A function that gives a structure a value for everything it owns is cerastes::must_init where that applies (A marked pointer to a structure with an owning member).

A marked pointer to a structure with an owning member

A pointer parameter, a result or a variable marked cerastes::ref_to_uninit may point to a structure that has an owning member, and the marked site closes nothing on either side of a call: cerastes does not add the clause b->data == NULL || cerastes_owns_block(b->data) that a plain cerastes_owns(*b) adds (Owning fields), because the structure may hold no value. The same holds for a marked global, static local or local that points to such a structure, in its own closure and in the closures of its loops. What it costs is on the caller’s side. The callee gives nothing back about the member, so after the call the caller does not know what it holds:

  • a block that the member held before the call stays the caller’s, and is reported at the caller’s end if the callee overwrote the member;

  • a local structure’s end is reported as leak ("owning field s.data still holds its block"), even when the callee sets the member to NULL, and free(s.data) after the call is reported as invalid-free;

  • a callee that leaves a block in the member is reported by its own end row (leak).

A structure with static storage may end holding blocks, so a global is not reported:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int n;
};

struct buf g;

void touch(struct buf *p CERASTES_REF_TO_UNINIT)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p))
{
  p->n = 0;
}

int main(void)
{
  touch(&g);
  return g.n;
}

A local structure is:

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int n;
};

void touch(struct buf *p CERASTES_REF_TO_UNINIT)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p))
{
  p->n = 0;
}

int main(void)
{
  struct buf s = { NULL, 0 };
  touch(&s);
  return s.n;
}

An initializer should be cerastes::must_init instead: its ensures closes the structure, so a caller that gave a structure without a value knows what the member holds afterwards. (An ensures that names the member of a ref_to_uninit parameter is rejected, as Initialization through pointers says, so a marked parameter’s callee cannot say it.)

#include <cerastes.h>
#include <stdlib.h>

struct buf {
  int *data CERASTES_OWNING;
  int n;
};

void init(struct buf *p CERASTES_MUST_INIT)
    CERASTES_REQUIRES(cerastes_owns(*p))
    CERASTES_ENSURES(cerastes_owns(*p))
{
  p->data = NULL;
  p->n = 0;
}

int main(void)
{
  struct buf s CERASTES_UNINIT;
  init(&s);
  free(s.data);
  return s.n;
}

P4417R0’s owners in cerastes

P4417R0’s invalidation profile marks owners with . In cerastes:

P4417R0 cerastes

on a local variable, a global or a static local

cerastes::owning (Owning locals, Owning globals and static locals)

on a member

cerastes::owning (this section)

on a result

cerastes::owning on the function (Allocated memory: malloc, calloc and free)

on a parameter: the callee takes the object and must delete it

CERASTES_REQUIRES(p == NULL || cerastes_owns_block(p)) with no ensures about p

(no attribute: a borrow)

cerastes::owning on a parameter, which lends the block for the call

a static owner need not delete its object

main may end while a static owner holds its block

raw storage (malloc, free) is outside the profile

checked like any other block

on a pointer parameter

cerastes::not_invalidating (The not_invalidating marker)

p4: an owning result must initialize an owner, be assigned to one, be returned by a function that gives its result’s block, or be released in its full expression

--strict-owner (The strict ownership mode)

p6: only an owner is released

--strict-owner; without the option the default mode reports the release of anything that is not a block it owns (invalid-free)

A block that depends on memory

cerastes_owns_block(p) may be under a condition, as the atoms of an owns and a reads may: cond ? cerastes_owns_block(p) : true, or p == NULL || …​. The condition may read memory, in the state the clause is about: a requires reads it on entry, an ensures on return. The function below takes the block exactly where *q is positive, and frees it under the same test:

#include <cerastes.h>
#include <stdlib.h>

void maybe_free(int *q, int *p)
    CERASTES_REQUIRES(cerastes_owns(*q) && (*q > 0 ? cerastes_owns_block(p) : true))
    CERASTES_ENSURES(cerastes_owns(*q))
{
  if (*q > 0) {
    free(p);
  }
}

int use_guard(void)
    CERASTES_ENSURES(r, r == 0 || r == -1)
{
  int *p = (int *)malloc(sizeof(int));
  if (p == NULL) {
    return -1;
  }
  *p = 1;
  int c = 1;
  maybe_free(&c, p);
  int d = 0;
  maybe_free(&d, NULL);
  return 0;
}

An ensures guard decides whether the caller receives a block, and is read on return, so the caller learns the block only where the guard holds after the call:

#include <cerastes.h>
#include <stdlib.h>

int *make(int *q)
    CERASTES_REQUIRES(cerastes_owns(*q))
    CERASTES_ENSURES(r, cerastes_owns(*q) && (*q > 0 ? cerastes_owns_block(r) : r == NULL))
{
  if (*q > 0) {
    int *p = (int *)malloc(sizeof(int));
    if (p == NULL) {
      abort();
    }
    *p = *q;
    return p;
  }
  return NULL;
}

int use_make(void)
    CERASTES_ENSURES(r, r == 0)
{
  int c = 3;
  int *p = make(&c);
  if (p != NULL) {
    free(p);
  }
  return 0;
}

A function that borrows a block under a guard and gives it back under the same guard must say that the guard still holds on return: *q == cerastes_old(*q), or use a guard that cannot change. The ensures guard is read on return, so without it the contract itself is wrong, whatever the body does: on a path where *q is no longer positive it returns a block that the requires did not take, which is permission, reported at the contract:

#include <cerastes.h>

void borrow(int *q, int *p)
    CERASTES_REQUIRES(cerastes_owns(*q) && (*q > 0 ? cerastes_owns_block(p) : true))
    CERASTES_ENSURES(cerastes_owns(*q) && *q == cerastes_old(*q) && (*q > 0 ? cerastes_owns_block(p) : true))
{
  if (*q > 0) {
    *p = 1;
  }
}
#include <cerastes.h>

void borrow(int *q, int *p)
    CERASTES_REQUIRES(cerastes_owns(*q) && (*q > 0 ? cerastes_owns_block(p) : true))
    CERASTES_ENSURES(cerastes_owns(*q) && (*q > 0 ? cerastes_owns_block(p) : true))
{
  if (*q > 0) {
    *p = 1;
  }
}

A guard may also read a global or cerastes_old. The caller must hold what the guard reads (here *q), like any contract read.

What is not supported yet

These are rejected with a diagnostic, never approximated (the full list):

  • contracts that name objects other than those reached from the parameters, the global variables and the result, and, in a function whose body is not in the file, an owns, reads, live or cerastes_owns_block that its requires does not take, except on the result and only where no clause equates the result with anything but a null pointer (nothing verifies the contract, so it may promise only what the caller cannot already hold: the contract manifest, planned with the concepts);

  • cerastes_old inside the path of a place (*cerastes_old(*pp), the object *pp pointed to on entry, read on return; cerastes_old(p)->q->x), and cerastes_old in a loop invariant (copy the value into a local before the loop);

  • globals defined in another file, volatile, _Atomic, const structure, const array and thread-local globals, and static const locals;

  • an array of three or more dimensions (int c[2][3][4]), an array of arrays whose cells are structures (struct point m[2][2]), and an element structure with an owning or marked member (Arrays of structures, Arrays of arrays); a structure with an array of arrays as a member, or with a member array of structures that have an array member, passed, returned or copied as a whole value when those members hold more than 7 cells (Arrays of arrays); a structure whose array member holds structures or arrays that is allocated with malloc or calloc, that also has an owning or marked member, whose pointer is owning or marked ref_to_uninit or must_init, that is reached through a pointer read from memory, or that is named by an ensures atom with no requires partner or by an atom in a loop invariant ([array-members]); calloc of a structure with an array member that holds more than 24 values in all; part of a global array or of an array member in a contract (cerastes_owns_range(table, n), &table[2]), one element as an atom, and table + i; an array member as the argument of a quantifier or a pure function anywhere, and a global array as one in a contract; a structure value holding more than 7 array elements passed or returned by value; an array compound literal in C++;

  • false alarms listed for array members ([array-members]): a loop that writes a member of a structure by name (an element of an array member, or a member of the element’s type, such as t.n beside int a[4]) cannot keep any array member of that element type unchanged; a function that reads an element of p→data in its requires and its ensures (with cerastes_reads(p→data)) cannot use that the two reads are equal; a function that returns the address of an element of its static local structure’s array member cannot promise cerastes_owns(*r);

  • for pure functions (A value computed from an array): a call in a decreases, in the count or the condition of an ownership or reading annotation, in an element’s index, as a trailing argument of cerastes_forall, under old and in the body of a function that cerastes_forall names; two pure functions that call each other, or a function that its own contract reaches again; a pure function that returns a pointer or a structure, reads a global or reads through a pointer loaded from memory; owns, owns_range, live or a conditional atom in its requires, and any atom in its ensures; cerastes_forall naming a function that has a contract; predicates, fold and unfold;

  • the structure features listed in Structures;

  • owns, reads and live in a do … while (0) invariant or a measure, and of a global itself in an invariant (cerastes_owns(g): the loop holds it already);

  • a structure that owns itself through its owning members (struct node { struct node *next CERASTES_OWNING; }, or two structures that own each other: a list, planned with recursive predicates), an owning member that is not a pointer to an object, and a function without a body in the file that hands over a new structure whose owning members hold blocks, other than a pointer with cerastes_owns(*r) whose structure owns one block (Owning fields);

  • an owning or marked global, static local or owning member whose initializer is not a null pointer, and owning(n) anywhere but on a parameter;

  • a function that returns the address of a static local structure on some paths and a new structure whose owning member holds a block on others is reported as a leak;

  • some loops over owning members are reported although they are correct: a loop that frees and replaces an owning pointer whose address is taken (pv = &v), if it also frees the member’s block (the invariant it needs cannot be written yet, Owning fields); a loop in main that hands a global structure to a function through a pointer it holds in a variable (pg = &g); a loop that may replace an owning global pointer, or store into a global structure through a pointer to it, and frees an owning member’s block; and a loop over a chain of owning members that also writes an unrelated variable whose address is taken, or whose middle owner it frees and sets to null (i == 0 || a.b == NULL in its invariant does not help yet); and a loop that copies a whole structure holding an owning member beside an integer member, reported as uninitialized at the end of an iteration;

  • cerastes::uninit on anything but a local, and cerastes::must_init on anything but a parameter (P4222 defines it for parameters only);

  • the attributes of the P4417R0 and P4418R0 invalidation profile that are not taken over: cerastes::not_invalidating on a function (the profile’s member function form; the front end refuses it, and a member function is planned with the classes) and no_dangling. An owner parameter that transfers its object to the callee is the contract requires(p == NULL || cerastes_owns_block(p)), and there is no suppression for a pointer that dangles on purpose: cerastes proves or reports each use;

  • allocations of more than one object (n * sizeof(T)) and realloc (Allocated memory: malloc, calloc and free);

  • in a function whose body is not in the file, an allocation that its contract takes or hands over through a pointer or a global ([blocks-through-memory]);

  • two pointers in a loop’s invariant that each own an allocation through a parameter’s pointee (*pp and *qq) verify, but slowly; a loop that calls a function borrowing the allocation of *pp needs *pp == keep in its invariant; and an owner that takes a block in a loop on some iterations only needs an invariant that says when (Owning locals);

  • vlibc_realloc, vlibc_aligned_alloc, vlibc_free_sized and vlibc_free_aligned_sized, which have no contract yet (call_without_contract), a block of vlibc’s allocator named by cerastes::owning or cerastes_owns_block (they name the platform’s allocator; cerastes_owns_vlibc_block is the spelling for vlibc’s), and vlibc_malloc, vlibc_calloc and cerastes_owns_vlibc_block in C++ (vlibc’s allocator);

  • void * other than an allocation’s result converted at once to T * and the argument of free (Allocated memory: malloc, calloc and free), and pointers to unions, to functions and to structures that are not supported;

  • restrict: on a parameter it is rejected because cerastes does not model the promise it makes, and dropping the keyword does not change a program with defined behaviour (Pointer parameters and contracts); on a local, a global, a member, a result or the object a pointer points to it is rejected as a type; in the type of a cast or of a compound literal it is accepted and promises nothing;

  • conversions between pointer types other than adding const to the object pointed to, comparisons of order and arithmetic on pointers.

In C, the compiler’s warnings about pointers of incompatible types (long *q = &i; for an int i) are errors under cerastes verify.