From cd14cde4c2939254dc0495c38b6bf65c0c26442e Mon Sep 17 00:00:00 2001 From: Owen Carey <37121709+owenthcarey@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:53:18 -0800 Subject: [PATCH 1/3] feat!: find the bounds of pointers with no declaration (RFC 0056) A pointer with no declared bound in a safe function is no longer an index-single or call-args error. Where it arrives and is indexed or stepped, the function asks the runtime once for the run of objects of its type the records give (__weavec_rt_bound), a safe caller passes the bounds it holds in the hidden parameter held, a member the code names bounds its pointer, and every access is compared with the bound found. The ledger and the audit list each found bound with the declaration the planner proposes, and weavec-cc --weavec-fix-bounds writes them. -fweavec-safe-bounds=declared keeps the language before. BREAKING CHANGE: runtime ABI 52, ledger 16, audit 11; index-single and the one-object cases of call-args are no longer errors by default. --- AGENTS.md | 24 +- docs/annotations.md | 13 + docs/architecture.md | 34 + docs/pages/guides/convert-cxx.md | 10 +- docs/pages/guides/safe-c.md | 54 +- docs/pages/guides/safe-cxx.md | 4 +- docs/pages/reference/cli.md | 53 +- docs/pages/reference/guarantees.md | 23 +- docs/rfcs/0056-bounds-without-declarations.md | 1084 ++++++++++++ docs/rfcs/README.md | 1 + docs/roadmap.md | 36 +- docs/scripts/check-examples.py | 21 +- include/weavec/Frontend/Driver.h | 10 +- include/weavec/Frontend/EnforcementLedger.h | 9 +- include/weavec/Frontend/RuleFix.h | 28 + include/weavec/Frontend/SafeCheck.h | 52 + lib/Frontend/Driver.cpp | 42 +- lib/Frontend/EnforcementLedger.cpp | 138 +- lib/Frontend/Fixer.cpp | 94 +- lib/Frontend/GuardGlobals.cpp | 76 + lib/Frontend/GuardLibrary.cpp | 27 + lib/Frontend/GuardPass.cpp | 42 + lib/Frontend/GuardPassImpl.h | 44 + lib/Frontend/GuardSafe.cpp | 1499 ++++++++++++++++- lib/Frontend/GuardTypes.cpp | 177 ++ lib/Frontend/SafeCheck.cpp | 167 ++ lib/Frontend/SafeCheckImpl.h | 28 + lib/Frontend/SafeCxx.cpp | 31 +- lib/Frontend/SafeFix.cpp | 55 +- lib/Frontend/SafeTypes.cpp | 496 +++++- lib/Frontend/SafeTypes.h | 18 + resources/safe/rules.md | 47 +- runtime/test/rt_test.c | 421 +++++ runtime/weavec_alloc.c | 37 + runtime/weavec_guard.c | 294 ++++ runtime/weavec_report.c | 231 ++- runtime/weavec_rt.exports | 4 + runtime/weavec_rt.h | 114 +- runtime/weavec_types.c | 395 +++++ scripts/corpus-gate.py | 8 +- scripts/run-cases.py | 2 +- scripts/test_corpus_gate.py | 8 +- scripts/test_run_cases.py | 6 +- test/Driver/Inputs/found-list.c | 39 + test/Driver/found-bounds.c | 101 ++ test/Driver/safe-cxx-threads.cpp | 4 +- test/Driver/safe-cxx-units.cpp | 4 +- test/Driver/safe-fix-command.cpp | 6 +- test/Driver/safe-fix-include.cpp | 6 +- test/Driver/safe-fix.cpp | 8 +- test/Driver/safe-survey.cpp | 12 +- test/Driver/typed-units.c | 4 +- test/Guards/found-bounds-held.c | 80 + test/Guards/found-bounds-lambda.cpp | 47 + test/Guards/found-bounds-members.c | 130 ++ test/Guards/found-bounds.c | 191 +++ test/Guards/ir-found-bounds.c | 87 + test/Guards/ir-typed-cxx.cpp | 24 +- test/Guards/ir-typed.c | 4 +- test/Guards/ledger.c | 2 +- test/Guards/report-json.c | 2 +- test/Guards/unsafe-region.c | 2 +- test/Safe/bounds-declared.c | 46 + test/Safe/calls.c | 4 +- test/Safe/cxx-bounds.cpp | 4 +- test/Safe/cxx-ends.cpp | 4 +- test/Safe/cxx-expressions.cpp | 4 +- test/Safe/cxx-found-bounds.cpp | 67 + test/Safe/cxx-units.cpp | 8 +- test/Safe/fix-bounds.c | 2 +- test/Safe/fix-bounds.cpp | 2 +- test/Safe/found-bounds.c | 68 + test/Safe/index-single.c | 4 +- test/Safe/notes.c | 4 +- test/Safe/safe-file.cpp | 4 +- test/Safe/typed-rules.c | 4 +- test/Safe/unit-safe.c | 8 +- test/cases/README.md | 1 + test/cases/bounds/count-off-by-one.c | 24 + test/cases/bounds/count-off-by-one_ok.c | 24 + test/cases/bounds/field-count.c | 23 + test/cases/bounds/field-count_ok.c | 23 + test/cases/bounds/global-table.c | 20 + test/cases/bounds/global-table_ok.c | 20 + test/cases/bounds/local-buffer.c | 26 + test/cases/bounds/local-buffer_ok.c | 26 + test/cases/bounds/member-array.c | 24 + test/cases/bounds/member-array_ok.c | 24 + test/cases/bounds/range-end.c | 28 + test/cases/bounds/range-end_ok.c | 28 + test/cases/bounds/span.cpp | 27 + test/cases/bounds/span_ok.cpp | 26 + test/cases/bounds/step-below.c | 21 + test/cases/bounds/step-below_ok.c | 21 + test/cases/bounds/string-scan.c | 25 + test/cases/bounds/string-scan_ok.c | 25 + 96 files changed, 7199 insertions(+), 180 deletions(-) create mode 100644 docs/rfcs/0056-bounds-without-declarations.md create mode 100644 test/Driver/Inputs/found-list.c create mode 100644 test/Driver/found-bounds.c create mode 100644 test/Guards/found-bounds-held.c create mode 100644 test/Guards/found-bounds-lambda.cpp create mode 100644 test/Guards/found-bounds-members.c create mode 100644 test/Guards/found-bounds.c create mode 100644 test/Guards/ir-found-bounds.c create mode 100644 test/Safe/bounds-declared.c create mode 100644 test/Safe/cxx-found-bounds.cpp create mode 100644 test/Safe/found-bounds.c create mode 100644 test/cases/bounds/count-off-by-one.c create mode 100644 test/cases/bounds/count-off-by-one_ok.c create mode 100644 test/cases/bounds/field-count.c create mode 100644 test/cases/bounds/field-count_ok.c create mode 100644 test/cases/bounds/global-table.c create mode 100644 test/cases/bounds/global-table_ok.c create mode 100644 test/cases/bounds/local-buffer.c create mode 100644 test/cases/bounds/local-buffer_ok.c create mode 100644 test/cases/bounds/member-array.c create mode 100644 test/cases/bounds/member-array_ok.c create mode 100644 test/cases/bounds/range-end.c create mode 100644 test/cases/bounds/range-end_ok.c create mode 100644 test/cases/bounds/span.cpp create mode 100644 test/cases/bounds/span_ok.cpp create mode 100644 test/cases/bounds/step-below.c create mode 100644 test/cases/bounds/step-below_ok.c create mode 100644 test/cases/bounds/string-scan.c create mode 100644 test/cases/bounds/string-scan_ok.c diff --git a/AGENTS.md b/AGENTS.md index f71dedd6..06de9ea5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -143,9 +143,25 @@ target type is there (`bad-cast`); the runtime keeps the type of every heap block, registered global and recorded local, from layouts the checker computes (`lib/Frontend/SafeTypes.cpp` marks the forms in the AST before code is made, `GuardTypes.cpp` expands the marks, `runtime/weavec_types.c` -answers). Full picture: +answers). Since RFC 0056 a safe function indexes a pointer with no +declared bound: where such a pointer arrives (a parameter, a load, a +call's result, a global) and is indexed or stepped, the checker marks it +(`__weavec.arrival`, `Arrivals` in `SafeTypes.cpp`), the pass asks the +runtime for its bound once (`__weavec_rt_bound`, the run of objects of its +type the records give: a heap block, a registered global's extent, a +recorded local; memory with no record is one object), a safe caller that +holds the bound passes it in the hidden last parameter `held` of the +callee's body, and every access is compared with the answer +(`pointer-out-of-bounds`, its report saying where the bound came from); +the checker lists each such declaration (`found`, ledger 16, audit 11) with +the bound the planner proposes, `weavec-cc --weavec-fix-bounds` writes +them, and `-fweavec-safe-bounds=declared` keeps the language before it +(`index-single`, `call-args`). Full picture: `docs/architecture.md`. Design and the reasoning behind it: `docs/rfcs/`. -Read `0055-a-heap-for-safe-code.md` first (the entries and the short +Read `0056-bounds-without-declarations.md` first (found bounds: the +arrivals and their questions, the records' answers, `held`, the list and +`--weavec-fix-bounds`; its *Implementation amendments* and *Measured +gates*), then `0055-a-heap-for-safe-code.md` (the entries and the short paths, typed `realloc`, one contract for both languages; its *Implementation amendments* and *Measured gates*), then `0054-one-of-several-types.md` (tagged unions, checked @@ -264,7 +280,8 @@ cmake --preset dev && cmake --build --preset dev && ctest --preset dev 2. WeaveC's only compile-time diagnostics are Safe C's and Safe C++'s errors (RFC 0041, RFC 0044), each ending in `[weavec-safe:]` with a note, and each pinned by a `test/Safe/` test (`cxx-*.cpp` for C++); - RFC 0051's one exception: in a unit compiled with `-fweavec-safe`, + under RFC 0056 a found bound is a remark (`-Rpass=weavec-safe`), not a + diagnostic; RFC 0051's one exception: in a unit compiled with `-fweavec-safe`, Clang's `-Wreturn-type`, `-Winvalid-noreturn`, `-Wformat`, `-Wformat-security` and `-Wunsequenced` (and in C `-Wdeprecated-non-prototype`) are errors under Clang's own names @@ -358,6 +375,7 @@ cmake --preset dev && cmake --build --preset dev && ctest --preset dev | Change what a callable or a container holds (callables by their loans, the narrowing, binders and pointers to member functions, the library's containers of views, out parameters, polymorphic objects, globals, `mutable`, `= default`, results a type does not show; RFC 0053) | `anyCallable`, `reachOf`, `lambdaReach`, `changedBy`, `deepen`, `holdsCallable`, `closures`, `keptCallable`, `heldIn`, `outStored`, `onlyPolymorphic`, `known`, `shows`, `changesGlobals`, `referencesIn`, the `Global` roots and the `escape` cases of `returned` in `lib/Frontend/SafeCxxFlow.cpp`; `libraryOfViews`, `readsOnly`, `polymorphicHolder`, `mutableOwners`, `runsProgram`, `ownsBlocks`, `changesOnly` in `SafeCxxKinds.h`; tests `test/Safe/cxx-loans-*.cpp` | | Change what a call may reach (reach by types, results, views' shallow `const`, lambdas' changes, `call-alias` for callables, kept callables, values built from borrows; RFC 0052) | `reaches`, `writesThrough`, `pointsAt`, `borrowing`, `mayBorrow`, `keptCapture` in `lib/Frontend/SafeCxxKinds.h`; `result`, `fit`, `lambdaChanges`, `lambdaObjects`, `closures`, `keptCallable`, `keptLambdas`, the `Reached` and `Runs` ends in `lib/Frontend/SafeCxxFlow.cpp`; `keptDefault` in `SafeCxx.cpp`; E8 in `lifetime` (`SafeFix.cpp`); tests `test/Safe/cxx-reach-*.cpp` | | Change one of several types (tagged unions, checked conversions and downcasts, the type records, `bad-cast`, `union-member`; RFC 0054) | `lib/Frontend/SafeTypes.cpp` (`taggedUnion`, `checkedConversion`, `TypeLayouts`, `TypeMarks`: the AST marks undone while the rules run, the rules `UnionRules`, E9 `tagWant`), the gates in `SafeCheck.cpp` (`checkPointerCast`, `byteViewAllowed`, `checkGlobalInits`), `SafeCxx.cpp`, `SafeUndefined.cpp`, `clearTagged` in `SafeOwnership.cpp`; `lib/Frontend/GuardTypes.cpp` (the markers' expansion, `layoutGlobal`, `typeRecord`, `recordLocals`, `noteAllocations`, `dropObjects`), the checked object as a root in `GuardSafe.cpp` and `GuardFast.cpp`; `runtime/weavec_types.c`, the slot types in `weavec_alloc.c`; tests `test/Safe/tagged-union*.c`, `cxx-tagged-union-uses.cpp`, `checked-cast.c`, `cxx-checked-cast.cpp`, `fix-tagged.c`, `test/Guards/union-member.c`, `bad-cast.c*`, `ir-tagged.c`, `ir-cast.c*`, cases `test/cases/sum/`, `rt_test` `type-at-*`, `frame-records`, `union-member` | +| Change found bounds (pointers with no declared bound in safe code, their questions, the records' answers, `held`, the list, `--weavec-fix-bounds`, `-fweavec-safe-bounds`; RFC 0056) | `Arrivals` and `arrivalDeclared` in `lib/Frontend/SafeTypes.cpp`; the `found` reports and `listFound` in `SafeCheck.cpp` (`libraryAccess`, the `held` flag in `Declarations`), `lambdasOf` in `SafeCxx.cpp`; `boundTarget` and `placeOf` in `SafeFix.cpp`; `findArrivals`, `placeQuestions`, `boundLibraryCalls`, `heldParameters`, `addHeld`, `pruneHeld`, `proposalOf` in `GuardSafe.cpp`, `readArrivals` and `recordLocals` in `GuardTypes.cpp`, the extents in `GuardGlobals.cpp`; the ledger's `found` list in `EnforcementLedger.cpp`, the bounds mode of `lib/Frontend/Fixer.cpp`, `-fweavec-safe-bounds` in `Driver.cpp`; `__weavec_rt_bound` in `runtime/weavec_alloc.c`, `boundOf`, `runIn`, `weavecRtBoundSlow`, `weavecRtBoundRecord` in `weavec_types.c`, the extents and `__weavec_rt_found_fail` in `weavec_guard.c`, the report's bounds line and the statistics in `weavec_report.c`; tests `test/Safe/found-bounds.c`, `bounds-declared.c`, `cxx-found-bounds.cpp`, `test/Guards/found-bounds*.c*`, `ir-found-bounds.c`, `test/Driver/found-bounds.c`, cases `test/cases/bounds/`, `rt_test` `bound-*`; the guide's "Found bounds", `docs/pages/reference/guarantees.md` (B1)–(B3) | | Add an annotation | Don't, without an RFC: `WEAVEC_UNSAFE` and Safe C's are the only ones (`UnsafeRegions.h`, `SafeCheck.h`, `weavec.h`, `docs/annotations.md`) | | Change build flags / warnings | `cmake/WeaveCWarnings.cmake`, `cmake/WeaveCLLVM.cmake` | | Add a CI job | `.github/workflows/ci.yml` | diff --git a/docs/annotations.md b/docs/annotations.md index 86d9cfb7..be1f4529 100644 --- a/docs/annotations.md +++ b/docs/annotations.md @@ -87,6 +87,19 @@ region too, with no source change. | `union { … } u WEAVEC_TAGGED_BY(tag)`, `WEAVEC_TAGGED_BY(tag, mask)` | after a union field's name, or after an anonymous union's closing brace | RFC 0054 §3: `tag`, an integer or enumeration field of the same struct (at most 64 bits, the tag of no other union), says which member is live (`tag & mask` with a mask). A safe function uses a member after a comparison of the tag the compiler adds (`union-member` when it fails), a store of a new value to the tag clears the union, and no member's address is taken. Expands to `annotate("weavec.tagged_by", "[, ]")`. | | `T m WEAVEC_WHEN(value, …)` | after a member of a tagged union | The constant values of the tag the member is for. Every member that holds a pointer has one; a member without one is not used by safe code. Expands to `annotate("weavec.when", value, …)`. | +The bounds (`WEAVEC_COUNTED_BY`, `WEAVEC_SIZED_BY`, `WEAVEC_ENDED_BY`, +their `_OR_NULL` forms and `WEAVEC_NULL_TERMINATED`) are no longer needed +for a function to be safe ([RFC 0056](rfcs/0056-bounds-without-declarations.md)): +a pointer with none that a safe function indexes has its bound found when +the function runs, the extent of the object the runtime's records place it +in. A declared bound promises the length the program means, which can be +less than the object (an index past it stops where a found bound lets it +pass); it is compared with a count, with no lookup when the function runs; +a safe caller passes it to its callees; and readers and other compilers see +it. `weavec-cc --weavec-audit` lists the declarations whose bound is found, +and `weavec-cc --weavec-fix-bounds` writes the proposed ones. +`-fweavec-safe-bounds=declared` requires them, as before. + ### In C++ `weavec-c++ -fweavec-safe` makes a unit's functions diff --git a/docs/architecture.md b/docs/architecture.md index 1b0653f1..40117d15 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -547,6 +547,40 @@ from a field and uses against the shadow (`__weavec_rt_reference_fail`, a fields' annotations, count reads and store pairs. Accesses whose pointer has no known bound keep their guards (`typed-unbounded`). +A pointer a safe function indexes or steps with no declared bound has its +bound found when the function runs (RFC 0056; `-fweavec-safe-bounds=declared` +turns it off). The checker reports such a use as a *found* bound instead +of an `index-single` or `call-args` error: `listFound` keeps one entry per +declaration (a parameter, a member, a result, a global; keyed as the fix +planner keys its fixes, with the proposals of RFC 0049's evidence) for the +ledger's `found` list. Before code is made, `Arrivals` +(`lib/Frontend/SafeTypes.cpp`) wraps each place such a pointer arrives (a +parameter's first use, a load, a call's result, a global) in a +`__weavec.arrival` marker that names the element's layout and the +declaration, transparent to constant evaluation in C++ and never around a +`musttail` call. GuardSafe (`findArrivals`, `placeQuestions`) turns the +arrivals whose accesses need a bound into one `__weavec_rt_bound` call each +(the *question*, with a per-declaration record of its site and counts), +placed before the loop that uses it when the loop calls nothing, and +compares the accesses, library calls (`boundLibraryCalls`) and conversions +to declared bounds with the `{low, high}` it returns +(`__weavec_rt_found_fail`). A safe function's body whose table has a +plain pointer parameter (`held` in `FunctionBounds`) takes a hidden last +parameter, an array of the bounds its safe callers hold (zeroes when they +hold none); a caller passes what it knows (a declared count, an array, a +bound it found), the body uses an element that is not zero instead of +asking, and `pruneHeld` drops the parameter of a body no caller fills. +Local arrays passed to a function of the program are recorded in their +guarded frame (`recordLocals`), and GuardGlobals registers each global's +extent and layout (`__weavec_rt_extents_register`). The runtime answers +(`boundOf` in `runtime/weavec_types.c`) from the heap block's type, a +registered global or extent, a recorded local, or the program's arguments +and environment: the run of objects of the element's type around the +pointer (`runIn`: an array member's elements, the data after a header, a +trailing array), one object where nothing is recorded, nothing in a +released block; a heap block of the element's type takes a short path in +`__weavec_rt_bound`. + ## The enforcement ledger GuardInsert records each access it collected, before any rule removes its diff --git a/docs/pages/guides/convert-cxx.md b/docs/pages/guides/convert-cxx.md index 0c70cf3f..72365510 100644 --- a/docs/pages/guides/convert-cxx.md +++ b/docs/pages/guides/convert-cxx.md @@ -15,7 +15,7 @@ A rewrite into Rust starts over: a new build, bindings at the boundary, tests po cmake --build build-survey ``` -2. **Let the compiler write its part** ([RFC 0049](/rfcs/0049-errors-that-carry-their-fix/)). Most errors of a conversion ask for one annotation on an existing declaration that the code already implies: a pointer that `memcmp` reads `size_` bytes of is `WEAVEC_COUNTED_BY(size_)`, a parameter stored in a member is kept. `--weavec-fix` writes those, runs the rules again on the units an edit reached (each unit's recorded command, with `-fsyntax-only`), repeats until a round writes nothing, and marks every file left with no error `WEAVEC_SAFE_FILE`: +2. **Let the compiler write its part** ([RFC 0049](/rfcs/0049-errors-that-carry-their-fix/)). Most errors of a conversion ask for one annotation on an existing declaration that the code already implies: a parameter stored in a member is kept, a returned end is `WEAVEC_COUNTED_BY(0)`. A pointer indexed with no declared bound is not an error: its bound is found when the function runs ([RFC 0056](/rfcs/0056-bounds-without-declarations/)), and the survey lists it. `--weavec-fix` writes those, runs the rules again on the units an edit reached (each unit's recorded command, with `-fsyntax-only`), repeats until a round writes nothing, and marks every file left with no error `WEAVEC_SAFE_FILE`: ```sh weavec-c++ --weavec-fix -j8 ledger/ @@ -48,7 +48,9 @@ A rewrite into Rust starts over: a new build, bindings at the boundary, tests po 5. **Rewrite what has no fix,** the file with the fewest errors first. Compile it with the rules on (`-fweavec-safe`, or mark it and build) and fix what they say; each note says what to write. `weavec-c++ --weavec-explain ` prints a rule with a rejected example and its rewrite. `WEAVEC_GUARDED` keeps one function or class guarded inside a marked file. -6. **Run the project's tests in the checked build** (`-fweavec-safe-checks=full`, the default of a build without optimization): every guard stays, so a mistake the rules do not see stops with a full report. Then repeat from 1. +6. **Declare the bounds the list proposes.** The audit's list of found bounds names each declaration a safe function indexes with no bound, the functions that need it, and the bound its uses agree on (a pointer that `memcmp` reads `size_` bytes of is `WEAVEC_COUNTED_BY(size_)`). `weavec-c++ --weavec-fix-bounds ledger/` writes the certain ones, `--weavec-fix-bounds=likely` the likely ones too; a declared bound is compared with a count, asks nothing when it runs, and stops an index past the length the program means, which a found bound (the object's extent) lets pass. Run the tests after it: a likely bound that is too small stops a program that ran. + +7. **Run the project's tests in the checked build** (`-fweavec-safe-checks=full`, the default of a build without optimization): every guard stays, so a mistake the rules do not see stops with a full report. Then repeat from 1. `WEAVEC_SAFE_FILE`, written once after `#include `, makes every function the file defines after it safe, with the member functions of the classes defined there, in every unit that includes it. It does not reach the files it includes. @@ -58,7 +60,7 @@ The annotations the fixer writes are the ones a person writes for pointers a fas ## Raw pointers keep their place -Existing C++ indexes raw pointers. Safe C++ indexes one whose declaration says how many elements it has, and compares each access with that bound when it runs. Declare the bound where the pointer is declared; the signature stays the same for callers that compile without WeaveC. +Existing C++ indexes raw pointers, and Safe C++ compiles it as written: a pointer with no declared bound is compared with the bound found for it when the function runs, the run of objects of its type that the runtime's records give (a heap block, a global, an array member, a local array the caller passed). Declaring the bound where the pointer is declared makes the comparison one with a count, which asks nothing, and says what the program means; the signature stays the same for callers that compile without WeaveC. Under `-fweavec-safe-bounds=declared` a pointer with no bound is one object, as before. | The code has | Declare | | ---------------------- | ------------------------------------------------------------------- | @@ -68,7 +70,7 @@ Existing C++ indexes raw pointers. Safe C++ indexes one whose declaration says h | a member and its count | `char *WEAVEC_COUNTED_BY(size_) data_;` beside `std::size_t size_;` | | an accessor | `const char *WEAVEC_COUNTED_BY(size_) data() const` | -Arrays keep their length as pointers, a container's `data()` has `size()` elements, and the library's pointer-and-count functions (`std::string(p, n)`, `append`, `std::string_view(p, n)`, `std::span(p, n)`) ask that their pointer have a bound. A count changes beside its pointer (`counted-pair`), and neither is passed by a reference that is not `const` (`field-address`). +Arrays keep their length as pointers, a container's `data()` has `size()` elements, and the library's pointer-and-count functions (`std::string(p, n)`, `append`, `std::string_view(p, n)`, `std::span(p, n)`) compare their count with the pointer's bound, declared or found. A count changes beside its pointer (`counted-pair`), and neither is passed by a reference that is not `const` (`field-address`). ```cpp accepted class Slice { diff --git a/docs/pages/guides/safe-c.md b/docs/pages/guides/safe-c.md index 0a41ee9a..743626c7 100644 --- a/docs/pages/guides/safe-c.md +++ b/docs/pages/guides/safe-c.md @@ -31,11 +31,11 @@ The first error of a compile names the command that explains its rule: `weavec-c ## Bounds -A pointer in a safe function points to **one object** unless its declaration says how many. The annotations go after the `*` of a pointer type, on parameters, results, fields and globals: +A pointer in a safe function is indexed and stepped inside its **bound**. Its declaration may say how many elements it points to; when it says nothing, the bound is **found** when the function runs, from what the runtime knows of the object the pointer points into ([found bounds](#found-bounds), [RFC 0056](/rfcs/0056-bounds-without-declarations/)). The annotations go after the `*` of a pointer type, on parameters, results, fields and globals: | Annotation | The pointer points to | | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| none | one object of its type | +| none | the objects of its type around it that the runtime's records give, found when the function runs | | `WEAVEC_COUNTED_BY(n)` | `n` elements; `n` names an integer parameter, or is an integer constant or a macro that expands to one | | `WEAVEC_SIZED_BY(n)` | `n` bytes | | `WEAVEC_ENDED_BY(e)` | the elements before `e`, another pointer parameter | @@ -70,6 +70,42 @@ WEAVEC_SAFE size_t length(const char *WEAVEC_NULL_TERMINATED s) { } ``` +### Found bounds + +A safe function that indexes a pointer with no declared bound compiles. Where the pointer arrives (a parameter, a load of a field, a call's result, a global) and is then indexed or stepped, the compiler asks the runtime once for its bound, and every access is compared with the answer as with a declared count: + +```c +struct buffer { char *data; size_t length; }; /* no annotation */ + +WEAVEC_SAFE void put(struct buffer *b, size_t i, char c) { + b->data[i] = c; /* outside the block data points into: stops */ +} +``` + +The runtime knows the extent and the type of every heap block, every global of a unit `weavec-cc` compiled, and every local array a safe function passes on. Its answer is the run of objects of the pointer's type around the pointer: a whole `int` array, the array member a pointer points into (not the rest of its struct), the data after a struct header, a string literal. Memory it has no record of (another allocator's, a mapping, a library's static buffer) is one object. A released block has no bytes. A pointer the function makes where it names a member (`s->items`, `grid[1]`, `&s->count`) is bounded by that member, wherever it goes next. A safe caller that holds a pointer's bound (an array it sees, a declared count, a bound it found) passes it with the call, so the callee asks nothing. + +An access outside the bound stops, and the report says where the bound came from: + +```text +weavec: pointer-out-of-bounds at put.c:4:16: write of 1 bytes at 0xbc80000040 +weavec: 0xbc80000040 is 0 bytes after the 64-byte bounds of the pointer at 0xbc80000000 +weavec: the bounds were found: 0xbc80000000 is 0 bytes inside the 64-byte heap block of type 'char' at 0xbc80000000, allocated by thread T0: +``` + +A found bound is the object's extent, not what the program means: a read of `data[length]` in a block of 64 bytes passes. A declared bound (`char *WEAVEC_COUNTED_BY(length) data`) stops it, asks nothing when the function runs, and documents the interface. So a found bound is listed, not hidden: + +- `-fweavec-summary` ends the unit's line with `…; 4 bounds found`, and `-Rpass=weavec-safe` gives a remark for each, with the declaration that would compare with a count instead: + + ```text + list.c:10:1: remark: the bound of 'values' is found when 'sum' runs; 'const int *WEAVEC_COUNTED_BY(n) values' compares with a count instead [-Rpass=weavec-safe] + ``` + +- The ledger lists each declaration once, with the functions that need it and the bound its uses propose; `weavec-cc --weavec-audit` prints the list, the declaration most functions need first. +- `weavec-cc --weavec-fix-bounds ...` (after a survey, `-fweavec-safe-survey`) writes the proposals the evidence makes certain; `--weavec-fix-bounds=likely` writes the likely ones too. A likely bound that is too small stops a program that ran, so run the tests after it. +- `WEAVEC_RT_STATS=1` prints how many bounds were found, how many had no record, and the sites that asked most. + +`-fweavec-safe-bounds=declared` is the language before RFC 0056: a pointer with no bound points to one object, it is not indexed or stepped (`index-single`), and it is not passed where a declaration gives a bound or to a library call that may access more (`call-args`). Use it for code whose list is empty and should stay so. The two modes link together. + ### Borrowed and escaping pointers A safe function's pointer parameters are **borrowed** for the call: it reads and writes through them, keeps them in locals and passes them on, but does not keep them after it returns. @@ -312,13 +348,13 @@ Each error ends with `[weavec-safe:]`. The [rules reference](/reference/ru | Rule | Rejects | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `index-single` | indexing or offsetting a pointer to one object (`p[1]`, `p + 2`, `p++`); `p[0]` is `*p` | +| `index-single` | stepping a pointer with no element type (`void *`), reading a pointer declared to no element; under `declared`, indexing a pointer to one object | | `int-to-pointer` | an integer converted to a pointer, other than the constant null | | `pointer-cast` | a conversion that could forge a pointer and is not one the runtime checks (a `void *` to a struct, a struct to one that begins with it, `container_of`) | | `pointer-bytes` | writing an object that holds pointers as bytes, or copying or zeroing part of one | | `union-pointer` | reading a member that holds a pointer of a union without a tag; a tagged union's member's address, or the union apart from its struct | | `escape` | keeping a pointer parameter after the call (stored in memory, returned) unless it is `WEAVEC_ESCAPES` or `WEAVEC_LIFETIMEBOUND` | -| `call-args` | a pointer to one object passed, stored or returned where a declaration gives a bound, or given to a library call that may access more | +| `call-args` | a local or member taken by `&` given to a library call that may access more; under `declared`, a pointer to one object where a bound is declared | | `variadic` | a variadic call the [library table](https://github.com/weavefoundry/weavec/blob/main/lib/Core/LibrarySpec.txt) does not describe | | `no-asm` | inline assembly, `setjmp`, `longjmp`, `__builtin_frame_address`, computed `goto` | | `unsafe-block` | a `WEAVEC_UNSAFE` block inside a safe function | @@ -340,11 +376,11 @@ A rule never tries to prove something about the code: it rejects a construct. Wh ## What runs -- An access through a pointer with bounds is compared against them; outside, the program stops with `pointer-out-of-bounds`. A pointer loaded from a field is bounded by the field's declaration (`WEAVEC_ENDED_BY` fields, and counts in another struct, are not used: those loads keep their guards). An access at a constant offset inside one object needs no check; an element at an index is one comparison of the index with the count, which the optimizer hoists out of loops and removes where the loop's own test implies it. +- An access through a pointer with bounds, declared or found, is compared against them; outside, the program stops with `pointer-out-of-bounds`. A pointer loaded from a field is bounded by the field's declaration (`WEAVEC_ENDED_BY` fields, and counts in another struct, are not used: those loads keep their guards). An access at a constant offset inside one object needs no check; an element at an index is one comparison of the index with the count, which the optimizer hoists out of loops and removes where the loop's own test implies it. - A store of a pointer into a field is compared with the field's bound (`bounds-conversion` when it does not cover it), and so are arguments of safe functions and the results they return. A count that grows alone (`n++`) is checked against the shadow. - A string is read at its current byte and stepped forward where a test showed the byte was not zero (the loop's own test in `while (*s) s++;`): no check at all. In a fast unit (RFC 0048) a step no test covers (`p += 4` after `strncmp(p, "