Skip to content

Latest commit

 

History

History
841 lines (706 loc) · 59.2 KB

safety-checker.md

File metadata and controls

841 lines (706 loc) · 59.2 KB

reloco-tidy: the safety checker

reloco-tidy is a clang-tidy plugin (tools/tidy) that enforces reloco's safe-coding rules on the AST, so derived projects (structo, microfmt, your own firmware) get the same guarantees reloco's own headers are written to. It complements, and does not replace, Clang's -Wlifetime-safety*, -Wdangling-gsl and -Wunsafe-buffer-usage.

Motivation

The author got fed up with how trivially easy it is to write undefined behavior or otherwise unsafe code in C and C++: dangling views, uninitialized locals, raw pointers and C arrays that lose their bounds, silent copies, aliasing mutation. None of it needs a warning to compile. The checker turns those habits into diagnostics, and every opt-out into a visible, greppable marker (NOLINT, RELOCO_BEGIN_UNSAFE_CODE, RELOCO_BORROW_EXEMPT) that a reviewer can question.

Trollface

Tests, examples, demos, benchmarks, build trees and third-party code are exempt by default; library headers and implementations must pass.

Building and running

# The newest /usr/lib/llvm-N with clang-tidy headers is chosen automatically (30 down to 19).
# Override with -DRELOCO_TIDY_LLVM_VERSION=24 or -DRELOCO_TIDY_LLVM_ROOT=/path/to/llvm.
cmake -S tools/tidy -B build-tidy -G Ninja -DCMAKE_BUILD_TYPE=Release
ninja -C build-tidy

# The plugin must match the major version of the clang-tidy executable that loads it.
clang-tidy-24 --load=build-tidy/libreloco-tidy.so --checks='-*,reloco-*' \
    -p build src/foo.cpp

Supported LLVM versions. Verified (plugin builds and every fixture passes): 20, 21, 22, 24. LLVM 19 builds and passes all fixtures except reloco-ns-pointer and reloco-static-string: those read annotate_type payloads from types, which the LLVM 19 API does not expose, so on 19 they treat every type as unannotated (and reloco-no-raw-pointer may report extra findings for RELOCO_STATIC_STR-style types). Use 20 or newer for full coverage. LLVM 18 and older are not supported.

Fixture tests: ctest target reloco_tidy_fixtures, or directly python3 tools/tidy/test/run_tests.py --clang-tidy <exe> --plugin <so> --include include. Fixtures use // expect: <check> on the offending line. A fixture with a file of the same name in tools/tidy/test/fixed/ also has its fix-its applied to a scratch copy and compared with that golden. Add --bless to create the golden for a fixture whose fix-its change the file (review the diff before keeping it).

Using the checker in your IDE

Every IDE below ends up running the same clang-tidy with the same plugin, so first make that work from a terminal, then point the IDE at it. Two prerequisites for all of them:

  1. A compile_commands.json (cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON, or Meson/Bear).
  2. A project-root .clang-tidy that enables the checks. IDEs read it automatically, so the per-IDE settings stay minimal. Plugins are not loadable from .clang-tidy; the --load flag has to come from the IDE or wrapper (shown below).
# .clang-tidy (project root)
# Enable only reloco's checks; add your own groups after them.
Checks: '-*,reloco-*'
# Make findings errors in CI; leave empty to keep them warnings in the editor.
WarningsAsErrors: ''
# Only report diagnostics from your own headers, not system/3rd-party ones.
HeaderFilterRegex: '^(?!.*(/_deps/|/third_party/)).*'
CheckOptions:
  # Opt-in mode for derived projects: check only RELOCO_BEGIN/END_SAFE_CODE regions.
  # SafeCodeMode is a per-check option; repeat it for every reloco check you enable
  # (or use 'all', the default, to check everything outside the exempt paths).
  - key: reloco-no-raw-pointer.SafeCodeMode
    value: opt-in
  - key: reloco-borrow-check.SafeCodeMode
    value: opt-in

Because the plugin cannot be loaded from .clang-tidy, the simplest portable approach is a wrapper script that every IDE can call in place of clang-tidy. This repository ships one as tools/clang-tidy-reloco. It loads build-tidy/libreloco-tidy.so; override with the RELOCO_TIDY_PLUGIN and CLANG_TIDY environment variables (the plugin and the executable must have the same LLVM major version). Copy it into your project if you build the plugin elsewhere. Use its path in the settings below.

VS Code

Use the clangd extension (preferred, live as you type) or the C/C++ extension.

  • clangd: clangd links its own clang-tidy and cannot load external plugins, so use it for the editor's compiler diagnostics and run reloco-tidy as a task (below) with problem matching. Set "clangd.arguments": ["--clang-tidy=false"] to avoid duplicate noise.
  • C/C++ extension: set "C_Cpp.codeAnalysis.clangTidy.enabled": true, "C_Cpp.codeAnalysis.clangTidy.path": "${workspaceFolder}/tools/clang-tidy-reloco" and "C_Cpp.codeAnalysis.runAutomatically": true. Findings appear in the Problems panel, and fix-its show up as quick fixes (lightbulb).

Task with problem matcher, so findings are clickable (.vscode/tasks.json):

{
  "version": "2.0.0",
  "tasks": [
    {
      // Runs reloco-tidy on the file open in the editor.
      "label": "reloco-tidy: current file",
      "type": "shell",
      "command": "${workspaceFolder}/tools/clang-tidy-reloco",
      // -p: directory containing compile_commands.json.
      "args": ["-p", "${workspaceFolder}/build", "${file}"],
      "problemMatcher": {
        "owner": "reloco-tidy",
        "fileLocation": "absolute",
        "pattern": {
          "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error|note):\\s+(.*)$",
          "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5
        }
      }
    },
    {
      // Applies the automatic fix-its (see "Fix-its" above); review the diff afterwards.
      "label": "reloco-tidy: fix current file",
      "type": "shell",
      "command": "${workspaceFolder}/tools/clang-tidy-reloco",
      "args": ["-fix", "-p", "${workspaceFolder}/build", "${file}"]
    }
  ]
}

CLion

CLion runs clang-tidy itself, so use its external-tool path for the plugin:

  1. Settings | Editor | Inspections | C/C++ | General | Clang-Tidy: enable it and choose Use .clang-tidy files. CLion shows the built-in checks live.
  2. Settings | Tools | External Tools | +: Program $ProjectFileDir$/tools/clang-tidy-reloco, Arguments -p $ProjectFileDir$/build $FilePath$, Working directory $ProjectFileDir$. Output filters (Advanced Options | Output Filters): $FILE_PATH$:$LINE$:$COLUMN$: .*. Assign a keyboard shortcut under Keymap.
  3. Optional: Settings | Build, Execution, Deployment | CMake, profile option -DCMAKE_CXX_CLANG_TIDY=/path/tools/clang-tidy-reloco makes every build run the checker, with findings shown in the Build tool window.

Other editors

Editor How
Visual Studio Use the clang-tidy wrapper through *Project
Qt Creator *Analyze
Neovim / Emacs Use nvim-lint / flycheck with the wrapper as the command and -p build %file; clang-tidy output is already in the standard file:line:col: format.
Any CI run-clang-tidy -clang-tidy-binary tools/clang-tidy-reloco -p build (parallel across files).
Any build system -DCMAKE_CXX_CLANG_TIDY=/path/tools/clang-tidy-reloco runs it on every compiled file.

Troubleshooting

  • "unable to load plugin" / undefined symbols: plugin and clang-tidy major versions differ.
  • Nothing is reported: the file lives under an exempt path (tests/, build/, ...), or SafeCodeMode: opt-in is set and the code is outside RELOCO_BEGIN/END_SAFE_CODE.
  • Missing includes in the IDE: regenerate compile_commands.json; headers need -I flags.
  • Slow: use run-clang-tidy -j$(nproc) and restrict to changed files in CI.

Rules

Check Rule Why
reloco-ref-qualified-member Non-static members that return an alias of the object must be &/const & qualified, or have an explicit && overload. Option StrictNonConst: true also requires & on non-const members that return no alias. Exempt: by-value handles/proxies (RELOCO_POINTER), operator(), unary * and ->, and members with any && overload. Calling them on temporaries is blocked, so views and references to a dying object cannot be created.
reloco-no-raw-pointer Raw pointers only inside RELOCO_POINTER/RELOCO_OWNER types, the unsafe tier, vtables, function pointers and extern "C". Use value_ptr, value_ref or span elsewhere. Raw pointers carry no size, lifetime or ownership.
reloco-no-c-array No raw C array variables or members; use reloco::array, inline_vector or a span. Arrays decay to pointers and lose their bounds.
reloco-noexcept Every function and lambda is noexcept (a conditional noexcept(expr) counts as explicit). Failure is a result<T>, never an exception.
reloco-lifetime-annotations Accessors returning aliases need RELOCO_LIFETIMEBOUND; handle constructors need RELOCO_LIFETIMEBOUND / RELOCO_LIFETIME_CAPTURE_BY_THIS on every pointer or reference parameter that reaches a pointer, reference or view member (initialiser or assignment in the body; a scalar read from the pointee, a copy/move construction, or a by-value member is a copy and borrows nothing). A delegating constructor borrows only through the target's annotated parameters. Declarations without a body are always reported. RELOCO_COPIES after a parameter name (view(const config &cfg RELOCO_COPIES)) states that it is only read and copied, so the argument may be a temporary. Lets Clang diagnose dangling views at the call site.
reloco-pointer-annotation Classes holding borrowed storage must be RELOCO_POINTER; owners RELOCO_OWNER. Without them Clang's lifetime analysis does not track the type.
reloco-banned-std-type std:: facilities with a reloco/microfmt/structo equivalent (containers, string, span, optional, variant, function, smart pointers, source_location, exception types, iostreams) are banned. The message names the replacement. Decided on the AST, so aliases are caught too. Complements scripts/check-no-std-types.py. Deliberate interop is accepted with the same comment markers as the script: // std-interop-ok[: reason] (line), // std-interop-begin / // std-interop-end (block), // std-interop-file (whole file).
reloco-banned-construct throw/try/catch, new/delete, const_cast, reinterpret_cast, dynamic_cast, C-style casts, and C string/memory/stdlib functions (memcpy, strlen, malloc, ...). Each defeats a static guarantee.
reloco-implicit-copy Classes are move-only unless marked RELOCO_COPYABLE (Rust's Copy). Implicit copies (T y = x, by-value arguments, by-value range-for, copy assignment) are flagged. Explicit copies (T(x), T y(x), T y{x}, static_cast<T>(x), member initialisers) are the equivalent of .clone() and always allowed. RELOCO_POINTER views are always copyable. Makes every duplicate of a resource visible in the source.
reloco-uninit-local Locals are always initialised at declaration. Classes with a non-trivial default constructor, and static locals, are fine. No indeterminate values. Branch-dependent initialisation of the remaining cases (int x; if (c) x = 1; use(x);, or passing a maybe-uninitialised object by reference) is caught by Clang's -Wsometimes-uninitialized (in -Wall) and -Wconditional-uninitialized, which the CMake warning set enables.
reloco-out-param A RELOCO_OUT parameter must be written on every returning path and not read before its first write. See below. Callers can rely on the output being set.
reloco-implicit-conversion Implicit narrowing, sign-changing and lossy float conversions are errors; use static_cast or a checked helper. Constants that fit are fine. Rust has no implicit as.
reloco-explicit-conversion Single-argument constructors and conversion operators must be explicit (initializer_list constructors excepted). No silent conversions.
reloco-must-use-result Functions returning expected/result/error/status/optional types must be [[nodiscard]] (or the type must be). Rust's #[must_use].
reloco-unused-result A discarded call result of those types is an error; cast to void with a reason. Dropped errors.
reloco-const-local A local that is never mutated must be const (pointers, references and arrays excluded). Immutable by default, like let.
reloco-no-shadow A local may not shadow another local or parameter of an enclosing scope.
reloco-enum-switch A switch over an enum lists every enumerator, even when it has a default: a default that stands in for enumerators (usually written to silence GCC/Clang or static analyzers) is reported. default stays allowed as an extra arm for out-of-range values once all enumerators are listed; suppress with NOLINT where a catch-all is intended. A new enumerator breaks the build. Pair with -Wimplicit-fallthrough for fallthrough. A switch over a non-enum integer or char must have a default.
reloco-banned-low-level goto, setjmp/longjmp, union and volatile (suppress MMIO with NOLINT and a reason). Each bypasses a static guarantee.
reloco-mutable-global Mutable namespace-scope, static-member and function-static variables are banned, except atomic/mutex/lock types. Rust's static mut.
reloco-unsafe-call-scope Calls to unsafe_* / [[unsafe_buffer_usage]] functions are only allowed from the unsafe tier or inside unsafe regions (also Clang's unsafe_buffer_usage blocks). Rust's unsafe blocks.
reloco-checked-operator operator[], unary operator* and operator-> must be RELOCO_CHECKED (they bounds/null check), on the operator or its class; using such an operator on a type that is not RELOCO_CHECKED is a violation. Callers inside the unsafe tier are exempt. These are where out-of-bounds and null dereferences hide.
reloco-safe-math Opt-in. Inside a function or class marked RELOCO_SAFE_MATH, raw integer + - * / % << >>, ++, --, unary - on non-constant operands are rejected; use checked.hpp, saturating.hpp or wrapping.hpp. Unmarked code is never checked. Overflow is explicit where it matters.
reloco-member-init Every field has a default member initializer (self-initialising class types excepted). No indeterminate members.
reloco-rule-of-five Declaring any of destructor, copy/move constructor, copy/move assignment means declaring all five (= default/= delete). A lone defaulted destructor is allowed. Explicit ownership semantics.
reloco-atomic-context Sleeping (RELOCO_MIGHT_SLEEP, or inferred transitively) while inside an atomic scope (irq/preemption/spinlock guards, RELOCO_ENTER_ATOMIC), and calls to RELOCO_ATOMIC_ONLY functions outside one. Full rules, macros and limits: atomic-context.md. Linux's might_sleep() / sparse context checking.
reloco-lock-balance Every lock/lock_shared/write_lock/read_lock is released on all paths; double lock/unlock reported. RELOCO_LOCK_IMPL opts out. Full rules: lock-discipline.md; applying annotations to derived, wrapped and legacy locks: lock-annotations.md. Linux sparse __must_hold, clang -Wthread-safety.
reloco-lock-alias No pointers to locks or &lock (references are fine) so lock tracking stays sound. See lock-discipline.md. Rust's exclusive borrow of a lock.
reloco-use-after-move A local or parameter passed to std::move may not be read again on any path (loops included) until it is reassigned or reinitialised (x = ..., x.clear(), reset, assign, emplace). A move is std::move(x), static_cast<T &&>(x) or std::forward<T>(x) with a non-reference T (std::forward<T &> is not a move). Trivially copyable types are exempt (a move is a copy). Moves are tracked per field: after std::move(p.first) the field, its sub-fields and the whole p are moved-from, while p.second stays valid; p.first = ... or p.first.clear() revives it, and assigning p revives everything. The same applies to members of this (std::move(name_) then name_.size()); a bare this/*this is not treated as a use. Emits a note at the move. Rust's "borrow of moved value".
reloco-iterator-invalidation Inside a range-for, the iterated container may not be modified (non-const member other than at/front/back/begin/end/find/size..., assignment, or passing it to a mutable-reference parameter), unless the change is immediately followed by break/return. Iterators bound to variables are covered by reloco-borrow-check. Hidden iterators dangle after reallocation.
reloco-leak Opt-in by type. A local or by-value parameter of a RELOCO_MUST_CONSUME class must be consumed on every path that leaves the function: std::move(x), return x, &x (escape) or a RELOCO_CONSUMES member. Reported at the exit, with a note at the declaration. Linear resources (transactions, tokens) cannot be dropped silently.
reloco-lock-guard In a class that owns a mutex (a RELOCO_CAPABILITY member), every other mutable member must be RELOCO_GUARDED_BY(mutex), RELOCO_UNGUARDED, const, a reference, atomic or a synchronisation primitive. Fix-it appends RELOCO_GUARDED_BY(mu) when there is exactly one mutex. Enable -Wthread-safety so access to guarded members is then enforced by Clang. Every shared field names its lock.
reloco-narrowing-flow Explicit integer casts (static_cast, functional, C-style) must be provably lossless. A value-range analysis understands constants, & masks, %, >>, /, + - * on known ranges, ?: and small types; casts that may truncate or change sign are reported with the computed range. Same-width char to byte reinterpretation is allowed. Complements reloco-implicit-conversion, which stops at explicit casts. Explicit casts are where truncation hides.
reloco-send-sync Arguments passed to a RELOCO_REQUIRE_SEND parameter (thread/task spawn) must be Send; arguments to a RELOCO_REQUIRE_SYNC parameter must be Sync. Send is structural: scalars and aggregates of Send members; owners (RELOCO_OWNER) iff their template arguments are; raw pointers, references, views (RELOCO_POINTER), RELOCO_NOT_SEND types and lambdas capturing by reference or this are not. RELOCO_SEND overrides after an audit. Sync: RELOCO_SYNC, atomics, mutexes, all-const types, or a mutex owner. Rust's Send/Sync.
reloco-signed-index [], at() and try_at() indices of signed integer type are rejected unless the value-range analysis (shared with reloco-narrowing-flow) proves them non-negative (constants, masks, unsigned casts). A negative index becomes a huge unsigned value or an out-of-bounds read. Fix: use std::size_t, a range-for, or check i >= 0 first. Signed indexing is a classic source of out-of-bounds bugs.
reloco-ns-pointer Opt-in by type. Pointers tagged RELOCO_NS(tag) (system-call arguments, VM guest memory) are numbers in a foreign address space: they may not be dereferenced (*p, p[i], p->m), assigned, initialised, passed, returned or cast to a normal pointer or a pointer with another tag. Integers may be cast to them (that is how they are created) and pointer arithmetic keeps the tag. Only a RELOCO_NS_TRANSLATOR function (or the unsafe tier) may convert. Confused-deputy and guest/user pointer bugs.
reloco-static-string Opt-in by type. const char *RELOCO_STATIC_STR declares that a string pointer only ever refers to string literals or static storage. Values returned, passed, initialised or assigned to such a pointer must be a literal, nullptr, a static array, or another RELOCO_STATIC_STR value. Unannotated const char * is reported by reloco-no-raw-pointer (use reloco::string_view). Dangling C-string pointers.
reloco-early-static Opt-in by type. A RELOCO_EARLY_STATIC class (or variable) must be usable before the C++ runtime starts: every user constructor is constexpr, the destructor is trivial (no atexit registration), the type is literal, and each static/global object of it is constant-initialised (constexpr, constinit or a provably constant initialiser). Fix-it inserts constinit (C++20). Bare-metal startup, no static-init-order fiasco.
reloco-borrow-check Best-effort Rust-style borrow checking inside one function. See below. Aliasing XOR mutability.
reloco-aliased-arguments A call may not receive overlapping places when one of them is bound as a mutable reference, mutable pointer (&x) or non-const this: f(x, x), x.m(x), x.m(x.field). See below. Rust's "cannot borrow as mutable more than once" across call arguments.
reloco-escaping-local A pointer, array decay, view or RELOCO_LIFETIMEBOUND result derived from a local may not be stored through a pointer or non-const reference parameter (*out = &x;, out->p = buf;). See below. The caller is left with a dangling pointer; Clang's -Wlifetime-safety does not see stores through parameters.
reloco-lifetime-names Opt-in by annotation. Rust-style named lifetimes: RELOCO_LT(a) on parameters, RELOCO_LT_RETURN(a) on the function, RELOCO_LT_THIS(a) on the receiver, and static for a lifetime that never ends. Validates declarations, return statements and static arguments. See below. Says exactly which arguments a result borrows, which Clang's all-or-nothing lifetimebound cannot.
reloco-member-order A member may not be initialised from a member declared after it, and a pointer/view member into a sibling member makes a copyable class unsafe. See below. Members are constructed in declaration order and destroyed in reverse; self-pointers dangle after copy or relocation.
reloco-mutable-member A mutable member must be an atomic, lock, once_flag or reloco cell, or be RELOCO_GUARDED_BY a lock. See below. mutable hides mutation behind a const interface (Rust's interior mutability needs Cell/Mutex); const_cast is already banned.
reloco-virtual-call-in-ctor No unqualified virtual call on this from a constructor or destructor (unless the class or method is final). See below. The call dispatches to the class under construction/destruction, never to a derived override.
reloco-virtual-default-argument A virtual function may not have default arguments. See below. Defaults are bound to the static type, so a call through a base reference ignores the override's default.
reloco-slicing A polymorphic class may not be copy/move-constructed from an object of a derived class (by-value parameters, T t = derived;). See below. The derived part is silently cut off (object slicing).
reloco-implicit-bool Pointers, integers, floats and member pointers may not be used as conditions (if (p), while (n), !n, a && p); compare explicitly. Types with explicit operator bool are fine. See below. Hides what is being tested (null vs zero vs valid) and mixes up if (n) for counts and flags.
reloco-lambda-default-capture Lambdas must list their captures: [=] and [&] (also with extras like [&, a]) are flagged, with the implicitly captured names in the message. See below. A default capture silently grabs new variables and this, and [&] makes escaping lambdas dangle.
reloco-move-const std::move of a const, non-trivially-copyable object is flagged: it yields const T&& and silently selects the copy constructor. See below. A move that is really a copy hides an expensive operation.

RELOCO_OUT

// x is an out-parameter: the function must assign it on every path that returns.
bool parse(int *x RELOCO_OUT, bool ok) noexcept {
  if (!ok)
    return false;   // error: 'x' is not written on every path that returns
  *x = 42;          // for `int &x RELOCO_OUT` write `x = 42;`
  return true;
}

A write is an assignment to *x, x[i], x->m (or the reference and its members), a non-const member call on it, or passing it to a callee taking a non-const pointer/reference. One member write counts as writing the whole object, and handing it to a callee counts as a write. Reading before the first write, and RELOCO_OUT on a const or non-pointer parameter, are errors. Paths ending in a noreturn call are ignored.

reloco-borrow-check

Intra-procedural and flow-sensitive (NLL-style):

  • A borrow is a local reference, pointer or RELOCO_POINTER view initialised from a place (a variable plus a field path): auto &r = x.first;, span s = buf;, r = x.cfirst();. A RELOCO_LIFETIMEBOUND call result borrows from the bound argument.
  • Inside a method, this is a root like any local: const int &r = a_; a_ = 5; use(r); and int &f = first(); push(3); use(f); are flagged (this->a_ and implicit members alike). A call to a non-const method of the same object counts as a mutation of every member. A bare auto *self = this; is a view of the whole object and is not tracked as a borrow.
  • It is live from its initialiser to its last use; inside a loop it lives to the loop end when declared outside the loop.
  • A shared borrow (const target) excludes mutation of the place: assignment, ++/--, a non-const method call, a non-const reference argument, or a move (&& argument).
  • A mutable borrow excludes every use of an overlapping place.
  • A range-for borrows its range for the whole body, mutably if the loop variable is a non-const reference.
  • Disjoint fields do not overlap.
  • Derived borrows: a variable initialised from another borrowing variable keeps everything that variable borrows alive for as long as it is used itself. int *q = p; (copy), auto it = view.begin(); and int &r = *view; borrow the storage p/view borrows, not only p/view. Taking the address of a handle (&h) is not derived. The derived borrow is mutable only when both the original borrow and the new variable's type are mutable.
  • Labelled handles: a class with a RELOCO_LT(name) field is treated as a view. Constructing one borrows every argument bound to a RELOCO_LT(name) constructor parameter (holder h(&x); keeps x borrowed while h is used), and the handle holds exactly the access it was built with (&x of a non-const x is a mutable borrow). A copy (holder h2 = h;) inherits the borrows. A method declared RELOCO_LT_RETURN(a) where a is carried by a field (and not by RELOCO_LT_THIS) hands out what the handle borrows, not the handle itself: int *p = h.get(); keeps x borrowed, but h.reset(&y); is still allowed while p is live.
  • A pointee is a different object from the pointer that stores it: *p, p->m(), view->m(), *view, and a view built from a pointer value (string_view(argv_[0])) borrow what the pointer points at. A pointee only conflicts with a pointee of the same pointer, so rewriting argv_ does not invalidate a view of its strings.
  • A bare T * returned by a non-standard-library method that is not RELOCO_LIFETIMEBOUND does not borrow its receiver (intrusive-list pop_front(), lookup tables handing out linked nodes). RELOCO_LIFETIMEBOUND and standard-library calls (vector::data()) keep borrowing. Views, references and iterators always borrow.
  • A conflicting access is not reported when it is followed, in the same block, by return/co_return (whose value does not read through the borrow), or by break/continue leaving the loop the borrow lives in. Statements between the access and the exit must not mention the borrow. Example: queue_.insert_before(existing, e); ++size_; return;.
  • Reading an element through a non-const operator[]/-> counts as a mutation; read through a const handle or the borrowing span instead (b[13], not (*sec)[13]), or make the local const.
  • Exemptions: RELOCO_BORROW_EXEMPT on the function (put the reason in a comment above it) or a NOLINT on the line. Method calls are field-insensitive (a non-const call mutates every member), which is the usual reason for exemption.

Limits: no inter-procedural reasoning, no aliasing through containers or heap (use-after-move is a separate check, reloco-use-after-move). Use Clang's -Wlifetime-safety for use-after-return/scope. It is a bug finder, not a proof.

Slicing is deliberately not a separate rule: polymorphic bases are already a red flag.

reloco-aliased-arguments

void mut_const(int &dst, const int &src) noexcept;  // dst is written, src is read

void bad() noexcept {
  int x = 0;
  mut_const(x, x);          // flagged: dst and src are the same object, so writing dst changes src
}
void ok(int (&v)[2]) noexcept {
  int n = 1;
  mut_const(v[0], n);       // fine: different objects (copy the value out first when it aliases)
}
struct buf { int a = 0; void copy_from(const buf &o) & noexcept; };
void receiver() noexcept {
  buf b;
  b.copy_from(b);           // flagged: the mutable 'this' and 'o' are the same object
}

Arguments are compared as places (a local plus a field path, as in reloco-borrow-check). A pair is flagged when the places overlap and at least one is bound mutably: a non-const lvalue reference parameter, a non-const pointer parameter given &place, or the implicit object of a non-const method. By-value and rvalue-reference parameters are copies or moves and never conflict, so v.set(v.get()) is fine. Array subscripts and arbitrary pointers are skipped because overlap cannot be decided. RELOCO_BORROW_EXEMPT, unsafe regions and NOLINT suppress it.

reloco-lifetime-names

Named lifetimes in the style of Rust's 'a, written as attributes. Nothing is checked until a function carries a label, so existing code is unaffected.

Macro Where Meaning
RELOCO_LT(a) after a parameter name The object the parameter refers to lives for lifetime a.
RELOCO_LT_RETURN(a) start of the declaration The result borrows from everything tagged a. Stack several for several lifetimes.
RELOCO_LT_THIS(a) start of a member declaration The receiver (*this) lives for lifetime a.
RELOCO_LT(a) after a field or variable name The pointer, reference or view the field/variable holds refers to something living for lifetime a. Every value stored into it must carry a.
RELOCO_LT(static) after a parameter, field or variable name The argument, or every value stored into the field/variable, must have static duration (string literal, global or static object, function, or another static parameter).
RELOCO_LT_RETURN(static) start of the declaration The result has static duration. It borrows from no parameter.
// The result borrows x and y (lifetime 'a'); z is unrelated, so it may be mutated while the result lives.
RELOCO_LT_RETURN(a) const item &pick(const item &x RELOCO_LT(a), const item &y RELOCO_LT(a),
                                     const item &z) noexcept;

struct holder {
  item it;
  // The pointer refers to something living for 'a; the constructor parameter must carry 'a too.
  RELOCO_LT(a) const item *link = nullptr;
  holder(const item *l RELOCO_LT(a)) noexcept : link(l) {}  // fine: 'l' carries 'a
  // RELOCO_LT(static) const char *name = nullptr; would accept only literals, statics and static parameters.
  // The result borrows the receiver: 'h.set(1)' while the result is live is a borrow-check error.
  RELOCO_LT_THIS(a) RELOCO_LT_RETURN(a) const item &get() const & noexcept { return it; }
};

// 'name' is stored for the lifetime of the program, so only literals and statics may be passed.
void register_name(const char *name RELOCO_LT(static)) noexcept;
// The result is static: the body may return only literals, statics or RELOCO_LT(static) parameters.
RELOCO_LT_RETURN(static) const char *name_of(int k) noexcept;

void use(const char *param, const char *fwd RELOCO_LT(static)) noexcept {
  register_name("literal");  // fine
  register_name(fwd);        // fine: forwarded 'static parameter
  register_name(param);      // flagged: 'param' is not known to be 'static
  char local[4] = {};
  register_name(local);      // flagged: borrows a local
}

Rules:

  • Declarations (reported once per function, annotations on all redeclarations are merged): RELOCO_LT_RETURN on a function that does not return a reference, pointer or view; RELOCO_LT_RETURN(a) where no parameter or RELOCO_LT_THIS carries a; RELOCO_LT on a parameter that is not a reference, pointer or view; RELOCO_LT_THIS on a non-member.
  • return statements in a function with RELOCO_LT_RETURN: a value borrowed from a parameter (or this) that does not carry a returned lifetime is flagged. A RELOCO_LT(static) parameter is always acceptable. With RELOCO_LT_RETURN(static) the value must instead be static; a borrow of a local or of a parameter not tagged static is flagged.
  • Fields and variables: RELOCO_LT(a) or RELOCO_LT(static) after a field or variable name (a field of a non-reference, non-pointer, non-view type is flagged). Every store into it is checked: constructor member initialisers, in-class initialisers, field = value and operator= in a body, and variable initialisers. static fields accept literals, nullptr, globals/statics and RELOCO_LT(static) parameters, and reject a local or a parameter not tagged static. A field tagged a accepts a parameter tagged a (or static) and rejects a local or a parameter that does not carry a. A method whose return hands out such a field satisfies RELOCO_LT_RETURN with the field's lifetime, and RELOCO_LT_RETURN(a) counts a field tagged a as carrying a.
  • Constructor coverage: every user-written constructor (not copy/move, not delegating) of a class with a labelled field must initialise that field in its member initialiser list, or the field needs a default member initialiser. Otherwise it is reported as constructor does not initialise the lifetime-labelled field 'p_'. Where uninitialised storage is valid (pool slots, placement storage filled in later), opt out with RELOCO_BORROW_EXEMPT on the field, the class or the constructor (with a comment giving the reason), or NOLINT(reloco-lifetime-names).
    class RELOCO_BORROW_EXEMPT slot {  // class-wide opt-out: the pointer is set by emplace() before any read
    public:
      slot() noexcept {}                // not reported
    private:
      RELOCO_LT(a) int *p_;
    };
  • Calls and constructors: an argument for a RELOCO_LT(static) parameter is flagged when it borrows a local (&local, a local array, a view of a local, a local passed by reference) or is a parameter not tagged static. Values of unknown origin (call results, pointers read from locals) are accepted.
  • Borrow tracking: reloco-borrow-check treats a result as borrowing exactly the arguments whose lifetime is listed in RELOCO_LT_RETURN (all of them, not only the first), and the receiver only when RELOCO_LT_THIS shares a label. A RELOCO_LT_RETURN(static) result borrows nothing. reloco-escaping-local and reloco-lifetime-annotations honour the labels too, so a labelled accessor needs no extra RELOCO_LIFETIMEBOUND to satisfy them.
  • Scope of the analysis: labels are matched by name within one function signature; there is no lifetime subtyping ('a: 'b), no labels on types, and a local that borrows a parameter and is then returned is not followed. A handle's borrows are tracked through its local variable (construction, copies, accessors that return a field's label) but not through members of other objects or containers, Clang does not see the labels, so keep RELOCO_LIFETIMEBOUND where Clang's -Wdangling should also fire.
  • Exempting: RELOCO_BORROW_EXEMPT, unsafe regions and NOLINT(reloco-lifetime-names) suppress the body checks.
  • In reloco itself: the classes that borrow more than one thing, or that are easy to misuse because they keep a raw reference, are labelled so the checker verifies their constructors: cow (value and allocator are separate lifetimes), allocator_ref (context), stack_allocator_context (buffer), external_vector (storage), fault_injector (hook) and the fault-injection hooks (hook, and predicate plus hook for conditional_hook). Single-pointer handles such as value_ptr and value_ref are left to Clang's lifetimebound, which already describes them fully.

reloco-escaping-local

struct sink { int *p = nullptr; };

void bad(int **out, sink &s) noexcept {
  int x = 0;
  int buf[4] = {};
  *out = &x;     // flagged: 'out' is caller storage, and x dies when this function returns
  s.p = buf;     // flagged: an array decays to a pointer into the local
}
void ok(int **out, int *in) noexcept {
  static int shared = 0;
  *out = &shared;  // fine: static storage outlives the call
  *out = in;       // fine: 'in' already points at caller-owned memory
}

Flagged: a store whose target is reached through a pointer parameter (*p, p->f, p[i]) or a non-const reference parameter, whose type is a pointer or RELOCO_POINTER view, and whose value is &local, a local array, a view built from a local, or a RELOCO_LIFETIMEBOUND call on a local. Locals that are themselves pointers, references or views are skipped because they may point at caller memory. Stores into globals, members of this and return values are left to Clang's -Wlifetime-safety, which the CMake warning set enables when the compiler supports it (-Wlifetime-safety). For code that destroys an object and then frees its storage, wrap the function in RELOCO_BEGIN_ALLOW_USE_AFTER_DESTROY / RELOCO_END_ALLOW_USE_AFTER_DESTROY (see lifetime.hpp) to silence its -Wlifetime-safety-invalidation false positive.

reloco-member-order

struct bad {
  guard g_;   // constructed first, destroyed last
  mutex mu_;  // constructed second: g_(mu_) uses an object that does not exist yet
  bad() noexcept : g_(mu_) {}  // flagged
};
struct good {
  mutex mu_;  // declare what is used before what uses it
  guard g_;
  good() noexcept : g_(mu_) {}
};
struct self_ref {
  char buf_[16] = {};
  char *cur_ = buf_;  // flagged: points into itself, but copy/move are still generated
};
struct self_ref_ok {
  char buf_[16] = {};
  char *cur_ = buf_;
  self_ref_ok() = default;
  self_ref_ok(const self_ref_ok &) = delete;             // copy and move deleted
  self_ref_ok &operator=(const self_ref_ok &) = delete;  // so cur_ can never dangle
};

Flagged: a constructor initialiser or default member initialiser that uses a member declared later; taking only its address is fine unless the member has a non-trivial destructor (it would run after the target is gone). Also flagged: a pointer, reference or RELOCO_POINTER member bound to another member of the same object (&m, array decay, direct reference, RELOCO_LIFETIMEBOUND call) when the class still has a generated or defaulted copy/move constructor. RELOCO_BORROW_EXEMPT, unsafe regions and NOLINT suppress it.

reloco-mutable-member

struct cache {
  mutable int hits_ = 0;               // flagged: a const method can silently change state
  mutable std::atomic<int> ok_{0};     // fine: atomics, locks, once_flags and cells are sanctioned
  mutable mutex mu_;                   // fine
  mutable int memo_ RELOCO_GUARDED_BY(mu_) = 0;  // fine: guarded by a lock
};

Flagged: any mutable field whose type is not an atomic, lock/mutex, once_flag, condition variable or cell, and that has no RELOCO_GUARDED_BY. Type names are matched by substring, also for dependent types. Use unsafe regions or NOLINT with a reason for the rare logically-const caches (lazy init, enable_shared_from_this back-pointers).

reloco-virtual-call-in-ctor

struct base {
  base() noexcept { setup(); }             // flagged: never reaches derived::setup
  virtual ~base() noexcept { teardown(); } // flagged: derived is already destroyed here
  virtual void setup() noexcept {}
  virtual void teardown() noexcept {}
};
struct explicit_binding {
  explicit_binding() noexcept { explicit_binding::setup(); }  // fine: qualified, statically bound
  virtual void setup() noexcept {}
};

Fix by calling a non-virtual helper, qualifying the call, marking the class or method final, or moving the work to an init() step run after construction. Unsafe regions and NOLINT suppress it.

reloco-slicing

struct shape { virtual ~shape() = default; virtual int area() const noexcept; };
struct square : shape { int side = 2; int area() const noexcept override; };

int by_value(shape s) noexcept;       // taking a polymorphic type by value invites slicing
int by_ref(const shape &s) noexcept;  // fine

void run(square sq) noexcept {
  shape copy = sq;  // flagged: 'side' and the override are lost
  by_value(sq);     // flagged: the parameter is copy-constructed from a derived object
  by_ref(sq);       // fine
}

Only classes with virtual functions are checked, so plain inheritance of data (plain_derived to plain_base) is left alone. Implicit special members of derived classes are ignored. Pass by reference or smart pointer, or give the base a virtual clone(). Unsafe regions and NOLINT suppress it.

reloco-implicit-bool

void run(int n, const int *p, bool b, flag_holder h) noexcept {
  if (n) {}          // flagged: fix-it appends '!= 0'
  if (p) {}          // flagged: fix-it appends '!= nullptr'
  bool none = !p;    // flagged: write 'p == nullptr' (no automatic fix for negations)
  if (n != 0) {}     // fine
  if (b) {}          // fine: already bool
  if (h) {}          // fine: explicit operator bool states the intent
}

Integer literals and macro expansions are skipped. Unsafe regions and NOLINT suppress it.

reloco-lambda-default-capture

void run() noexcept {
  int a = 1, b = 2;
  auto bad = [&]() noexcept { return a + b; };       // flagged: names are implicit
  auto good = [a, &b]() noexcept { return a + b; };  // fine: each capture is visible
  auto moved = [v = std::move(a)]() noexcept { return v; };  // init-capture moves explicitly
}

There is no automatic fix because choosing copy or reference per variable is a design decision. Unsafe regions and NOLINT suppress it.

reloco-move-const

void run() noexcept {
  const heavy c;
  heavy m;
  heavy a = std::move(c);  // flagged: const heavy&& binds to heavy(const heavy&), a copy
  heavy b = std::move(m);  // fine: a real move
  const int n = 3;
  int i = std::move(n);    // fine: trivially copyable, copying is what happens either way
}

Remove const from the source object, or drop the std::move and spell the copy. Unsafe regions and NOLINT suppress it.

reloco-virtual-default-argument

struct widget {
  virtual ~widget() = default;
  virtual int size(int scale = 1) const noexcept;  // flagged: an override's own default is ignored via widget&
  int size_default() const noexcept { return size(1); }  // fix: a non-virtual overload supplies the default
};

Unsafe regions and NOLINT suppress it.

RELOCO_NS poison pointers

#include <reloco/lifetime.hpp>

// A pointer that came from user space: only a number here, never dereferenceable.
// 'user' is the address-space tag; pointers with different tags never mix.
using user_ptr = char *RELOCO_NS(user);

// The only way out: a translator validates the range and returns a real pointer
// (or copies the data). Inside it, dereferences and casts are allowed.
RELOCO_NS_TRANSLATOR char *translate(user_ptr p, unsigned long size) noexcept;

long sys_write(int fd, user_ptr buf, unsigned long n) noexcept {
  char *real = translate(buf, n);   // ok: translator
  // buf[0] = 0;                    // error: dereference of RELOCO_NS(user) pointer
  // takes_plain(buf);              // error: user pointer where a normal pointer is expected
  return real ? 0 : -1;
}

RELOCO_EARLY_STATIC

#include <reloco/lifetime.hpp>

// A device-state block the startup code touches before any constructor has run.
// RELOCO_EARLY_STATIC makes the checker enforce: constexpr constructors only, trivial destructor,
// and constant initialisation of every static object of this type.
struct RELOCO_EARLY_STATIC boot_state {
  unsigned stage;
  constexpr boot_state() noexcept : stage(0) {}  // constexpr: no code runs before main
};

// constinit: compile error if the initialiser is not a constant expression, so the
// object lands in .data and needs no dynamic initialiser (or atexit registration).
constinit boot_state g_boot;

Annotations used by the flow checks

#include <reloco/lifetime.hpp>

// reloco-leak: a transaction must be committed or handed over on every path.
// RELOCO_MUST_CONSUME marks the class; RELOCO_CONSUMES (first in the declaration) marks the
// member that releases it.
struct RELOCO_MUST_CONSUME txn { RELOCO_CONSUMES void commit() noexcept; };

// reloco-lock-guard: every mutable member next to a mutex names its lock (-Wthread-safety
// then rejects unlocked access). RELOCO_UNGUARDED documents a deliberate exception.
class counter {
  reloco::mutex mu_;
  int hits_ RELOCO_GUARDED_BY(mu_) = 0;
  int generation_ RELOCO_UNGUARDED = 0;  // written once before threads start
};

// reloco-send-sync: the parameter that crosses a thread boundary says so. The checker then
// verifies each argument at the call site; the lambda below captures by value, so it is Send.
template <typename F> void spawn(F fn RELOCO_REQUIRE_SEND) noexcept;
void start(int n) noexcept { spawn([n]() noexcept { (void)n; }); }

Reloco's own reloco::spawn and thread_builder::spawn carry RELOCO_REQUIRE_SEND, so reloco::spawn([&x] { ... }) and lambdas capturing raw pointers are reported with a fix note. thread_scope::spawn is deliberately not annotated: scoped threads are joined before the borrowed data dies, so by-reference captures are allowed there (Rust's Scope::spawn bound is Send, not 'static).

CMake integration and profiles

# Build the plugin together with reloco and add `ninja jplcz_reloco_tidy`, which checks every public header.
# Requires libclang-N-dev / llvm-N-dev matching clang-tidy-N.
cmake -S . -B build -G Ninja -DJPLCZ_RELOCO_BUILD_TIDY=ON
ninja -C build jplcz_reloco_tidy

In your own project (after add_subdirectory(<reloco>/tools/tidy) or setting RELOCO_TIDY_PLUGIN):

include(<reloco>/tools/tidy/RelocoTidy.cmake)

# Which profile to use: "strict" (all rules everywhere) or "library" (opt-in, for gradual adoption).
set(RELOCO_TIDY_PROFILE strict)

# Run the checker on every compile of my_target (CMake's CXX_CLANG_TIDY hook; slows the build).
reloco_tidy_attach(my_target)

# Or keep builds fast and add a separate `ninja my_lint` target covering the sources of these targets,
# plus extra files that no target compiles (EXTRA_ARGS are the compiler flags for those files).
reloco_tidy_add_target(my_lint TARGETS my_target FILES src/extra.cpp EXTRA_ARGS -std=c++20)

tools/tidy/profiles/strict.clang-tidy and library.clang-tidy are ready-made .clang-tidy files; the helpers pass the chosen one with --config-file, and you can copy either to your repository root for IDE use (see the IDE guide above).

Calibration against reloco's own headers

The plugin is run over tests/compile_all_headers.cpp (all public headers, -std=c++20) to find false positives and to decide what the library itself must fix:

clang-tidy-24 --load=build-tidy/libreloco-tidy.so --checks='-*,reloco-*' \
    --header-filter='include/reloco/.*' tests/compile_all_headers.cpp -- -std=c++20 -Iinclude

Results of the first pass (about 2300 findings, now about 755) and what they led to:

Finding Resolution
reloco-member-init fired on fields of instantiated class templates whose in-class initializer is instantiated lazily The check skips template instantiations; the template pattern is checked instead.
reloco-ref-qualified-member fired on every non-const member (418 of 517) Default narrowed to members that return an alias; StrictNonConst: true restores the strict rule.
reloco-no-raw-pointer fired on parameters of function pointer types and of captureless lambdas (vtable slots) Those parameters are exempt; the function implementing the slot is still checked.
reloco-no-raw-pointer fired on ~55 const char * names/messages Static-lifetime ones are annotated RELOCO_STATIC_STR (type_id, call_location, error category names, expect(msg)); string_view, obfuscated_string and masked_byte_region are unsafe-by-design regions.
reloco-ref-qualified-member: 180 findings, mostly missing & and missing deleted const && overloads Applied the check's own fix-its (& on members; a deleted const && twin for const & accessors). The check now exempts by-value handles and proxies (RELOCO_POINTER, e.g. masked_byte_region::reference), call operators, unary */-> and accessors with any && overload. 180 findings down to 0.
reloco-checked-operator: 80 library operators lacked RELOCO_CHECKED They assert, delegate to an asserting accessor, or are non-null by construction, so they are now annotated; the iterator operators without a check gained an assertion. 207 findings down to 0.
detail/ type-erased bases and the allocator and OS shims address raw memory by design Wrapped in RELOCO_BEGIN_UNSAFE_CODE / RELOCO_END_UNSAFE_CODE with a comment saying why.

| reloco::unsafe namespace | Treated as the unsafe tier by reloco-banned-construct. | | reloco-banned-construct C-style cast in a template instantiation | Exempt: the compiler synthesises a cast for an enum-typed non-type template argument (SubstNonTypeTemplateParmExpr); there is no cast in the source. | | reloco-rule-of-five with both copy operations deleted | Satisfied; move operations need not be spelled out. | | reloco-narrowing-flow with static_cast<unsigned>(-1) | Exempt: an all-ones constant is not a narrowing. | | reloco-noexcept on deduction guides | Exempt: guides cannot carry an exception specification. | | reloco-lifetime-annotations with RELOCO_CALLABLE_WHEN after RELOCO_LIFETIMEBOUND | The check now walks every sugar layer, so the attribute is found. |

With these refinements, real fixes (annotations, noexcept, initialisers, RELOCO_GUARDED_BY, RELOCO_COPYABLE on value types) and reasoned NOLINTs, tests/compile_all_headers.cpp reports 0 findings for every reloco-* check. Keep it at 0: new findings are either bugs or need a reasoned suppression.

Fix-its and "how to fix" notes

Every diagnostic that has a well-known remedy carries a note: how to fix: ... line showing the concrete replacement. Mechanical remedies are also offered as automatic fix-its, applied with clang-tidy -fix:

# Apply all automatic fixes, then review the diff before building.
clang-tidy-24 --load=libreloco-tidy.so --checks='-*,reloco-*' -fix src/foo.cpp -- -std=c++20 -Iinclude
Check Automatic fix
reloco-explicit-conversion inserts explicit
reloco-must-use-result inserts [[nodiscard]]
reloco-ref-qualified-member inserts & after the cv-qualifiers on every redeclaration (in-class and out-of-line definitions); the deleted const && twin is added only to definitions, never to declaration-only members
reloco-noexcept inserts noexcept after cv/ref qualifiers
reloco-const-local inserts const (single-declarator statements only); see the skip list under Instantiation and fix-it notes
reloco-uninit-local appends = {}
reloco-lifetime-annotations inserts RELOCO_LIFETIMEBOUND after the qualifiers (after noexcept(...)); skipped when a trailing return type, requires or try follows
reloco-implicit-bool appends != 0 / != nullptr; non-primary operands are parenthesised, so if (flags & m) becomes if ((flags & m) != 0)
reloco-implicit-conversion wraps the expression in static_cast<T>(...)
reloco-member-init appends {} to the field

Fix-its are skipped inside macro expansions. Fixes such as = {}, const and static_cast change semantics, so review the diff rather than applying it blindly. All other checks (borrow, copy, out-param, C arrays, banned constructs, ...) only emit the note, because the right fix depends on the design.

Exemptions

Every check honours these; each use should say why it is sound.

Mechanism Scope
// NOLINT(reloco-xxx): reason, NOLINTNEXTLINE, NOLINTBEGIN/END line / block (standard clang-tidy)
RELOCO_BEGIN_UNSAFE_CODE / RELOCO_END_UNSAFE_CODE region, all reloco checks
RELOCO_UNSAFE_BUFFER_USAGE function or a function named unsafe_* the unsafe tier (raw pointers, casts, arrays tolerated)
#pragma clang unsafe_buffer_usage begin/end, RELOCO_BEGIN/END_UNSAFE_BUFFER_USAGE region, borrow check only
RELOCO_BORROW_EXEMPT on a function or class borrow check, e.g. swap/exchange primitives
RELOCO_CHECKED / RELOCO_SAFE_MATH not exemptions: they declare a type is checked / opt code into strict math
ExemptPaths option (;-separated substrings, none to disable) default /tests/;/test/;/examples/;/example/;/demos/;/benchmarks/;/_deps/;/third_party/;/build/;/build-

System headers are never reported.

Opt-in mode for derived projects

By default (SafeCodeMode: all) the rules apply to all non-exempt code. Projects that include 3rd-party sources can switch to SafeCodeMode: opt-in, where only code between the safe-region macros is checked:

#include <reloco/lifetime.hpp>

RELOCO_BEGIN_SAFE_CODE   // checked from here ...
void ours(int *x RELOCO_OUT) noexcept { *x = 1; }
RELOCO_END_SAFE_CODE     // ... to here

RELOCO_BEGIN_UNSAFE_CODE // always exempt, also inside a safe region
RELOCO_END_UNSAFE_CODE

The macros expand to _Pragma("region ..."), which GCC, Clang and MSVC accept silently (-Wunknown-pragmas clean), so they are safe in any compiler. Set the mode in .clang-tidy: CheckOptions: [{key: reloco-no-raw-pointer.SafeCodeMode, value: opt-in}] (the same option exists on every check).

Macro reference (reloco/lifetime.hpp)

RELOCO_POINTER, RELOCO_OWNER, RELOCO_LIFETIMEBOUND, RELOCO_LT, RELOCO_LT_RETURN, RELOCO_LT_THIS, RELOCO_COPIES, RELOCO_COPYABLE, RELOCO_OUT, RELOCO_BORROW_EXEMPT, RELOCO_CHECKED, RELOCO_SAFE_MATH, RELOCO_MUST_CONSUME, RELOCO_CONSUMES, RELOCO_UNGUARDED, RELOCO_SEND, RELOCO_NOT_SEND, RELOCO_SYNC, RELOCO_REQUIRE_SEND, RELOCO_REQUIRE_SYNC, RELOCO_NS(tag), RELOCO_NS_TRANSLATOR, RELOCO_EARLY_STATIC, RELOCO_UNSAFE_BUFFER_USAGE, RELOCO_BEGIN/END_SAFE_CODE, RELOCO_BEGIN/END_UNSAFE_CODE, RELOCO_BEGIN/END_UNSAFE_BUFFER_USAGE. All compile to nothing where the compiler lacks the attribute. See also lifetime safety.

RELOCO_STATIC_STR

// Declares that the returned string has static lifetime (only literals / static storage).
// The annotation goes after the '*'; it is empty on GCC/MSVC.
const char *RELOCO_STATIC_STR name() noexcept { return "widget"; }

// Parameter: callers may only pass literals or other RELOCO_STATIC_STR values.
void log_msg(const char *RELOCO_STATIC_STR msg) noexcept;

// Anything else must use reloco::string_view instead.

Instantiation and fix-it notes

  • reloco-implicit-copy skips copies of a type that equals or contains a template argument of the enclosing function/class specialization: the caller chose that type, not the template.
  • reloco-checked-operator does not flag use-site *it / it-> on iterator types (iterator_category member or a name ending in iterator); operator[] stays checked.
  • reloco-narrowing-flow tracks for (T i = C0; i < C1; ++i) loops when the body never writes i.
  • reloco-explicit-conversion fix-its insert explicit after any leading [[attribute]] list.
  • tests/compile_all_headers.cpp covers nearly all public headers; calibration must report 0.
  • reloco-implicit-conversion accepts x & MASK when MASK is a non-negative constant that fits the destination (the hex-nibble idiom table[x & 0x0F]). Its fix-it spells the canonical type, never a member typedef that the use site cannot name.
  • reloco-member-init offers no fix-it for fields of nested records and ignores pre-C++20 bit-fields (they cannot have default member initializers).
  • reloco-implicit-bool rewrites !p as p == nullptr (parenthesised unless the parent is if/while/for/ return/a logical operator) and offers no fix-it for condition variables (if (T *p = f())).
  • reloco-lambda-default-capture fix-its list the captures explicitly ([&n, this], [&, x] drops the default). No fix-it is offered inside dependent contexts, where the captured set is not known.
  • reloco-pointer-annotation skips classes named formatter (stateless specialisations).
  • reloco-aliased-arguments ignores a const reference bound to a temporary: v = v.substr(1) copies the view by value, the temporary never overlaps the receiver.
  • reloco-borrow-check treats copying a pointer or view out of another object (lvalue-to-rvalue, or a copy/move constructor) as a value copy, not a borrow: int *old = head_; does not borrow head_.
  • reloco-enum-switch skips a switch whose case labels are value-dependent (member enums of class templates, where the pattern cannot list enumerators); the instantiation is not analysed.
  • reloco-aliased-arguments compares pointees separately from the pointers storing them: owner_->remove(*this) and a_->swap_with(*b_) are different objects; peer_->swap_with(*peer_) is reported.
  • reloco-unused-result/reloco-must-use-result skip glvalue calls (a.at(i) used as an lvalue) and lambda operator(); reloco-use-after-move treats std::move as a mutation only of the moved path and a DeclStmt re-initialisation as reviving the variable.
  • reloco-lifetime-annotations on handle constructors only reports a pointer/reference parameter that flows into an aliasing member (pointer, reference or RELOCO_POINTER); parameters that are copied or only read are not borrows. RELOCO_COPIES after a parameter name declares an intentional copy and silences the report (explicit cfg_view(const config &c RELOCO_COPIES)). Annotating a copied parameter with RELOCO_LIFETIMEBOUND is wrong: it makes callers that pass temporaries fail with -Wdangling.
  • reloco-const-local does not flag: variables written by inline-asm output operands; non-trivially-copyable locals that are returned by name (const would turn the move into a copy); variables used as a range-for range (the analysis cannot see the non-const begin()/end() call).
  • reloco-uninit-local skips range-for loop variables (initialised by the loop).
  • reloco-explicit-conversion exempts std::nullptr_t converting constructors (T(nullptr_t) is the idiom for "empty").
  • reloco-lifetime-annotations offers a fix-it only for the annotation-less accessor shape; constructors still need a manual choice between lifetimebound and capture annotations.
  • reloco-implicit-bool parenthesises any operand that is not a DeclRef, Member, Call, Paren, ArraySubscript or unary operator, so the inserted comparison binds to the whole expression (!(a & b) becomes (a & b) == 0).
  • reloco-member-init skips incomplete (flexible) array fields.
  • reloco-implicit-copy is silenced by RELOCO_COPYABLE; value types that have a user destructor and so no move (reloco::expected, array, sentinel, instant) carry it.