safe-c-std/safec.h
Raw file ยท Directory on GitHub
1/*===---- safec.h - Safe C annotations -------------------------------------===
2 *
3 * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 * See https://llvm.org/LICENSE.txt for license information.
5 * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 *
7 *===-----------------------------------------------------------------------===
8 *
9 * One header for every Safe C annotation. With the Safe C compiler the
10 * annotations are checked; with any other C compiler (GCC, MSVC, stock Clang)
11 * they expand to nothing and the code compiles as ordinary C. The file has no
12 * dependencies, so a project can copy it into its own tree.
13 *
14 * -fsafe-c includes this header automatically.
15 */
16
17#ifndef __SAFEC_H
18#define __SAFEC_H
19
20/* VS Code's IntelliSense parses with its own front end, which says it is clang
21 but rejects many of the annotations. It gets plain C: every annotation empty, as for gcc.
22 The compiler, not the editor, checks Safe C. */
23#if defined(__INTELLISENSE__)
24#define __SAFEC_EDITOR 1
25#endif
26
27
28/* What you annotate. One line per annotation; the README's table is generated
29 from these lines (clang/utils/safe-c/gen-readme.ts), so keep them current.
30 @annotation `_Nullable` | Clang | may be null; must be checked before use (with `__counted_by(n)`: null, or `n` elements) | `Option<&T>`: plain `&T` is never null | `char *_Nullable getenv(const char *name);`
31 @annotation `__counted_by(n)` | Apple | points to `n` elements; `n` is another parameter or field | `&[T]` (a slice: pointer plus length) | `int sum(const int *__counted_by(n) v, size_t n);`
32 @annotation `__sized_by(n)` | Apple | points to `n` bytes | `&[u8]` | `void fill(void *__sized_by(n) dst, size_t n);`
33 @annotation `__ended_by(end)` | Apple | valid up to the pointer `end` | a slice given as two pointers (`slice::from_ptr_range`) | `int scan(const char *__ended_by(end) p, const char *end);`
34 @annotation `__null_terminated` | Apple | a string ending in 0 (string literals and libc strings are already) | `&CStr` | `size_t my_strlen(const char *__null_terminated s);`
35 @annotation `_Owned` | Safe C | on a parameter: the function takes ownership (frees it, or keeps it to free later); the caller may not use it afterwards | taking a `Box<T>` by value (a move) | `void json_delete(struct json *_Owned item);`
36 @annotation `T *_Owned` (field, local, result) | Safe C | this pointer is responsible for freeing its target; it is moved, never copied | `Box<T>` | `struct node { int v; struct node *_Owned _Nullable next; };`
37 @annotation `_Take(place)` | Safe C | moves an owned pointer out of a field or global, leaving null | `Option::take` | `struct node *_Owned _Nullable pop(struct node *n) { return _Take(n->next); }`
38 @annotation `T *_Static` | Safe C | points only at string literals, globals or functions | `&'static T` | `struct op { const char *_Static name; int code; };`
39 @annotation `_Noescape` | Safe C (Clang's `noescape`) | on a parameter: the function does not keep the pointer | a plain `&T` parameter, which cannot outlive the call | `size_t count_spaces(const char *s _Noescape);`
40 @annotation `T *_Unchecked` | Safe C | kept for its value: stored, copied and compared freely, followed only inside a `_Trusted` function | `*const T` (a raw pointer) | `struct child { struct child *_Unchecked _Nullable up; };`
41 @annotation `struct _View` | Safe C | a struct holding borrows: lives in locals and parameters, and ends with what it borrows | a struct with a lifetime, `struct S<'a>` | `struct _View span { const int *__counted_by(n) p; int n; };`
42 @annotation `_Tagged_by(f)`, `_When(V)` | Safe C | a union whose live member is named by the sibling field `f`: a member is read or written only where `f` is known to be one of its `_When` values; a `switch` on `f` must handle every value | an `enum` with data, and `match` | `struct shape { int kind; union _Tagged_by(kind) { double radius _When(0); double side _When(1); }; };`
43 @annotation `_Guarded_by(m)` | Safe C (Clang's `guarded_by`) | data read or written only while holding lock `m`; Clang's thread-safety analysis checks it | `Mutex<T>` | `struct _Capability("mutex") mtx { int state; }; struct mtx stats_lock; int hits _Guarded_by(stats_lock);`
44 @annotation `_Requires(m)`, `_Acquires(m)`, `_Releases(m)` | Safe C (Clang's thread-safety attributes) | a function's callers must hold `m`; or it takes or releases `m` | a `MutexGuard` held across a call | `void bump(void) _Requires(&stats_lock);`
45 @annotation `_Trusted` | Safe C | a function whose ownership is not checked inside; its callers are held to its signature | a safe function around an `unsafe` body | `_Trusted void swap(struct node *a, struct node *b);`
46 @annotation `__unsafe` | Safe C | a block or function where Safe C's rules are lifted, except ownership (that is `_Trusted`) | `unsafe { }` | `int first(va_list ap) { int v; __unsafe { v = va_arg(ap, int); } return v; }`
47 @annotation `#pragma clang safe_c legacy` | Safe C | in a header not yet ported: its declarations are trusted, its code unchecked | an `extern "C"` block over unaudited C | first line of a header not yet ported
48 @annotation `_Slice(T, name, base, start, n)` | Safe C | declares `name`, `n` elements of `base` from index `start`, and its count `name_n`; checked once where it is made, so a loop over it has no check per element (a slice that does not fit stops the program there) | `&buf[start..start + n]` | `void tail(const unsigned char *__counted_by(n) out, size_t n, size_t at) { _Slice(const unsigned char, from, out, at, 4); (void)from; }`
49 @annotation `__unsafe _No_bounds_checks` | Safe C | on a function: compiled without run-time bounds, null and integer checks, for an audited hot loop; say in a comment why every access is in bounds | `get_unchecked` | `__unsafe _No_bounds_checks static void zero(int *__counted_by(n) p, size_t n) { for (size_t i = 0; i < n; i++) p[i] = 0; }`
50 Everything else needs nothing: an unannotated pointer is non-null and points to
51 exactly one element, like Rust's `&T`. */
52
53/* Bounds annotations: Apple's ptrcheck.h defines them, and defines them as
54 nothing when bounds safety is off. Without ptrcheck.h, do the same here. */
55#if defined(__has_include) && !defined(__SAFEC_EDITOR)
56#if __has_include(<ptrcheck.h>)
57#include <ptrcheck.h>
58#define __SAFEC_HAVE_PTRCHECK 1
59#endif
60#endif
61
62/* Some ptrcheck.h versions (Apple clang 21) define only a few macros when bounds
63 safety is off, so fill in each missing one. */
64#ifndef __single
65#define __single
66#endif
67#ifndef __indexable
68#define __indexable
69#endif
70#ifndef __bidi_indexable
71#define __bidi_indexable
72#endif
73#ifndef __unsafe_indexable
74#define __unsafe_indexable
75#endif
76#ifndef __counted_by
77#define __counted_by(N)
78#endif
79#ifndef __counted_by_or_null
80#define __counted_by_or_null(N)
81#endif
82#ifndef __sized_by
83#define __sized_by(N)
84#endif
85#ifndef __sized_by_or_null
86#define __sized_by_or_null(N)
87#endif
88#ifndef __ended_by
89#define __ended_by(E)
90#endif
91#ifndef __terminated_by
92#define __terminated_by(T)
93#endif
94#ifndef __null_terminated
95#define __null_terminated
96#endif
97#ifndef __unsafe_forge_single
98#define __unsafe_forge_single(T, P) ((T)(P))
99#endif
100#ifndef __unsafe_forge_bidi_indexable
101#define __unsafe_forge_bidi_indexable(T, P, S) ((T)(P))
102#endif
103#ifndef __unsafe_forge_null_terminated
104#define __unsafe_forge_null_terminated(T, P) ((T)(P))
105#endif
106#ifndef __null_terminated_to_indexable
107#define __null_terminated_to_indexable(P) (P)
108#endif
109#ifndef __unsafe_null_terminated_to_indexable
110#define __unsafe_null_terminated_to_indexable(P) (P)
111#endif
112#ifndef __unsafe_null_terminated_from_indexable
113#define __unsafe_null_terminated_from_indexable(P, ...) (P)
114#endif
115
116/* libc string functions. The system headers leave their `const char *`
117 parameters unannotated, so bounds safety would hand any buffer to them
118 unchecked, and strlen() of an unterminated buffer reads past its end. These
119 redeclarations add __null_terminated to the read-only string parameters
120 (types are otherwise identical, so they merge with the system declarations
121 in either order). A buffer with known bounds passed to one of them is then
122 scanned for its terminator, and the program traps if there is none.
123 Known gap: printf-style variadic arguments cannot be annotated this way. */
124/* Apple's libc annotates these itself when __LIBC_STAGED_BOUNDS_SAFETY_ATTRIBUTES
125 is set (the driver sets it under -fsafe-c), and its declarations would
126 conflict with these. Where it leaves a string parameter __unsafe_indexable
127 (strncmp), Safe C accepts terminated strings (checkSafeCUncheckedParams). */
128#if defined(__SAFEC_HAVE_PTRCHECK) && __has_ptrcheck && \
129 !defined(__LIBC_STAGED_BOUNDS_SAFETY_ATTRIBUTES)
130typedef __SIZE_TYPE__ __safec_size_t;
131/* The read-only scans are also marked pure, so Safe C code marked
132 __attribute__((pure)) may call them. */
133__attribute__((__pure__)) __safec_size_t strlen(const char *__null_terminated);
134__attribute__((__pure__)) int strcmp(const char *__null_terminated,
135 const char *__null_terminated);
136__attribute__((__pure__)) int strncmp(const char *__null_terminated,
137 const char *__null_terminated,
138 __safec_size_t);
139__attribute__((__pure__)) char *strchr(const char *__null_terminated, int);
140__attribute__((__pure__)) char *strrchr(const char *__null_terminated, int);
141__attribute__((__pure__)) char *strstr(const char *__null_terminated,
142 const char *__null_terminated);
143char *strcpy(char *, const char *__null_terminated);
144char *strcat(char *, const char *__null_terminated);
145char *strdup(const char *__null_terminated);
146int puts(const char *__null_terminated);
147int atoi(const char *__null_terminated);
148long atol(const char *__null_terminated);
149double atof(const char *__null_terminated);
150char *getenv(const char *__null_terminated);
151#endif
152
153/* __unsafe marks a block or a function in which Safe C's own rules are not
154 enforced: `__unsafe { ... }` or `__unsafe int f(void) { ... }`. Elsewhere
155 it expands to nothing, and `__unsafe { ... }` is an ordinary block. */
156#if defined(__has_c_attribute) && !defined(__SAFEC_EDITOR)
157#if __has_c_attribute(clang::suppress)
158#define __unsafe [[clang::suppress("safe-c")]]
159#endif
160#endif
161#ifndef __unsafe
162#define __unsafe
163#endif
164
165/* _No_bounds_checks on an `__unsafe` function: compiled without run-time
166 bounds, null and integer checks, for an audited hot loop whose own tests already keep every
167 access in bounds (say which, in a comment). Use as a last resort for speed;
168 the compiler should remove such checks itself. */
169#if (defined(__SAFE_C__) && !defined(__SAFEC_EDITOR))
170/* Also the trap checks -fsafe-c adds for null dereference and integer UB:
171 the same audited promise covers them. */
172#define _No_bounds_checks \
173 __attribute__((annotate("safec_no_bounds_checks"), \
174 no_sanitize("null", "signed-integer-overflow", \
175 "shift-exponent", "integer-divide-by-zero", \
176 "vla-bound")))
177#else
178#define _No_bounds_checks
179#endif
180
181/* Nullability qualifiers are Clang keywords; other compilers do not have them. */
182/* On a parameter: the function does not keep the pointer (lets a buffer be
183 passed where a terminated string is expected). */
184#if (defined(__clang__) && !defined(__SAFEC_EDITOR))
185#define _Noescape __attribute__((noescape))
186/* Pointer kinds go right after the '*' they describe, so a pointer to
187 owned pointers is 'char *_Owned *_Owned items'.
188 On a parameter, owned means the function takes ownership. */
189#if (defined(__SAFE_C__) && !defined(__SAFEC_EDITOR))
190#define _Owned [[clang::annotate_type("safec_owned")]]
191#else /* plain clang: [[]] after _Nullable would not parse */
192#define _Owned
193#endif
194/* On a field or result: points only at static data (string literals,
195 globals, functions), like Rust's &'static. */
196#if (defined(__SAFE_C__) && !defined(__SAFEC_EDITOR))
197#define _Static [[clang::annotate_type("safec_static")]]
198#else /* plain clang: [[]] after _Nullable would not parse */
199#define _Static
200#endif
201/* On a parameter: the function leaves what the struct's fields own freed,
202 and its callers know it: void text_free(struct text *_Empties t). */
203#if (defined(__SAFE_C__) && !defined(__SAFEC_EDITOR))
204#define _Empties [[clang::annotate_type("safec_empties")]]
205#else
206#define _Empties
207#endif
208/* On a function: its ownership is not checked inside; its callers are held to
209 its signature all the same. */
210#define _Trusted __attribute__((annotate("safec_trusted")))
211/* A pointer kept for its value: stored, copied and compared freely, followed
212 only inside a _Trusted function. */
213#if (defined(__SAFE_C__) && !defined(__SAFEC_EDITOR))
214#define _Unchecked [[clang::annotate_type("safec_unchecked")]]
215#else /* plain clang: [[]] after _Nullable would not parse */
216#define _Unchecked
217#endif
218/* On a struct: holds borrows, so it lives only in locals and parameters and
219 ends with what it borrows. Behind a pointer it may be changed only if it has
220 one pointer, which stays inside what it pointed into. */
221#if (defined(__clang__) && !defined(__SAFEC_EDITOR))
222#define _View __attribute__((annotate("safec_view")))
223#else
224#define _View
225#endif
226/* Move an owned pointer out of a field or global, leaving null (and a zero
227 count): free(_Take(n->next)). Like Rust's Option::take. */
228#if (defined(__SAFE_C__) && !defined(__SAFEC_EDITOR))
229#define _Take(lv) __builtin_safec_take(lv)
230#else /* clang without Safe C has no builtin; lv is evaluated twice */
231#define _Take(lv) ({ __typeof__(lv) __safec_t = (lv); (lv) = 0; __safec_t; })
232#endif
233#else
234#define _Noescape
235#define _Owned
236#define _Static
237#define _Unchecked
238#define _Empties
239#define _View
240#define _Trusted
241/* Evaluates lv twice; fine for the plain lvalues take is used on. */
242#define _Take(lv) ({ __typeof__(lv) __safec_t = (lv); (lv) = 0; __safec_t; })
243#endif
244
245#if !(defined(__clang__) && !defined(__SAFEC_EDITOR))
246#define _Nonnull
247#define _Nullable
248#define _Null_unspecified
249#endif
250
251
252/* Set a pointer and its count together: _Set(s->p, s->n, new_p, new_n). Both
253 new values are read, and checked against each other, before either is set. */
254#define _Set(ptr, count, new_ptr, new_count) \
255 ((void)((ptr) = (new_ptr), (count) = (new_count)))
256
257/* A slice: n elements of a buffer from index start, bounds-checked once where
258 it is made, so a loop over it needs no check per element:
259 _Slice(const unsigned char, from, s->out, s->outcnt - dist, len);
260 for (size_t i = 0; i < from_n; i++) ...
261 Declares the pointer name and its count name_n. A slice that does not fit
262 in the buffer stops the program where it is made. */
263#define _Slice(T, name, base, start, n) \
264 __SIZE_TYPE__ name##_n = (n); \
265 T *__counted_by(name##_n) name = (base) + (start)
266
267/* Tagged unions, like Rust's enums with data:
268 struct shape {
269 enum kind kind;
270 union _Tagged_by(kind) {
271 struct circle c _When(CIRCLE);
272 struct rect r _When(RECT, SQUARE);
273 };
274 };
275 _Tagged_by names the sibling field holding the tag; _When lists the tag
276 values for which a member is live. A switch on the tag must handle every
277 value (or have a default). */
278#if (defined(__clang__) && !defined(__SAFEC_EDITOR))
279#define _Tagged_by(f) __attribute__((annotate("safec_tagged_by", #f)))
280#define _When(...) __attribute__((annotate("safec_when", __VA_ARGS__)))
281#else
282#define _Tagged_by(f)
283#define _When(...)
284#endif
285
286/* Data shared between threads, checked by Clang's thread-safety analysis
287 (always on under Safe C):
288 safec_mutex lock;
289 int hits _Guarded_by(lock); every access must hold lock
290 void bump(void) _Requires(lock); callers must hold lock
291 Lock types are declared with _Capability("mutex"); their lock and unlock
292 functions with _Acquires(m) and _Releases(m). */
293#if (defined(__clang__) && !defined(__SAFEC_EDITOR))
294#define _Capability(name) __attribute__((capability(name)))
295#define _Guarded_by(m) __attribute__((guarded_by(m)))
296#define _Pt_guarded_by(m) __attribute__((pt_guarded_by(m)))
297#define _Requires(...) __attribute__((requires_capability(__VA_ARGS__)))
298#define _Acquires(...) __attribute__((acquire_capability(__VA_ARGS__)))
299#define _Releases(...) __attribute__((release_capability(__VA_ARGS__)))
300#else
301#define _Capability(name)
302#define _Guarded_by(m)
303#define _Pt_guarded_by(m)
304#define _Requires(...)
305#define _Acquires(...)
306#define _Releases(...)
307#endif
308
309#endif /* __SAFEC_H */
310