diff --git a/AGENTS.md b/AGENTS.md index 06de9ea..f6b1650 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,9 +156,28 @@ callee's body, and every access is compared with the answer 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: +(`index-single`, `call-args`). Since RFC 0057 a safe function reaches code +WeaveC did not compile (*foreign* code: the C library, a system library, a +unit built with `-fno-weavec`) only through a *contract*: a row of the +library table, which has one for every function and global of the covered +headers through which a pointer crosses (`scripts/check-table.py` holds it +to the platform's headers), or a declaration the program marks +`WEAVEC_FOREIGN` (with `*p` counts and `WEAVEC_FOREIGN_FIELD` for a foreign +struct's members), which the checker lowers to a row +(`lib/Frontend/SafeForeign.cpp`) so that the guards, the comparisons and +the thunks read it as they read the table; each safe unit records what it +calls with no contract, and the driver refuses a link in which no input +WeaveC compiled defines one (`foreign-call`, with the contract proposed); +the checked build watches the bytes after what a contract lets foreign code +write (`__weavec_rt_foreign_before`, `__weavec_rt_foreign_after`, +`foreign-overflow`); and the ledger and the audit list every contract and +say whether the program is `closed`. Full picture: `docs/architecture.md`. Design and the reasoning behind it: `docs/rfcs/`. -Read `0056-bounds-without-declarations.md` first (found bounds: the +Read `0057-foreign-code-by-contract.md` first (the three kinds of code, +what crosses, contracts and their rows, the checks at the call, the link's +check and the image mark, the monitor, the lists; its *Implementation +amendments* and *Measured gates*), then +`0056-bounds-without-declarations.md` (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 @@ -286,12 +305,14 @@ cmake --preset dev && cmake --build --preset dev && ctest --preset dev `-Wformat-security` and `-Wunsequenced` (and in C `-Wdeprecated-non-prototype`) are errors under Clang's own names (`test/Safe/defined.cpp`, `defined.c`), and a link's - `definition-mismatch` ends in the rule's tag. A new run-time report + `definition-mismatch` and `foreign-call` (RFC 0057, + `test/Driver/foreign-link.c`) end in the rule's tag. A new run-time report kind gets a `test/Guards/` test that pins its exact report line, and an entry in the command-line reference's list of kinds (`docs/pages/reference/cli.md`); the case runner's list of kinds (`scripts/run-cases.py`) must know it too. -3. The annotations are `WEAVEC_UNSAFE` and Safe C's (RFC 0041). Each +3. The annotations are `WEAVEC_UNSAFE`, Safe C's (RFC 0041) and the + contracts' `WEAVEC_FOREIGN` and `WEAVEC_FOREIGN_FIELD` (RFC 0057). Each spelling lives in exactly two places that must agree: `resources/include/weavec.h`, and `UnsafeAnnotation` in `include/weavec/Frontend/UnsafeRegions.h` (`annotate("weavec.unsafe")`) @@ -376,6 +397,7 @@ cmake --preset dev && cmake --build --preset dev && ctest --preset dev | 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 foreign code by contract (what crosses, `WEAVEC_FOREIGN` declarations and their rows, `*p` counts, `WEAVEC_FOREIGN_FIELD`, foreign globals, callbacks, the link's `foreign-call`, the image mark, the monitor, the table's completeness, `-fweavec-contracts`; RFC 0057) | `lib/Frontend/SafeForeign.cpp` (`crosses`, `contractsIn`, `lowerContracts`, `contractDeclaration`, `adoptContract`, `proposeContract` (evidence E10), the `...` case of `foreign-call`, `givesEnded` for a struct with a member an end bounds, `keptLocals`); `markIn`, `parameterNamed`, the `*p` checks and `storesBounded` (a member's pair stored by an initializer in a checked C++ unit) in `SafeCheck.cpp`; `lent` in `SafeTypes.cpp` and `lentByContract` in `GuardExpand.cpp` (a local lent to a contract call keeps its plain frame); `keeps` in `SafeCxxFlow.cpp` (a table row's `kept`); the unit rows in `lib/Core/LibrarySpec.cpp` (`*aN`, `aE-aS` for a bound that is an end, `handle`, `kept`, `ptr:str`, `ptr:bytes`, `ptr:of`, `global` rows) and the rows of `lib/Core/LibrarySpec.txt`; the comparisons, guards, thunks and the monitor's calls in `GuardLibrary.cpp` and `GuardSafe.cpp`; the records' `X`, `K`, `N`, `U` entries, the image mark and `checkForeignUses` in `lib/Frontend/Definitions.cpp`, `-fweavec-contracts` and the link summary in `Driver.cpp`; the ledger's `foreign`, `expects`, `uncrossed`, `unchecked` and the audit's `closed` in `EnforcementLedger.cpp`; the monitor's calls (`monitor` in `GuardLibrary.cpp`, made only at a redzone by `gateWatches` in `GuardExpand.cpp`), `__weavec_rt_foreign_before`, `__weavec_rt_foreign_after` in `runtime/weavec_guard.c` (`weavecRtHeapSlotEnd` in `weavec_alloc.c`), `weavecRtFailForeign` and the contract line in `weavec_report.c`; `scripts/check-table.py` (the hygiene gate's `table-row`); tests `test/Safe/foreign-*.c`, `cxx-foreign-call.cpp`, `test/Guards/foreign-*.c`, `foreign-member.cpp`, `ir-foreign.c`, `test/Driver/foreign-link.c`, `foreign-audit.c`, `contracts-flag.c`, cases `test/cases/foreign/`, `rt_test` `foreign-watch*`, `unittests/Core/LibrarySpecTest.cpp` (`ContractGrammar`, the contract rows); the rule's page `foreign-call`, the guide `docs/pages/guides/foreign-code.md`, `docs/pages/reference/guarantees.md` (F1)–(F4) | +| Add an annotation | Don't, without an RFC: `WEAVEC_UNSAFE`, Safe C's and RFC 0057's `WEAVEC_FOREIGN` 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/README.md b/README.md index 0f82a7e..36ceccc 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,7 @@ Other presets are `dev-asan`, `dev-tidy`, `release` and `relwithdebinfo`; see [` | Guarantees and scope | [docs/pages/reference/guarantees.md](docs/pages/reference/guarantees.md) | | Safe C | [docs/pages/guides/safe-c.md](docs/pages/guides/safe-c.md), [its rules](resources/safe/rules.md) | | Safe C++ | [docs/pages/guides/safe-cxx.md](docs/pages/guides/safe-cxx.md), [the same rules page](resources/safe/rules.md) | +| Calling code WeaveC did not compile | [docs/pages/guides/foreign-code.md](docs/pages/guides/foreign-code.md) | | Unsafe regions | [docs/pages/guides/unsafe.md](docs/pages/guides/unsafe.md) | | Architecture | [docs/architecture.md](docs/architecture.md) | | Design decisions (RFCs) | [docs/rfcs/](docs/rfcs/) | diff --git a/docs/annotations.md b/docs/annotations.md index be1f452..72b18d7 100644 --- a/docs/annotations.md +++ b/docs/annotations.md @@ -7,7 +7,7 @@ in C++, [RFC 0044](rfcs/0044-safe-cxx.md) and [its guide](pages/guides/safe-cxx.md)). `weavec-cc` puts the header on the system include path (`#include `) and defines `__WEAVEC__` to `1` in every unit it -compiles with WeaveC enabled. The header is at version 3.5 +compiles with WeaveC enabled. The header is at version 3.6 (`WEAVEC_H_VERSION_MAJOR`, `WEAVEC_H_VERSION_MINOR`): 3.0 added `WEAVEC_OWNED` and made `WEAVEC_SAFE` name the one safe tier ([RFC 0043](rfcs/0043-ownership.md)), below; 3.1 adds no macro and gives @@ -18,7 +18,10 @@ meaning in C++ ([RFC 0047](rfcs/0047-conversion-in-place.md)); 3.4 adds no macro and lets `WEAVEC_ESCAPES` follow a reference's `&` and a member function's parameter list ([RFC 0048](rfcs/0048-safe-code-without-the-shadow.md)); 3.5 adds `WEAVEC_TAGGED_BY` and `WEAVEC_WHEN`, a union's tag -([RFC 0054](rfcs/0054-one-of-several-types.md)). +([RFC 0054](rfcs/0054-one-of-several-types.md)); 3.6 adds `WEAVEC_FOREIGN` +and `WEAVEC_FOREIGN_FIELD`, the contracts of code WeaveC did not compile, +and `*p` as a count in one +([RFC 0057](rfcs/0057-foreign-code-by-contract.md), _Contracts_ below). `WEAVEC_UNSAFE` expands to `__attribute__((annotate("weavec.unsafe")))` under compilers that understand Clang's `annotate` attribute and to nothing @@ -87,6 +90,25 @@ 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, …)`. | +### Contracts + +A safe function reaches code WeaveC did not compile only through a +contract ([RFC 0057](rfcs/0057-foreign-code-by-contract.md), +[the guide](pages/guides/foreign-code.md), the rule `foreign-call`). The C +library's are the rows of the library table. A program declares the rest: + +| Form | Placement | Meaning | +| ------------------------------------------------------------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `WEAVEC_FOREIGN int f(char *WEAVEC_COUNTED_BY(n) p, size_t n);` | before a function declaration with no body | The declaration is the contract of a function no code WeaveC compiled defines: what it does with what it is given, said with the annotations of this page. Through a pointer it uses at most what the bound gives (one object with no bound; nothing through a pointer to an incomplete type or `void`), it keeps only a `WEAVEC_ESCAPES` parameter, releases only a `WEAVEC_OWNED` one, and its result has the bound and the owner its declaration states and lives as long as a `WEAVEC_LIFETIMEBOUND` parameter. Safe code may then call it, and every call, from safe and from guarded code, is checked against it. The language checks the declaration against the library's prototype, before or after it. In a unit that defines the function the mark means nothing. `bad-annotation` on a definition, on a member function, and for a function the library table has a row for. Expands to `annotate("weavec.foreign")`. | +| `WEAVEC_FOREIGN extern char *WEAVEC_NULL_TERMINATED name;` | before an `extern` variable declaration | The same for a global foreign code defines: its type's annotations are believed. | +| `WEAVEC_COUNTED_BY(*p)`, `WEAVEC_SIZED_BY(*p)` and their `_OR_NULL` forms | on a parameter of a contract | The count is the integer the parameter `p` points to when the call is made (a capacity passed by reference, which the function overwrites with a length). A null `p` is a count of zero. Only in a contract, and not on a result. | +| `WEAVEC_FOREIGN_FIELD(type, member, annotations);` | at file scope | The pointer member `member` of the struct or union `type`, which a header the program does not own defines, has `annotations` (a bound that names another member, `WEAVEC_OWNED`, `WEAVEC_BORROWED`) as if its declaration carried them: it is a member of typed memory. `bad-annotation` for a member that is not a pointer, one with an annotation of its own, a second that differs, and a contract that gives foreign code a struct with a member `WEAVEC_ENDED_BY` bounds (typed memory keeps a count beside a member's pointer, and no end). Expands to two `typedef`s that are never used (the member's type under a name, then that name with the annotations and `annotate("weavec.foreign_field", "", "")`). | + +Under a compiler that is not WeaveC, `WEAVEC_FOREIGN` expands to nothing +(the declaration is a plain redeclaration) and `WEAVEC_FOREIGN_FIELD` to an +unused `typedef`. `-fweavec-contracts=
` includes a header of +contracts in every unit of a build. + 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)): diff --git a/docs/architecture.md b/docs/architecture.md index 40117d1..18d9f71 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -581,6 +581,67 @@ 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`. +## Foreign code + +Code no input of the link that `weavec-cc` compiled defines is *foreign* +(RFC 0057): the C library, a system library, a unit built with +`-fno-weavec`. A safe function reaches it only through a *contract*, and +`lib/Frontend/SafeForeign.cpp` is where a unit's contracts are read and +its uses of foreign code are sorted. + +A contract is a row. The library table has one for every function and +global of the headers it covers through which a pointer crosses +(`scripts/check-table.py` compares it with the platform's headers, and the +hygiene gate runs it). A program declares the others: a prototype marked +`WEAVEC_FOREIGN`, with Safe C's annotations, a `*p` count where the callee +takes a capacity by reference, and `WEAVEC_FOREIGN_FIELD` for the members +of a struct a foreign header defines. `contractsIn` collects the +declarations, `adoptContract` gives every declaration of the function the +contract's types (so that it may come before or after the library's own +prototype), and `lowerContracts` writes for each the row its annotations +state (`SafeUnit::contractRows`, parsed by `core::LibrarySpec` with the +table's parser). The ownership and borrow rules read the annotations from +the AST, as for any declared function; everything that reads the table +reads the rows: the guards of a guarded caller (`GuardLibrary.cpp`), the +comparison of a safe caller's arguments with the bounds it holds +(`boundLibraryCalls`, a `pointer-out-of-bounds` whose report names the +contract), the thunk of a function whose address is taken, and the checked +build's monitor. An argument lent to a contract call (a parameter that is +not `WEAVEC_ESCAPES`) is not a reason to record a local or to give it a +guarded frame (`lent` in `SafeTypes.cpp`, `lentByContract` in +`GuardExpand.cpp`). + +For every function with no body, no row and no contract that safe code +calls or takes the address of, and every such global it names, the unit's +record (RFC 0051 §5, `weavec-defs 3`) gains an `X` entry: the symbol, the +first place, and the contract `proposeContract` writes from the prototype. +`checkForeignUses` (`lib/Frontend/Definitions.cpp`), in the driver's read +of a link's inputs, looks for an input that defines each: an object or an +archive member that carries a record, or a shared library with the image +mark `weavec-cc` gives an image it links whole from its own objects +(`__DATA,__weavec_img`, `.note.weavec`). Any other symbol is +`foreign-call`, and the linker is not run. The one case decided when a +unit compiles is a pointer passed through `...` to a function with no +format. + +In a checked safe unit, and in guarded code under verify mode, each +argument a row lets the callee write (and each a contract the program +declares says is only read, since a `const` may be wrong) is bracketed by +`__weavec_rt_foreign_before` and `__weavec_rt_foreign_after` +(`runtime/weavec_guard.c`), for a callee with no body in the unit: where +the bytes end at the end of an object the runtime laid out, the redzone +that follows gets a pattern (a global's is only remembered, and a heap +block's stops at its slot's end), and a byte changed when the call returns +is `foreign-overflow`, reported at the call with the contract's +declaration. `before` answers whether it watches and `after` takes the +answer; `gateWatches` (`GuardExpand.cpp`) makes both calls only where the +shadow of the byte after the contract's bytes is a redzone's, so a buffer +that ends inside its object costs one load. The watches are a per-thread +stack of eight, since a foreign function may call back into code that +makes a call of its own; `after` finds its watch by the pointer and the +argument, and a watch left by a call that never returned (`longjmp`, an +exception) is dropped with no report. + ## The enforcement ledger GuardInsert records each access it collected, before any rule removes its @@ -947,7 +1008,8 @@ accesses are not guarded`. When an input of the link, an object or a member of an archive, defines `malloc` strongly, `checkLinkInputs` prints a note (the same read of the -inputs compares their safe units' definitions, RFC 0051 §5): the loader binds +inputs compares their safe units' definitions, RFC 0051 §5, and looks for +the definitions of what safe code calls with no contract, RFC 0057 §7): the loader binds `malloc` to the program's definition first, so the program keeps its allocator, its heap is untracked (unless it poisons it through ASan's interface), guards pass on it, and releases are not validated. Stack and diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index 3fd53a3..6baa724 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -67,6 +67,7 @@ export default defineConfig({ item('Safe C', 'guides/safe-c'), item('Safe C++', 'guides/safe-cxx'), item('Convert C++ in place', 'guides/convert-cxx'), + item('Foreign code', 'guides/foreign-code'), ], }, { diff --git a/docs/pages/guides/foreign-code.md b/docs/pages/guides/foreign-code.md new file mode 100644 index 0000000..a9abafb --- /dev/null +++ b/docs/pages/guides/foreign-code.md @@ -0,0 +1,194 @@ +--- +title: Call code WeaveC did not compile +description: Write contracts for the libraries a safe program calls, so that every call that leaves the checked code is bounded, owned and listed. +--- + +A safe program still calls zlib, SQLite, OpenSSL, the C library and the operating system. None of that code was checked by WeaveC's rules, and most of it was not compiled by `weavec-cc` at all. This guide is about that edge: what a safe function may call, what you write so that it may, and what WeaveC checks there ([RFC 0057](/rfcs/0057-foreign-code-by-contract/)). + +## Three kinds of code + +- **Safe** code is checked when it compiles: a `WEAVEC_SAFE` function, or every function of a unit built with `-fweavec-safe` ([Safe C](/guides/safe-c/), [Safe C++](/guides/safe-cxx/)). +- **Guarded** code is anything else `weavec-cc` compiled. Every access it makes is guarded when it runs. +- **Foreign** code is code no input of the link that `weavec-cc` compiled defines: the C library, a system library, a unit built with `-fno-weavec` or by another compiler, assembly, a Rust or Go archive. + +Safe code calls safe and guarded code freely. It reaches foreign code only where something says what the foreign code does with the pointers it is given. That something is a _contract_. + +## What needs a contract + +A function needs one when a pointer _crosses_ it: a parameter or a result that is a pointer, a function pointer or an array, or a struct passed by value that holds one. A foreign global needs one when it holds a pointer. `int abs(int)` needs nothing. In C++ a reference to a complete object and a class whose kind the rules derive (an owner, a view, a value) need nothing either; a raw pointer crosses as in C. + +For the C library and the POSIX headers WeaveC covers, the contract ships with the compiler: the library table has a row for every such function and global (about a thousand), and `scripts/check-table.py` holds it to the platform's headers. `memcpy`, `fopen`, `getenv`, `qsort`, `pthread_create`, `stdout` and `environ` work in safe code with nothing from you. + +For every other library, you write the contract. + +## What happens without one + +A unit that calls a foreign function with no contract compiles: the function might be another unit's. Its summary line counts the calls (`2 calls the link must find`). The link then looks for a definition WeaveC compiled, before the linker runs, and stops when there is none: + +```text +main.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +main.c:10:24: note: called here, in 'main' +main.c:10:24: note: say what it does with what it is given: 'WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);'; or compile its library with weavec-cc; or call it from a function that is not safe +note: 'weavec-cc --weavec-explain foreign-call' explains this rule +``` + +The note names the three ways out. There is no flag that turns the rule off. + +1. **Write the contract.** The rest of this guide. +2. **Compile the library with `weavec-cc`.** Its functions are then guarded code. A shared library `weavec-cc` linked whole from its own objects carries a mark that says so, and needs no contract from the programs that load it. +3. **Call it from a function that is not safe.** Mark the caller `WEAVEC_GUARDED`. The call is unchecked, and the audit lists it with the contract it lacks. + +The contract in the note is proposed from the prototype's names and types. It is a guess about code the compiler cannot see. Read the library's documentation and correct it. + +## Writing a contract + +A contract is the function's prototype written again, marked `WEAVEC_FOREIGN`, with [Safe C's annotations](/reference/annotations/) on its pointers. Put the contracts of a library in a header of your own that includes the library's header first: the language then checks every contract against the library's prototype, so a contract cannot drift from the types. + +```c +// zlib-contracts.h +#include +#include + +WEAVEC_FOREIGN const char *WEAVEC_NULL_TERMINATED zlibVersion(void); +WEAVEC_FOREIGN uLong crc32(uLong crc, const Bytef *WEAVEC_COUNTED_BY_OR_NULL(len) buf, uInt len); +WEAVEC_FOREIGN int compress(Bytef *WEAVEC_COUNTED_BY(*destLen) dest, uLongf *destLen, + const Bytef *WEAVEC_COUNTED_BY(sourceLen) source, uLong sourceLen); +``` + +The annotations mean what they mean on a function of your program. On a contract they are promises about the library: + +| You write | The library | +| -------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `WEAVEC_COUNTED_BY(n)`, `WEAVEC_SIZED_BY(n)`, `WEAVEC_ENDED_BY(end)` | reads, and writes unless the pointee is `const`, at most that much | +| `WEAVEC_NULL_TERMINATED` | reads the string and its terminator | +| nothing, on a pointer to a complete type | uses one object of that type | +| nothing, on a pointer to an incomplete type or `void` | is given no bytes of yours: the pointer is a _handle_ | +| `WEAVEC_ESCAPES` | keeps the pointer after it returns | +| `WEAVEC_OWNED` on a parameter | releases what it is given | +| `WEAVEC_OWNED` on a result, or on the pointee of an out parameter | gives you something you must release | +| `WEAVEC_LIFETIMEBOUND` after a parameter's name | returns a pointer that lives as long as that argument is not changed or released | + +### Counts that go in and come back + +`compress` takes the capacity of `dest` through `destLen` and stores the length there. In a contract, and only in one, a count may be `*p`, where `p` is a parameter that points to an integer. The count is what `p` points to when the call is made. + +```c +#include "zlib-contracts.h" + +unsigned long pack(const unsigned char *WEAVEC_COUNTED_BY(n) in, unsigned long n) { + unsigned char out[64]; + unsigned long len = sizeof(out); + return compress(out, &len, in, n) == Z_OK ? len : 0; +} +``` + +If `len` were 4200, the program would stop at the call: + +```text +weavec: pointer-out-of-bounds at pack.c:6:10: write of 4200 bytes at 0x16d6d6f00 +weavec: 0x16d6d6f00 is 0 bytes inside the 64-byte bounds of the pointer at 0x16d6d6f00 +weavec: the contract is declared at ./zlib-contracts.h:7:20 +``` + +### Buffers a struct carries + +zlib's stream interface names its buffers in the members of `z_stream`, which is the library's struct. `WEAVEC_FOREIGN_FIELD` gives a member of a struct you do not define the annotation its declaration would carry: + +```c +WEAVEC_FOREIGN_FIELD(z_stream, next_in, WEAVEC_COUNTED_BY(avail_in)); +WEAVEC_FOREIGN_FIELD(z_stream, next_out, WEAVEC_COUNTED_BY(avail_out)); +WEAVEC_FOREIGN_FIELD(z_stream, msg, WEAVEC_NULL_TERMINATED_OR_NULL); + +WEAVEC_FOREIGN int deflateInit_(z_streamp strm, int level, const char *WEAVEC_NULL_TERMINATED version, + int stream_size); +WEAVEC_FOREIGN int deflate(z_streamp strm, int flush); +WEAVEC_FOREIGN int deflateEnd(z_streamp strm); +``` + +From there the members are [typed memory](/guides/safe-c/): a safe function stores the pointer and its count together, and a pointer loaded from the member has the member's bound. `deflate`'s contract gives the library one `z_stream`; the members say what the stream's pointers reach. A member's bound is a count: a struct with a member that `WEAVEC_ENDED_BY` bounds is not given to foreign code (`bad-annotation`), because typed memory keeps a count beside a member's pointer and no end. + +### Handles, and who releases them + +Nothing in a prototype says who owns a handle, and the proposal never guesses. This is the part of a contract that turns a use after a release into a compile error, so write it first: + +```c +struct db; +struct stmt; +WEAVEC_FOREIGN int db_prepare(struct db *db, const char *WEAVEC_NULL_TERMINATED sql, + struct stmt *WEAVEC_OWNED *out); +WEAVEC_FOREIGN const char *WEAVEC_NULL_TERMINATED_OR_NULL +db_text(struct stmt *stmt WEAVEC_LIFETIMEBOUND, int column); +WEAVEC_FOREIGN int db_finalize(struct stmt *WEAVEC_OWNED stmt); +``` + +With these, [ownership's rules](/guides/safe-c/) hold for the statement as for a block of your own: reading `db_text`'s result after `db_finalize` is `stale-borrow`, a statement that is never finalized is `owner-leak`, and a second `db_finalize` is `owner-moved`. All three are errors when the unit compiles. + +In safe C++ an owner is an object, not an annotation. Hold the handle in a `std::unique_ptr` whose deleter makes the releasing call, and mark the deleter, and the function that first takes the handle from the library, `WEAVEC_GUARDED`. Everything else uses the owner. + +### Callbacks + +A function-pointer parameter's type says the bounds of what the library will pass. The function you pass must declare the same bounds (the error, `call-args`, carries the fix that writes them), and the `void *` that travels with it is `WEAVEC_ESCAPES` when the library keeps it: + +```c +typedef void (*on_data)(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n); +WEAVEC_FOREIGN void loop_listen(struct loop *loop, on_data callback, void *WEAVEC_ESCAPES user); +``` + +A local's address passed as `user` is then `escape`: the library would keep a pointer into a frame that returns. + +### Globals + +A foreign global that holds a pointer is declared again the same way: + +```c +WEAVEC_FOREIGN extern const char *WEAVEC_NULL_TERMINATED lib_version; +``` + +### Variadic functions + +A variadic foreign function is callable when its declaration has a `format` attribute (the arguments are checked against the format, as `printf`'s are) or when no pointer passes through `...` (`open(path, flags, 0644)`). A pointer through `...` with no format is the one `foreign-call` reported when the unit compiles: no contract can say what `ioctl` does with its third argument. Make that call in a `WEAVEC_GUARDED` function. (In C, the same call of a variadic function that the program's own header declares, with no contract, is the [`variadic`](/reference/rules/#variadic) rule's error: the function may be another unit's.) + +## Giving a build its contracts + +Include the contracts' header where the library is used, or let the build do it: + +```sh +weavec-cc -fweavec-safe -fweavec-contracts=zlib-contracts.h -c pack.c +``` + +`-fweavec-contracts=
` includes the header in every C and C++ unit, after the command line's own `-include` files, and may be given more than once. A contract may come before or after the library's own prototype. + +Guarded code needs no contract and gets no error. Where a contract is in scope, its calls are guarded too: each pointer argument is tested against the shadow over the bytes the contract states, before the library runs. That makes `-fweavec-contracts` useful for code you have not converted: give an unmodified program its libraries' contracts, and a bug that passed a short buffer to the library stops at the call. + +## What is checked when the program runs + +- **At the call.** The bytes the contract lets the library use through each pointer are compared with the bound the caller holds (declared, passed, or [found](/guides/safe-c/)). A count past it stops with `pointer-out-of-bounds`, or in guarded code with the guard's own kind, and the report names the contract's declaration. +- **What comes back.** A result, a pointer stored through a parameter, and what a callback receives arrive with the bound the contract declares. Where WeaveC has a record of the memory (the library allocated it with the process's `malloc`), the declared bound is compared with the record once; where it has none (the library's static data, its own allocator), the bound is believed. +- **A wrong contract, in the checked build.** `-fweavec-safe-checks=full` watches the bytes after each buffer a contract lets the library write (and after each your own contract says it only reads), where the buffer ends its object, and stops when the call returns and they have changed: + +```text +weavec: foreign-overflow at main.c:31:10: 'lib_fill_past' wrote past the 16 bytes its contract gives argument 1, at 0x16fdff240 +weavec: the contract is declared at ./contracts.h:9:20 +``` + +Run your tests in the checked build. The fast build does not make this check. + +## Reviewing what a program rests on + +`-fweavec-summary` says what a link found: + +```text +weavec: prog: 14 objects, 14 safe; 96 types, 212 functions and 9 globals agree; 9 foreign functions by contract, 21 with nothing crossing; closed +``` + +`closed` means every call that leaves the code WeaveC compiled has a contract. `weavec-cc --weavec-audit ` begins with the same statement, then lists every declared contract with where it is written, the row it means and the number of safe and guarded callers, the library table's rows the program uses by header, and every call guarded code makes with no contract. The contracts are the program's trusted statements, as `unsafe` blocks are a Rust program's: that list is what a review reads. + +## Limits + +- A contract is trusted. Nothing proves the library does no more than it says, and the fast build does not look. A contract that gives the library less than it writes is an overflow only the checked build reports, and only where the buffer ends its object. +- What the library does inside its own memory is not checked. +- The link's check is made by `weavec-cc`. A link by another driver or by the linker directly compares nothing; the ledger then lists the calls no link checked (`expects`). +- A shared library that was not linked whole from WeaveC's objects is foreign to the programs that call it, even if some of its code was guarded. +- A member function of a foreign C++ class cannot be declared again outside its class. Where a raw pointer crosses one, call it from a function that is not safe. + +The rule's page, [`foreign-call`](/reference/rules/#foreign-call), has each form with an example that compiles; [the guarantees](/reference/guarantees/) state (F1) to (F4) and what they rest on. diff --git a/docs/pages/guides/safe-c.md b/docs/pages/guides/safe-c.md index 743626c..6e94261 100644 --- a/docs/pages/guides/safe-c.md +++ b/docs/pages/guides/safe-c.md @@ -346,31 +346,34 @@ followed by the stack and the released block's paragraph. The test is exact for Each error ends with `[weavec-safe:]`. The [rules reference](/reference/rules/) gives each one's rejected example and its rewrite; `weavec-cc --weavec-explain ` prints the same section. -| Rule | Rejects | -| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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 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 | -| `bad-annotation` | a bound that names nothing of the right type, or differs between declarations | -| `cxx` | a safe function in C++ | -| `counted-pair` | a count changed without its pointer in the adjacent statement (other than a step), or a struct initializer whose count exceeds its array | -| `string-index` | a string indexed or offset by a variable, or stepped back, before its length is known | -| `string-write` | a store through a `WEAVEC_NULL_TERMINATED` pointer, or passing it where the callee may write | -| `field-address` | the address of a pointer field leaving the function | -| `owner-moved` | an owner used after it was moved or released (a second release included), or before the `realloc` that took it was tested | -| `owner-leak` | an owner dropped while it may still hold a block: at a return, at the end of its scope, when assigned over, when its struct is released | -| `owner-source` | something other than an owner's value stored in an owner (a borrow, a literal, an address, arithmetic), and an owner stepped | -| `owner-path` | an owner moved, released or replaced through a reference, a pointer to `const` or a global read in place | -| `owner-slot` | an element or `*pp` moved out of or released without an assignment to the same place in the next statement | -| `stale-borrow` | a borrow used after the owner it was taken below was moved, released or replaced, by the function or by a call that could | -| `call-alias` | one call given a pointer it could change owners through and another argument above, below or equal to it | +| Rule | Rejects | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 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` | reading variadic arguments, a variadic call of a function the unit defines, and a pointer passed through `...` to a function the program declares with no format | +| `no-asm` | inline assembly, `setjmp`, `longjmp`, `__builtin_frame_address`, computed `goto` | +| `unsafe-block` | a `WEAVEC_UNSAFE` block inside a safe function | +| `bad-annotation` | a bound that names nothing of the right type, or differs between declarations | +| `cxx` | a safe function in C++ | +| `counted-pair` | a count changed without its pointer in the adjacent statement (other than a step), or a struct initializer whose count exceeds its array | +| `string-index` | a string indexed or offset by a variable, or stepped back, before its length is known | +| `string-write` | a store through a `WEAVEC_NULL_TERMINATED` pointer, or passing it where the callee may write | +| `field-address` | the address of a pointer field leaving the function | +| `owner-moved` | an owner used after it was moved or released (a second release included), or before the `realloc` that took it was tested | +| `owner-leak` | an owner dropped while it may still hold a block: at a return, at the end of its scope, when assigned over, when its struct is released | +| `owner-source` | something other than an owner's value stored in an owner (a borrow, a literal, an address, arithmetic), and an owner stepped | +| `owner-path` | an owner moved, released or replaced through a reference, a pointer to `const` or a global read in place | +| `owner-slot` | an element or `*pp` moved out of or released without an assignment to the same place in the next statement | +| `stale-borrow` | a borrow used after the owner it was taken below was moved, released or replaced, by the function or by a call that could | +| `call-alias` | one call given a pointer it could change owners through and another argument above, below or equal to it | +| `foreign-call` | at the link, a call of a function no code WeaveC compiled defines and no [contract](/guides/foreign-code/) describes; when the unit compiles, a pointer passed through `...` with no format | + +The last one is about the code a safe program calls and WeaveC did not compile. The C library needs nothing from you: the library table is its contract. Any other library needs a contract, a header of `WEAVEC_FOREIGN` declarations that say what each function does with what it is given; [Call code WeaveC did not compile](/guides/foreign-code/) shows how to write one. A rule never tries to prove something about the code: it rejects a construct. When code needs something the rules reject, keep that piece in a small `WEAVEC_GUARDED` helper function and call it; the helper's own accesses stay guarded, and the audit lists it. diff --git a/docs/pages/guides/safe-cxx.md b/docs/pages/guides/safe-cxx.md index 6b427b8..93df056 100644 --- a/docs/pages/guides/safe-cxx.md +++ b/docs/pages/guides/safe-cxx.md @@ -116,6 +116,7 @@ A safe unit has no behavior the language leaves undefined ([RFC 0051](/rfcs/0051 - nothing the code asserts is believed: `[[assume]]`, `__builtin_assume`, `[[gnu::pure]]` and their kin are errors ([`assumed`](/reference/rules/#assumed)), whose certain fix `--weavec-fix` applies, and `-ffast-math` and the other flags that assume are refused; - bytes do not become a `bool` or a pointer ([`pointer-bytes`](/reference/rules/#pointer-bytes)), a handler the system runs between any two instructions is registered by code that is not safe ([`signal-handler`](/reference/rules/#signal-handler)), and `-Wreturn-type`, `-Winvalid-noreturn`, `-Wformat`, `-Wformat-security` and `-Wunsequenced` are errors; - the units of a program agree: two files that each define a `struct Entry` of their own, or a header compiled with two values of a macro, do not link ([`definition-mismatch`](/reference/rules/#definition-mismatch)). Put a type one file uses in an unnamed namespace. +- the program is closed: a safe function calls code WeaveC did not compile only through a contract, a row of the library table or a `WEAVEC_FOREIGN` declaration that says what the function does with what it is given, and a call with none does not link ([`foreign-call`](/reference/rules/#foreign-call), [the guide](/guides/foreign-code/)). The C++ standard library is not foreign. ## Building blocks diff --git a/docs/pages/reference/cli.md b/docs/pages/reference/cli.md index 90acb25..86c587a 100644 --- a/docs/pages/reference/cli.md +++ b/docs/pages/reference/cli.md @@ -17,27 +17,28 @@ make CC=weavec-cc CXX=weavec-c++ ## weavec-cc -| Flag | Default | Meaning | -| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `-fweavec` / `-fno-weavec` | on | Guard memory accesses. Off compiles as plain Clang. | -| `-fweavec-checks=trap\|report\|verify\|none` | `trap` | What a failed guard does; see [check modes](#check-modes). | -| `-fweavec-zero-init` / `-fno-weavec-zero-init` | on unless checks are `none` | Zero-initialize locals of up to 4 KiB (`-ftrivial-auto-var-init=zero`; a `-ftrivial-auto-var-init-max-size` on the command line sets another limit). The runtime's allocator zero-fills every block regardless. | -| `-fweavec-asan-compat` / `-fno-weavec-asan-compat` | on | Compile and preprocess C as AddressSanitizer would for the source; see [AddressSanitizer compatibility](#addresssanitizer-compatibility). | -| `-fweavec-colors` / `-fno-weavec-colors` | on | Check an access computed from a pointer against the color of the pointer's object, so that an index or pointer that jumps over a redzone into a live neighbor traps ([guarantee (C)](/reference/guarantees/#the-guarantee)). Off, the shadow is colored all the same and only redzones stop such a jump. | -| `-fweavec-ledger=` | unset | Write the [enforcement ledger](#ledger-and-summary-line). A value ending in `/`, or naming an existing directory, receives `.ledger.json` per unit (a second object of the same name, from another directory, `..ledger.json`, RFC 0049 §7; a unit with no object, `..ledger.json`); a file receives one ledger, and naming one for an invocation that compiles several C files is an error. | -| `-fweavec-summary` / `-fno-weavec-summary` | off, on when a ledger is written | Print the unit's summary line on stderr. | -| `-fweavec-safe` / `-fno-weavec-safe` | off | Make every function the unit defines outside system headers a [safe function](/guides/safe-c/) (RFC 0041, RFC 0042, RFC 0043): checked when it is compiled against [Safe C's rules](/reference/rules/) (bounds, typed memory and ownership), and when it runs against the bounds its pointers declare, which it believes of pointers loaded from memory. Code that is not safe is trusted to keep those bounds and owners; [`--weavec-audit`](#weavec-cc) lists it. `WEAVEC_GUARDED` keeps one function guarded. Without the flag, `WEAVEC_SAFE` marks one function. The rules run under `-fweavec-checks=none` and `-fsyntax-only` too. A program that links a safe unit records no allocation stacks unless `WEAVEC_RT_HEAP_STACKS` asks. With `weavec-c++` the flag makes the unit's functions [safe C++](/guides/safe-cxx/) (RFC 0044): checked when they compile against Safe C++'s rules (moves, borrows, views, no raw memory), with their lambdas and the instantiations of the unit's templates. `WEAVEC_SAFE` and `WEAVEC_GUARDED` may also mark a class. RFC 0051: in a unit with the flag, nothing is left undefined ([the list](/reference/undefined/)): signed arithmetic wraps, shifts and conversions from floating point have one result, loops may run forever and every local is zeroed, in every function the unit emits (its library code included); in its safe functions a division by zero or of the least value by -1, unreachable code, the end of a function that must return a value, and a full stack stop with a report. `-Wreturn-type`, `-Winvalid-noreturn`, `-Wformat`, `-Wformat-security` and `-Wunsequenced` (and in C `-Wdeprecated-non-prototype`) are errors, and the flags that let the optimizer assume what the unit does not check are refused: `-ffast-math`, `-Ofast`, `-ffinite-math-only`, `-fstrict-enums`, `-fstrict-vtable-pointers`, `-ffinite-loops`, `-fstrict-overflow`, `-fno-wrapv`, `-fstrict-float-cast-overflow` and `-fno-weavec-zero-init` (`weavec-cc: error: '-ffast-math' lets the optimizer assume what a safe unit does not check (RFC 0051)`), unless a later flag takes them back. | -| `-fweavec-safe-checks=bounds\|full` | Whether safe functions' accesses are checked against their bounds only, or keep their guards as well (`full`), so that a use after free in safe code is reported as in guarded code. Without the flag a unit compiled with optimization (`-O1` and above) is in the fast mode and one without in the checked mode (RFC 0048 §1). In the fast mode (`bounds`, RFC 0045, RFC 0048) a unit compiled with `-fweavec-safe` types its allocations, and a block its safe code releases is reused at once by its own type; its safe code is checked against what it holds: in C++ an access through a reference, `this`, a pointer parameter, a pointer it loaded or a project function returned, at a constant offset inside its type, a string's current byte and the standard library's trusted functions carry no guard, its locals that only safe code reaches are in a plain frame, the container annotations are off, and a safe function's pointer result is checked not to be into its own frame. `full` is the checked mode: safe functions keep every guard, every block waits for a sweep, and a safe C++ unit compiles to the object it gives without `-fweavec-safe`. | Whether safe functions' accesses are checked against their bounds only, or keep their guards as well (`full`), so that a use after free in safe code is reported as in guarded code. No effect in a C++ unit, whose safe functions keep every guard. | -| `-fweavec-safe-bounds=found\|declared` | `found` | RFC 0056: what a pointer of a safe function with no declared bound is. `found`: it is indexed and stepped, and its bound is found when the function runs, from the runtime's records of the object it points into (a heap block, a global, a recorded local; memory with no record is one object), or passed by a safe caller that holds it; the ledger lists each such declaration. `declared`: it points to one object, and `index-single` and `call-args` reject what would need a found bound, as before RFC 0056. Any other value is an error. The two modes link together. | -| `-fweavec-safe-survey` / `-fno-weavec-safe-survey` | off | RFC 0047 §7: the rules also run over every function that is not safe, as if it were; their errors are not printed and do not fail the compile, and the ledger records them with their fixes, and the compile's command (RFC 0049 §7). `--weavec-audit` then prints the conversion's plan, and `--weavec-fix` applies the fixes. | -| `-fweavec-definitions` / `-fno-weavec-definitions` | on | RFC 0051 §5: before a link, compare what its safe units record of the types, functions and globals they share (from its objects, LTO objects included, and the members of its archives; a linked image keeps no record, so a shared library is compared when it is linked), and refuse to link two that disagree (`weavec-cc: error: 'Entry' is defined differently in two safe units [weavec-safe:definition-mismatch]`, a note for each place, and the linker is not run). With `-fweavec-summary` the link prints `weavec: : objects, safe; types, functions and globals agree`. Off, the link says `weavec-cc: note: -fno-weavec-definitions: the safe units of this link were not compared (RFC 0051)`. A link flag; compiles ignore it. | -| `-fweavec-rpath=` / `-fno-weavec-rpath` | the toolchain's `lib/weavec` | Where a linked program or library finds [the runtime's library](#the-runtime): `` (`$ORIGIN`, `@loader_path`, an installation path) instead of the toolchain's runtime directory, or no rpath at all, for a package that installs `libweavec_rt` beside the program. A `default-rpath` file in the toolchain's `lib/weavec` names the default instead (the Homebrew formula's stable path). | -| `--help-weavec` | | List the WeaveC flags and exit. | -| `--weavec-audit [--format=json] ...` | | Not a compile: what a program's safe functions trust (RFC 0042 §10, RFC 0043 §11), from its [ledgers](#ledger-and-summary-line) (files, or directories searched for `*.ledger.json`). It prints ` of functions safe`, then the functions that are not safe (`, owns` after the tier when one has a `WEAVEC_OWNED` parameter or result), the accesses of safe functions that keep a guard and why, the library calls that keep a checked wrapper, the reference fields, the shared and the erased members of C++ classes (RFC 0044 §12: a `std::shared_ptr` to an object that is not `const`, through which safe C++ may change what it does not follow; a `std::function` or another member that may hold borrows its type does not show), the global owners read in place, and what the thread rules rest on (RFC 0046 §12): the functions that are not safe and start threads or use locks, their `WEAVEC_SENDS` parameters, and the globals that code which is not safe defines and safe code names. It lists the aliased classes (RFC 0047 §8), and, when the ledgers were written with `-fweavec-safe-survey`, starts with the conversion's plan: `conversion: of functions safe (

%); more have no error`, the files ready to mark `WEAVEC_SAFE_FILE` (every function in them safe or without an error), and the blocked files with their errors by rule, fewest first. It says how many locals were placed in typed memory (RFC 0048 §9). RFC 0049 §8: the plan counts the certain and likely fixes the errors carry, lists the choices by the errors each would decide and the files whose errors have no fix, and the audit lists each bound on a member that code which is not safe can write (`unchecked`: the member is not private or its class has friends, or a member function of the class is not safe). `--format=json` writes `weavec-audit` version 8, with the keys `functions`, `placedLocals`, `safe`, `trusted`, `guarded`, `wrapped`, `references`, `shared`, `erased`, `globals`, `library`, `untyped`, `threads`, `sends`, `threadGlobals`, `aliased`, `unchecked` and `conversion` (null without a survey; else `files`, each with `file`, `functions`, `safe`, `clean`, `errors`, `unfixed`, `ready` and `places`, each error's `file`, `line`, `column`, `rule` and number of `fixes`; `fixes`, the certain and likely fixes by level; and `choices`). | -| `--weavec-fix [options] ...`, `--weavec-fix [options] -- ` | | Not a compile: RFC 0049 §6. Applies the fixes the rules' errors carry, from a survey's ledgers or, after `--`, of the command given (surveyed first, with `-fsyntax-only`). Each round writes the certain fixes and the likely ones every unit agrees on, on every declaration they are about, adding `#include ` where a file needs it; runs the rules again on the units an edit reached, from their recorded commands; takes out a likely fix that brought an error with no fix, and a round that broke a compile (its likely fixes for good, its certain ones tried again without them); and stops when a round applies nothing (`--rounds=`, 16 by default). It then marks the files left with no error `WEAVEC_SAFE_FILE` (`--no-mark` does not). `--dry-run` prints the first round as a diff and writes nothing; `--level=certain` writes no likely fix; `--only=,...` edits only files under those paths; `-j` runs that many compiles at once. It refuses a file that changed since its ledger was written, and writes nothing of that round. Beside the ledgers' directory, `weavec-fix/` holds `weavec-fix.json`, written on every exit (its `status`, each round's fixes, what was taken out and why, the `choices` left; what was taken out stays out on the next run) and `ledger/`, the units as the rules last left them, for `--weavec-audit`; neither command reads a `weavec-fix/` directory inside one it is given. | -| `--weavec-fix-bounds[=certain\|likely] [options] ...`, `... -- ` | | Not a compile: RFC 0056 §8. The fixer of `--weavec-fix`, over the found bounds of a survey's ledgers instead of the errors: it writes the declarations the evidence proposes for them (the certain ones by default, `=likely` the likely ones too), runs the rules again and repeats, and prints how many bounds were found before and after. It marks no file and ignores `--level`; `--dry-run`, `--only`, `-j` and `--rounds` are `--weavec-fix`'s. `--weavec-fix` writes no found bound. | -| `--weavec-explain [... \| all]` | | Not a compile: print each named rule's section of [the rules of Safe C and Safe C++](/reference/rules/) (what it rejects, why, a rejected example and its accepted rewrite, in C and, where the rule has one, in C++), every section for `all`, or, alone, the list of rules. `safe-cxx` is not a rule but the page that introduces Safe C++'s. The first error of a rule in a compile carries the note `'weavec-cc --weavec-explain ' explains this rule` (`weavec-c++` in a C++ unit). | -| `--weavec-symbolize [...]` | | Not a compile: the runtime's [symbolizer](#symbolization). Without an operand it answers `CODE 0x` lines on standard input as `llvm-symbolizer` does; with the paths of saved reports it prints them with the frames the runtime could name only by module and offset given their functions, files and lines. | +| Flag | Default | Meaning | +| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `-fweavec` / `-fno-weavec` | on | Guard memory accesses. Off compiles as plain Clang. | +| `-fweavec-checks=trap\|report\|verify\|none` | `trap` | What a failed guard does; see [check modes](#check-modes). | +| `-fweavec-zero-init` / `-fno-weavec-zero-init` | on unless checks are `none` | Zero-initialize locals of up to 4 KiB (`-ftrivial-auto-var-init=zero`; a `-ftrivial-auto-var-init-max-size` on the command line sets another limit). The runtime's allocator zero-fills every block regardless. | +| `-fweavec-asan-compat` / `-fno-weavec-asan-compat` | on | Compile and preprocess C as AddressSanitizer would for the source; see [AddressSanitizer compatibility](#addresssanitizer-compatibility). | +| `-fweavec-colors` / `-fno-weavec-colors` | on | Check an access computed from a pointer against the color of the pointer's object, so that an index or pointer that jumps over a redzone into a live neighbor traps ([guarantee (C)](/reference/guarantees/#the-guarantee)). Off, the shadow is colored all the same and only redzones stop such a jump. | +| `-fweavec-ledger=` | unset | Write the [enforcement ledger](#ledger-and-summary-line). A value ending in `/`, or naming an existing directory, receives `.ledger.json` per unit (a second object of the same name, from another directory, `..ledger.json`, RFC 0049 §7; a unit with no object, `..ledger.json`); a file receives one ledger, and naming one for an invocation that compiles several C files is an error. | +| `-fweavec-summary` / `-fno-weavec-summary` | off, on when a ledger is written | Print the unit's summary line on stderr. | +| `-fweavec-safe` / `-fno-weavec-safe` | off | Make every function the unit defines outside system headers a [safe function](/guides/safe-c/) (RFC 0041, RFC 0042, RFC 0043): checked when it is compiled against [Safe C's rules](/reference/rules/) (bounds, typed memory and ownership), and when it runs against the bounds its pointers declare, which it believes of pointers loaded from memory. Code that is not safe is trusted to keep those bounds and owners; [`--weavec-audit`](#weavec-cc) lists it. `WEAVEC_GUARDED` keeps one function guarded. Without the flag, `WEAVEC_SAFE` marks one function. The rules run under `-fweavec-checks=none` and `-fsyntax-only` too. A program that links a safe unit records no allocation stacks unless `WEAVEC_RT_HEAP_STACKS` asks. With `weavec-c++` the flag makes the unit's functions [safe C++](/guides/safe-cxx/) (RFC 0044): checked when they compile against Safe C++'s rules (moves, borrows, views, no raw memory), with their lambdas and the instantiations of the unit's templates. `WEAVEC_SAFE` and `WEAVEC_GUARDED` may also mark a class. RFC 0051: in a unit with the flag, nothing is left undefined ([the list](/reference/undefined/)): signed arithmetic wraps, shifts and conversions from floating point have one result, loops may run forever and every local is zeroed, in every function the unit emits (its library code included); in its safe functions a division by zero or of the least value by -1, unreachable code, the end of a function that must return a value, and a full stack stop with a report. `-Wreturn-type`, `-Winvalid-noreturn`, `-Wformat`, `-Wformat-security` and `-Wunsequenced` (and in C `-Wdeprecated-non-prototype`) are errors, and the flags that let the optimizer assume what the unit does not check are refused: `-ffast-math`, `-Ofast`, `-ffinite-math-only`, `-fstrict-enums`, `-fstrict-vtable-pointers`, `-ffinite-loops`, `-fstrict-overflow`, `-fno-wrapv`, `-fstrict-float-cast-overflow` and `-fno-weavec-zero-init` (`weavec-cc: error: '-ffast-math' lets the optimizer assume what a safe unit does not check (RFC 0051)`), unless a later flag takes them back. | +| `-fweavec-safe-checks=bounds\|full` | Whether safe functions' accesses are checked against their bounds only, or keep their guards as well (`full`), so that a use after free in safe code is reported as in guarded code. Without the flag a unit compiled with optimization (`-O1` and above) is in the fast mode and one without in the checked mode (RFC 0048 §1). In the fast mode (`bounds`, RFC 0045, RFC 0048) a unit compiled with `-fweavec-safe` types its allocations, and a block its safe code releases is reused at once by its own type; its safe code is checked against what it holds: in C++ an access through a reference, `this`, a pointer parameter, a pointer it loaded or a project function returned, at a constant offset inside its type, a string's current byte and the standard library's trusted functions carry no guard, its locals that only safe code reaches are in a plain frame, the container annotations are off, and a safe function's pointer result is checked not to be into its own frame. `full` is the checked mode: safe functions keep every guard, every block waits for a sweep, and a safe C++ unit compiles to the object it gives without `-fweavec-safe`. | Whether safe functions' accesses are checked against their bounds only, or keep their guards as well (`full`), so that a use after free in safe code is reported as in guarded code. No effect in a C++ unit, whose safe functions keep every guard. | +| `-fweavec-safe-bounds=found\|declared` | `found` | RFC 0056: what a pointer of a safe function with no declared bound is. `found`: it is indexed and stepped, and its bound is found when the function runs, from the runtime's records of the object it points into (a heap block, a global, a recorded local; memory with no record is one object), or passed by a safe caller that holds it; the ledger lists each such declaration. `declared`: it points to one object, and `index-single` and `call-args` reject what would need a found bound, as before RFC 0056. Any other value is an error. The two modes link together. | +| `-fweavec-contracts=
` | | RFC 0057 §3.1: include `
` in every C and C++ unit of the command, after its own `-include` files. The header holds a program's [contracts](/guides/foreign-code/): the `WEAVEC_FOREIGN` declarations that say what the functions of a library WeaveC did not compile do with what they are given. Safe code may then call them, and every call of one, from safe and from guarded code, is checked against its contract. May be given more than once. An assembly or preprocessed input is left alone; a header that is not found is Clang's error. | +| `-fweavec-safe-survey` / `-fno-weavec-safe-survey` | off | RFC 0047 §7: the rules also run over every function that is not safe, as if it were; their errors are not printed and do not fail the compile, and the ledger records them with their fixes, and the compile's command (RFC 0049 §7). `--weavec-audit` then prints the conversion's plan, and `--weavec-fix` applies the fixes. | +| `-fweavec-definitions` / `-fno-weavec-definitions` | on | RFC 0051 §5: before a link, compare what its safe units record of the types, functions and globals they share (from its objects, LTO objects included, and the members of its archives; a linked image keeps no record, so a shared library is compared when it is linked), and refuse to link two that disagree (`weavec-cc: error: 'Entry' is defined differently in two safe units [weavec-safe:definition-mismatch]`, a note for each place, and the linker is not run). With `-fweavec-summary` the link prints `weavec: : objects, safe; types, functions and globals agree; foreign functions by contract, with nothing crossing; closed`. RFC 0057 §4: the same pass looks, for every function a safe unit calls with no contract and every such global it names, for an input WeaveC compiled that defines it (an object, an archive's member, named or found by `-l` in the command's own `-L` directories, a shared library `weavec-cc` linked whole from its own objects), and refuses to link one that has none (`main.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call]`, with the call and the contract proposed for it). `closed` says every call that leaves the code WeaveC compiled has a contract; without it the line ends with the number of foreign functions guarded code calls with none. `-fno-weavec-definitions` does not turn this check off: nothing does. Off, the link says `weavec-cc: note: -fno-weavec-definitions: the safe units of this link were not compared (RFC 0051)`. A link flag; compiles ignore it. | +| `-fweavec-rpath=` / `-fno-weavec-rpath` | the toolchain's `lib/weavec` | Where a linked program or library finds [the runtime's library](#the-runtime): `` (`$ORIGIN`, `@loader_path`, an installation path) instead of the toolchain's runtime directory, or no rpath at all, for a package that installs `libweavec_rt` beside the program. A `default-rpath` file in the toolchain's `lib/weavec` names the default instead (the Homebrew formula's stable path). | +| `--help-weavec` | | List the WeaveC flags and exit. | +| `--weavec-audit [--format=json] ...` | | Not a compile: what a program's safe functions trust (RFC 0042 §10, RFC 0043 §11), from its [ledgers](#ledger-and-summary-line) (files, or directories searched for `*.ledger.json`). RFC 0057 §9 (`weavec-audit` version 12): its first line says whether the program is closed, `closed: every call that leaves the code WeaveC compiled has a contract ( declared, of the table)`, or what is missing (`not closed: …`: the foreign functions guarded code calls with no contract, and the functions safe code uses with none that no unit of the ledgers defines). After the guarded functions it lists the contracts (each declared one with where it is written, the row it means and its safe and guarded callers; then the library table's rows the program uses, counted by header), the foreign calls with no contract from code that is not safe, each with the contract proposed, and what safe code uses with no contract. It prints ` of functions safe`, then the functions that are not safe (`, owns` after the tier when one has a `WEAVEC_OWNED` parameter or result), the accesses of safe functions that keep a guard and why, the library calls that keep a checked wrapper, the reference fields, the shared and the erased members of C++ classes (RFC 0044 §12: a `std::shared_ptr` to an object that is not `const`, through which safe C++ may change what it does not follow; a `std::function` or another member that may hold borrows its type does not show), the global owners read in place, and what the thread rules rest on (RFC 0046 §12): the functions that are not safe and start threads or use locks, their `WEAVEC_SENDS` parameters, and the globals that code which is not safe defines and safe code names. It lists the aliased classes (RFC 0047 §8), and, when the ledgers were written with `-fweavec-safe-survey`, starts with the conversion's plan: `conversion: of functions safe (

%); more have no error`, the files ready to mark `WEAVEC_SAFE_FILE` (every function in them safe or without an error), and the blocked files with their errors by rule, fewest first. It says how many locals were placed in typed memory (RFC 0048 §9). RFC 0049 §8: the plan counts the certain and likely fixes the errors carry, lists the choices by the errors each would decide and the files whose errors have no fix, and the audit lists each bound on a member that code which is not safe can write (`unchecked`: the member is not private or its class has friends, or a member function of the class is not safe). `--format=json` writes `weavec-audit` version 8, with the keys `functions`, `placedLocals`, `safe`, `trusted`, `guarded`, `wrapped`, `references`, `shared`, `erased`, `globals`, `library`, `untyped`, `threads`, `sends`, `threadGlobals`, `aliased`, `unchecked` and `conversion` (null without a survey; else `files`, each with `file`, `functions`, `safe`, `clean`, `errors`, `unfixed`, `ready` and `places`, each error's `file`, `line`, `column`, `rule` and number of `fixes`; `fixes`, the certain and likely fixes by level; and `choices`). | +| `--weavec-fix [options] ...`, `--weavec-fix [options] -- ` | | Not a compile: RFC 0049 §6. Applies the fixes the rules' errors carry, from a survey's ledgers or, after `--`, of the command given (surveyed first, with `-fsyntax-only`). Each round writes the certain fixes and the likely ones every unit agrees on, on every declaration they are about, adding `#include ` where a file needs it; runs the rules again on the units an edit reached, from their recorded commands; takes out a likely fix that brought an error with no fix, and a round that broke a compile (its likely fixes for good, its certain ones tried again without them); and stops when a round applies nothing (`--rounds=`, 16 by default). It then marks the files left with no error `WEAVEC_SAFE_FILE` (`--no-mark` does not). `--dry-run` prints the first round as a diff and writes nothing; `--level=certain` writes no likely fix; `--only=,...` edits only files under those paths; `-j` runs that many compiles at once. It refuses a file that changed since its ledger was written, and writes nothing of that round. Beside the ledgers' directory, `weavec-fix/` holds `weavec-fix.json`, written on every exit (its `status`, each round's fixes, what was taken out and why, the `choices` left; what was taken out stays out on the next run) and `ledger/`, the units as the rules last left them, for `--weavec-audit`; neither command reads a `weavec-fix/` directory inside one it is given. | +| `--weavec-fix-bounds[=certain\|likely] [options] ...`, `... -- ` | | Not a compile: RFC 0056 §8. The fixer of `--weavec-fix`, over the found bounds of a survey's ledgers instead of the errors: it writes the declarations the evidence proposes for them (the certain ones by default, `=likely` the likely ones too), runs the rules again and repeats, and prints how many bounds were found before and after. It marks no file and ignores `--level`; `--dry-run`, `--only`, `-j` and `--rounds` are `--weavec-fix`'s. `--weavec-fix` writes no found bound. | +| `--weavec-explain [... \| all]` | | Not a compile: print each named rule's section of [the rules of Safe C and Safe C++](/reference/rules/) (what it rejects, why, a rejected example and its accepted rewrite, in C and, where the rule has one, in C++), every section for `all`, or, alone, the list of rules. `safe-cxx` is not a rule but the page that introduces Safe C++'s. The first error of a rule in a compile carries the note `'weavec-cc --weavec-explain ' explains this rule` (`weavec-c++` in a C++ unit). | +| `--weavec-symbolize [...]` | | Not a compile: the runtime's [symbolizer](#symbolization). Without an operand it answers `CODE 0x` lines on standard input as `llvm-symbolizer` does; with the paths of saved reports it prints them with the frames the runtime could name only by module and offset given their functions, files and lines. | An unknown `-fweavec-*` flag is an error. Every other flag is Clang's. When WeaveC is on, the driver defines `__WEAVEC__=1` and puts the directory of `weavec.h` on the system include path. `weavec-cc --version` prints Clang's version block first, then `weavec-cc version ()`, the LLVM it was built with, and the runtime's interface version and the platform (`runtime ABI 46, for arm64-apple-darwin…`), so a configure script that reads the first line sees Clang. Clang's headers and builtins are those of the toolchain (`lib/clang/` beside `bin/`). Assembly sources (`.s`, `.S`) and `-save-temps` compiles are assembled by the system assembler (`as`), since Clang's integrated assembler is not part of `weavec-cc`. On macOS a link with `-flto` uses the libLTO of the LLVM `weavec-cc` is built with, which the toolchain carries as `lib/libLTO.dylib`. Response files (`@file`) are expanded first, as Clang's driver does. C++ and Objective-C compiles get every Clang action but the static analyzer, the rewriters and plug-ins. @@ -94,38 +95,39 @@ weavec: summary: heap-buffer-overflow at vec.c:9:43 in get (thread T0) The kinds are: -| Kind | The access | Object paragraph | -| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `heap-buffer-overflow` | reaches the bytes after a heap object in its slot, or, computed from a pointer, another heap object of another color | `… is bytes after the -byte heap object at …, allocated by thread T:` and the allocation's stack; for another object, first `… is bytes after its base …, in another object`, then the paragraph of the object the access landed in | -| `heap-use-after-free` | reaches a released heap block; or a [safe function](/guides/safe-c/#references) loads a reference to one from a field (RFC 0043 §7), in every check mode: `weavec: heap-use-after-free at cache.c:12:41: reference to 0x… loaded from a field` | `… is bytes inside the -byte heap block at …, released by thread T:` and the release's stack, then `weavec: the block was allocated by thread T:` and the allocation's stack | -| `stack-buffer-overflow` | reaches a redzone of a local | `… is bytes after 'buf' (8 bytes at offset 64) in the frame of (thread T), whose locals are:` (or `before`), then one `[64, 72) 'buf'` line per tracked local of the frame | -| `dynamic-stack-buffer-overflow` | reaches the redzone of an `alloca` block or a variable-length array | | -| `stack-use-after-scope` | reaches a local whose block has ended | as for `stack-buffer-overflow`, with `… is bytes inside 'n' (4 bytes at offset 64), whose scope has ended, in the frame of …` | -| `stack-use-after-return` | reaches a local of a function that returned, before another frame reused its bytes | `… is in a frame that returned`: the report's own frames usually overwrite the returned frame's record of its locals, so the local is named only when the frame lay deeper than the report's | -| `container-overflow` | reaches a `std::vector`'s or `std::deque`'s storage past its elements (RFC 0039 §5; `WEAVEC_RT_CONTAINERS=0` turns the check off) | `… is bytes past the elements of a container in the -byte heap object at …` and the object's allocation stack | -| `library-assertion` | a check of the C++ library failed (its hardening mode or its assertions): `weavec: library-assertion at vec.cpp:9:10: libc++ Hardening assertion __n < size() failed: vector[] index out of bounds`; it stops the program in every mode | | -| `pointer-out-of-bounds` | an access of a [safe function](/guides/safe-c/) outside the bounds of the pointer it is computed from (RFC 0041 §4) | `… is bytes after the -byte bounds of the pointer at …` (or `before`, `inside`) | -| `stack-escape` | a safe function's `WEAVEC_ESCAPES` parameter points into the calling thread's stack (RFC 0041 §5): `weavec: stack-escape at list.c:12: access at 0x…`; or a fast safe C++ function's result points into its own frame (RFC 0045): `weavec: stack-escape at f.cpp:7:3: result of 'worst()' points into its own frame at 0x…` | | -| `bounds-conversion` | a [safe function](/guides/safe-c/#what-runs) stores, passes or returns a pointer whose bounds do not cover what its destination declares (RFC 0042 §6): `weavec: bounds-conversion at vec.c:12:10: needs 20 bytes at 0x…` | `… is bytes inside the -byte bounds of the pointer at …` | -| `global-buffer-overflow` | reaches the redzone of a global the unit defines | `… is bytes after the -byte global 'table' defined at :` (`` alone when the unit was compiled without `-g`); a static local is named `.` | -| `intra-object-overflow` | a fortified call writes past the size of the field or object its `_chk` form names | `… is bytes inside the -byte destination at …` | -| `use-after-poison` | reaches bytes the program poisoned through ASan's interface | the paragraph of the heap block, global or local the bytes are in | -| `null-dereference` | is through a null pointer, or reaches the lowest 64 KiB | | -| `unterminated-string` | a string argument of a library call has no terminator in its object (a search that found nothing read up to one), or a safe function converts a buffer with no zero byte in its bounds to a string | | -| `overlapping-copy` | the operands of `memcpy` or another call that requires disjoint operands overlap | | -| `index-out-of-bounds` | an index into an array whose bound the type declares is outside it: `weavec: index-out-of-bounds at lookup.c:8:12: index -1` | | -| `invalid-access` | is to bytes that are not addressable, of no kind the runtime can name | | -| `memory-fault` | faulted where the shadow saw nothing to stop (a wild address, the inaccessible part of a huge block): `weavec: memory-fault at pc 0x…: read at 0x…`, after which the program dies of the signal as it would have (`WEAVEC_RT_FAULTS=0` reports nothing) | the heap paragraph, for a heap address; the stack starts at the faulting instruction and the summary line names its location | -| `double-free` | a release of a heap block that was already released: `weavec: double-free at cases.c:7:48: free of 0x…` | `… is the -byte heap block at …, released by thread T:` and the first release's stack, then the allocation's | -| `invalid-free` | a release of an address no live block starts at: `: free of 0x…: inside the 8-byte heap block at 0x…`, `: no block was allocated there`, or `: not heap memory` (a global, a local, memory the runtime does not track) | the paragraph of the heap block, global or local the address is in | -| `alloc-release-mismatch` | a release by another form than the allocation's (`: operator delete of 0x…: allocated by operator new[]`), or a sized `delete` of another size (`: operator delete of 0x…: size 16 for a 48-byte block`) | `… is the -byte heap object at …, allocated by thread T:` and the allocation's stack | -| `unreachable` | a [safe function](/guides/safe-c/) reached code its source says cannot be reached (`std::unreachable()`, `__builtin_unreachable()`): `weavec: unreachable at ub8.cpp:21:3: reached code the program says cannot be reached` (RFC 0051) | -| `missing-return` | a safe function that must return a value reached its end: `weavec: missing-return at step.cpp:12:8: the function ended without returning a value` (RFC 0051) | -| `division-by-zero` | a safe function divided by zero, or took a remainder by it: `weavec: division-by-zero at quot.c:4:61: division by zero` (RFC 0051) | -| `division-overflow` | a safe function divided the least value of a signed type by -1: `weavec: division-overflow at quot.c:4:61: the least 32-bit integer divided by -1` (RFC 0051) | -| `bad-cast` | a safe function's checked conversion found no object of the target type at the address (a `void *` to a struct, a struct to one that begins with it, `container_of`, a C++ downcast or `static_cast` from `void *`): `weavec: bad-cast at shape.c:9:12: 0x7ff3a0 is not a 'struct circle'`, then the paragraph of what is there, which names its type (RFC 0054) | -| `union-member` | a safe function used a tagged union's member while its tag said another: `weavec: union-member at value.c:14:12: 'text' read while 'kind' is 0` (RFC 0054) | -| `stack-exhaustion` | a thread's stack is full (a safe function's frame is probed page by page, so the fault is at the guard below the stack), reported from the thread's alternate signal stack: `weavec: stack-exhaustion at deep.cpp:31: thread T1's stack of 512 KiB is full` (RFC 0051) | +| Kind | The access | Object paragraph | +| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `heap-buffer-overflow` | reaches the bytes after a heap object in its slot, or, computed from a pointer, another heap object of another color | `… is bytes after the -byte heap object at …, allocated by thread T:` and the allocation's stack; for another object, first `… is bytes after its base …, in another object`, then the paragraph of the object the access landed in | +| `heap-use-after-free` | reaches a released heap block; or a [safe function](/guides/safe-c/#references) loads a reference to one from a field (RFC 0043 §7), in every check mode: `weavec: heap-use-after-free at cache.c:12:41: reference to 0x… loaded from a field` | `… is bytes inside the -byte heap block at …, released by thread T:` and the release's stack, then `weavec: the block was allocated by thread T:` and the allocation's stack | +| `stack-buffer-overflow` | reaches a redzone of a local | `… is bytes after 'buf' (8 bytes at offset 64) in the frame of (thread T), whose locals are:` (or `before`), then one `[64, 72) 'buf'` line per tracked local of the frame | +| `dynamic-stack-buffer-overflow` | reaches the redzone of an `alloca` block or a variable-length array | | +| `stack-use-after-scope` | reaches a local whose block has ended | as for `stack-buffer-overflow`, with `… is bytes inside 'n' (4 bytes at offset 64), whose scope has ended, in the frame of …` | +| `stack-use-after-return` | reaches a local of a function that returned, before another frame reused its bytes | `… is in a frame that returned`: the report's own frames usually overwrite the returned frame's record of its locals, so the local is named only when the frame lay deeper than the report's | +| `container-overflow` | reaches a `std::vector`'s or `std::deque`'s storage past its elements (RFC 0039 §5; `WEAVEC_RT_CONTAINERS=0` turns the check off) | `… is bytes past the elements of a container in the -byte heap object at …` and the object's allocation stack | +| `library-assertion` | a check of the C++ library failed (its hardening mode or its assertions): `weavec: library-assertion at vec.cpp:9:10: libc++ Hardening assertion __n < size() failed: vector[] index out of bounds`; it stops the program in every mode | | +| `pointer-out-of-bounds` | an access of a [safe function](/guides/safe-c/) outside the bounds of the pointer it is computed from (RFC 0041 §4) | `… is bytes after the -byte bounds of the pointer at …` (or `before`, `inside`) | +| `stack-escape` | a safe function's `WEAVEC_ESCAPES` parameter points into the calling thread's stack (RFC 0041 §5): `weavec: stack-escape at list.c:12: access at 0x…`; or a fast safe C++ function's result points into its own frame (RFC 0045): `weavec: stack-escape at f.cpp:7:3: result of 'worst()' points into its own frame at 0x…` | | +| `bounds-conversion` | a [safe function](/guides/safe-c/#what-runs) stores, passes or returns a pointer whose bounds do not cover what its destination declares (RFC 0042 §6): `weavec: bounds-conversion at vec.c:12:10: needs 20 bytes at 0x…` | `… is bytes inside the -byte bounds of the pointer at …` | +| `global-buffer-overflow` | reaches the redzone of a global the unit defines | `… is bytes after the -byte global 'table' defined at :` (`` alone when the unit was compiled without `-g`); a static local is named `.` | +| `intra-object-overflow` | a fortified call writes past the size of the field or object its `_chk` form names | `… is bytes inside the -byte destination at …` | +| `use-after-poison` | reaches bytes the program poisoned through ASan's interface | the paragraph of the heap block, global or local the bytes are in | +| `null-dereference` | is through a null pointer, or reaches the lowest 64 KiB | | +| `unterminated-string` | a string argument of a library call has no terminator in its object (a search that found nothing read up to one), or a safe function converts a buffer with no zero byte in its bounds to a string | | +| `overlapping-copy` | the operands of `memcpy` or another call that requires disjoint operands overlap | | +| `index-out-of-bounds` | an index into an array whose bound the type declares is outside it: `weavec: index-out-of-bounds at lookup.c:8:12: index -1` | | +| `invalid-access` | is to bytes that are not addressable, of no kind the runtime can name | | +| `memory-fault` | faulted where the shadow saw nothing to stop (a wild address, the inaccessible part of a huge block): `weavec: memory-fault at pc 0x…: read at 0x…`, after which the program dies of the signal as it would have (`WEAVEC_RT_FAULTS=0` reports nothing) | the heap paragraph, for a heap address; the stack starts at the faulting instruction and the summary line names its location | +| `double-free` | a release of a heap block that was already released: `weavec: double-free at cases.c:7:48: free of 0x…` | `… is the -byte heap block at …, released by thread T:` and the first release's stack, then the allocation's | +| `invalid-free` | a release of an address no live block starts at: `: free of 0x…: inside the 8-byte heap block at 0x…`, `: no block was allocated there`, or `: not heap memory` (a global, a local, memory the runtime does not track) | the paragraph of the heap block, global or local the address is in | +| `alloc-release-mismatch` | a release by another form than the allocation's (`: operator delete of 0x…: allocated by operator new[]`), or a sized `delete` of another size (`: operator delete of 0x…: size 16 for a 48-byte block`) | `… is the -byte heap object at …, allocated by thread T:` and the allocation's stack | +| `unreachable` | a [safe function](/guides/safe-c/) reached code its source says cannot be reached (`std::unreachable()`, `__builtin_unreachable()`): `weavec: unreachable at ub8.cpp:21:3: reached code the program says cannot be reached` (RFC 0051) | +| `missing-return` | a safe function that must return a value reached its end: `weavec: missing-return at step.cpp:12:8: the function ended without returning a value` (RFC 0051) | +| `division-by-zero` | a safe function divided by zero, or took a remainder by it: `weavec: division-by-zero at quot.c:4:61: division by zero` (RFC 0051) | +| `division-overflow` | a safe function divided the least value of a signed type by -1: `weavec: division-overflow at quot.c:4:61: the least 32-bit integer divided by -1` (RFC 0051) | +| `bad-cast` | a safe function's checked conversion found no object of the target type at the address (a `void *` to a struct, a struct to one that begins with it, `container_of`, a C++ downcast or `static_cast` from `void *`): `weavec: bad-cast at shape.c:9:12: 0x7ff3a0 is not a 'struct circle'`, then the paragraph of what is there, which names its type (RFC 0054) | +| `union-member` | a safe function used a tagged union's member while its tag said another: `weavec: union-member at value.c:14:12: 'text' read while 'kind' is 0` (RFC 0054) | +| `foreign-overflow` | a function WeaveC did not compile wrote past what its contract gives an argument, found when the call returned (the checked build, `-fweavec-safe-checks=full`, and guarded code under `-fweavec-checks=verify`): `weavec: foreign-overflow at main.c:31:10: 'lib_fill_past' wrote past the 16 bytes its contract gives argument 1, at 0x16fdff240`, then the paragraph of the object the bytes follow and `weavec: the contract is declared at contracts.h:9:20` (or `is a row of the library table`) (RFC 0057) | +| `stack-exhaustion` | a thread's stack is full (a safe function's frame is probed page by page, so the fault is at the guard below the stack), reported from the thread's alternate signal stack: `weavec: stack-exhaustion at deep.cpp:31: thread T1's stack of 512 KiB is full` (RFC 0051) | ### Bad releases @@ -172,19 +174,20 @@ It prints the logs with each such frame rewritten and the rest of their lines as `WEAVEC_RT_REPORT_FORMAT=json` writes each report as one line of JSON instead of text, to the report log or stderr; the case runner and the corpus gate read reports this way. Its fields: -| Field | Meaning | -| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `weavec` | The schema's version, the runtime's ABI (52). | -| `kind` | The report's kind, as in the kinds table. | -| `proven` | `true` for a `weavec.proven` report of verify mode. | -| `site` | `{"file", "line", "column"}`: the location of the first line (`file` is `null` when it is ``; `column` is 0 when the location has none). | -| `what` | The first line's text after the location (`read of 4 bytes at 0x…`, `index -1`, `free of 0x…: not heap memory`). | -| `access` | `{"op", "width", "address"}`: `op` is `read`, `write` or `access`, or for a bad release its form (`free`, `realloc`, `operator delete`, `operator delete[]`, with `width` 0). Absent for `library-assertion` and `index-out-of-bounds`. | -| `message` | The C++ library's message, for `library-assertion`. | -| `thread` | `{"id"}`: the thread's number, `0` for the main thread. | -| `stack` | The access's frames, innermost first, each `{"pc", "module", "offset", "function", "file", "line", "column", "inlined"}`; addresses and offsets are hexadecimal strings, `file` is `null` and `line` 0 when the frame has no line, and `inlined` marks a frame inlined into the next. | -| `bounds` | For a `pointer-out-of-bounds` report whose bound was found (RFC 0056): `{"low", "high", "found": "record" \| "released" \| "no-record", "declaration"}`, the bound's addresses (hexadecimal strings), where it came from, and the declaration that has no bound. | -| `object` | Absent, or the object paragraph: `{"memory": "heap", "base", "size", "state": "live" \| "released", "released": [frames] \| null, "allocated": [frames] \| null}`; `{"memory": "stack", "function", "name", "locals": [{"name", "offset", "size"}]}`; `{"memory": "global", "name", "location", "base", "size"}`; or, for `intra-object-overflow`, `{"memory": "destination", "base", "size"}`. | +| Field | Meaning | +| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `weavec` | The schema's version, the runtime's ABI (53). | +| `kind` | The report's kind, as in the kinds table. | +| `proven` | `true` for a `weavec.proven` report of verify mode. | +| `site` | `{"file", "line", "column"}`: the location of the first line (`file` is `null` when it is ``; `column` is 0 when the location has none). | +| `what` | The first line's text after the location (`read of 4 bytes at 0x…`, `index -1`, `free of 0x…: not heap memory`). | +| `access` | `{"op", "width", "address"}`: `op` is `read`, `write` or `access`, or for a bad release its form (`free`, `realloc`, `operator delete`, `operator delete[]`, with `width` 0). Absent for `library-assertion` and `index-out-of-bounds`. | +| `message` | The C++ library's message, for `library-assertion`. | +| `thread` | `{"id"}`: the thread's number, `0` for the main thread. | +| `stack` | The access's frames, innermost first, each `{"pc", "module", "offset", "function", "file", "line", "column", "inlined"}`; addresses and offsets are hexadecimal strings, `file` is `null` and `line` 0 when the frame has no line, and `inlined` marks a frame inlined into the next. | +| `bounds` | For a `pointer-out-of-bounds` report whose bound was found (RFC 0056): `{"low", "high", "found": "record" \| "released" \| "no-record", "declaration"}`, the bound's addresses (hexadecimal strings), where it came from, and the declaration that has no bound. | +| `contract` | For a report at a call of a function with a declared contract (RFC 0057): `{"file", "line", "column"}`, where the contract is declared. | +| `object` | Absent, or the object paragraph: `{"memory": "heap", "base", "size", "state": "live" \| "released", "released": [frames] \| null, "allocated": [frames] \| null}`; `{"memory": "stack", "function", "name", "locals": [{"name", "offset", "size"}]}`; `{"memory": "global", "name", "location", "base", "size"}`; or, for `intra-object-overflow`, `{"memory": "destination", "base", "size"}`. | ```json {"weavec":46,"kind":"heap-use-after-free","proven":false,"site":{"file":"uaf.c","line":6,"column":56},"what":"read of 1 bytes at 0xba80000000","access":{"op":"read","width":1,"address":"0xba80000000"},"thread":{"id":0},"stack":[{"pc":"0x1021e05f3","module":"/src/uaf","offset":"0x5f3","function":"use","file":"/src/uaf.c","line":6,"column":0,"inlined":false},…],"object":{"memory":"heap","base":"0xba80000000","size":24,"state":"released","released":[…],"allocated":[…]}} @@ -264,7 +267,7 @@ The counters are not synchronized between threads. ## Ledger and summary line -The enforcement ledger records what the guard passes decided for each access of a unit. It is JSON, `weavec-ledger` version 16: +The enforcement ledger records what the guard passes decided for each access of a unit. It is JSON, `weavec-ledger` version 17: ```json { @@ -328,6 +331,8 @@ weavec: lookup.c: 3 accesses: 1 proven, 2 guarded, 0 unguarded A unit with safe functions adds their count and its pointer fields': `…, 0 unguarded; 7 of 9 functions safe; 4 owner and 2 reference fields`; one whose safe functions find bounds ends with their declarations' count: `…; 12 bounds found`. Its `found` list (version 16, RFC 0056 §8) has an entry for each declaration with no bound that a safe function indexes: `declaration` (the key the fixes name), `name`, `of` (the function or class it belongs to), `kind` (`parameter`, `member`, `result`, `global`, `local`), `file`, `line`, `column`, the `functions` that need it, the `places` that do, the `rules` that would reject it under `-fweavec-safe-bounds=declared`, and the `fixes` the planner proposes. The summary's `foundBounds` counts the entries and `boundQuestions` the questions the unit's code asks. Under `-fweavec-safe-survey` the functions that are not safe are listed too. `--weavec-audit` (version 11) prints the list, the declaration most functions need first, with its proposal. In a C++ unit the `functions` list names each function by its qualified name, and the `fields` list has each member of the unit's classes that owns (`owner`: an object with a destructor to run), refers (`reference`: a raw pointer), borrows (`borrowed`: a reference, a view, a `WEAVEC_BORROWED` pointer), shares (`shared`) or erases (`erased`); version 7 added the last two kinds (RFC 0044 §12). Version 9 (RFC 0046 §12) adds to each function `starts` (the thread starts it makes), `locks` (whether it uses a lock or a guard object) and `sends` (whether a parameter is `WEAVEC_SENDS`); to `fields`, the kinds `lock`, `locked` (a member the class's lock guards) and `thread` (a member that holds a thread), a row with `kind` `class` and no field for each class the unit defines, with `sendable` and `shareable`, and `thread-global` (`record` a safe function, `field` a global that code which is not safe defines and the function names). A unit with locked classes or thread starts adds `; locked classes, thread starts` to its summary line. Version 10 (RFC 0047 §8) adds to `fields` the kinds `counted` (a pointer member with a bound, tested where safe code loads it, as a reference is) and `aliased` (a `WEAVEC_ALIASED` class, no field), and, under `-fweavec-safe-survey`, to each function that is not safe `survey`, its errors by rule. Version 12 (RFC 0049 §7) records every rule error of the unit, printed or surveyed, as `errors` (each with `rule`, `file`, `line`, `column`, `message`, the function or global whose code has it as `owner`, `ownerFile`, `ownerLine` and `global`, `surveyed`, the declarations the rule read as `subjects`, and `fixes`: each a `level` (`certain`, `likely`, `choice`), a `declaration`, a `name`, an `aspect` and a `fact`, the `text` to write, a likely fix's `evidence`, and `edits`, each a `file`, an `offset`, the `text` inserted there and `needsInclude`); `evidence`, what the unit's uses say of declarations other units want; and under the survey the compile's `command` (`directory`, `arguments`, `cxx`) and the project's `files` it read (`path`, `size`, `hash`). A function that is not safe and was surveyed has `surveyed: true` in place of version 11's `survey` counts, and the unit's `surveyGlobals` is gone: both are counts of `errors`. A unit that does not reach code generation (`-fsyntax-only`, or an error) still writes a ledger of the checker's part, with `partial: true`, named after its source and a hash of its path in a directory. +RFC 0057 §9 (version 17): each unit also lists what it reaches outside itself. `foreign` has an entry for each function with a contract the unit calls, and each such global it names: `function`, `contract` (`table` for a row of the library table, `declared` for a `WEAVEC_FOREIGN` declaration), where it is declared (`file`, `line`, `column`), the `row` a declared contract means, and `safeCalls` and `guardedCalls`. `expects` lists what the unit's safe code uses with no contract, which the link must find compiled by WeaveC: `function`, `symbol`, `use` (`call`, `address` or `global`), the first place (`file`, `line`, `column`, `caller`), the number of `places`, and the `proposal`, the contract the compiler would write from the prototype. `unchecked` lists the same for calls from functions that are not safe of functions with no body, no row and no contract through which a pointer crosses, and `uncrossed` the functions with no body that safe code calls and through which nothing crosses. `defines` lists the symbols of the globals the unit defines that other units can name; the audit finds another unit's `expects` among them and among the units' functions. A unit with `expects` ends its summary line with their count: `…; 2 calls the link must find`. + In a Makefile, pass a directory so parallel compiles write separate files: ```sh diff --git a/docs/pages/reference/guarantees.md b/docs/pages/reference/guarantees.md index bd59c97..ddaca55 100644 --- a/docs/pages/reference/guarantees.md +++ b/docs/pages/reference/guarantees.md @@ -184,6 +184,24 @@ A found bound is the extent of the object, not the length the program means: an Memory with no record (another allocator's, a mapping, a library's static buffer, a frame of code WeaveC did not compile) is one object, not believed. In the fast build a stale pointer has the bound of what lives at its address now ((Y2)); the checked build stops it. +## Foreign code + +Code is _foreign_ when no object, archive member or shared library of the link that `weavec-cc` compiled defines it: the C library, a system library, a unit built with `-fno-weavec`, assembly, another language's archive. A _contract_ says what a foreign function does with the pointers it is given: a row of the library table, or a declaration the program marks `WEAVEC_FOREIGN` ([RFC 0057](/rfcs/0057-foreign-code-by-contract/), [the guide](/guides/foreign-code/), the rule [`foreign-call`](/reference/rules/#foreign-call)). For a program that meets F-A1 and F-A2, in both builds unless said: + +- **(F1) A closed edge.** A safe function calls, takes the address of, or names a global of foreign code only where a contract says what crosses, or where no pointer crosses (no parameter or result is or holds a pointer, a function pointer or an array). Otherwise the link fails with `foreign-call`; a pointer passed through `...` to a foreign function with no format is the same error when the unit compiles (in C, `variadic` where the program's own header declares the function with no contract). No flag turns it off. +- **(F2) In bounds at the call.** Before a call of a function with a contract, the bytes the contract lets the callee read or write through each pointer argument lie inside the bound a safe caller holds for it (declared, passed or found, (B1)) or, in a guarded caller, inside addressable memory of the shadow ((A)). Outside it the program stops at the call (`pointer-out-of-bounds`, or the guard's kind), and the report names the contract. A function with a contract whose address is taken is reached through a thunk that makes the guarded caller's checks. +- **(F3) The rules cross the call.** An owner given to a `WEAVEC_OWNED` parameter of a contract is moved, an owned result or one stored through a pointer to an owner is an owner, a result bound to a parameter (`WEAVEC_LIFETIMEBOUND`) is a borrow of the argument, and a local's address is not given directly to a parameter the callee keeps (`WEAVEC_ESCAPES`, a table row's `kept`; a local that reaches one through a pointer variable or a safe function's own `WEAVEC_ESCAPES` parameter is a placed local, whose slot foreign code may still hold after its scope): (O1) to (O3) and (X1) to (X3) hold for a library's handles as for the program's own objects. A member of a foreign struct with a `WEAVEC_FOREIGN_FIELD` is a member of typed memory ((V1)). +- **(F4) A wrong contract, in the checked build.** Where a contract lets foreign code write through an argument (or a contract the program declares says an argument is only read) and the argument's bytes end at the end of an object WeaveC allocated or laid out (a heap block, a local of a guarded frame, a registered global), and the callee writes into the bytes that follow it, the checked build (`-fweavec-safe-checks=full`; guarded code under `-fweavec-checks=verify`) stops with `foreign-overflow` when the call returns. The fast build does not look. + +A pointer foreign code returns, stores through a parameter or passes to a callback has the bound its contract declares. Where the runtime has a record of the memory, the declared bound is compared with it once, where the pointer arrives; where it has none (the library's static data, its own allocator, a mapping), the declared bound is believed (F-A1). With no declared bound, (B1) stands: one object where there is no record. + +| | Assumption | +| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **F-A1** | Foreign code does no more with what it is given than its contract says: it reads and writes inside the bounds, keeps and releases only what the contract lets it, and what it returns is what the contract declares. Nothing proves a contract; (F4) tests the writes it can see. `weavec-cc --weavec-audit` lists every declared contract with its callers, and the rows of the library table the program uses: the list is the program's trusted statements. | +| **F-A2** | `weavec-cc` links the image. A link by another driver, or by the linker directly, compares nothing: the units' ledgers then list the calls no link checked (`expects`), and the audit says the program is not closed unless a unit of its ledgers defines each. A shared library is WeaveC's only when `weavec-cc` linked it whole from objects it compiled (it carries a mark); any other is foreign to the images that call it. | + +Not caught: what foreign code reads past its contract; what it writes past it inside the same object, into memory with no record, or in the fast build; a pointer into a foreign allocator's block that the library released, unless the contract binds it to a handle; a function pointer that arrives from foreign code, which is believed to be a function of its type; a foreign function through which no pointer passes that reaches memory by other means; threads foreign code starts. Guarded code needs no contract: its calls of a foreign function with none are unchecked, as before, and the audit lists each (`unchecked`) with the contract it lacks. + ## Threads A safe C++ function is also checked against the rules of threads ([RFC 0046](/rfcs/0046-thread-safety/), [the guide](/guides/safe-cxx/#threads)), in both builds; nothing at run time stands behind them. For a program that meets Z-A1 to Z-A5: @@ -252,7 +270,7 @@ The runtime's allocator also serves the C library's own allocations (`strdup`, ` - **Hidden pointers.** A pointer the program stores only in a form the sweep does not recognize (XOR-linked, transformed, written to a file, held only by the kernel) does not keep its block from reuse (A6); a use of the block through it after a sweep reuses the block is not caught. - **The program's own poisoning of a local or a global at a constant offset.** An access to a local or a global at a constant offset inside it needs no guard, so it is not checked against bytes the program poisoned there; accesses at a computed offset are. - **Untracked memory.** Memory from another allocator (unless the program poisons it through ASan's interface), `mmap`, string literals, and objects of code built without WeaveC have no redzones; an access into them passes (A1). A write into a string literal passes its guard (the hardware usually faults on it). `WEAVEC_RT_STATS=1` prints, at exit, how many MiB of writable memory the runtime does not track. -- **Functions outside the library table** are not checked at the call, nor is a library function found with `dlsym`, nor a library's own use of a buffer the program freed (`setvbuf`); their own accesses are guarded only if `weavec-cc` built them (A2). +- **Functions with no contract, called from code that is not safe,** are not checked at the call: a function outside the library table for which no `WEAVEC_FOREIGN` declaration is in scope ((F2) checks the calls a contract covers, and (F1) keeps safe code from making any other). Nor is a library function found with `dlsym`, nor a library's own use of a buffer the program freed (`setvbuf`); their own accesses are guarded only if `weavec-cc` built them (A2). - **`memcpy` and `memset` past a field** inside its struct: code that copies over consecutive fields on purpose is common and correct in practice. - **Uninitialized pointers** in memory other than locals and the runtime's heap (which are zero) point anywhere; accesses through them are guarded, and one into untracked memory passes. - **Data races.** A release by another thread between a guard and its access is not caught (A3). @@ -262,17 +280,17 @@ The runtime's allocator also serves the C library's own allocations (`strdup`, ` ## Assumptions -| | Assumption | -| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **A1** | An access to bytes the runtime does not track (memory from another allocator that the program does not poison through ASan's interface, `mmap`, string literals, code built without WeaveC) is to a live object it stays inside. | -| **A2** | A function in the library table accesses only what its row says. A function outside it is not checked at the call. A search on a string with no terminator in its object that never stops reads past the object, as the C library does, before the check after the call reports it (or faults). | -| **A3** | No other thread releases memory between a guard and its access: the guard and the access are not atomic together. | -| **A4** | The program does not write the runtime's shadow or metadata except through guarded accesses. | -| **A5** | A frame left by `longjmp`, `pthread_exit` or another call that does not return leaves no poison behind: the stack's shadow below the caller is cleared before the call. A frame left by an exception is marked returned when the exception is caught or reaches a cleanup in guarded code. | -| **A6** | A pointer to a heap block is kept, while the program may still use it, as a whole aligned pointer in memory the sweep scans (any readable mapping but code and shared files the program cannot write through) or in a register. One kept only in memory the program made inaccessible, in device memory or as a transformed integer does not keep its block. | -| **A7** | On Linux every thread accepts the sweep's signal within a second (`pthread_sigmask` and `sigprocmask` never block it). A thread that blocks it by other means holds up the reuse of released memory (nothing is reused until it accepts), never safety. | -| **A8** | A pointer the function did not compute (a parameter, a loaded value, a call's result) points into the object it is meant to: (C) checks arithmetic from it, not the pointer itself. | -| **A9** | Every unit that instantiates a standard container and changes its size is compiled with the same container annotations (`weavec-c++`, or ASan); `WEAVEC_RT_CONTAINERS=0` turns (K) off for a program that links one that is not. | +| | Assumption | +| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **A1** | An access to bytes the runtime does not track (memory from another allocator that the program does not poison through ASan's interface, `mmap`, string literals, code built without WeaveC) is to a live object it stays inside. | +| **A2** | A function in the library table accesses only what its row says, and one with a declared contract only what the contract says (F-A1). A function with neither is not checked at the call. A search on a string with no terminator in its object that never stops reads past the object, as the C library does, before the check after the call reports it (or faults). | +| **A3** | No other thread releases memory between a guard and its access: the guard and the access are not atomic together. | +| **A4** | The program does not write the runtime's shadow or metadata except through guarded accesses. | +| **A5** | A frame left by `longjmp`, `pthread_exit` or another call that does not return leaves no poison behind: the stack's shadow below the caller is cleared before the call. A frame left by an exception is marked returned when the exception is caught or reaches a cleanup in guarded code. | +| **A6** | A pointer to a heap block is kept, while the program may still use it, as a whole aligned pointer in memory the sweep scans (any readable mapping but code and shared files the program cannot write through) or in a register. One kept only in memory the program made inaccessible, in device memory or as a transformed integer does not keep its block. | +| **A7** | On Linux every thread accepts the sweep's signal within a second (`pthread_sigmask` and `sigprocmask` never block it). A thread that blocks it by other means holds up the reuse of released memory (nothing is reused until it accepts), never safety. | +| **A8** | A pointer the function did not compute (a parameter, a loaded value, a call's result) points into the object it is meant to: (C) checks arithmetic from it, not the pointer itself. | +| **A9** | Every unit that instantiates a standard container and changes its size is compiled with the same container annotations (`weavec-c++`, or ASan); `WEAVEC_RT_CONTAINERS=0` turns (K) off for a program that links one that is not. | Outside safe functions, no guard is removed because of what another function does, so nothing is assumed about callers, callees or the rest of the heap. The rules that remove guards are local to a function (an access inside a local or global at a known offset, an access a dominating guard on the same pointer covered with nothing between that may free, guards merged in a block, a loop whose whole range was found addressable before it ran), and `-fweavec-checks=verify` monitors them: it keeps every removed guard as a monitor that reports `weavec.proven` if it would have failed. diff --git a/docs/rfcs/0057-foreign-code-by-contract.md b/docs/rfcs/0057-foreign-code-by-contract.md new file mode 100644 index 0000000..dcd69aa --- /dev/null +++ b/docs/rfcs/0057-foreign-code-by-contract.md @@ -0,0 +1,1302 @@ +# RFC 0057: Foreign code by contract + +- **Status**: Accepted +- **Authors**: WeaveC authors +- **Created**: 2026-12-05 +- **Tracking issue**: TBD +- **Supersedes / superseded by**: Amends [RFC 0041](0041-safe-c.md) and + [RFC 0044](0044-safe-cxx.md) (what a safe function may call), + [RFC 0035](0035-guard-by-default.md) §2.5 (a call of a function with a + contract is guarded as a call of a table row is), + [RFC 0051](0051-nothing-undefined.md) §5 (the link's records gain two + kinds and every enforcing unit carries one), + [RFC 0056](0056-bounds-without-declarations.md) §5 (a library call's + comparison is made for a contract too) and + [RFC 0049](0049-errors-that-carry-their-fix.md) §3 (evidence for a + proposed contract). Guarded code that calls no function with a contract, + the rules of ownership, borrows and threads, and what a declared bound + means are unchanged. + +## Summary + +A program is safe functions, guarded functions, and code WeaveC never +compiled: the system's libraries, a vendor's archive, the other language in +the process. Every guarantee WeaveC gives is about the first two. The third +is where a rewritten program spends its time (a database, a compressor, a +TLS library, the operating system), and today a safe function calls it with +nothing said and nothing checked. + +On today's main, a C program whose every function is safe passes an 8-byte +local to the system's `compress` with a length of 4,200. zlib writes 4,107 +bytes over the stack. There is no error when it compiles, no report when +it runs, the exit status is 0, and the audit prints `every function is +safe`. The same call from safe C++ writes 946 bytes over an 8-byte +`std::vector` in the fast build and in the checked one. Rust does not +compile either program: a call of a foreign function is `unsafe`, and the +safe wrapper a crate puts around it takes a slice. + +This RFC makes the edge of the program part of the guarantee: + +- **Foreign code is a third kind of code.** A function no input of the link + that WeaveC compiled defines is _foreign_. The link decides it, exactly, + from the records the units already carry. +- **A safe function reaches foreign code only through a contract** + (`foreign-call`). A contract is a row of the library table, which is + what WeaveC ships for the C library, or a declaration the program writes: + the function's own prototype, marked `WEAVEC_FOREIGN`, with the + annotations safe code already uses for its own functions. A call through + which no pointer passes needs none. +- **The compiler checks every call against the contract**, in safe code and + in guarded code: the bytes the contract lets the callee read or write lie + inside what the caller holds, compared before the call. Ownership, + borrows and kept addresses follow the contract's annotations through the + rules that exist, so that a statement used after `sqlite3_finalize` is a + compile error. +- **A wrong contract is found in the checked build**, where the bytes after + each object the callee may write are tested when the call returns + (`foreign-overflow`). +- **The audit states the program's edge**: every foreign function, its + contract and who calls it, and one line that says whether the program is + _closed_ (no call leaves the code WeaveC compiled without a contract). + +A Rust project gets this by writing, or depending on, a wrapper crate of +`unsafe` code for each C library. A WeaveC project gets it from a header of +declarations that the compiler checks every call against. Calling C +libraries with no binding layer is the reason to rewrite into C or C++ +rather than Rust; today it is where the guarantee ends, and this RFC makes +it where WeaveC asks less than Rust and checks more. + +## Motivation + +### Where the guarantee stops today + +Probes on main at `528733cb` (darwin-arm64, the dev compiler; sources in +`build/rfc57/s0/`). Every function of every program is safe, and each +compiles with no error. + +| Program | Foreign code | What happens | +| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| C: `compress(out, &n, in, 4096)`, `unsigned char out[8]`, `n = 4200` | the system's zlib | 4,107 bytes written over an 8-byte local. No report, exit 0, fast and checked. | +| C++: the same, `std::vector out(8)` | the system's zlib | 946 bytes written over an 8-byte heap block. No report, fast and checked. | +| C: `text = sqlite3_column_text(st, 0); sqlite3_finalize(st); text[0]` | the system's sqlite3 | Reads the released row and prints a byte: fast, checked and guarded. | +| C: `adler32(1, in, 4096)`, `in` of 256 bytes, with `adler32` redeclared `const unsigned char *WEAVEC_COUNTED_BY(len) buf` | the system's zlib | 3,840 bytes read past the local in the fast, the checked and the guarded build. The declared bound is not compared at the call. | +| C: `lib_fill(c, buf, 64)`, `char buf[16]`; `lib_on_event(c, on_event, &app)` (the library keeps `&app`, a local) | a library compiled with `-fno-weavec` | The overflow is silent and keeping the local's address is no error. Then the library's correct callback `cb(user, "bye", 3)` stops: `pointer-out-of-bounds`, no record. | +| The same program, the library compiled by `weavec-cc` | none: the library is guarded | `stack-buffer-overflow` in `lib_fill`, at the write. This case is right today. | + +For each of these `weavec-cc --weavec-audit` prints `nothing undefined: +every function is safe`, and its list of `functions that are not safe (safe +code trusts them)` is empty: a function with no body in any ledger is not +listed at all. + +The guarantees page says as much under what is not caught: _functions +outside the library table are not checked at the call_ and _objects of code +built without WeaveC have no redzones; an access into them passes_. That +was a fair limit for a compiler that guards unmodified code. It is not one +for a language whose claim is that a program that compiles is safe: the +bug in the first row is the oldest one in C, it is in the safe function, +and nothing looks at it. + +### What a rewrite is made of + +The trial programs RFCs 0044 to 0056 measured (two JSON ports, an +interpreter, a key-value server, an LRU cache) call the C library and +nothing else, and the fifteen surveyed projects were chosen to build with +no dependency. A codebase someone would pay to have rewritten is not like +that. Of the corpus's larger projects, libpng cannot be built without +zlib, libssh2 not without a cryptography library, and curl, libgit2 and +libarchive are built against both wherever they are packaged. An agent +that rewrites a service out of Python or Go needs a database client, a +compressor and TLS before it needs a second kind of borrow. + +### What Rust does with the same calls + +Rust makes the crossing visible and puts the checking on the Rust side. A +foreign function is declared in an `extern` block; calling it is `unsafe`; +the ecosystem's answer is a `-sys` crate of declarations and a wrapper +crate whose safe functions take slices and owned handles and contain the +`unsafe` calls. The compiler checks none of the wrapper's claims: that +`dest.len()` is what the C function writes at most is a line a person +wrote. What Rust guarantees is that the claims are in one place, that +every call goes through them, and that the count of `unsafe` blocks says +how much to review. + +WeaveC has no such place. It has half of the mechanism twice over. + +### What WeaveC already has + +**The library table.** `lib/Core/LibrarySpec.txt` has about 800 rows: for +each C library function, what it reads and writes through each pointer in +terms of its arguments, what it releases and what it returns owned. The +guards read +it (RFC 0035 §2.5), the ownership rules read it (RFC 0043 §2) and safe +code's library calls are compared against it (RFC 0050 §5.1, RFC 0056 §5). +A row is a contract. The table is closed: a project cannot add one. + +**The annotations.** With hand-written redeclarations of four sqlite3 +functions (`build/rfc57/s0/system/q2.c`): + +```c +int sqlite3_prepare_v2(sqlite3 *db, const char *WEAVEC_NULL_TERMINATED sql, int n, + sqlite3_stmt *WEAVEC_OWNED *stmt, const char **tail); +int sqlite3_finalize(sqlite3_stmt *WEAVEC_OWNED stmt); +const unsigned char *WEAVEC_NULL_TERMINATED_OR_NULL +sqlite3_column_text(sqlite3_stmt *stmt WEAVEC_LIFETIMEBOUND, int col); +``` + +today's checker rejects, with no change to it, a text read after +`sqlite3_finalize` (`stale-borrow`), a second `sqlite3_finalize` +(`owner-moved`) and a return that leaves the statement open (`owner-leak`). +These are the errors a Rust wrapper's types give, from three declarations. +What is missing is that nothing asks for the declarations, nothing compares +a count they declare (the fourth row of the table above), and nothing lists +them. + +### How much it asks + +The ten C projects of the survey call 148 distinct functions they do not +define (`build/rfc57/s0/rows/`: undefined symbols of their objects against +the table's names). 98 have a row. Of the 50 that have none, through 36 no +pointer passes (the `` and `` functions, `close`, +`socket`, `clock`), 12 take or return a pointer (`fclose`, `pclose`, +`tmpfile`, `dlclose`, `dlerror`, `freeaddrinfo`, `gai_strerror`, +`localeconv`, `atexit`, `setjmp`, `longjmp`, `__srget`), and 2 are variadic +(`fcntl`, `ioctl`). For code that calls only the C library, this RFC is a +few hundred rows WeaveC writes once (§4.3). What it asks of a project is a +contract for each foreign library the project chose to call, which is what +Rust asks, in a form the compiler reads. + +### Why this, of what is left + +- **The thread rules** on correct programs (51 `lock-held` errors in the + trial key-value server as written) cost an agent minutes. They reject too + much; they do not accept a memory error. +- **The open holes of the last rounds** (RFC 0056 G7, RFC 0053 G4) are + narrow constructs an adversary writes. A wrong length at a library call + is what every C program has. +- **The rules existing code still fails** (`union-pointer` 1,892, `escape` + 772, `pointer-cast` 527 on the fifteen projects) decide how much of an + old program is safe. This decides what _safe_ means once it is. +- **Cost.** The fast build of new safe code is 0.98 to 1.28 of Clang's + since RFC 0055. + +## Soundness + +### What is guaranteed that was not + +For a program that meets the assumptions of the guarantees page and that +`weavec-cc` links, in both builds: + +- **(F1) A closed edge.** A safe function calls, takes the address of, or + names a global of code that no input WeaveC compiled defines only where + a contract says what crosses, or where no pointer crosses. Otherwise the + link fails with `foreign-call`. +- **(F2) In bounds at the call.** Before a call of a function with a + contract, from safe code and from guarded code, the bytes the contract + lets the callee read or write through each pointer argument lie inside + the bound the caller holds for it (declared, passed or found) or, in + guarded code, inside addressable memory of the shadow. Outside it the + program stops at the call. +- **(F3) The rules cross the call.** An owner given to a `WEAVEC_OWNED` + parameter of a contract is moved, an owned result is an owner, a result + bound to a parameter is a borrow of the argument, and a pointer given to + a parameter that is not `WEAVEC_ESCAPES` is not a local's address the + callee may keep: the errors of RFC 0043 and RFC 0052 hold for foreign + handles as for the program's own. +- **(F4) A wrong contract, in the checked build.** Where a contract lets + foreign code write an object WeaveC allocated or laid out, and the callee + writes past that object's end, the checked build reports + `foreign-overflow` when the call returns. + +### What it rests on + +- **The contracts are trusted.** A contract is a statement about code the + compiler cannot see. (F2) and (F3) hold if foreign code does no more with + what it is given than its contract says (F-A1). The audit lists every + contract and its callers: that list is the program's `unsafe`. +- **Foreign code is correct inside itself** (A2, unchanged): what it does + to its own memory is not WeaveC's to check. +- **`weavec-cc` links the image** (F-A2). A link by another driver compares + nothing; the ledger then lists the calls no link checked. +- **A shared library that `weavec-cc` did not link whole from WeaveC's + objects is foreign** to the images that call it (§7.3). + +### Bugs caught + +Each compiles today and runs to the end. Under this RFC the first two do +not link without a contract, and with it they stop or fail to compile where +marked. + +```c +#include +#include +WEAVEC_FOREIGN int compress(unsigned char *WEAVEC_COUNTED_BY(*destLen) dest, + unsigned long *destLen, + const unsigned char *WEAVEC_COUNTED_BY(sourceLen) source, + unsigned long sourceLen); + +WEAVEC_SAFE int pack(const unsigned char *in, unsigned long n) { + unsigned char out[8]; + unsigned long len = 4200; + return compress(out, &len, in, n); /* stops: 4200 bytes of an 8-byte local */ +} +``` + +```c +#include +#include +WEAVEC_FOREIGN int sqlite3_finalize(sqlite3_stmt *WEAVEC_OWNED stmt); +WEAVEC_FOREIGN const unsigned char *WEAVEC_NULL_TERMINATED_OR_NULL +sqlite3_column_text(sqlite3_stmt *stmt WEAVEC_LIFETIMEBOUND, int col); + +WEAVEC_SAFE int first(sqlite3_stmt *WEAVEC_OWNED st) { + const unsigned char *text = sqlite3_column_text(st, 0); + sqlite3_finalize(st); + return text ? text[0] : 0; /* error: stale-borrow */ +} +``` + +```c +struct ctx; +struct app { int events; }; +void on_event(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n); +WEAVEC_FOREIGN void lib_on_event(struct ctx *c, + void (*cb)(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n), + void *WEAVEC_ESCAPES user); + +WEAVEC_SAFE void listen(struct ctx *c) { + struct app app = {0}; + lib_on_event(c, on_event, &app); /* error: escape (a local's address is kept) */ +} +``` + +And one that is correct and stops today: the callback `on_event`, declared +with the bound the contract's function-pointer type states, reads the +library's `"bye"` with no stop (§6). + +### Bugs deliberately not caught + +- **A wrong contract in the fast build.** A contract that gives the callee + more than the function takes is a false stop; one that gives it less than + the function writes is an overflow the fast build does not see. (F4) is + the checked build's. +- **What foreign code reads** past its contract, and what it writes past + its contract inside the same object or into an object WeaveC did not lay + out. +- **A pointer into foreign memory that foreign code released.** Where the + library's blocks come from the runtime's allocator the checked build + stops the use; where the library has an allocator of its own (the third + row of the motivation's table) only a contract that binds the result to a + handle makes it an error, and only when it compiles. +- **A function pointer that arrives from foreign code** (a field of a + library's struct, the result of `dlsym`) is believed to be a function of + its type, as any pointer loaded from memory is believed (RFC 0048). +- **A foreign function through which no pointer passes** that reaches + memory by other means (an integer that names a mapping). +- **Threads foreign code starts.** A callback run on a thread of the + library's is the thread rules' question (RFC 0046), not this RFC's. +- **Code that is not safe** calling foreign code with no contract, as + before. It is listed. + +### Accepted stops and errors + +- **A correct program that calls a foreign library with no contract no + longer links.** This is the point, and the cost: §14's G3 and G4 measure + it. +- **A contract stricter than its function** stops a correct call. The + report names the contract's declaration; the fix is there. +- **Guarded code gains stops.** Unmodified code that includes a contract + header is guarded at the calls the contract covers. A bug that ran + silently stops. + +### What gets weaker + +Nothing. Every call this RFC checks is unchecked today. + +## Detailed design + +### 1. Three kinds of code + +- **Safe**: a function the rules checked (RFC 0041, RFC 0044). +- **Guarded**: a function `weavec-cc` compiled with enforcement that is not + safe. Every access it makes is guarded. +- **Foreign**: a function or a global that no object, archive member or + shared library among the link's inputs that WeaveC compiled defines. + The C library is foreign. So is a unit compiled with `-fno-weavec`, an + assembly file, and another language's archive. + +Guarded code is unchanged by this RFC except in §5.2. A function of a +third-party library whose body is in the unit (an inline function of a +header, a template) is safe or guarded as RFC 0044 says; it is not foreign. + +### 2. What crosses + +A pointer _crosses_ a call or a global when the callee, or the code that +owns the global, may use memory the caller names or hand back memory the +caller will use. Something crosses a declaration when any of these is, or +holds at any depth: + +- a parameter or a result of pointer type, function-pointer type or array + type, or a struct or union passed or returned by value that has such a + member; +- a variadic argument list (decided for each call, §3.6); +- for a global, a pointer type, or an aggregate with a pointer member. + +In C++, a reference to a complete object type, and a class type whose kind +RFC 0044 derives (an owner, a view, a value), do not need a contract: the +type says its bound and its kind, and RFC 0052's reach is read from it. A +raw pointer in a C++ signature crosses as it does in C. + +A declaration through which nothing crosses needs no contract. A foreign +function called this way is listed (§9). + +### 3. A contract + +#### 3.1 The declaration + +A contract is a declaration of the foreign function, with no body, marked +`WEAVEC_FOREIGN`, written by the program in a header of its own after the +library's header: + +```c +#include +WEAVEC_FOREIGN unsigned long adler32(unsigned long adler, + const unsigned char *WEAVEC_COUNTED_BY_OR_NULL(len) buf, + unsigned int len); +``` + +The language checks it against the library's prototype (C's compatible +types, C++'s redeclaration), so a contract cannot drift from the header's +types. A unit sees a contract by including its header; the driver's +`-fweavec-contracts=

` includes one in every unit (an `-include` +after the command line's own). + +`WEAVEC_FOREIGN` on a declaration says: + +- **(C1) Access.** Through a pointer parameter the callee reads, and + writes where the pointee is not `const`, at most the bytes its bound + gives: the count of a `WEAVEC_COUNTED_BY`, `WEAVEC_SIZED_BY` or + `WEAVEC_ENDED_BY`, the string of a `WEAVEC_NULL_TERMINATED`, one object + of the pointee type with no annotation. A pointer to an incomplete type + or to `void` with no bound is a _handle_: the callee is given no bytes + of the caller's through it. +- **(C2) Keeping.** The callee keeps no pointer it is given past its + return unless the parameter is `WEAVEC_ESCAPES`. +- **(C3) Owning.** The callee releases only what a `WEAVEC_OWNED` parameter + gives it, and the caller owns only a `WEAVEC_OWNED` result or what the + callee stores through a pointer to an owner + (`sqlite3_stmt *WEAVEC_OWNED *stmt`). +- **(C4) Results.** A pointer result, and a pointer the callee stores + through a parameter, has the bound its declaration states and points to + memory that is live at least until a parameter it is bound to + (`WEAVEC_LIFETIMEBOUND`) is changed, moved or released. +- **(C5) Nothing else.** The callee does not start a thread that uses what + it was given unless a parameter is `WEAVEC_SENDS` (C++), and does not + unwind or leave by a jump unless its row says so (`exits`, `unwinds`). + +These are the meanings the annotations have on a function of the program. +No annotation is new but the mark. + +#### 3.2 A count the callee is given by reference + +Many C functions take a capacity through a pointer and store the length +back (`compress`, `recvfrom`, `getsockname`, `EVP_EncryptUpdate`). In a +contract a count may be `*p`, where `p` is a parameter of the declaration +that points to an integer: + +```c +WEAVEC_FOREIGN int compress(unsigned char *WEAVEC_COUNTED_BY(*destLen) dest, + unsigned long *destLen, /* ... */); +``` + +The count is the integer `p` points to when the call is made, read once +before the call. What the callee stores there afterwards is the program's +to use as it would any integer. A null `p` is a count of zero. `*p` is +accepted only in a declaration with no body; a function of the program +takes its count by value. + +#### 3.3 Members of a foreign struct + +A library's struct whose members are a pointer and its count (`z_stream`'s +`next_out` and `avail_out`, `struct iovec`, `uv_buf_t`) carries buffers no +parameter names. Its definition is the library's. A contract states the +bound of a member: + +```c +WEAVEC_FOREIGN_FIELD(z_stream, next_in, WEAVEC_COUNTED_BY(avail_in)); +WEAVEC_FOREIGN_FIELD(z_stream, next_out, WEAVEC_COUNTED_BY(avail_out)); +WEAVEC_FOREIGN_FIELD(struct iovec, iov_base, WEAVEC_SIZED_BY(iov_len)); +``` + +From there the member is one of typed memory (RFC 0042): the checker reads +the annotation as if the field's declaration carried it +(`annotateFields`), a safe function's store of the pointer and of its count +is the checked pair (`counted-pair`), and a pointer loaded from the member +has the member's bound. A contract that takes the struct (`deflate(z_streamp +strm, int flush)`) gives the callee one object, and typed memory says what +the object's pointers reach. Foreign code that writes the members is +believed to keep the pair, as code that is not safe is today (T-A1). + +`WEAVEC_OWNED`, `WEAVEC_BORROWED` and the bounds are accepted. A field that +has an annotation in its own declaration, or two contracts for one field +that differ, is `bad-annotation`. + +#### 3.4 Globals + +A foreign global through which a pointer crosses (`environ`, `optarg`, a +library's table of names) has a contract of the same form: + +```c +WEAVEC_FOREIGN extern char *WEAVEC_NULL_TERMINATED_OR_NULL optarg; +``` + +A safe function that names one with no contract is `foreign-call`. The +audit's list of globals of code that is not safe (RFC 0046) says which are +foreign. + +#### 3.5 Callbacks + +A function-pointer parameter of a contract is the function foreign code +will call, during the call or, with the pointer kept, later. Three things +follow from what exists: + +- The function passed is entered at its validating entry (RFC 0041's split + entry), as from any code that is not safe. +- Where the contract's function-pointer type declares a bound for a + parameter, the function passed declares the same bound, or the call is + `call-args` with the certain fix that writes it. The bound is then + believed where the memory has no record (§6), which removes the false + stop of the motivation's table. +- The `void *` that travels with the callback is `WEAVEC_ESCAPES` when the + library keeps it. The callback converts it back with RFC 0054's checked + conversion. + +#### 3.6 Variadic functions + +A call of a variadic foreign function is covered when the declaration has +a `format` attribute (its arguments are checked as a `printf` or `scanf` +row's are) or when no variadic argument of the call is or holds a pointer +(`fcntl(fd, F_SETFL, flags)`, `open(path, flags, 0644)`). A pointer passed +through `...` with no format is `foreign-call` at the call, when the unit +compiles: no contract can say what `ioctl`'s third argument is. Such a call +belongs in a function that is not safe. + +### 4. A contract is a row + +#### 4.1 One form for every reader + +For each contract a unit uses, the checker writes the row its annotations +state and attaches it to the module (named metadata `weavec.contracts`: +the symbol and the row's text). `core::LibrarySpec` parses unit rows with +the table's parser and answers for them as for its own. Everything that +reads the table today then reads contracts with no code of its own: + +- the guards of a guarded caller (`GuardLibrary.cpp`); +- the comparisons of a safe caller's library calls (`boundLibraryCalls`, + `libraryAccess`); +- the thunk of a function whose address is taken; +- the fast unit's direct call of a read-only function on what it holds. + +The ownership and borrow rules keep reading the declaration's annotations +from the AST, as they do for any declared function. + +A contract for a function the table has a row for is `bad-annotation`: the +table is WeaveC's contract for the C library, and a project that finds a +row wrong reports it. + +#### 4.2 What the grammar gains + +So that a row can say what a contract can: + +- the term `*aN`: the integer argument `N` points to, read before the call, + of the width the parameter's `bytes(W)` gives; +- results `ptr:str`, `ptr:bytes(t)` and `ptr:of(aN)`: a string, `t` bytes, + a borrow of argument `N`; +- the parameter flag `kept`: the callee keeps the pointer (`WEAVEC_ESCAPES` + to the rules); +- the parameter access `handle`: no byte of the caller's is accessed, and + null is allowed. + +The table uses them where its rows could not say what the function does +(`recvfrom`'s and `accept`'s address length, `getsockname`). + +#### 4.3 The table, completed + +The table was written for the guards: a function has a row where an +argument needed one. Under this RFC a row is also what lets safe code make +the call, so the table gains a row for every function through which a +pointer crosses that ISO C's library declares, and that the POSIX headers +the table already covers declare, on the two platforms. Most are one +handle (`fclose (handle) -> int;`). `scripts/check-table.py` compares the +table with the declarations of the platform's headers and lists what has +no row; the hygiene gate runs it. `ioctl` and `syscall` stay absent +(§3.6). Each new row has its unit test, as rule 9 requires. + +### 5. At the call + +#### 5.1 A safe caller + +Before the call, for each pointer argument the row accesses, the bound the +function holds for the argument (declared, passed in `held`, or found: +RFC 0056 §1) is compared with the row's bytes for the call's arguments. +This is RFC 0056 §5's comparison for a library call, made for every row +including a contract's; the fourth probe of the motivation shows it is not +made today for a declared count. A failure is `pointer-out-of-bounds` at +the call, and its report names the contract (§Diagnostics). A handle is not +compared. A string is checked as a string argument of a library call is. + +An argument that is the address of a local, for a parameter that is not +`kept`, leaves the local in the plain frame of a fast unit: the callee is +given its bytes for the call and no longer. For a `kept` parameter the +`escape` rule applies as at any call. + +#### 5.2 A guarded caller + +A direct call from guarded code of a function with a contract is guarded +as a call of a table row is: each pointer argument over the bytes the row +gives, against the shadow, before the call. Guarded code has no error when +it compiles and needs no contract; where one is in scope, its calls are +checked. This is the one change to guarded code: a new guard, which is why +this RFC amends RFC 0035 §2.5. + +#### 5.3 An address taken + +A safe or guarded function that takes the address of a function with a +contract gets the address of a thunk that makes §5.2's guards and calls it, +as RFC 0037 §5 does for a row. Taking the address of a foreign function +with no contract through which a pointer crosses is `foreign-call`, at the +link. + +### 6. What comes back + +A pointer foreign code returns, stores through a parameter or passes to a +callback arrives in safe code as a pointer from code that is not safe does +today, with one addition. Where its declaration (the contract's result, the +callback's parameter, a `WEAVEC_FOREIGN_FIELD`) states a bound: + +- if the runtime has a record for the memory (the library allocated it + with the runtime's `malloc`, or it is an object WeaveC laid out), the + declared bound is compared with the record's once, where it arrives, and + a bound the record does not cover stops with `bounds-conversion`; +- if there is no record (the library's static data, its own allocator, a + mapping), the declared bound is believed. + +With no declared bound, RFC 0056 stands: the record's bound if there is +one, one object if not. + +### 7. `foreign-call` + +#### 7.1 When a unit compiles + +The checker knows a callee is covered when it has a body in the unit, a row +of the table or a contract in scope, or when nothing crosses (§2). For any +other function a safe function calls or takes the address of, and any other +global it names, the unit's record (RFC 0051 §5) gains an entry of a new +kind: + +- `X`: the symbol; the first place safe code uses it; and, as its + description, the contract the planner proposes (§10). + +The compile does not fail: the function may be another unit's. The summary +line counts the entries (`3 calls the link must find`), and the ledger +lists them (`expects`). + +The one compile-time case is §3.6's pointer through `...`. + +#### 7.2 When the image links + +Every unit compiled with enforcement, guarded or safe, carries a record +(an empty one is its header), which marks the object as WeaveC's. Before a +link the driver already reads every input's record (`readLink`). It now +also: + +1. collects the `X` entries. With none, it is done, and reads nothing more + than today; +2. finds, for each `X` symbol, an input that defines it, from the symbol + tables of the objects and archive members; +3. accepts a symbol defined by an object that carries a record, or by a + shared library with the image mark of §7.3; +4. reports every other symbol, defined by a foreign input or by none + (the system's libraries), as `foreign-call`, with the places and the + proposed contract from the entry. + +An LTO link reads the bitcode's records as it does today. `ld -r` joins +records, and the final link checks them. + +#### 7.3 Shared libraries + +The linker drops the records from an image. An image `weavec-cc` links +whose every object carries a record gets a mark (a note section, +`.note.weavec` or `__DATA,__weavec_img`, which holds the runtime's ABI). +A function defined by a marked image is WeaveC's. An image linked from a +mix is not marked, and safe code of another image reaches its functions +through contracts. An image that leaves `X` symbols for the loader (a +plugin whose host defines them) fails its link unless they have contracts: +the host is foreign to it. + +#### 7.4 No flag + +There is no option that turns `foreign-call` off for safe code. The ways +out are the ones Rust has: write the contract, compile the library with +`weavec-cc`, or make the call from a function that is not safe +(`WEAVEC_GUARDED`), where the audit lists it. + +### 8. The monitor + +A contract is the one thing in a safe program nothing checks. The checked +build tests what it can. + +For each argument through which the row lets the callee write, a checked +safe unit (`-fweavec-safe-checks=full`), and guarded code under +`-fweavec-checks=verify`, calls `__weavec_rt_foreign_before` with the +pointer and the row's bytes before the call and `__weavec_rt_foreign_after` +when it returns: + +- _before_ finds the object the bytes lie in from the records (a heap + block, a local of a guarded frame, a registered global). If the bytes + end at the object's end, the redzone that follows the object, which is + the runtime's own memory, gets a pattern in its first bytes (at most + 32), and the call's site, the address and the argument's number are + noted in the thread's state; +- _after_ compares the pattern. A changed byte is `foreign-overflow`. + +A buffer that ends inside its object, memory with no record and a fast +unit's plain frames have no redzone to test, and are not monitored. This +is the debug heap's no-man's-land check made when the call returns rather +than when the block is freed, so that the report names the call. + +### 9. The list + +**The ledger** (`weavec-ledger` 17) gains, for each unit: + +- `foreign`: for each function with a row or a contract the unit calls: + the function, `"contract": "table" | "declared"`, where a declared + contract is written, the row's text, and the calls from safe and from + guarded functions; +- `expects`: the `X` entries; +- `uncrossed`: functions with no body in the unit that safe code calls and + through which nothing crosses; +- `unchecked`: calls from functions that are not safe of functions with no + body, no row and no contract through which a pointer crosses. + +**The link's summary line** says what the link found: `weavec: prog: 14 +objects, 14 safe; ...; 9 foreign functions by contract, 21 with nothing +crossing; closed`. Without `closed` it names the count the guarded code +calls with no contract. + +**The audit** (`weavec-audit` 12) replaces `functions that are not safe +(safe code trusts them)` with three lists: + +- _guarded functions safe code calls_ (today's list); +- _contracts_: each declared contract, where it is written, its row, and + the number of safe and of guarded callers; then the table's rows the + program uses, as a count by header; +- _foreign calls with no contract_: `unchecked`, by function, with the + proposed contract for each. + +Its first line states the program: `closed: every call that leaves the code +WeaveC compiled has a contract (12 declared, 31 of the table)`, or what is +missing. A set of ledgers no link has checked says so, and lists the +`expects` no ledger's unit defines. + +### 10. Proposals + +`foreign-call` carries a fix as RFC 0049's errors do, as data. The planner +proposes the contract's declaration from the foreign prototype (evidence +E10): + +- a pointer followed or preceded by an integer parameter whose name is a + count's (`len`, `n`, `size`, `count`, `length`, a suffix of the + pointer's name): `WEAVEC_COUNTED_BY`, or `WEAVEC_SIZED_BY` for `void *`; + a pointer to an integer with such a name: `*p`; +- `const char *` with no such neighbor: `WEAVEC_NULL_TERMINATED`; +- a pointer to an incomplete type: a handle, written as it is; +- a `void *` beside a function pointer: `WEAVEC_ESCAPES`. + +Every proposal is _likely_, never certain: it is a promise about code the +planner cannot see. The note prints it; `weavec-cc --weavec-fix` does not +write a contract at any level. An agent reads the proposal and the +library's documentation and writes the declaration. Ownership +(`WEAVEC_OWNED`) and result lifetimes (`WEAVEC_LIFETIMEBOUND`) are never +proposed: the planner has no evidence for them, and they are the part that +turns a use after a release into a compile error, so the rule's page shows +them first. + +### 11. C++ + +- An `extern "C"` function is §3's. A foreign function with C++ linkage + that is not a member is redeclared with `WEAVEC_FOREIGN` in its + namespace. +- A member function of a foreign class cannot be redeclared outside its + class. If nothing crosses it by §2 (references, views, owners, values), + it needs no contract. If a raw pointer crosses, the call is + `foreign-call` and belongs in a function that is not safe, or the class + in a library `weavec-cc` compiles. +- The C++ standard library is not foreign: what is trusted of it is RFC + 0044's and RFC 0050's, and its table rows and class rows stand. +- A library call that takes a raw pointer from a container + (`compress(out.data(), &n, in.data(), in.size())`) is §5.1's comparison: + `data()`'s result has the bound RFC 0056 finds for it. + +### 12. What changes elsewhere, and what goes + +- **The guarantees page**: (F1) to (F4), F-A1 and F-A2; the entry + _functions outside the library table are not checked at the call_ is + narrowed to calls from code that is not safe with no contract in scope. +- **The audit's statement** `every function is safe` is no longer the + statement of a program. `closed` is, beside it. +- **The table's comment** on rows the guards did not need goes: every + pointer-crossing function of the covered headers has a row. +- **RFC 0056's stop on a callback's data in memory with no record** (one + object) becomes a `call-args` error with a certain fix where a contract + declares the callback's bound. +- **Versions**: runtime ABI 53 (`__weavec_rt_foreign_before`, + `__weavec_rt_foreign_after`), ledger 17, audit 12, records + `weavec-defs 3`, `weavec.h` 3.6. +- **Breaking**: a program whose safe functions call a foreign function + with no contract does not link. Guarded code that includes a contract + gains guards. + +### 13. What does not change + +Guarded code with no contract in scope. The rules of ownership, borrows, +threads and types. Found bounds. The fast build's code for a call of a +table row. What a function of the program that is not safe may do: it is +guarded and listed, as before. + +### 14. Stages and gates + +- **S0. Measure first.** (a) The table: the rows §4.3 adds, counted, and + the call sites of the fifteen projects and the trial programs that §3.6 + sends to a function that is not safe (expected: the `ioctl` calls of + linenoise); more than 20 sites returns to the owner. (b) The link: with + no `X` entry at most 0.2% of libzmq's and leveldb's link time over + main's, and with entries at most 2% (RFC 0051's limit). (c) The + comparison of §5.1 for a declared count: at most 1 ns a call, and RFC + 0050's programs within 1.01 of main's fast build. (d) The monitor: at + most 25 ns for a written argument, and the checked builds of RFC 0050's + programs within 1.02. A limit missed goes back to the owner with the + numbers (D9). +- **S1.** The table: the grammar's additions, `check-table.py`, the rows, + their unit tests. +- **S2.** Contracts: `WEAVEC_FOREIGN`, `*p` counts, the lowering to a row, + unit rows in `LibrarySpec`, the comparison in safe callers, the guards + in guarded callers, the thunks, what comes back. +- **S3.** `WEAVEC_FOREIGN_FIELD`, globals, callbacks, variadic calls. +- **S4.** `foreign-call`: the `X` entries, the marks, the link's check, + shared libraries, LTO. +- **S5.** The monitor and `foreign-overflow`. +- **S6.** The ledger, the audit, the summary, the proposals. +- **S7.** The rule's page, a guide (`docs/pages/guides/foreign-code.md`), + the guarantees page, the command-line reference, the annotations page, + the roadmap. + +Gates: + +- **G1. Tests.** `test/Safe/foreign-call.c`, `cxx-foreign-call.cpp`, + `foreign-contract.c` (each form of §3 and each `bad-annotation`), + `foreign-callback.c`; `test/Guards/foreign-contract.c` (a stop at the + call from a safe and from a guarded caller, with its report lines), + `foreign-overflow.c`, `foreign-result.c`, `ir-foreign.c` (the row in + the module, the comparison, no call of the monitor in a fast unit); + `test/Driver/foreign-link.c` (the link error, an archive, a marked and + an unmarked shared library, LTO), `foreign-audit.c`; cases + `test/cases/foreign/`; `rt_test` `foreign-*`; a row test for each row. + The foreign side of each test is a C file compiled with `-fno-weavec`. +- **G2. The probes.** Each program of the motivation's table: without a + contract it does not link; with the contract of this RFC's examples it + is a compile error or stops at the call, in the fast and the checked + build, and the guarded caller of the fourth stops too; the callback's + correct read does not stop. +- **G3. Nothing breaks that should not.** The fifteen projects surveyed + with no edit: no `foreign-call` beyond S0 (a)'s sites, and no other + rule's count higher. RFC 0056's G3 projects still pass as written. The + corpus gate's quick tier is unchanged: no contract is in scope there. +- **G4. New code over foreign libraries.** A fresh agent writes, in Safe C + and again in safe C++, a program over the system's zlib (its stream + interface) and sqlite3: an archive tool that keeps compressed blobs in a + database, about 1,500 lines, from a brief that names the rule's page and + nothing else about contracts. A Rust agent writes the same with `flate2` + and `rusqlite`. Measured: minutes and rounds to all-safe, closed and + passing, and the contract's lines. The gate: at most 1.25 of the Rust + agent's minutes. Then ten boundary bugs are injected into each port's + calls (a capacity too large, a length too large, a statement used after + it is finalized, a second close, a leaked statement, a local's address + kept, a blob read after its row is stepped): each is a compile error or + a stop at the call in both builds. +- **G5. Unmodified code with a contract.** libpng (in the corpus), guarded + and built against the system's zlib, with G4's zlib contract given by + `-fweavec-contracts`: its tests pass + with no stop, within 1.02 of the time without the contract. A stop is a + wrong contract or a real bug, and is triaged. +- **G6. Wrong contracts.** Eight contracts with a count made too large or + a `const` added to a written parameter, called on a buffer that ends its + object: the checked build reports `foreign-overflow` for each. +- **G7. A round.** Two fresh adversarial agents, one for C and one for + C++, try to make all-safe, closed code read or write outside an object + across the edge with correct contracts, and to stop a correct program. + Every hole is rerun. The gate is none. +- **G8. Nothing slower.** RFC 0050's programs, both json ports and the + LRU port within 1.01 of main's fast build and 1.02 of its checked + build; compiles within 1.02 and links within S0 (b), with a Release + compiler. +- **G9. The lines of code** the library and the runtime gain and lose, + reported. The draft expects about 1,300 in the library, 250 in the + runtime and 300 rows. + +## Annotation surface + +`resources/include/weavec.h` 3.6 adds two spellings and one form. + +- **`WEAVEC_FOREIGN`**, before a function declaration with no body or an + `extern` variable declaration: `__attribute__((annotate("weavec.foreign")))`. + The declaration is the contract of a function or a global that code + WeaveC did not compile defines (§3). In a unit that defines the function + the mark is ignored and the annotations mean what they mean on any + declaration, so that a contract header may be included by the library's + own units when `weavec-cc` compiles them. On a definition it is + `bad-annotation`. Its constant is `ForeignAnnotation` in + `include/weavec/Frontend/SafeCheck.h`. +- **`WEAVEC_FOREIGN_FIELD(type, field, annotations)`**, at file scope: the + member `field` of the struct or union `type`, defined in a header the + program does not own, has `annotations` (a bound, `WEAVEC_OWNED`, + `WEAVEC_BORROWED`) as if its declaration carried them (§3.3). It expands + to a declaration that is never defined and carries + `annotate("weavec.foreign_field", "", "")` and the + annotations on a type made with `__typeof__` of the member. +- **`*p` as a count** in `WEAVEC_COUNTED_BY`, `WEAVEC_SIZED_BY` and their + `_OR_NULL` forms, in a declaration with no body (§3.2). + +Under a compiler that is not WeaveC, `WEAVEC_FOREIGN` expands to nothing +(the declaration is a plain redeclaration) and `WEAVEC_FOREIGN_FIELD` to an +empty declaration. `docs/annotations.md` gains both, and the guide a +worked contract for a library with handles, in-out counts, a stream struct +and a callback. + +## Diagnostics + +**Compile time and link time.** One rule, `foreign-call`, with a page in +`resources/safe/rules.md`. + +At a link: + +``` +: error: '' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +::: note: called here, in '' (and more places) +::: note: say what it does with what it is given: ''; or compile its library with weavec-cc; or call it from a function that is not safe +note: 'weavec-cc --weavec-explain foreign-call' explains this rule +``` + +with `'' is named by safe code` for a global and `the address of +'' is taken by safe code` for an address. When a unit compiles: + +``` +::: error: a pointer is passed to '' through '...', where no contract says what is done with it [weavec-safe:foreign-call] +::: note: make the call in a function that is not safe (WEAVEC_GUARDED), which the audit lists +``` + +`bad-annotation` gains: `WEAVEC_FOREIGN` on a definition; a contract for a +function the table has a row for; `*p` where `p` names no parameter that +points to an integer, or in a declaration with a body; +`WEAVEC_FOREIGN_FIELD` that names no member, a member with an annotation of +its own, or a second contract that differs. `call-args` gains: `'' +is passed where '' declares '' for parameter , and +declares none` (certain fix: the bound on the function's parameter). + +`test/Safe/foreign-call.c`, `foreign-contract.c`, `foreign-callback.c` and +`test/Driver/foreign-link.c` pin each. + +**Run time.** One kind is added. + +``` +weavec: foreign-overflow at ::: '' wrote past the bytes its contract gives argument , at
+``` + +then the object's paragraph as a guard's report gives it, a line `weavec: +the contract is declared at ::` (or `is a row of the +library table`), and the summary line. + +```c +#include +/* fill.c, compiled with -fno-weavec: void fill(char *p, unsigned n) { memset(p, 1, n + 8); } */ +WEAVEC_FOREIGN void fill(char *WEAVEC_COUNTED_BY(n) p, unsigned n); +WEAVEC_SAFE int main(void) { + char buffer[16]; + fill(buffer, 16); + return buffer[0]; +} +``` + +built with `-fweavec-safe -fweavec-safe-checks=full`. +`test/Guards/foreign-overflow.c` pins it; the command-line reference's list +of kinds and `scripts/run-cases.py` gain it. + +A `pointer-out-of-bounds` or guard report at a call of a function with a +declared contract gains the same line naming the contract's declaration, +and its JSON a `contract` field. + +## Drawbacks + +- **A contract is trusted.** WeaveC deleted its last unverified + annotations with the analysis (RFC 0036). These come back for one + purpose: code the compiler cannot read. The monitor tests one side of + them, in one build. +- **A program that worked stops linking** until someone writes + declarations for a library they did not write. Rust asks the same, but + Rust has the crates. +- **Errors at the link**, not at the call, for the common case. An + `-fsyntax-only` round does not see them; the audit over the round's + ledgers does. +- **A second place to keep in step with a library.** A contract can lag + the library's next release. The prototype is checked by the language; + the counts are not. +- **A few hundred rows** for handle-only functions that no guard needs. +- **Member contracts are awkward to spell**, because C cannot reopen a + struct. +- **C++ members with raw pointers** have no contract form. + +## Alternatives + +- **Do nothing; say it on the guarantees page.** It is said there. The + first probe is still a stack overwrite in a program the audit calls + safe. +- **Rust's form: a foreign call only in a function that is not safe.** + Simpler, and it is this RFC's way out. But the wrapper is then + hand-written checks in the one kind of function the rules do not read, + which is where Rust's FFI bugs are. A declaration the compiler checks + each call against is less to write and less to get wrong. +- **Decide what is foreign by the header** (a system header is foreign). + It is known when the unit compiles, which is better for the loop. It is + also wrong both ways: a dependency compiled by `weavec-cc` and included + as a system header (CMake's default for imported targets) would need + contracts for guarded code, and a vendor's archive behind a project + header would need none. The link knows. A remark for calls into system + headers can come later if agents' rounds show the link is too late. +- **Contracts in a file of their own** (the table's row language, or + Clang's API notes). A second language for an agent that already writes + the annotations, with positional terms, and nothing checks a row's shape + against the header but its arity. Rows stay the internal form. +- **Annotate the libraries' headers.** They are not the project's. +- **Compile everything with `weavec-cc`.** Right wherever it can be done, + and this RFC's errors say so. The operating system and a closed library + remain. +- **Run foreign code in a sandbox** (a process, or WebAssembly as RLBox + does). It enforces what a contract only promises, at a cost per call and + per library that no drop-in compiler can impose by default. +- **A flag that keeps today's behavior.** RFC 0056's `declared` mode is a + second language to test; this would be a second meaning of _safe_. + +## Prior art + +- **Rust**: `extern` blocks, `unsafe extern` and `safe` items (2024 + edition), and the convention of `-sys` and wrapper crates. We take the + discipline (every crossing declared, the undeclared ones listed) and + move the check from a person's wrapper to the compiler. +- **The `cxx` crate** states a shared interface once and generates checked + glue on both sides. A contract is that statement for a side that cannot + be regenerated. +- **Checked C** ships headers that redeclare the C library with + bounds-safe interface types (`itype`), so that checked code calls + unchecked libraries with declared bounds. `WEAVEC_FOREIGN` is that + mechanism, required instead of offered, and with ownership. +- **Apple's `-fbounds-safety`** treats unannotated system headers as + unsafe pointers and adopts annotated SDK headers and API notes; a + `__counted_by` on a prototype is compared in the caller, as §5.1 does. +- **Microsoft's SAL** (`_In_reads_(n)`, `_Out_writes_(n)`) is contracts on + declarations read by a static analyzer. +- **AddressSanitizer's interceptors** and MemorySanitizer's are checks per + library function in code; MSan's false reports on libraries it did not + instrument are the cost of having no contract. The table is interceptors + as data, and this RFC opens it. +- **Go's `cgocheck`** tests, when a call runs, the rule for what may cross + into C. +- **CHERI** gives foreign code a capability bounded to what the call + passes, enforced by hardware: what (C1) can only promise. +- **Debug heaps** (the Windows CRT's no-man's-land fill, glibc's + `MALLOC_CHECK_`) fill the bytes after a block and test them at `free`. + §8 tests them when the foreign call returns. + +## Unresolved questions + +1. **How an object is known as WeaveC's** (§7.2): the empty record's size + and time in a guarded build, against a symbol every enforcing unit + already references. S0 (b). +2. **A mixed shared library** (§7.3) is wholly foreign to other images. + Whether it should instead list the functions its foreign objects + define is left to the first project that has one. +3. **Where the monitor has a redzone** (§8): the heap's slack after a + block's size, a guarded frame's right redzone and a global's, and + whether any holds a word the runtime reads. Whether guarded code can + afford the monitor in its default build. S0 (d). +4. **The bounds of a function-pointer type against the function passed** + (§3.5): whether the same check should hold between safe functions, and + what it finds in the corpus. +5. **A signed count read through `*p`** that is negative: it stops as a + count too large. Whether any library means it. +6. **The table's reach** (§4.3): whether _the POSIX headers the table + already covers_ leaves common functions to contracts a project must + write (`` is covered; `` is not). +7. **A foreign class's member with a raw pointer** (§11): how often an + agent meets one, from G4's C++ port. + +## Future work + +- **Contracts WeaveC ships** for the libraries most programs call (zlib, + sqlite3, OpenSSL, libcurl, libuv), each tested against the library's own + tests under the monitor. G4's and G5's are the first two. +- **Contracts from documentation**: a mode of the fixer that proposes a + whole header from a library's prototypes, for an agent to review. +- **Foreign code in a sandbox**, for a library whose contract nobody will + vouch for. +- **A remark when a unit compiles** for calls of functions declared in + system headers with no contract, if the link proves too late. +- **The thread rules** on correct programs (RFC 0046's G3), still the + largest class of errors in new threaded code. + +## Decisions to accept + +Accepted as drafted on 2026-12-05. + +- **D1. Scope.** Calls, addresses and globals that leave the code WeaveC + compiled: required contracts for safe functions, guards for guarded + functions where a contract is in scope. No sandbox, and no rule of + ownership, borrows, threads or types changes. +- **D2. Three kinds of code**, and what is foreign is decided by the link + from the units' records (§1, §7), not by where a declaration is written. +- **D3. A contract is a declaration**: the function's prototype marked + `WEAVEC_FOREIGN` with the existing annotations, `*p` counts and + `WEAVEC_FOREIGN_FIELD` (§3). The table is WeaveC's contracts for the C + library. No contract language of its own. +- **D4. Nothing crosses, no contract** (§2), listed. +- **D5. A contract is lowered to a row** (§4), so that safe and guarded + callers are checked by the code that reads the table. +- **D6. `foreign-call`**, at the link and for a pointer through `...`, + with no flag to turn it off (§7). +- **D7. The monitor** in the checked build and under `verify`, and + `foreign-overflow` (§8), subject to S0 (d). +- **D8. The table is completed** for ISO C and the POSIX headers it + covers, by a script the hygiene gate runs (§4.3). +- **D9. Measured first.** S0's limits (§14); one missed returns to the + owner before S1. +- **D10. Versions.** Runtime ABI 53, ledger 17, audit 12, records + `weavec-defs 3`, `weavec.h` 3.6. + +## Implementation amendments + +These record where the implementation departs from the design above, from +building it and from what S0 and the gates found. They override the body. + +1. **A contract's row reaches the passes in the process, not in the + module** (§4). `lowerContracts` writes each row's text into + `SafeUnit::contractRows`, which `core::LibrarySpec` parses with the + table's parser as *unit rows*; nothing is added to the IR. G1's + `ir-foreign.c` pins the comparison, the guards, the thunk and the + monitor's calls instead of a row in the module. +2. **`WEAVEC_FOREIGN_FIELD` expands to two `typedef`s that are never + used** (§3.4): the member's type under a name, then that name with the + annotations and `annotate("weavec.foreign_field", "", "")`, + since C++ takes no attribute after `__typeof__(...)`. A diagnostic of + Clang's own about the member then spells its type by that name. +3. **`*p` counts are for parameters** (§3.2): on a result they are + `bad-annotation`. A null `p` is a count of zero. +4. **`WEAVEC_ENDED_BY` in a contract is the bytes from the pointer to its + end** (§4.1, §4.2). The grammar gains a term for it, `aE-aS`, the bytes + from pointer argument S to pointer argument E when the call is made + (`LibTerm::Kind::Distance`), and a contract's parameter lowers to + `rw:bytes(aE-aS):null-if-zero(aE-aS)`. An end that lies before its start + is no range: the term is then more than any object has, so the call + stops. As first built the parameter lowered to an access of its first + byte, which G7 found (a start in one object and an end in another passed + in every mode); G6's ninth wrong contract is reported since. A struct + with a member bounded by an end is another matter: typed memory keeps a + count beside a member's pointer and no end (RFC 0042 amendment 2: an + end's loads keep their guards), so nothing holds the bound foreign code + would believe. A contract whose parameter, result or global gives + foreign code such a member, directly or through a pointer, is + `bad-annotation` (`givesEnded`); the member takes a count instead, or + the call is made from a function that is not safe. +5. **Foreign globals are rows too** (§3.5, §4): `global NAME : kind;`, in + the table (`environ`, `stdin`, `tzname`, ...) and lowered from a + `WEAVEC_FOREIGN extern` declaration. +6. **Which C++ classes cross** (§2, §11): a class that is C-like (Clang's + `isCLike`: no constructor, destructor, base, virtual or member function) + crosses by its pointer members as a C struct does; every other class is + one whose kind RFC 0044 derives, and does not. A contract on a member + function is `bad-annotation`. +7. **A contract's thunk is named with a hash of its row** (§5.3): + `__weavec_thunk_.`, `linkonce_odr`, so that units that + declare the contract alike share one thunk and units that differ do not. +8. **The records** (§7.1, `weavec-defs 3`) carry a flags field and three + more kinds than the `X` of the design, each for the link's summary: + `K` (a function the unit calls by contract, declared or the table's), + `N` (a foreign function it calls through which nothing crosses) and `U` + (a call from code that is not safe with no contract). Every enforcing + unit carries a record, guarded ones too. Two safe units whose contracts + for one function differ are `definition-mismatch` by RFC 0051's + comparison of declarations, which reads the annotations. +9. **`-fno-weavec-definitions` does not skip the foreign check** (§7): it + turns off RFC 0051's comparison only. D6 has no flag. +10. **What defines a symbol** (§7.2): an object or archive member with a + record, or a shared library with the image mark. A `-l` library is + looked for only in the command's `-L` directories; one found nowhere + there (a system library) is foreign. The mark is put on shared + libraries only (an executable defines nothing another link reads). On + Darwin it is an empty section (`-add_empty_section __DATA + __weavec_img`) with Apple's linker, and a section made from a file with + another (`-fuse-ld=`); the first cost 200 to 400 µs less a link (S0 + (b)). A Mach-O partial link (`-r`) carries its inputs' records joined; + one that mixes inputs with and without records is marked so. +11. **What comes back** (§6) is checked by the validating check safe code + already makes where a pointer arrives from code that is not safe (RFC + 0048, RFC 0056): the declared bound is compared with the record once, + and believed where there is none. No new entry point. +12. **A local lent to a contract call keeps its plain frame** (§5.1): + `lent` (`SafeTypes.cpp`) and `lentByContract` (`GuardExpand.cpp`). In + Safe C the address of a local given to a parameter the contract says is + kept (`WEAVEC_ESCAPES`) is `escape`; a table row's `kept` reaches Safe + C++'s `escape` the same way (`keeps`, `SafeCxxFlow.cpp`). +13. **The table's additions** (§4.3): 247 function rows, 19 global rows and + 22 fortified aliases (1,041 entries in all). `scripts/check-table.py` + holds the table to ISO C23 and POSIX.1-2008 with XSI as the platform's + 65 covered headers declare them (613 functions with a row, 458 through + which nothing crosses); the hygiene gate runs it (`table-row`). New + clauses: `*aN` counts, `handle` (a `FILE *`, `DIR *` or locale: an + opaque object the library made, used only through it), `kept`, and the + declarative results `ptr:str`, `ptr:bytes`, `ptr:of`. `recvfrom`, + `accept` and `getsockname` keep their wrappers (their in-out length is + checked there). +14. **`-fweavec-contracts=
`** is applied in the compile step for C + and C++ source only (not assembly, not a link), after the command's own + `-include` files. The header is read before the unit's own text: a + library's configuration macro the program defines before including the + library's header (libpng's `ZLIB_CONST`) has to be given on the command + line (G5). +15. **A contract adopts the library's prototype** (`adoptContract`): it may + come before or after it, its annotations are added to the declaration + the unit uses, and a type that disagrees is Clang's own error. A + `noreturn` contract lowers to `exits`. +16. **A pointer through `...`** (§3.6, §7): in C, `foreign-call` is + reported when the unit compiles only where a contract or a system + header declares the variadic function. For one the program's own + header declares with no contract the error is `variadic`, as on main + (the function may be another unit's): S0 (a) counted 72 `foreign-call` + sites by the first naming, 71 of them calls of the projects' own + variadic functions that main already rejected, and 2 by this one. C++ + is as designed. +17. **In safe C++ a stop at a contract call on `data()`** of a container is + the library-call guard's kind (`heap-buffer-overflow`, ...), not + `pointer-out-of-bounds`: the container's pointer is guarded as a + library call's argument is. +18. **The monitor** (§8), from S0 (d) and a false report found in G8's + checked json port: + - Only a callee with no body in the unit is watched. A library's + inline or `available_externally` function is WeaveC's code where it + lands, and watching it reported a correct program. + - `__weavec_rt_foreign_before(pointer, bytes, site, function, + argument)` answers whether it watches, and + `__weavec_rt_foreign_after(pointer, argument, watched)` takes the + answer. The expansion (`gateWatches`) makes both calls only where + the shadow of the byte after the contract's bytes is a redzone's, so + a buffer that ends inside its object costs one load and a branch. + The Safe C json port's checked build went from 1.07 of main's to + 1.014 to 1.017. + - `after` finds its watch by the pointer and the argument, not the + site: sites are remade after inlining and the optimizer merges the + `after` calls of two paths. Every `before` that is called pushes a + watch (an empty one where there is no redzone). A watch left by a + call that did not return (`longjmp`, an exception) is dropped with no + report, and its bytes are put back only if they are still the + pattern in a redzone; a full stack of eight is emptied. + - A heap watch stops at its slot's end (the bytes after belong to a + neighbor that may be handed out during the call). A global's redzone + is remembered and compared, not patterned (it may be read-only). + - For a contract the program declares, an argument the contract says + is only read is watched too (a string past its terminator): a `const` + that is wrong was G6's second half. The table's rows, which + `check-table.py` holds to the headers, are watched for what they + write only. + - The fast build makes no call of the monitor and reports nothing. +19. **The list** (§9): the ledger (version 17) gains per unit `foreign` + (its contracts and their rows), `expects` (what it calls with no + contract), `uncrossed`, `unchecked` (calls from code that is not safe) + and `defines` (its externally visible globals); the audit (version 12) + resolves `expects` and `unchecked` against the functions and the + `defines` of the ledgers it is given before it says `closed`. The link + summary's count of foreign functions by contract includes the table's + rows. +20. **A proposal may be wrong** (§10): `proposeContract` (evidence E10) + writes a bound only where the prototype shows one (a pointer followed + by an integer whose name says count or size, a `const char *` as a + string) and leaves the rest for the author. It is printed with the + link's error and kept in the ledger's `expects`; nothing writes it into + a file. +21. **Which kept locals are `escape`** (§5.1, amendment 12). Safe C rejects + the address of a local given directly to a parameter a contract keeps: + `&local`, a local array, and a block-scope compound literal (G4's + injection found the last one accepted). A local whose address reaches a + kept parameter through a pointer variable, or through a safe function's + own `WEAVEC_ESCAPES` parameter, is not rejected: it is a placed local + (typed memory for its scope, RFC 0048 §5), so foreign code that uses it + after the scope reaches a released slot of its type, and no check sees + that use. (F3) says so. +22. **A member's pair in a checked C++ unit** (§3.3). A checked safe C++ + unit compares the stores of a function that uses a bound (RFC 0047 + §1.2), and a function that only fills a struct by an initializer named + no member: `lib_slice s{data, 40}` stored a count its pointer's object + did not have, and foreign code given the struct read past it, in the + checked build and at `-O0` (the fast build stopped). G7 found it. An + initializer of a struct with a bounded member, braced or parenthesized, + now counts as a use (`storesBounded`), in every unit; pinned by + `test/Guards/foreign-member.cpp`. +23. **Rows that keep a pointer** (§4.3). G7's C++ round found table rows + whose function keeps an argument and did not say so: `setvbuf`, + `setbuf` and `setbuffer` (the stream's buffer), `putenv`, `tsearch` + (the key), `initstate` and `setstate`, `openlog` (the identifier), + `aio_read` and `aio_write`. Each is `kept` now, so that a borrow or a + local given to it is `escape`, and `setbuf`'s buffer is 1024 bytes (the + smaller `BUFSIZ` of the supported libraries). `strtok_r`'s saved + position is a pointer foreign code stores through a parameter (§6): it + is believed in a fast unit, and its uses are guarded in a checked one. +24. **On ELF a partial link's inputs are read for their records** as on + Mach-O (`readLink`'s `join`), so that `ld -r` of a mix of WeaveC's and + foreign objects is known not to be WeaveC's alone (§7.2), and the + records' reader skips the padding a partial link puts between its + inputs' sections; the Linux run of `test/Driver/foreign-link.c` found + both. + +## Measured gates + +darwin-arm64 (Apple M-series, macOS 27), the dev compiler for the tests, +the trials and the rounds, Release compilers of main at `528733cb` (M) and +of this branch (B) for times. Evidence: `build/rfc57/` (README.txt). + +**S0.** Every limit met, so nothing went back (D9). (a) The table gained +247 function rows, 19 global rows and 22 aliases (amendment 13), and the +fifteen projects and the trial programs have 2 sites that §3.6 sends to a +function that is not safe (limit 20): linenoise's `ioctl` and leveldb's +`fcntl`. (b) The link's check with no `X` entry: libzmq 0.03% and leveldb +0.06% over main's link (limit 0.2%); with entries 0.44% to 0.5% (limit +2%). (c) The comparison for a declared count was not measurable: 0.81 ns a +call with it and without, and RFC 0050's programs within 1.01 of main's +fast build. (d) The monitor: 14.6 to 18.8 ns for a watched argument (limit +25), and the checked builds at most 1.017 of main's (limit 1.02) once the +calls are made only at a redzone (amendment 18). + +| Gate | Result | +| --- | --- | +| G1 Tests | **Pass.** The tests §14 names, and `test/Guards/foreign-member.cpp`, cases `test/cases/foreign/end-past*.c` and the `Distance` term's unit tests for what G7 found. darwin: lit 241, the cases 650 (4 expected failures), 17 core and 21 frontend unit tests, `rt_test` 81. linux-aarch64 (glibc, libstdc++; a container, the `ci-release` preset): the 241 lit tests and the 60 CTest suites pass after amendment 24, the table's check there covers 74 headers (752 functions with a row, none missing), and CI's clang-tidy build is clean. | +| G2 The probes | **Pass.** Each program of the motivation's table does not link without a contract (`foreign-call`), and with one is a compile error (`stale-borrow`, `owner-leak`, `owner-moved`, `escape`, `call-args`) or stops at the call (`pointer-out-of-bounds`; `heap-buffer-overflow` from `std::vector`), in the fast and the checked build; the guarded caller of the fourth stops (`stack-buffer-overflow`); the callback's correct read does not stop. | +| G3 Nothing breaks | **Pass, with one difference in the corpus tier.** The fifteen projects surveyed with no edit: `foreign-call` at S0 (a)'s two sites and nowhere else, and no other rule's count higher (`variadic` falls from 495 to 278 in the C projects, the calls that pass no pointer through `...`); the same counts after amendments 4 and 21 to 23. RFC 0056's G3 projects pass as written in the fast and the checked build with no stop (cJSON 136 functions marked, sds 23, http-parser 18, inih 3, tinyxml2 147). The corpus gate's quick tier is main's for nine of its ten configs; lua gains two accesses, calls the new rows guard (7,529 to 7,531, 2,774 to 2,775 proven). On this machine main's own compiler and this branch's both report zlib 3 proven accesses under the recorded ratchet (2,181 to 2,178 of 4,243), so that is not this change's. | +| G4 New code | **Time fails; the injections pass in Safe C and fail in safe C++.** The archive tool (zlib's stream interface and sqlite3), each port written by a fresh agent from the brief and verified here (96 of 96 checks in the fast and the checked build, every function safe, the audit `closed`, no stop). Rust (`flate2`, `rusqlite`, `#![forbid(unsafe_code)]`): 4.5 minutes, 1 round, 631 lines. Safe C: 7 minutes (1.56; limit 1.25), 2 rounds with no rule error and no link error, 773 lines and a contract header of 45 (24 functions, 2 members). Safe C++: 6.5 minutes (1.44), 3 rounds (`counted-pair` four times, then twice), 757 lines and a header of 59 (25 functions, 2 members). The ports are about 800 lines, not the 1,500 the gate supposed. Ten bugs injected into each port's calls. Safe C: 10 of 11 are a compile error or a stop at the call in both builds (two capacities `bounds-conversion`, three lengths `pointer-out-of-bounds`, a statement used after `sqlite3_finalize` and a second close `owner-moved`, a leaked statement `owner-leak`, a local and a compound literal kept `escape`, the second found accepted and fixed: amendment 21); a text read after its row is stepped does not stop (a contract binds the result to the statement, and nothing says a step ends it). Safe C++: 6 of 10 (five counts `heap-buffer-overflow` at the call, a local kept `escape`); a statement used after it is finalized faults inside sqlite3, and a second close, a leaked statement and the stale text do not stop: safe C++ has no owner for a C handle, and the port's classes hold raw pointer members. Both agents kept zlib's stream in memory that outlives the call (`deflateInit_` keeps it) and read blobs with `sqlite3_blob_read`, since `sqlite3_column_blob`'s length is another call's result, which a bound cannot name. | +| G5 Unmodified code | **Pass.** libpng guarded against the system's zlib with a zlib contract given by `-fweavec-contracts` (and `-DZLIB_CONST`, amendment 14): 33 of 33 tests, no stop, 1.0004 of the time without the contract (median of five; limit 1.02). The contract is the reference one of `build/rfc57/g5`, not the agent's. | +| G6 Wrong contracts | **Pass.** Nine contracts (five counts, among them a `*p`, a constant, wide elements and an end; a `const` on three written parameters; one more count), each called on a buffer that ends its object: the checked build and the verify build report `foreign-overflow` for each; the fast build, which has no monitor, for none. The `const` ones needed amendment 18's watch of read arguments, the end amendment 4. | +| G7 A round | **Fail: two holes found, both closed.** C: 45 probes, one hole in four programs: a contract's `WEAVEC_ENDED_BY` was checked for its first byte only. Closed (amendment 4): three stop at the call in every build, and the fourth, a struct member bounded by an end given to foreign code, is `bad-annotation`. C++: 53 probes, one hole in two programs: a counted member stored by a braced initializer was not compared in the checked build or at `-O0`. Closed (amendment 22). No false error, false stop or false link error in either round. Left open, and outside the gate's terms: a wrong contract whose extra writes stay inside the caller's object, or that runs past an exact-fit heap slot, is not reported (the monitor patterns only a redzone that is the buffer's own, amendment 18); a function pointer parameter with no declared bound accepts a safe callback that declares a stronger one, which is then believed of the pointer foreign code passes; table rows that kept a pointer without saying so (amendment 23), with `strtok_r`'s saved position still believed in a fast unit. | +| G8 Nothing slower | **Pass.** Measured before G7's fixes, which change no guard of these programs (their ledgers' summaries are the same before and after, in both builds). Medians of interleaved runs, this branch over main: the fast builds within noise (json49 1.007, the C++ json port 1.007, cJSON 1.003 to 1.03 over three runs, LRU 0.998, tinyxml2 0.97, the interpreter 0.999), the checked builds at most 1.017. Compiles 1.013 fast and 0.999 checked in all (the LRU port 1.016 to 1.017); links within S0 (b). | +| G9 Lines | The library 38,344 lines of code (main 35,729: +2,615; 46,702 lines in all), the runtime 10,708 (main 10,499: +209; 13,672 in all), the table's file 1,854 lines (main 1,388). The draft expected about 1,300, 250 and 300 rows. | + +Found on main and not changed here: safe C++ rejects +`static_cast` of a `const void *` (`pointer-cast`) +and accepts the form without `const`; `int-to-pointer` does not see a cast +that a system header's macro makes (`SQLITE_TRANSIENT`) in safe C++; RFC +0049's libzmq conversion no longer compiles as safe, and main reports +`definition-mismatch` for six of its types whose descriptions print alike. + diff --git a/docs/rfcs/README.md b/docs/rfcs/README.md index c071903..aa56fce 100644 --- a/docs/rfcs/README.md +++ b/docs/rfcs/README.md @@ -106,5 +106,6 @@ decision is a new RFC that supersedes the relevant section. | [0054](0054-one-of-several-types.md) | One of several types | Accepted | | [0055](0055-a-heap-for-safe-code.md) | A heap for safe code | Accepted | | [0056](0056-bounds-without-declarations.md) | Bounds without declarations | Accepted | +| [0057](0057-foreign-code-by-contract.md) | Foreign code by contract | Accepted | The [roadmap](../roadmap.md) links each milestone to the RFCs that define it. diff --git a/docs/roadmap.md b/docs/roadmap.md index 7032a03..889c954 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -4,7 +4,7 @@ Rough ordering of the major pieces of work. This page is the one-screen view; the design detail and the reasoning live in the [RFCs](rfcs/README.md) each milestone links to. Everything here is subject to change as we learn. -The design today is [RFC 0056](rfcs/0056-bounds-without-declarations.md) for the bounds of pointers with no declaration (found from the runtime's records when a safe function runs, passed by a safe caller that holds them, listed for `--weavec-fix-bounds`), [RFC 0055](rfcs/0055-a-heap-for-safe-code.md) for the heap of fast safe code (the threads' entries and the short paths, typed `realloc`, one contract for both languages), [RFC 0054](rfcs/0054-one-of-several-types.md) for values of one of several types (tagged unions, checked conversions and downcasts), [RFC 0053](rfcs/0053-callables-and-containers-by-their-loans.md) for callables and containers by their loans and [RFC 0052](rfcs/0052-what-a-call-may-reach.md) for what a call may reach in safe C++ (reach by types, results, views, callables, values built from borrows), [RFC 0051](rfcs/0051-nothing-undefined.md) for what a safe function may not leave undefined (the list of the two languages' undefined behavior, the definitions and the stops, the rules that reject what asserts, the comparison of safe units at the link), [RFC 0050](rfcs/0050-checked-once.md) for what a fast safe unit checks once (views, the typed allocator's paths, Safe C's library calls), [RFC 0049](rfcs/0049-errors-that-carry-their-fix.md) for the fixes errors carry and `--weavec-fix`, [RFC 0048](rfcs/0048-safe-code-without-the-shadow.md) for what a fast safe unit checks and believes, [RFC 0047](rfcs/0047-conversion-in-place.md) for converting existing C++, [RFC 0046](rfcs/0046-thread-safety.md), [RFC 0045](rfcs/0045-type-stable-memory.md) and [RFC 0044](rfcs/0044-safe-cxx.md) for safe C++, [RFC 0043](rfcs/0043-ownership.md), [RFC 0042](rfcs/0042-typed-memory.md) and [RFC 0041](rfcs/0041-safe-c.md) for safe C, and [RFC 0038](rfcs/0038-drop-in-everywhere.md), over the +The design today is [RFC 0057](rfcs/0057-foreign-code-by-contract.md) for code WeaveC did not compile (a safe function reaches it only through a contract: a row of the library table or a `WEAVEC_FOREIGN` declaration, checked at the call, with the link refusing a call that has none), [RFC 0056](rfcs/0056-bounds-without-declarations.md) for the bounds of pointers with no declaration (found from the runtime's records when a safe function runs, passed by a safe caller that holds them, listed for `--weavec-fix-bounds`), [RFC 0055](rfcs/0055-a-heap-for-safe-code.md) for the heap of fast safe code (the threads' entries and the short paths, typed `realloc`, one contract for both languages), [RFC 0054](rfcs/0054-one-of-several-types.md) for values of one of several types (tagged unions, checked conversions and downcasts), [RFC 0053](rfcs/0053-callables-and-containers-by-their-loans.md) for callables and containers by their loans and [RFC 0052](rfcs/0052-what-a-call-may-reach.md) for what a call may reach in safe C++ (reach by types, results, views, callables, values built from borrows), [RFC 0051](rfcs/0051-nothing-undefined.md) for what a safe function may not leave undefined (the list of the two languages' undefined behavior, the definitions and the stops, the rules that reject what asserts, the comparison of safe units at the link), [RFC 0050](rfcs/0050-checked-once.md) for what a fast safe unit checks once (views, the typed allocator's paths, Safe C's library calls), [RFC 0049](rfcs/0049-errors-that-carry-their-fix.md) for the fixes errors carry and `--weavec-fix`, [RFC 0048](rfcs/0048-safe-code-without-the-shadow.md) for what a fast safe unit checks and believes, [RFC 0047](rfcs/0047-conversion-in-place.md) for converting existing C++, [RFC 0046](rfcs/0046-thread-safety.md), [RFC 0045](rfcs/0045-type-stable-memory.md) and [RFC 0044](rfcs/0044-safe-cxx.md) for safe C++, [RFC 0043](rfcs/0043-ownership.md), [RFC 0042](rfcs/0042-typed-memory.md) and [RFC 0041](rfcs/0041-safe-c.md) for safe C, and [RFC 0038](rfcs/0038-drop-in-everywhere.md), over the sweep and colors of [RFC 0037](rfcs/0037-complete-sweep-and-colors.md), the reuse after a sweep of [RFC 0036](rfcs/0036-deterministic-heap-reuse.md) and the guards of [RFC 0035](rfcs/0035-guard-by-default.md). The @@ -12,7 +12,50 @@ milestones before it are summarized under _History_; their RFCs keep the detail, and the per-RFC validation records of the milestones before RFC 0030 remain in the repository history at tag `v0.10.0`. -## Now: RFC 0056 — Bounds without declarations +## Now: RFC 0057 — Foreign code by contract + +Design: [RFC 0057 — Foreign code by contract](rfcs/0057-foreign-code-by-contract.md) +(Accepted, built; its _Implementation amendments_ and _Measured gates_ say +how). A safe function reaches code WeaveC did not compile (the C library, a +system library, a unit built with `-fno-weavec`) only through a _contract_: +a row of the library table, which now has one for every function and global +of the covered headers through which a pointer crosses, or a declaration +the program marks `WEAVEC_FOREIGN` (with `*p` counts and +`WEAVEC_FOREIGN_FIELD` for a foreign struct's members). The call is checked +against the contract before it is made, the rules cross it (owners, borrows, +kept addresses), a link in which safe code calls a foreign function with no +contract fails (`foreign-call`, with the contract proposed), the checked +build watches the bytes after what a contract lets foreign code write +(`foreign-overflow`), and the ledger and the audit list every contract and +say whether the program is `closed`. Runtime ABI 53, ledger 17, audit 12, +records 3. + +- [x] **The RFC**, accepted as drafted on 2026-12-05. +- [x] **S0**: every limit met (2 calls through `...` left to code that is + not safe; the link's check 0.03% to 0.5%; the monitor 14.6 to 18.8 ns + a watched argument). +- [x] **The probes** (G2): each of the motivation's programs does not link + without a contract, and with one is a compile error or stops at the + call in both builds. +- [x] **Nothing breaks** (G3): the fifteen surveyed projects have + `foreign-call` at those two sites and no other rule's count higher; + RFC 0056's projects pass as written; the corpus quick tier is main's + but for two more guarded accesses in lua. +- [x] **Unmodified code** (G5): libpng against the system's zlib with a + zlib contract passes its tests at 1.0004 of the time without it. +- [x] **Wrong contracts** (G6): nine of nine reported by the checked build. +- [x] **Nothing slower** (G8): fast builds within noise of main, checked + builds at most 1.017, compiles 1.013. +- [ ] **New code** (G4): a fresh agent's archive tool over zlib and sqlite3 + is all-safe and closed in 7 minutes in Safe C and 6.5 in safe C++, + 1.56 and 1.44 of the Rust agent's 4.5 (asks 1.25). Injected boundary + bugs: 10 of 11 caught in Safe C, 6 of 10 in safe C++, which has no + owner for a C handle. +- [ ] **A round** (G7): two holes found (a contract's `WEAVEC_ENDED_BY` + checked for its first byte; a counted member stored by an initializer + in a checked C++ unit), both closed; the gate asks for none. + +## Before: RFC 0056 — Bounds without declarations Design: [RFC 0056 — Bounds without declarations](rfcs/0056-bounds-without-declarations.md) (Accepted, built; its _Implementation amendments_ and _Measured gates_ say diff --git a/docs/scripts/check-examples.py b/docs/scripts/check-examples.py index f94c4f2..e164e85 100755 --- a/docs/scripts/check-examples.py +++ b/docs/scripts/check-examples.py @@ -3,7 +3,7 @@ Every example in docs/examples must compile. `weavec-cc` must compile lookup.c, record the guarded load of `table[i]` in the enforcement ledger -(`weavec-ledger` version 16, RFC 0035 section 9, RFC 0039 section 8, RFC 0042 section 10, RFC 0043 section 11, RFC 0046 section 12), link it, run it, and stop +(`weavec-ledger` version 17, RFC 0035 section 9, RFC 0039 section 8, RFC 0042 section 10, RFC 0043 section 11, RFC 0046 section 12), link it, run it, and stop a negative index with an `index-out-of-bounds` report; and it must build vec.c and stop a read past its heap block with a `heap-buffer-overflow` report, its stack and its summary line (RFC 0035 section 5.3, RFC 0040 @@ -65,7 +65,7 @@ def expect_trap(result, kind, name, line, detail): assert enforcement_summary(compiled.stderr, "lookup.c"), "no summary line:\n" + compiled.stderr ledger = json.loads((ledgers / "lookup.o.ledger.json").read_text()) - assert ledger["schema"] == "weavec-ledger" and ledger["version"] == 16, ledger + assert ledger["schema"] == "weavec-ledger" and ledger["version"] == 17, ledger rows = [row for unit in ledger["units"] for row in unit["rows"] if row["function"] == "lookup" and row["line"] == 8 and row["operation"] == "load"] assert rows, "no ledger row for the load of table[i]" diff --git a/include/weavec/Core/LibrarySpec.h b/include/weavec/Core/LibrarySpec.h index e6d74ba..168f20d 100644 --- a/include/weavec/Core/LibrarySpec.h +++ b/include/weavec/Core/LibrarySpec.h @@ -43,15 +43,19 @@ namespace weavec::core { /// A small expression over a call's arguments: /// -/// term ::= INT | 'a' N | 'strlen(a' N ')' | term '*' term -/// | term '+' term | term '-' INT | term '/' INT +/// term ::= INT | 'a' N | '*a' N | 'strlen(a' N ')' | 'a' N '-' 'a' N +/// | term '*' term | term '+' term | term '-' INT | term '/' INT /// | 'min(' term ',' term ')' | '(' term ')' /// /// `*` and `/` bind tighter than `+` and `-`; all associate to the left. /// `strlen(aN)` counts the elements of argument N's string before its /// terminator; inside `min(t, …)` it is the bounded length `strnlen(aN, t)` -/// and requires no terminator within `t` elements. Terms are mathematical -/// integers. +/// and requires no terminator within `t` elements. `*aN` (RFC 0057 §4.2) is +/// the unsigned integer argument N points to when the call is made, of the +/// width the parameter's `bytes(W)` gives (zero when the argument is null). +/// `aE-aS` (RFC 0057 amendment 4) is the bytes from pointer argument S to +/// pointer argument E; an end before its start is more than any object has. +/// Terms are mathematical integers. struct LibTerm { enum class Kind : std::uint8_t { Constant, ///< `value` @@ -62,6 +66,8 @@ struct LibTerm { Difference, ///< `operands[0] - value` Min, ///< `min(operands[0], operands[1])` Quotient, ///< `operands[0] / value`, rounded down + Pointee, ///< `*a` + Distance, ///< `a - a`: the bytes from one pointer to another }; Kind kind = Kind::Constant; std::int64_t value = 0; @@ -72,6 +78,10 @@ struct LibTerm { [[nodiscard]] static LibTerm constant(std::int64_t value); [[nodiscard]] static LibTerm argument(unsigned index); [[nodiscard]] static LibTerm stringLength(unsigned index); + [[nodiscard]] static LibTerm pointee(unsigned index); + /// RFC 0057 amendment 4: the bytes from pointer argument `start` to + /// pointer argument `end`. + [[nodiscard]] static LibTerm distance(unsigned end, unsigned start); [[nodiscard]] static LibTerm product(LibTerm left, LibTerm right); [[nodiscard]] static LibTerm sum(LibTerm left, LibTerm right); [[nodiscard]] static LibTerm difference(LibTerm left, std::int64_t right); @@ -89,6 +99,9 @@ struct LibTerm { struct Values { std::function(unsigned)> argument; std::function(unsigned)> stringLength; + // A designated initializer may leave it out. + // NOLINTNEXTLINE(readability-redundant-member-init) + std::function(unsigned)> pointee = {}; }; /// Evaluates the term, or `std::nullopt` when a leaf is unknown or the /// value leaves the range of `std::int64_t`. @@ -172,6 +185,13 @@ struct LibraryParam { /// `owner` (RFC 0043 §2): the pointer points to a place the call stores /// an owner in (`asprintf`'s first argument). bool owner = false; + /// `kept` (RFC 0057 §4.2): the callee keeps the pointer past its return + /// (`WEAVEC_ESCAPES` to the rules). + bool kept = false; + /// `handle` (RFC 0057 §4.2): the access of a pointer through which the + /// callee is given no byte of the caller's (a `FILE *`, a pointer to an + /// incomplete type). Its `access` is `None` and null is allowed. + bool handle = false; friend bool operator==(const LibraryParam &, const LibraryParam &) = default; }; @@ -208,6 +228,12 @@ struct LibraryEntry { bool owned = false; /// `value(t)` (Int): the result equals `t` (`strlen` is `strlen(a0)`). std::optional value; + /// RFC 0057 §4.2: `ptr:str`, the result points to a terminated string; + /// `ptr:bytes(t)`, to `t` bytes; `ptr:of(aN)`, into what argument N + /// points to or owns (a borrow of it). + bool resultString = false; + std::optional resultBytes; + std::optional resultOf; /// `fills(t)` (RFC 0051 amendment 18): every byte the call writes into its /// first written argument is `t` (`memset`'s `fills(a1)`, `bzero`'s /// `fills(0)`), so that a fill with zero is known for one. @@ -324,6 +350,16 @@ class LibrarySpec { [[nodiscard]] bool functionIs(std::string_view qualified, std::string_view trait) const; + /// RFC 0057 §3.4: the kind of the table's row for the global `name` + /// (`global NAME : KIND;`): `handle` (a pointer safe code passes on and + /// does not read through, `stdout`), `str` (a string or null, `optarg`), + /// `strings` (an array of strings, `environ`) or `object` (an object of + /// its type); `std::nullopt` when the table has none. + [[nodiscard]] std::optional + global(std::string_view name) const; + /// How many global rows the table has. + [[nodiscard]] std::size_t globalCount() const { return globals.size(); } + /// The row named exactly `name` (the first, if it has overloads). [[nodiscard]] const LibraryEntry *find(std::string_view name) const; /// Resolves a callee name: the row's own name, a `chk` alias, or either @@ -345,6 +381,8 @@ class LibrarySpec { std::set> traits; std::set> members; std::set> functions; + /// RFC 0057 §3.4: the global rows, each with its kind. + std::map> globals; /// RFC 0047: (class, member) to its count's member; to its arguments' /// bounds. std::map, std::string> counts; diff --git a/include/weavec/Frontend/Definitions.h b/include/weavec/Frontend/Definitions.h index 5392e51..fd47fa5 100644 --- a/include/weavec/Frontend/Definitions.h +++ b/include/weavec/Frontend/Definitions.h @@ -43,10 +43,18 @@ inline constexpr llvm::StringLiteral DefinitionsSectionMachO = inline constexpr llvm::StringLiteral DefinitionsSectionName = "__weavec_defs"; inline constexpr llvm::StringLiteral DefinitionsSectionELF = ".weavec.defs"; /// The bytes each unit's record starts with. -inline constexpr llvm::StringLiteral DefinitionsHeader = "weavec-defs 2\n"; +inline constexpr llvm::StringLiteral DefinitionsHeader = "weavec-defs 3\n"; +/// RFC 0057 §7.3: the section that marks an image every object of which +/// carries a record (it holds the runtime's ABI, a 32-bit integer; ELF's +/// is a note of the owner `WeaveC`). +inline constexpr llvm::StringLiteral ImageMarkSegmentMachO = "__DATA"; +inline constexpr llvm::StringLiteral ImageMarkSectionMachO = "__weavec_img"; +inline constexpr llvm::StringLiteral ImageMarkSectionELF = ".note.weavec"; -/// §5.1: the record of a unit with safe functions, from its AST at the end -/// of the unit; empty when it has none. +/// §5.1: the record of a unit, from its AST at the end of the unit: what a +/// safe unit shares, and (RFC 0057 §7.1) what every unit calls that it +/// does not define. A unit with no safe function has a record too, which +/// marks its object as code WeaveC compiled. [[nodiscard]] std::string recordDefinitions(clang::ASTContext &ast, const SafeUnit &unit); @@ -60,23 +68,74 @@ struct DefinitionsCompared { unsigned mismatches = 0; }; +/// RFC 0057 §7.2: what a link's records say of the code WeaveC did not +/// compile. +struct ForeignChecked { + /// The functions and globals safe code uses that their units do not + /// define (`X`), and those of them no input WeaveC compiled defines: + /// each is a `foreign-call` error. + unsigned expected = 0; + unsigned missing = 0; + /// The functions the link's units call by a contract or a row; with + /// the read's `counts`, those no input WeaveC compiled defines through + /// which nothing crosses, and those code that is not safe calls with no + /// contract. + unsigned contracts = 0; + unsigned uncrossed = 0; + unsigned unchecked = 0; + /// Every relocatable object and archive member read carries a record + /// (and there is one): the image is WeaveC's whole (§7.3). + bool whole = false; +}; + /// What one read of a link's inputs found. struct LinkRead { DefinitionsCompared definitions; + ForeignChecked foreign; /// The first input that is (or, an archive, holds) a relocatable object /// defining the allocator's symbol strongly: the program's own allocator /// (RFC 0032 §2.6); empty for none. std::string allocator; + /// With `LinkWanted::join`: the records of every input, one after + /// another. + // A designated initializer may leave it out. + // NOLINTNEXTLINE(readability-redundant-member-init) + std::string joined = {}; +}; + +/// What a read of a link's inputs is to do: compare the safe units' +/// records (§5.2); count, for the summary line, the functions the link's +/// units call that no input WeaveC compiled defines; keep the bytes of +/// every record read (`joined`), for a partial link to carry; and find the +/// input that defines the `allocator` symbol. +struct LinkWanted { + bool compare = true; + bool counts = false; + bool join = false; + /// The link is a partial one (`-r`): what its records use is looked for + /// by the link of the image. + bool partial = false; + llvm::StringRef allocator; }; /// §5.2: reads each of `inputs` (objects, archives, linked images) once, in /// parallel: with `compare`, compares the safe units' records, writing an /// error and its notes to `errors` for each name two disagree on; with an -/// `allocator` symbol, finds the input that defines it. +/// `allocator` symbol, finds the input that defines it. RFC 0057 §7.2: +/// whatever `compare` says, each function or global safe code uses that +/// no input WeaveC compiled defines is an error (`foreign-call`); the +/// inputs' symbols are read only when a record names one, or for the +/// counts. [[nodiscard]] LinkRead readLink(llvm::ArrayRef inputs, - bool compare, llvm::StringRef allocator, + const LinkWanted &want, llvm::raw_ostream &errors); +/// A record that says the object it is in holds code WeaveC did not +/// compile too: what a partial link of such inputs adds, so that the +/// object's definitions are not taken for WeaveC's by the link that +/// follows. +[[nodiscard]] std::string mixedRecord(); + } // namespace weavec::frontend #endif // WEAVEC_FRONTEND_DEFINITIONS_H diff --git a/include/weavec/Frontend/Driver.h b/include/weavec/Frontend/Driver.h index 2879507..0731492 100644 --- a/include/weavec/Frontend/Driver.h +++ b/include/weavec/Frontend/Driver.h @@ -64,6 +64,10 @@ struct DriverOptions { /// `-f[no-]weavec-safe-survey` (RFC 0047 §7): the rules also run over the /// functions that are not safe, and the ledger counts their errors. bool survey = false; + /// `-fweavec-contracts=
` (RFC 0057 §3.1): headers of contracts + /// (`WEAVEC_FOREIGN` declarations) included in every C and C++ unit, + /// after the command line's own `-include` files, in the order given. + std::vector contracts; /// `-fweavec-ledger=` (RFC 0035 §9). std::string ledger; /// RFC 0049 §5: `-fweavec-fix-wants=`, which `--weavec-fix` passes diff --git a/include/weavec/Frontend/EnforcementLedger.h b/include/weavec/Frontend/EnforcementLedger.h index 02bbd45..5bd6b87 100644 --- a/include/weavec/Frontend/EnforcementLedger.h +++ b/include/weavec/Frontend/EnforcementLedger.h @@ -34,7 +34,7 @@ namespace weavec::frontend { /// The version of the `weavec-ledger` JSON this writes. -inline constexpr unsigned EnforcementLedgerVersion = 16; +inline constexpr unsigned EnforcementLedgerVersion = 17; /// What the pass decided for one access. struct LedgerRow { @@ -147,6 +147,19 @@ struct EnforcementLedger { /// find when they run, and the questions those functions ask. std::vector found; std::uint64_t foundBounds = 0; + /// RFC 0057 §9: the functions with a row or a contract the unit calls; + /// what safe code uses that the link must find (`expects`); the + /// functions with no body in the unit that safe code calls and through + /// which nothing crosses; and the calls from functions that are not safe + /// of functions with no body, no row and no contract through which a + /// pointer crosses. + std::vector foreign; + std::vector expects; + std::vector uncrossed; + std::vector unchecked; + /// The globals the unit defines that other units can name (`defines`), + /// among which the audit finds what another unit expects. + std::vector defines; /// RFC 0054 §5: the checked conversions and the checked accesses of a /// tagged union's members in safe code. std::uint64_t checkedCasts = 0; @@ -231,6 +244,13 @@ bool writeEnforcementLedger(const EnforcementLedger &ledger, [[nodiscard]] llvm::json::Value errorJson(const RuleError &error); bool readFix(const llvm::json::Value &value, RuleFix &fix); bool readError(const llvm::json::Value &value, RuleError &error); +/// RFC 0057 §9: an entry of a unit's `foreign` list, and one of its +/// `expects`, `uncrossed` and `unchecked` lists. +[[nodiscard]] llvm::json::Value foreignJson(const ForeignFunction &function); +bool readForeign(const llvm::json::Value &value, ForeignFunction &function); +[[nodiscard]] llvm::json::Value foreignUseJson(const ForeignUse &use); +bool readForeignUse(const llvm::json::Value &value, ForeignUse &use); + /// RFC 0056 §8: an entry of a unit's `found` list. [[nodiscard]] llvm::json::Value foundJson(const FoundBound &found); bool readFound(const llvm::json::Value &value, FoundBound &found); diff --git a/include/weavec/Frontend/RuleFix.h b/include/weavec/Frontend/RuleFix.h index aca6f20..31b2531 100644 --- a/include/weavec/Frontend/RuleFix.h +++ b/include/weavec/Frontend/RuleFix.h @@ -110,6 +110,49 @@ struct FoundBound { std::vector fixes; }; +/// RFC 0057 §9: a function with a contract (a row of the library table, +/// or a declaration marked `WEAVEC_FOREIGN`) that a unit calls. +struct ForeignFunction { + std::string function; + /// `table` or `declared`. + std::string contract; + /// A declared contract: where it is written. A table row: the header + /// that declares the function. + std::string file; + unsigned line = 0; + unsigned column = 0; + /// The row (a declared contract's as it was lowered: §4.1). + std::string row; + /// The calls from safe and from guarded functions. + unsigned safeCalls = 0; + unsigned guardedCalls = 0; + /// A global's contract (§3.4). + bool global = false; +}; + +/// RFC 0057 §7.1, §9: a function or a global with no body, no row and no +/// contract in the unit. `expects`: safe code calls it, takes its address +/// or names it, and a pointer crosses (the link must find it in code +/// WeaveC compiled). `uncrossed`: safe code uses it and nothing crosses. +/// `unchecked`: code that is not safe calls it and a pointer crosses. +struct ForeignUse { + /// The source's name and the linker's symbol (without Mach-O's `_`). + std::string function; + std::string symbol; + /// `call`, `address` or `global`. + std::string use; + /// The first place, its function, and how many places there are. + std::string file; + unsigned line = 0; + unsigned column = 0; + std::string caller; + unsigned places = 0; + /// The contract the planner proposes (§10); empty where nothing crosses. + std::string proposal; + /// Under the survey: of code that is not safe yet. + bool surveyed = false; +}; + /// A file of the project a unit read (§6): to refuse to edit one that /// changed since. struct ReadFile { diff --git a/include/weavec/Frontend/SafeCheck.h b/include/weavec/Frontend/SafeCheck.h index 802a671..43bfeaf 100644 --- a/include/weavec/Frontend/SafeCheck.h +++ b/include/weavec/Frontend/SafeCheck.h @@ -48,6 +48,10 @@ class ASTConsumer; class CompilerInstance; } // namespace clang +namespace weavec::core { +class LibrarySpec; +} // namespace weavec::core + namespace weavec::frontend { /// The annotations of `resources/include/weavec.h` (§1, §2, §5), which spells @@ -81,6 +85,14 @@ inline constexpr llvm::StringLiteral SafeFilePragmaNamespace = "weavec"; inline constexpr llvm::StringLiteral SafeFilePragmaWord = "safe"; /// RFC 0043 §2: the one pointer responsible for releasing its block. inline constexpr llvm::StringLiteral OwnedAnnotation = "weavec.owned"; +/// RFC 0057 §3: `WEAVEC_FOREIGN`, on a declaration with no body: the +/// contract of a function or a global that code WeaveC did not compile +/// defines. `WEAVEC_FOREIGN_FIELD(type, field, annotations)`: a typedef, +/// never used, of the member's type with the annotations, marked with the +/// names (§3.3). +inline constexpr llvm::StringLiteral ForeignAnnotation = "weavec.foreign"; +inline constexpr llvm::StringLiteral ForeignFieldAnnotation = + "weavec.foreign_field"; /// RFC 0043 amendment: the function leaves every owner below the parameter /// null (a destructor of a struct the caller keeps). inline constexpr llvm::StringLiteral DropsAnnotation = "weavec.drops"; @@ -194,6 +206,11 @@ struct PointerBounds { int count = -1; /// Counted: the count's type is signed (a negative count is empty). bool countSigned = false; + /// RFC 0057 §3.2, in a contract: the count is the integer of + /// `pointeeWidth` bytes that parameter `countPointee` points to when the + /// call is made (`WEAVEC_COUNTED_BY(*p)`); `count` is then -1. + int countPointee = -1; + unsigned pointeeWidth = 0; std::uint64_t constant = 0; /// Counted: the bytes of one element (1 for `WEAVEC_SIZED_BY`). std::uint64_t elementSize = 1; @@ -436,6 +453,26 @@ struct SafeUnit { /// the evidence proposes (what `-fweavec-safe-bounds=declared` reports /// as errors). std::vector boundsFound; + /// RFC 0057 §4.1: the unit's contracts as rows, which the passes read + /// before the table's (null when it declares none), and each contract by + /// its row's name (the function's symbol as the IR names it, without + /// Darwin's variant suffix) with where it is declared. + std::shared_ptr contractRows; + struct Contract { + std::string file; + unsigned line = 0; + unsigned column = 0; + std::string row; + }; + llvm::StringMap contracts; + /// RFC 0057 §9: what the unit calls that it does not define. + std::vector foreign; + std::vector expects; + std::vector uncrossed; + std::vector unchecked; + /// The globals the unit defines that other units can name (their + /// symbols): the audit finds another unit's `expects` among them. + std::vector definedGlobals; /// RFC 0054 §3: each access of a tagged union's member in safe code. struct TaggedAccess { /// The tag's offset in its struct, its width in bytes, its mask. diff --git a/lib/Core/LibrarySpec.cpp b/lib/Core/LibrarySpec.cpp index 5de8e1f..679c4d7 100644 --- a/lib/Core/LibrarySpec.cpp +++ b/lib/Core/LibrarySpec.cpp @@ -41,6 +41,17 @@ LibTerm LibTerm::stringLength(unsigned index) { .arg = static_cast(index)}; } +LibTerm LibTerm::pointee(unsigned index) { + return LibTerm{.kind = Kind::Pointee, + .arg = static_cast(index)}; +} + +LibTerm LibTerm::distance(unsigned end, unsigned start) { + return LibTerm{.kind = Kind::Distance, + .value = static_cast(start), + .arg = static_cast(end)}; +} + static LibTerm binary(LibTerm::Kind kind, LibTerm left, LibTerm right) { LibTerm term{.kind = kind}; term.operands.push_back(std::move(left)); @@ -74,7 +85,8 @@ LibTerm LibTerm::quotient(LibTerm left, std::int64_t divisor) { static bool isAdditive(const LibTerm &term) { return term.kind == LibTerm::Kind::Sum || - term.kind == LibTerm::Kind::Difference; + term.kind == LibTerm::Kind::Difference || + term.kind == LibTerm::Kind::Distance; } static std::string parenthesised(const LibTerm &term, bool needed) { @@ -89,6 +101,10 @@ std::string LibTerm::str() const { return "a" + std::to_string(arg); case Kind::StringLength: return "strlen(a" + std::to_string(arg) + ")"; + case Kind::Pointee: + return "*a" + std::to_string(arg); + case Kind::Distance: + return "a" + std::to_string(arg) + "-a" + std::to_string(value); case Kind::Product: return parenthesised(operands[0], isAdditive(operands[0])) + "*" + parenthesised(operands[1], isAdditive(operands[1]) || @@ -147,6 +163,11 @@ std::optional LibTerm::evaluate(const Values &values) const { return ask(values.argument, arg); case Kind::StringLength: return ask(values.stringLength, arg); + case Kind::Pointee: + return ask(values.pointee, arg); + // Two addresses, which only the running program has. + case Kind::Distance: + return std::nullopt; case Kind::Difference: { const auto left = operands[0].evaluate(values); if (!left || value == std::numeric_limits::min()) @@ -338,6 +359,17 @@ class TermReader { return std::nullopt; left = LibTerm::sum(std::move(*left), std::move(*right)); } else if (accept("-")) { + // RFC 0057 amendment 4: `aE-aS`, the bytes from one pointer + // argument to another. + skipSpace(); + if (pos + 1 < text.size() && text[pos] == 'a' && + isDigit(text[pos + 1])) { + const auto start = argumentIndex(); + if (!start || left->kind != LibTerm::Kind::Argument) + return fail("expected 'aN-aM' of two pointer arguments in a term"); + left = LibTerm::distance(left->arg, *start); + continue; + } const auto right = number(); if (!right) return fail("expected an integer after '-' in a term"); @@ -408,6 +440,15 @@ class TermReader { return fail("argument index out of range in a term"); return LibTerm::argument(*index); } + // RFC 0057 §4.2: the integer an argument points to. + if (text[pos] == '*' && pos + 2 < text.size() && text[pos + 1] == 'a' && + isDigit(text[pos + 2])) { + ++pos; + const auto index = argumentIndex(); + if (!index) + return fail("argument index out of range in a term"); + return LibTerm::pointee(*index); + } return fail("expected a term"); } }; @@ -572,6 +613,11 @@ std::optional LibrarySpecParser::parseParam() { param.access = LibraryParam::Access::ReadWrite; } else if (head == "none") { param.access = LibraryParam::Access::None; + } else if (head == "handle") { + // RFC 0057 §4.2: no byte of the caller's, and null is allowed. + param.access = LibraryParam::Access::None; + param.null = LibraryParam::Null::Allowed; + param.handle = true; } else { fail("expected a parameter, found '" + head + "'"); return std::nullopt; @@ -614,6 +660,8 @@ std::optional LibrarySpecParser::parseParam() { param.effect = LibraryParam::Effect::Realloc; } else if (flag == "owner") { param.owner = true; + } else if (flag == "kept") { + param.kept = true; } else { fail("unknown parameter flag '" + flag + "'"); return std::nullopt; @@ -627,6 +675,12 @@ std::optional LibrarySpecParser::parseParam() { fail("'bytes' and 'count' exclude each other"); return std::nullopt; } + if (param.handle && + (param.bytes || param.count || param.string || param.scan || + seen.contains("null-ok") || seen.contains("null-if-zero"))) { + fail("'handle' takes no bytes, string or null flag"); + return std::nullopt; + } if (param.string && param.access != LibraryParam::Access::Read && param.access != LibraryParam::Access::ReadWrite) { fail("'str' needs 'r' or 'rw'"); @@ -645,11 +699,37 @@ bool LibrarySpecParser::parseResult(LibraryEntry &entry) { entry.result = LibraryEntry::Result::Void; } else if (kind == "ptr") { entry.result = LibraryEntry::Result::Pointer; - if (accept(':')) { - if (word() != "owned") - return fail("expected 'owned' after 'ptr:'"); - entry.owned = true; + // RFC 0057 §4.2: `ptr:str`, `ptr:bytes(t)`, `ptr:of(aN)`, in any + // order after `owned`. + std::set seen; + while (accept(':')) { + const std::string flag = word(); + if (!seen.insert(flag).second) + return fail("duplicate result flag '" + flag + "'"); + if (flag == "owned") { + entry.owned = true; + } else if (flag == "str") { + entry.resultString = true; + } else if (flag == "bytes") { + entry.resultBytes = parenthesisedTerm("bytes"); + if (!entry.resultBytes) + return false; + } else if (flag == "of") { + if (!expect('(', "after 'of'") || !accept('a')) + return fail("expected 'of(aN)' after 'ptr:'"); + const auto argument = index("an argument index"); + if (!argument || !expect(')', "after 'of(aN'")) + return false; + entry.resultOf = argument; + } else { + return fail("expected 'owned', 'str', 'bytes(…)' or 'of(aN)' after " + "'ptr:'"); + } } + if (entry.resultString && entry.resultBytes) + return fail("'ptr:str' and 'ptr:bytes' exclude each other"); + if (entry.owned && entry.resultOf) + return fail("'ptr:owned' and 'ptr:of' exclude each other"); } else if (kind == "int") { entry.result = LibraryEntry::Result::Int; if (accept(':')) { @@ -817,10 +897,40 @@ bool LibrarySpecParser::validateTerm(const LibraryEntry &entry, const LibTerm &value, std::string_view where) { if ((value.kind == LibTerm::Kind::Argument || - value.kind == LibTerm::Kind::StringLength) && + value.kind == LibTerm::Kind::StringLength || + value.kind == LibTerm::Kind::Pointee || + value.kind == LibTerm::Kind::Distance) && value.arg >= entry.params.size()) return fail("argument a" + std::to_string(value.arg) + " of " + std::string(where) + " is past the row's parameters"); + // RFC 0057 §4.2: `*aN` reads an integer of the width `bytes(W)` gives. + if (value.kind == LibTerm::Kind::Pointee) { + const LibraryParam &pointer = entry.params[value.arg]; + const bool readable = pointer.type == LibraryParam::Type::Pointer && + (pointer.access == LibraryParam::Access::Read || + pointer.access == LibraryParam::Access::ReadWrite); + const bool width = + pointer.bytes && pointer.bytes->kind == LibTerm::Kind::Constant && + (pointer.bytes->value == 1 || pointer.bytes->value == 2 || + pointer.bytes->value == 4 || pointer.bytes->value == 8); + if (!readable || !width) + return fail("*a" + std::to_string(value.arg) + " of " + + std::string(where) + + " needs a read pointer with 'bytes(1)', 'bytes(2)', " + "'bytes(4)' or 'bytes(8)'"); + } + // RFC 0057 amendment 4: a difference of two pointer arguments. + if (value.kind == LibTerm::Kind::Distance) { + const auto start = static_cast(value.value); + if (start >= entry.params.size()) + return fail("argument a" + std::to_string(start) + " of " + + std::string(where) + " is past the row's parameters"); + if (entry.params[value.arg].type != LibraryParam::Type::Pointer || + entry.params[start].type != LibraryParam::Type::Pointer) + return fail("a" + std::to_string(value.arg) + "-a" + + std::to_string(start) + " of " + std::string(where) + + " names a non-pointer"); + } if (value.kind == LibTerm::Kind::StringLength && entry.params[value.arg].type != LibraryParam::Type::Pointer) return fail("strlen(a" + std::to_string(value.arg) + ") of " + @@ -843,6 +953,14 @@ bool LibrarySpecParser::validateEntry(const LibraryEntry &entry) { } if (entry.value && !validateTerm(entry, *entry.value, "the result")) return false; + if (entry.resultBytes && + !validateTerm(entry, *entry.resultBytes, "the result")) + return false; + if (entry.resultOf && + (*entry.resultOf >= entry.params.size() || + entry.params[*entry.resultOf].type != LibraryParam::Type::Pointer)) + return fail("'ptr:of(a" + std::to_string(*entry.resultOf) + + ")' names no pointer parameter"); if (entry.fills && !validateTerm(entry, *entry.fills, "'fills'")) return false; if ((entry.fills || entry.permutes) && @@ -990,6 +1108,25 @@ bool LibrarySpecParser::parseEntry() { return false; if ((*rowName == "class" || *rowName == "function") && !accept('(')) return parseClass(*rowName == "function"); + // RFC 0057 §3.4: `global NAME : handle;` and the other kinds, the table's + // contract for a global of the C library through which a pointer + // crosses. + if (*rowName == "global" && !accept('(')) { + auto global = name("a global's name"); + if (!global || !expect(':', "after the name")) + return false; + entryName = *global; + const std::string kind = word(); + if (kind != "handle" && kind != "str" && kind != "strings" && + kind != "object") + return fail("expected 'handle', 'str', 'strings' or 'object'"); + if (!spec.globals.emplace(*global, kind).second) + return fail("two rows for the global"); + if (!expect(';', "at the end of the entry") || !atEnd()) + return fail("unexpected text after the entry"); + entryName.clear(); + return true; + } entry.name = *rowName; entryName = entry.name; if (!expect('(', "after the function name")) @@ -1107,6 +1244,14 @@ bool LibrarySpec::functionIs(std::string_view qualified, std::pair(std::string(qualified), std::string(trait))); } +std::optional +LibrarySpec::global(std::string_view name) const { + const auto found = globals.find(name); + if (found == globals.end()) + return std::nullopt; + return found->second; +} + const LibraryEntry *LibrarySpec::find(std::string_view name) const { const auto found = byName.find(name); return found == byName.end() ? nullptr : &rows[found->second]; diff --git a/lib/Core/LibrarySpec.txt b/lib/Core/LibrarySpec.txt index 2a38d0d..d4f2eea 100644 --- a/lib/Core/LibrarySpec.txt +++ b/lib/Core/LibrarySpec.txt @@ -20,13 +20,16 @@ # # ENTRIES # entry ::= NAME '(' params ')' '->' result { clause } ';' +# | 'global' NAME ':' gkind ';' # params ::= [ param { ',' param } ] [ ',' '...' ] # param ::= 'int' | 'other' | 'fn' | access { ':' pflag } -# access ::= 'r' | 'w' | 'rw' | 'none' +# access ::= 'r' | 'w' | 'rw' | 'none' | 'handle' # pflag ::= 'bytes(' term ')' | 'count(' term ')' | 'str' | 'null-ok' # | 'null-if-zero(' term ')' | 'release' | 'realloc' -# | 'scan' | 'scan(' term ')' | 'owner' -# result ::= 'void' | 'int' [ ':value(' term ')' ] | 'ptr' [ ':owned' ] +# | 'scan' | 'scan(' term ')' | 'owner' | 'kept' +# result ::= 'void' | 'int' [ ':value(' term ')' ] +# | 'ptr' [ ':owned' | ':str' | ':bytes(' term ')' | ':of(a' N ')' ] +# gkind ::= 'handle' | 'str' | 'strings' | 'object' # clause ::= 'disjoint(' INT ',' INT ',' term ')' | 'wide' # | 'printf(' INT ',' INT ')' | 'scanf(' INT ',' INT ')' # | 'chk(' NAME ':' carg { ',' carg } ')' @@ -34,8 +37,8 @@ # | 'permutes' # | 'exits' | 'unwinds' | 'typed(' NAME ',' INT ')' # carg ::= INT | '_' | 'size' -# term ::= INT | 'a' N | 'strlen(a' N ')' | term '*' term -# | term '+' term | term '-' INT | term '/' INT +# term ::= INT | 'a' N | '*a' N | 'strlen(a' N ')' | 'a' N '-' 'a' N +# | term '*' term | term '+' term | term '-' INT | term '/' INT # | 'min(' term ',' term ')' | '(' term ')' # # PARAMETERS @@ -66,11 +69,23 @@ # the call consumes (realloc: when its result is not null). # owner the pointer points to a place the call stores an owner # in (RFC 0043 section 2): asprintf's first argument. +# handle (RFC 0057 section 4.2) the call accesses no byte of the +# caller's through the pointer (a FILE *, a pointer to a +# type the library keeps to itself, a locale): nothing is +# guarded and null is allowed. +# kept (RFC 0057 section 4.2) the callee keeps the pointer past +# its return, as a parameter declared WEAVEC_ESCAPES does. # # RESULTS # void, int, ptr no result, any non-pointer result, a pointer. # ptr:owned the caller owns the block the result points to (RFC # 0043 section 2); the allocations' blocks are zero. +# ptr:str, ptr:bytes(t), ptr:of(aN) +# (RFC 0057 section 4.2) the result points to a string, +# to t bytes, or into what argument N points to or owns. +# These are what a declared contract's result lowers to +# (WEAVEC_FOREIGN, section 4.1); a row of this file says +# them where they hold. # value(t) the result equals t (strlen: strlen(a0)); a call whose # result only a value computes from what it reads is # replaced by the guards that compute t. @@ -132,10 +147,19 @@ # # TERMS # aN the value of argument N. +# *aN (RFC 0057 section 4.2) the unsigned integer argument N +# points to when the call is made, of the width the +# parameter's bytes(W) gives; zero when the argument is +# null. An in-out count: w:bytes(*a2) beside rw:bytes(8). # strlen(aN) the length of argument N's string, in elements. Under # min(t, e) a strlen(aN) in e is bounded by t, as # strnlen(aN, t), and needs no terminator within t # elements: min(a2,strlen(a1)+1) is what strncpy reads. +# aE-aS (RFC 0057 amendment 4) the bytes from pointer argument +# S to pointer argument E, when the call is made: what a +# function accesses that takes a start and an end, +# rw:bytes(a1-a0). An end before its start is no range, +# and no access through the start is in bounds. # t / N t divided by the positive integer N, rounded down. # Terms are mathematical integers; a value that leaves 64 bits saturates. # '*' and '/' bind tighter than '+' and '-'. @@ -193,6 +217,19 @@ # any two instructions of the program (a signal handler), which a safe # function does not call (but signal with SIG_IGN or SIG_DFL). # +# CONTRACTS (RFC 0057) +# A safe function calls a function that no code WeaveC compiled defines +# only where a contract says what crosses: a row of this file, or the +# function's prototype declared WEAVEC_FOREIGN, which is lowered to a row +# of this grammar (section 4.1). So this file has a row for every +# function through which a pointer crosses that ISO C's and POSIX's +# headers declare on the two platforms, whether or not a guard needs it +# (section 4.3), and a global row for each of their globals that is or +# holds a pointer: handle (a pointer safe code passes on, stdout), str (a +# string or null, optarg), strings (an array of strings, environ) or +# object (an object of its type). scripts/check-table.py compares the +# file with the platform's headers; the hygiene gate runs it. +# # OVERLOADS # A name may have several rows; a call uses the first whose arity it # matches (a variadic row accepts more arguments), or else the first. @@ -255,7 +292,7 @@ vasprintf (w:bytes(8):owner, r:str, other) -> int printf(1,2) \ # after a failed read: it is freed on every path. getline (rw:null-ok:bytes(8):owner, rw:null-ok, rw) -> int wrapper(getline); getdelim (rw:null-ok:bytes(8):owner, rw:null-ok, int, rw) -> int \ - wrapper(getdelim); + wrapper(getdelim) chk(__getdelim:0,1,2,3); tempnam (r:str:null-ok, r:str:null-ok) -> ptr:owned; # getcwd(NULL, n) allocates (glibc, BSD, macOS). @@ -305,11 +342,12 @@ strncpy (w:bytes(a2):null-if-zero(a2), \ chk(__builtin___strncpy_chk:0,1,2,size) chk(__strncpy_chk:0,1,2,size); stpcpy (w:bytes(strlen(a1)+1), r:str) -> ptr disjoint(0,1,strlen(a1)+1) \ wrapper(stpcpy) chk(__builtin___stpcpy_chk:0,1,size) \ - chk(__stpcpy_chk:0,1,size); + chk(__stpcpy_chk:0,1,size) chk(__stpcpy:0,1); stpncpy (w:bytes(a2):null-if-zero(a2), \ r:bytes(min(a2,strlen(a1)+1)):null-if-zero(a2), int) -> ptr \ disjoint(0,1,min(a2,strlen(a1)+1)) \ - chk(__builtin___stpncpy_chk:0,1,2,size) chk(__stpncpy_chk:0,1,2,size); + chk(__builtin___stpncpy_chk:0,1,2,size) chk(__stpncpy_chk:0,1,2,size) \ + chk(__stpncpy:0,1,2); strcat (rw:bytes(strlen(a0)+strlen(a1)+1):str, r:str) -> ptr \ disjoint(0,1,strlen(a0)+strlen(a1)+1) wrapper(strcat) \ chk(__builtin___strcat_chk:0,1,size) chk(__strcat_chk:0,1,size); @@ -347,7 +385,7 @@ strpbrk (r:scan, r:str) -> ptr; strspn (r:scan, r:str) -> int; strcspn (r:scan, r:str) -> int; strtok (rw:str:null-ok, r:str) -> ptr unshared; -strtok_r (rw:str:null-ok, r:str, rw:bytes(8)) -> ptr; +strtok_r (rw:str:null-ok, r:str, rw:bytes(8)) -> ptr chk(__strtok_r:0,1,2); strsep (rw, r:str) -> ptr; # GNU: the message is in buf or in static storage. XSI: an int result. # RFC 0046 section 1: strerror's result is a buffer every caller shares. @@ -363,7 +401,7 @@ bzero (w:bytes(a1):null-if-zero(a1), int) -> void fills(0); bcopy (r:bytes(a2):null-if-zero(a2), w:bytes(a2):null-if-zero(a2), int) -> \ void; bcmp (r:bytes(a2):null-if-zero(a2), r:bytes(a2):null-if-zero(a2), int) -> \ - int; + int chk(__memcmpeq:0,1,2); index (r:str:scan, int) -> ptr; rindex (r:str, int) -> ptr; strcasecmp (r:str, r:str) -> int wrapper(strcasecmp); @@ -387,9 +425,11 @@ open_memstream (w:null-ok:bytes(8), w:null-ok) -> ptr; popen (r:str, r:str) -> ptr; fflush (rw:null-ok) -> int; fpurge (rw) -> int; -setvbuf (rw, w:bytes(a3):null-ok, int, int) -> int; -setbuf (rw, w:null-ok) -> void; -setbuffer (rw, w:bytes(a2):null-ok, int) -> void; +# The stream keeps the buffer until it is closed or given another. setbuf's +# is BUFSIZ bytes: 1024 on Darwin, the smaller of the two. +setvbuf (rw, w:bytes(a3):null-ok:kept, int, int) -> int; +setbuf (rw, w:bytes(1024):null-ok:kept) -> void; +setbuffer (rw, w:bytes(a2):null-ok:kept, int) -> void; setlinebuf (rw) -> void; fileno (r) -> int; fileno_unlocked (r) -> int; @@ -507,7 +547,8 @@ secure_getenv (r:str) -> ptr; setenv (r:str:null-ok, r:str, int) -> int unshared; unsetenv (r:str:null-ok) -> int unshared; # The string itself becomes part of the environment. -putenv (r:str:null-ok) -> int unshared; +# The string becomes part of the environment. +putenv (r:str:null-ok:kept) -> int unshared; system (r:str:null-ok) -> int; qsort (rw:bytes(a1*a2):null-if-zero(a1*a2), int, int, fn) -> void permutes; # glibc (and C2y): compar(a, b, arg). BSD and macOS: compar(thunk, a, b). @@ -534,8 +575,9 @@ mkdtemp (rw:str) -> ptr; mktemp (rw:str) -> ptr; rand_r (rw) -> int; # The library keeps using the state array after the call. -initstate (int, w:bytes(a2), int) -> ptr; -setstate (rw) -> ptr; +# The generator keeps the state array. +initstate (int, w:bytes(a2):kept, int) -> ptr; +setstate (rw:kept) -> ptr; erand48 (rw:bytes(6)) -> int; nrand48 (rw:bytes(6)) -> int; jrand48 (rw:bytes(6)) -> int; @@ -765,7 +807,8 @@ error (int, int, r:str, ...) -> void printf(2,3); error_at_line (int, int, r:str:null-ok, int, r:str, ...) -> void printf(4,5); # glibc and BSD keep the ident pointer, not a copy. -openlog (r:str:null-ok, int, int) -> void; +# The identifier is kept, not copied. +openlog (r:str:null-ok:kept, int, int) -> void; syslog (int, r:str, ...) -> void printf(1,2) chk(__syslog_chk:0,_,1,2); vsyslog (int, r:str, other) -> void printf(1,2) chk(__vsyslog_chk:0,_,1,2); @@ -906,7 +949,8 @@ sem_timedwait (none, r) -> int; sem_getvalue (none, w) -> int; # The tree keeps the key; comparisons see the key and the tree's keys. -tsearch (none:null-ok, rw:null-ok, fn) -> ptr; +# A key that is not found is kept as the new node's. +tsearch (none:null-ok:kept, rw:null-ok, fn) -> ptr; tfind (none:null-ok, r:null-ok, fn) -> ptr; tdelete (none:null-ok, rw:null-ok, fn) -> ptr; # The element count is behind a pointer, which no term can read. @@ -1031,8 +1075,9 @@ mq_send (int, r:bytes(a2):null-if-zero(a2), int, int) -> int; mq_receive (int, w:bytes(a2), int, w:null-ok) -> int; # The control block and its buffer are used until the operation completes. -aio_read (rw) -> int; -aio_write (rw) -> int; +# The control block is the request's until it completes. +aio_read (rw:kept) -> int; +aio_write (rw:kept) -> int; aio_error (r) -> int; aio_return (rw) -> int; aio_suspend (r:bytes(a1*8), int, r:null-ok) -> int; @@ -1109,7 +1154,8 @@ wcstold (r:str, w:null-ok:bytes(8)) -> int wide; mbsinit (r:null-ok) -> int wide; # Their strings are multibyte (narrow): not 'wide' (RFC 0037 §5 scans wide # strings in elements). -mbrlen (r:bytes(min(a1,strlen(a0)+1)):null-ok, int, rw:null-ok) -> int; +mbrlen (r:bytes(min(a1,strlen(a0)+1)):null-ok, int, rw:null-ok) -> int \ + chk(__mbrlen:0,1,2); mbrtowc (w:null-ok, r:bytes(min(a2,strlen(a1)+1)):null-ok, int, rw:null-ok) \ -> int; wcrtomb (w:null-ok, int, rw:null-ok) -> int chk(__wcrtomb_chk:0,1,2,size) \ @@ -1173,23 +1219,338 @@ c32rtomb (w:null-ok, int, rw:null-ok) -> int; # , , #============================================================================ -frexp (other, w) -> int; -frexpf (other, w) -> int; -frexpl (other, w) -> int; -modf (other, w) -> int; -modff (other, w) -> int; -modfl (other, w) -> int; -remquo (other, other, w) -> int; -remquof (other, other, w) -> int; -remquol (other, other, w) -> int; -nan (r:str) -> int; -nanf (r:str) -> int; -nanl (r:str) -> int; +frexp (other, w) -> int chk(__frexp:0,1); +frexpf (other, w) -> int chk(__frexpf:0,1); +frexpl (other, w) -> int chk(__frexpl:0,1); +modf (other, w) -> int chk(__modf:0,1); +modff (other, w) -> int chk(__modff:0,1); +modfl (other, w) -> int chk(__modfl:0,1); +remquo (other, other, w) -> int chk(__remquo:0,1,2); +remquof (other, other, w) -> int chk(__remquof:0,1,2); +remquol (other, other, w) -> int chk(__remquol:0,1,2); +nan (r:str) -> int chk(__nan:0); +nanf (r:str) -> int chk(__nanf:0); +nanl (r:str) -> int chk(__nanl:0); sincos (other, w, w) -> void; sincosf (other, w, w) -> void; sincosl (other, w, w) -> void; lgamma_r (other, w) -> int; +#============================================================================ +# Functions no guard needed a row for (RFC 0057 section 4.3) +#============================================================================ + +# . Darwin's getc and putc call __srget and __swbuf, glibc's +# __uflow and __overflow. +fclose (handle) -> int; +pclose (handle) -> int; +tmpfile () -> ptr; +__srget (handle) -> int; +__swbuf (int, handle) -> int; +__svfscanf (handle, r:str, other) -> int scanf(1,2); +__uflow (handle) -> int; +__overflow (handle, int) -> int; + +# , , , +atexit (fn) -> int; +at_quick_exit (fn) -> int; +ecvt (other, int, w:bytes(4), w:bytes(4)) -> ptr:str unshared; +fcvt (other, int, w:bytes(4), w:bytes(4)) -> ptr:str unshared; +l64a (int) -> ptr:str unshared; +ptsname (int) -> ptr:str unshared; +setkey (r:bytes(64)) -> void unshared; +encrypt (rw:bytes(64), int) -> void unshared; +crypt (r:str, r:str) -> ptr:str unshared; +getlogin () -> ptr:str unshared; +ttyname (int) -> ptr:str unshared; +strsignal (int) -> ptr:str unshared; +strerror_l (int, handle) -> ptr:str; +strfromd (w:bytes(a1):null-if-zero(a1), int, r:str, other) -> int; +strfromf (w:bytes(a1):null-if-zero(a1), int, r:str, other) -> int; +strfroml (w:bytes(a1):null-if-zero(a1), int, r:str, other) -> int; +memalign (int, int) -> ptr:owned; +pvalloc (int) -> ptr:owned; +malloc_usable_size (handle) -> int; +malloc_info (int, handle) -> int; + +# errno, and glibc's tables of . +__error () -> ptr; +__errno_location () -> ptr; +__ctype_b_loc () -> ptr; +__ctype_tolower_loc () -> ptr; +__ctype_toupper_loc () -> ptr; + +# : glibc's setjmp is _setjmp, its sigsetjmp __sigsetjmp. +setjmp (w) -> int; +_setjmp (w) -> int; +sigsetjmp (w, int) -> int; +__sigsetjmp (w, int) -> int; +longjmp (r, int) -> void; +_longjmp (r, int) -> void; +siglongjmp (r, int) -> void; + +# : glibc's FE_DFL_ENV and FE_DFL_MODE are not addresses. +fegetenv (w) -> int; +feholdexcept (w) -> int; +fesetenv (handle) -> int; +feupdateenv (handle) -> int; +fegetexceptflag (w, int) -> int; +fesetexceptflag (r, int) -> int; +fetestexceptflag (r, int) -> int; +fegetmode (w) -> int; +fesetmode (handle) -> int; +canonicalize (w, r) -> int; +canonicalizef (w, r) -> int; +canonicalizel (w, r) -> int; + +# , , : a locale_t is a handle. +localeconv () -> ptr unshared; +duplocale (handle) -> ptr; +freelocale (handle) -> int; +uselocale (handle) -> ptr; +nl_langinfo (int) -> ptr:str unshared; +nl_langinfo_l (int, handle) -> ptr:str; +catopen (r:str, int) -> ptr; +catgets (handle, int, int, r:str) -> ptr:str; +catclose (handle) -> int; + +# , , with a locale. +isalnum_l (int, handle) -> int; +isalpha_l (int, handle) -> int; +isblank_l (int, handle) -> int; +iscntrl_l (int, handle) -> int; +isdigit_l (int, handle) -> int; +isgraph_l (int, handle) -> int; +islower_l (int, handle) -> int; +isprint_l (int, handle) -> int; +ispunct_l (int, handle) -> int; +isspace_l (int, handle) -> int; +isupper_l (int, handle) -> int; +isxdigit_l (int, handle) -> int; +tolower_l (int, handle) -> int; +toupper_l (int, handle) -> int; +__tolower_l (int, handle) -> int; +__toupper_l (int, handle) -> int; +iswalnum_l (int, handle) -> int; +iswalpha_l (int, handle) -> int; +iswblank_l (int, handle) -> int; +iswcntrl_l (int, handle) -> int; +iswdigit_l (int, handle) -> int; +iswgraph_l (int, handle) -> int; +iswlower_l (int, handle) -> int; +iswprint_l (int, handle) -> int; +iswpunct_l (int, handle) -> int; +iswspace_l (int, handle) -> int; +iswupper_l (int, handle) -> int; +iswxdigit_l (int, handle) -> int; +iswctype_l (int, int, handle) -> int; +towlower_l (int, handle) -> int; +towupper_l (int, handle) -> int; +# glibc's wctrans_t is a pointer to its table. +towctrans (int, handle) -> int; +towctrans_l (int, handle, handle) -> int; +wctrans_l (r:str, handle) -> ptr; +wctype_l (r:str, handle) -> int; +wcscasecmp_l (r:str, r:str, handle) -> int wide; +wcsncasecmp_l (r:count(min(a2,strlen(a0)+1)):null-if-zero(a2), \ + r:count(min(a2,strlen(a1)+1)):null-if-zero(a2), int, handle) -> int wide; +wcscoll_l (r:str, r:str, handle) -> int wide; +wcsxfrm_l (w:count(a2):null-if-zero(a2), r:str, int, handle) -> int wide; +wcswcs (r:scan(strlen(a1)), r:str) -> ptr wide; +wcstoimax (r:str, w:null-ok:bytes(8), int) -> int \ + chk(__isoc23_wcstoimax:0,1,2) wide; +wcstoumax (r:str, w:null-ok:bytes(8), int) -> int \ + chk(__isoc23_wcstoumax:0,1,2) wide; + +# , , , , , +closedir (handle) -> int; +fdopendir (int) -> ptr; +dlclose (handle) -> int; +dlerror () -> ptr:str unshared; +mlock (handle, int) -> int; +munlock (handle, int) -> int; +mprotect (handle, int, int) -> int; +msync (handle, int, int) -> int; +posix_madvise (handle, int, int) -> int; +iconv_close (handle) -> int; +getdate (r:str) -> ptr unshared; +times (w:null-ok) -> int; +clock_getcpuclockid (int, w:bytes(4)) -> int; +timer_delete (handle) -> int; +timer_getoverrun (handle) -> int; + +# , , , , , +getpwent () -> ptr unshared; +getpwuid (int) -> ptr unshared; +getgrent () -> ptr unshared; +getgrgid (int) -> ptr unshared; +freeaddrinfo (handle) -> void; +gai_strerror (int) -> ptr:str; +gethostent () -> ptr unshared; +getnetbyaddr (int, int) -> ptr unshared; +getnetbyname (r:str) -> ptr unshared; +getnetent () -> ptr unshared; +getprotobynumber (int) -> ptr unshared; +getprotoent () -> ptr unshared; +getservent () -> ptr unshared; +inet_ntoa (other) -> ptr:str unshared; +if_nameindex () -> ptr; +if_freenameindex (handle) -> void; +freeifaddrs (handle) -> void; +getifmaddrs (w:bytes(8)) -> int; +freeifmaddrs (handle) -> void; +# CMSG_NXTHDR. +__cmsg_nxthdr (r, r) -> ptr; + +# : insque links the element it is given into the caller's list. +hsearch (other, int) -> ptr unshared; +insque (handle:kept, handle) -> void; +remque (handle) -> void; +twalk (handle, fn) -> void; + +# , : Darwin's forms that take blocks. +glob_b (r:str, int, fn, rw) -> int; +scandir_b (r:str, w:bytes(8), fn, fn) -> int; + +# , , : Darwin's. +errc (int, int, r:str:null-ok, ...) -> void printf(2,3) exits; +verrc (int, int, r:str:null-ok, other) -> void printf(2,3) exits; +warnc (int, r:str:null-ok, ...) -> void printf(1,2); +vwarnc (int, r:str:null-ok, other) -> void printf(1,2); +err_set_exit (fn) -> void; +err_set_exit_b (fn) -> void; +err_set_file (handle) -> void; +backtrace_from_fp (handle, w:bytes(a2*8), int) -> int; +backtrace_async (w:bytes(a1*8), int, w:null-ok:bytes(4)) -> int; +backtrace_image_offsets (r:bytes(a2*8), w:bytes(a2*20), int) -> void; +__darwin_check_fd_set_overflow (int, handle, int) -> int; +kevent64 (int, r:bytes(a2*48):null-if-zero(a2), int, \ + w:bytes(a4*48):null-if-zero(a4), int, int, r:null-ok) -> int; + +# , +epoll_pwait2 (int, w:bytes(a2*12):null-if-zero(a2), int, r:null-ok, \ + r:null-ok) -> int; +eventfd_read (int, w:bytes(8)) -> int; + +# +posix_spawn_file_actions_init (w) -> int; +posix_spawn_file_actions_destroy (rw) -> int; +posix_spawn_file_actions_addclose (rw, int) -> int; +posix_spawn_file_actions_adddup2 (rw, int, int) -> int; +posix_spawn_file_actions_addopen (rw, int, r:str, int, int) -> int; +posix_spawn_file_actions_addchdir (rw, r:str) -> int; +posix_spawn_file_actions_addfchdir (rw, int) -> int; +posix_spawnattr_init (w) -> int; +posix_spawnattr_destroy (rw) -> int; +posix_spawnattr_getflags (r, w:bytes(2)) -> int; +posix_spawnattr_getpgroup (r, w:bytes(4)) -> int; +posix_spawnattr_getsigdefault (r, w) -> int; +posix_spawnattr_getsigmask (r, w) -> int; +posix_spawnattr_getschedparam (r, w) -> int; +posix_spawnattr_getschedpolicy (r, w:bytes(4)) -> int; +posix_spawnattr_setflags (rw, int) -> int; +posix_spawnattr_setpgroup (rw, int) -> int; +posix_spawnattr_setsigdefault (rw, r) -> int; +posix_spawnattr_setsigmask (rw, r) -> int; +posix_spawnattr_setschedparam (rw, r) -> int; +posix_spawnattr_setschedpolicy (rw, int) -> int; + +# , , , , . A value +# given to pthread_setspecific, tss_set or pthread_exit is kept for the +# thread. +pthread_self () -> int; +pthread_equal (other, other) -> int; +pthread_detach (other) -> int; +pthread_cancel (other) -> int; +pthread_kill (other, int) -> int; +pthread_exit (handle:kept) -> void; +pthread_getspecific (int) -> ptr; +pthread_setspecific (int, handle:kept) -> int; +tss_get (int) -> ptr; +tss_set (int, handle:kept) -> int; +pthread_atfork (fn, fn, fn) -> int; +pthread_getschedparam (other, w:null-ok:bytes(4), w:null-ok) -> int; +pthread_setschedparam (other, int, r) -> int; +pthread_getcpuclockid (other, w:bytes(4)) -> int; +pthread_attr_getguardsize (r, w:bytes(8)) -> int; +pthread_attr_getinheritsched (r, w:bytes(4)) -> int; +pthread_attr_getschedparam (r, w) -> int; +pthread_attr_getschedpolicy (r, w:bytes(4)) -> int; +pthread_attr_getscope (r, w:bytes(4)) -> int; +pthread_attr_getstack (r, w:bytes(8), w:bytes(8)) -> int; +pthread_attr_getstackaddr (r, w:bytes(8)) -> int; +pthread_attr_setguardsize (rw, int) -> int; +pthread_attr_setinheritsched (rw, int) -> int; +pthread_attr_setschedparam (rw, r) -> int; +pthread_attr_setschedpolicy (rw, int) -> int; +pthread_attr_setscope (rw, int) -> int; +pthread_attr_setstackaddr (rw, handle) -> int; +pthread_condattr_getpshared (r, w:bytes(4)) -> int; +pthread_condattr_setpshared (rw, int) -> int; +pthread_condattr_getclock (r, w:bytes(4)) -> int; +pthread_mutex_consistent (rw) -> int; +pthread_mutex_getprioceiling (r, w:bytes(4)) -> int; +pthread_mutex_setprioceiling (rw, int, w:null-ok:bytes(4)) -> int; +pthread_mutexattr_getprioceiling (r, w:bytes(4)) -> int; +pthread_mutexattr_getprotocol (r, w:bytes(4)) -> int; +pthread_mutexattr_getpshared (r, w:bytes(4)) -> int; +pthread_mutexattr_getrobust (r, w:bytes(4)) -> int; +pthread_mutexattr_getpolicy_np (r, w:bytes(4)) -> int; +pthread_mutexattr_setprioceiling (rw, int) -> int; +pthread_mutexattr_setprotocol (rw, int) -> int; +pthread_mutexattr_setrobust (rw, int) -> int; +pthread_mutexattr_setpolicy_np (rw, int) -> int; +pthread_rwlock_timedrdlock (rw, r) -> int; +pthread_rwlock_timedwrlock (rw, r) -> int; +pthread_rwlockattr_init (w) -> int; +pthread_rwlockattr_destroy (rw) -> int; +pthread_rwlockattr_getpshared (r, w:bytes(4)) -> int; +pthread_rwlockattr_setpshared (rw, int) -> int; +pthread_rwlockattr_getkind_np (r, w:bytes(4)) -> int; +pthread_rwlockattr_setkind_np (rw, int) -> int; +pthread_barrierattr_init (w) -> int; +pthread_barrierattr_destroy (rw) -> int; +pthread_barrierattr_getpshared (r, w:bytes(4)) -> int; +pthread_barrierattr_setpshared (rw, int) -> int; +# glibc's pthread_cleanup_push and pthread_cleanup_pop. +__pthread_register_cancel (handle) -> void; +__pthread_unregister_cancel (handle) -> void; +__pthread_unwind_next (handle) -> void; +sched_rr_get_interval (int, w) -> int; +# glibc's CPU_ALLOC, CPU_FREE and CPU_COUNT. +__sched_cpualloc (int) -> ptr; +__sched_cpufree (handle) -> void; +__sched_cpucount (int, r:bytes(a0)) -> int; +sem_close (none) -> int; +sem_destroy (none) -> int; +sem_post (none) -> int; +sem_trywait (none) -> int; +sem_wait (none) -> int; +sigqueue (int, int, other) -> int; +__sysv_signal (int, none:null-ok) -> ptr handler; + +# Globals of the C library that are, or hold, a pointer (RFC 0057 section +# 3.4): Darwin's standard streams are __stdinp and its neighbors. +global stdin : handle; +global stdout : handle; +global stderr : handle; +global __stdinp : handle; +global __stdoutp : handle; +global __stderrp : handle; +global environ : strings; +global __environ : strings; +global tzname : strings; +global __tzname : strings; +global optarg : str; +global suboptarg : str; +global program_invocation_name : str; +global program_invocation_short_name : str; +global sys_errlist : strings; +global sys_siglist : strings; +global sys_signame : strings; +global _CurrentRuneLocale : object; +global _DefaultRuneLocale : object; + #============================================================================ # Generic atomics (RFC 0037 section 4) #============================================================================ diff --git a/lib/Frontend/CMakeLists.txt b/lib/Frontend/CMakeLists.txt index 3690292..3498c95 100644 --- a/lib/Frontend/CMakeLists.txt +++ b/lib/Frontend/CMakeLists.txt @@ -24,6 +24,8 @@ weavec_add_library( SafeCheck.cpp # RFC 0051 §4: what a safe function may not assert. SafeUndefined.cpp + # RFC 0057: contracts for code WeaveC did not compile. + SafeForeign.cpp # RFC 0049: the fixes of the rules' errors, and --weavec-fix. SafeFix.cpp Fixer.cpp diff --git a/lib/Frontend/Definitions.cpp b/lib/Frontend/Definitions.cpp index 3913bc5..2df70c6 100644 --- a/lib/Frontend/Definitions.cpp +++ b/lib/Frontend/Definitions.cpp @@ -10,13 +10,15 @@ // area it reads only to report a mismatch, so that a link touches little of // each object: // -// "weavec-defs 2\n" u32 count u32 string bytes +// "weavec-defs 3\n" u32 count u32 string bytes u32 flags // count entries of 40 bytes, little-endian: // u8 kind, 3 bytes of zero, u32 name, u64 key, u64 hash, u32 place, // u32 description, u32 users, 4 bytes of zero // the strings, each ending in a zero byte (the u32s are their offsets) // -// The kinds: +// Flag 1 says the unit is a safe unit; a unit of guarded code alone has a +// record too (RFC 0057 §7.2), which marks its object as code WeaveC +// compiled. The kinds: // // T a C++ class, struct, union or enumeration other units can name (its // qualified name): Clang's ODR hash of its definition, its layout (size, @@ -31,6 +33,18 @@ // names in its type, with those declarations (`users`, comma-separated): // C has no one-definition rule, so two units' differ only where they // share a user +// X RFC 0057 §7.1: a function or global safe code uses that the unit +// does not define, that has no row and no contract, and through which +// a pointer crosses (its symbol, without Mach-O's `_`): the first +// place, the contract the planner proposes (the description), and in +// `users`, separated by tabs, the use (`call`, `address`, `global`), +// the function it is in, the number of places and the source's name. +// The link finds its definition in an input that carries a record, or +// reports `foreign-call` +// K a function the unit calls by a contract or a row of the table +// (hash 1 for a declared contract), N one through which nothing +// crosses, U one that code that is not safe calls with no contract: +// what the link's summary counts // // `key` is a hash of the kind and the name, `hash` of what the units must // agree on. Records follow one another with nothing between them (an ELF @@ -90,6 +104,24 @@ namespace weavec::frontend { // The record (§5.1) //===----------------------------------------------------------------------===// +/// The header's flags: the unit is a safe unit; the object holds code +/// WeaveC did not compile too (a partial link's: RFC 0057, amendment). +static constexpr std::uint32_t DefinitionsSafeUnit = 1; +static constexpr std::uint32_t DefinitionsMixed = 2; + +std::string mixedRecord() { + std::string record = DefinitionsHeader.str(); + const auto put = [&record](std::uint32_t value) { + for (unsigned i = 0; i < 4; ++i) + record.push_back(static_cast((value >> (8 * i)) & 0xFFU)); + }; + put(0); + put(1); + put(DefinitionsMixed); + record.push_back('\0'); + return record; +} + /// The WeaveC annotations of a type, as text. static std::string annotationText(clang::QualType type, const clang::ASTContext &ast) { @@ -128,6 +160,10 @@ struct Entry { std::string place; std::string description; std::set users; + /// `X`: the users' text as it is. + // A designated initializer may leave it out. + // NOLINTNEXTLINE(readability-redundant-member-init) + std::string usersText = {}; }; class Recorder final : public clang::RecursiveASTVisitor { @@ -189,6 +225,15 @@ class Recorder final : public clang::RecursiveASTVisitor { if (!function->isReferenced()) return true; chosen = function->getFirstDecl(); + // RFC 0057 §3: a contract is the declaration units agree on. + for (const clang::FunctionDecl *each : function->redecls()) + if (!attributeText(*each).empty() && + llvm::any_of(each->specific_attrs(), + [](const clang::AnnotateAttr *annotate) { + return annotate->getAnnotation() == + ForeignAnnotation; + })) + chosen = each; } const std::string symbol = symbolOf(*chosen); if (symbol.empty() || !seen.insert("F" + symbol).second) @@ -270,9 +315,44 @@ class Recorder final : public clang::RecursiveASTVisitor { } // NOLINTEND(readability-identifier-naming,bugprone-derived-method-shadowing-base-method) + /// RFC 0057 §7.1: what the unit calls that it does not define. + void foreign(const SafeUnit &unit) { + for (const ForeignUse &use : unit.expects) { + // (Under the survey nothing is an error yet: the ledger lists it.) + if (use.surveyed || use.symbol.empty()) + continue; + add({.kind = 'X', + .name = use.symbol, + .hash = 0, + .place = use.file + ":" + std::to_string(use.line) + ":" + + std::to_string(use.column), + .description = use.proposal, + .users = {}, + .usersText = use.use + "\t" + use.caller + "\t" + + std::to_string(use.places) + "\t" + use.function}); + } + const auto listed = [&](char kind, const std::string &name, + std::uint64_t hash) { + if (!name.empty() && seen.insert(std::string(1, kind) + name).second) + add({.kind = kind, + .name = name, + .hash = hash, + .place = {}, + .description = {}, + .users = {}}); + }; + for (const ForeignFunction &each : unit.foreign) + if (each.safeCalls + each.guardedCalls != 0) + listed('K', each.function, each.contract == "declared" ? 1 : 0); + for (const ForeignUse &use : unit.uncrossed) + listed('N', use.symbol, 0); + for (const ForeignUse &use : unit.unchecked) + listed('U', use.symbol, 0); + } + /// The record: its header, then the entries, and (C) the tags the /// recorded declarations name. - std::string text() { + std::string text(std::uint32_t flags) { for (const auto &[tag, users] : tagUsers) { const auto found = tags.find(tag); if (found == tags.end()) @@ -299,7 +379,7 @@ class Recorder final : public clang::RecursiveASTVisitor { into.push_back(static_cast((value >> (8 * i)) & 0xFFU)); }; for (const Entry &entry : entries) { - std::string users; + std::string users = entry.usersText; for (const std::string &user : entry.users) { if (!users.empty()) users += ','; @@ -315,9 +395,14 @@ class Recorder final : public clang::RecursiveASTVisitor { put(table, string(users), 4); put(table, 0, 4); } + // (A record's strings are never empty: the reader tells a whole record + // by their last byte.) + if (strings.empty()) + strings.push_back('\0'); std::string out = DefinitionsHeader.str(); put(out, entries.size(), 4); put(out, strings.size(), 4); + put(out, flags, 4); return out + table + strings; } @@ -469,11 +554,15 @@ class Recorder final : public clang::RecursiveASTVisitor { std::string recordDefinitions(clang::ASTContext &ast, const SafeUnit &unit) { // A unit compiled with -fweavec-safe is a safe unit with or without a // function (a file of globals), and a WEAVEC_SAFE function makes one. - if (unit.definedSafe.empty() && !unit.defined) + const bool safe = !unit.definedSafe.empty() || unit.defined; + // (A unit of guarded code has a record where it has an object.) + if (!safe && !unit.annotates) return {}; Recorder recorder(ast); - recorder.TraverseDecl(ast.getTranslationUnitDecl()); - return recorder.text(); + if (safe) + recorder.TraverseDecl(ast.getTranslationUnitDecl()); + recorder.foreign(unit); + return recorder.text(safe ? DefinitionsSafeUnit : 0); } //===----------------------------------------------------------------------===// @@ -537,11 +626,29 @@ struct Records { DefinitionsCompared found; /// The input defines the allocator's symbol strongly. bool allocator = false; + /// RFC 0057 §7.2: the files WeaveC compiled (a relocatable object or an + /// LTO module with a record, a linked image with the mark of §7.3), + /// whose symbols are read if a record names a foreign use; and the + /// number of relocatable objects with no record. + std::vector ours; + /// The bytes of the LTO objects kept in `modules` that are files of + /// their own (an archive's members are its mapping's, in `binaries`): + /// a module is read lazily from them. + std::vector> buffers; + std::vector> contexts; + std::vector> modules; + unsigned foreign = 0; + /// The bytes of each record section read, for a partial link to join. + std::vector sections; }; +/// What a read of records found: one that is whole; one that says its +/// object holds foreign code too. +constexpr unsigned RecordRead = 1; +constexpr unsigned RecordMixed = 2; + /// What one read of a link's inputs looks for. struct Wanted { - bool compare = true; llvm::StringRef allocator; }; @@ -556,18 +663,22 @@ static std::uint64_t little(const char *at, unsigned bytes) { return value; } -/// The records of a section's contents. -static void readRecords(llvm::StringRef contents, unsigned from, - Records &records) { - constexpr std::size_t Header = DefinitionsHeader.size() + 8; +/// The records of a section's contents; what it found (`RecordRead`, +/// `RecordMixed`). +static unsigned readRecords(llvm::StringRef contents, unsigned from, + Records &records) { + constexpr std::size_t Header = DefinitionsHeader.size() + 12; constexpr std::size_t EntryBytes = 40; + unsigned any = 0; + records.sections.push_back(contents); while (contents.size() >= Header && contents.starts_with(DefinitionsHeader)) { const char *at = contents.data() + DefinitionsHeader.size(); const std::uint64_t count = little(at, 4); const std::uint64_t bytes = little(at + 4, 4); + const std::uint64_t flags = little(at + 8, 4); const std::uint64_t size = Header + (count * EntryBytes) + bytes; if (contents.size() < size) - return; + return any; const char *table = contents.data() + Header; const char *strings = table + (count * EntryBytes); // Every string ends inside the area, and every offset is into it: a @@ -582,8 +693,12 @@ static void readRecords(llvm::StringRef contents, unsigned from, inside(entry, 32); } if (!whole) - return; - ++records.found.safe; + return any; + any |= RecordRead; + if ((flags & DefinitionsMixed) != 0) + any |= RecordMixed; + if ((flags & DefinitionsSafeUnit) != 0) + ++records.found.safe; for (std::uint64_t i = 0; i < count; ++i) { const char *entry = table + (i * EntryBytes); records.entries.push_back( @@ -597,20 +712,35 @@ static void readRecords(llvm::StringRef contents, unsigned from, .users = static_cast(little(entry + 32, 4)), .from = from}); } - contents = contents.drop_front(size); + // (A partial link pads between its inputs' sections to the alignment + // of the next one.) + contents = contents.drop_front(size).ltrim('\0'); } + return any; } -/// The records in the definitions section of `object`, if it has one. -static void readObject(const llvm::object::ObjectFile &object, std::string from, +/// The records in the definitions section of `object`, if it has one; +/// whether WeaveC compiled it: it has a record, or (a linked image) the +/// mark of an image whose every object had one (RFC 0057 §7.3). +static bool readObject(const llvm::object::ObjectFile &object, std::string from, Records &records) { + // (A record that says its object is a partial link of foreign code too + // is read for what its safe units use; the object's definitions are not + // WeaveC's.) + const auto ours = [](unsigned read) { + return (read & RecordRead) != 0 && (read & RecordMixed) == 0; + }; ++records.found.objects; + const bool image = !object.isRelocatableObject(); for (const llvm::object::SectionRef §ion : object.sections()) { llvm::Expected name = section.getName(); if (!name) { llvm::consumeError(name.takeError()); continue; } + if (image && + (*name == ImageMarkSectionMachO || *name == ImageMarkSectionELF)) + return true; if (*name != DefinitionsSectionName && *name != DefinitionsSectionELF) continue; llvm::Expected contents = section.getContents(); @@ -619,10 +749,10 @@ static void readObject(const llvm::object::ObjectFile &object, std::string from, continue; } records.names.push_back(std::move(from)); - readRecords(*contents, static_cast(records.names.size() - 1), - records); - return; + return ours(readRecords( + *contents, static_cast(records.names.size() - 1), records)); } + return false; } /// Whether `file` defines `symbol` as a strong global. @@ -663,8 +793,12 @@ static void readFile(const llvm::object::Binary &binary, std::string from, if (!wanted.allocator.empty() && !records.allocator && (object == nullptr || object->isRelocatableObject())) records.allocator = definesStrongly(*file, wanted.allocator); - if (wanted.compare && object != nullptr) - readObject(*object, std::move(from), records); + if (object == nullptr) + return; + if (readObject(*object, std::move(from), records)) + records.ours.push_back(file); + else if (object->isRelocatableObject()) + ++records.foreign; } /// An LTO object (bitcode): what it defines, from its symbol table, and its @@ -672,17 +806,16 @@ static void readFile(const llvm::object::Binary &binary, std::string from, /// its functions' code is not). static void readBitcode(llvm::MemoryBufferRef buffer, const std::string &from, const Wanted &wanted, Records &records) { - llvm::LLVMContext context; + auto context = std::make_unique(); llvm::Expected> file = - llvm::object::IRObjectFile::create(buffer, context); + llvm::object::IRObjectFile::create(buffer, *context); if (!file) { llvm::consumeError(file.takeError()); return; } readFile(**file, from, wanted, records); - if (!wanted.compare) - return; ++records.found.objects; + bool recorded = false; for (const llvm::Module &module : (*file)->modules()) for (const llvm::GlobalVariable &global : module.globals()) { const llvm::StringRef section = global.getSection(); @@ -697,9 +830,18 @@ static void readBitcode(llvm::MemoryBufferRef buffer, const std::string &from, records.copies.push_back( std::make_unique(data->getRawDataValues())); records.names.push_back(from); - readRecords(*records.copies.back(), - static_cast(records.names.size() - 1), records); + recorded |= readRecords(*records.copies.back(), + static_cast(records.names.size() - 1), + records) == RecordRead; } + if (!recorded) { + ++records.foreign; + return; + } + // RFC 0057 §7.2: its symbols may be asked for. + records.ours.push_back(file->get()); + records.modules.push_back(std::move(*file)); + records.contexts.push_back(std::move(context)); } /// Reads `path`: an object, a linked image or each member of an archive. @@ -714,7 +856,11 @@ static void readInput(const std::string &path, const Wanted &wanted, return; if (llvm::identify_magic((*buffer)->getBuffer()) == llvm::file_magic::bitcode) { + const std::size_t kept = records.modules.size(); readBitcode((*buffer)->getMemBufferRef(), path, wanted, records); + // (A module kept for its symbols reads them from these bytes.) + if (records.modules.size() != kept) + records.buffers.push_back(std::move(*buffer)); return; } llvm::Expected> binary = @@ -764,7 +910,13 @@ static void readInput(const std::string &path, const Wanted &wanted, /// The comparison of what each input's read found. static DefinitionsCompared compareRecords(std::vector &each, + bool compare, llvm::raw_ostream &errors); +/// RFC 0057 §7.2: the foreign uses of the inputs' records, each looked for +/// among what the inputs WeaveC compiled define. +static ForeignChecked checkForeignUses(const std::vector &each, + bool counts, bool partial, + llvm::raw_ostream &errors); /// Compares one entry with those met before of its kind and name. static void compareEntry( @@ -792,11 +944,14 @@ static bool shareUser(llvm::StringRef a, llvm::StringRef b) { return false; } -LinkRead readLink(llvm::ArrayRef inputs, bool compare, - llvm::StringRef allocator, llvm::raw_ostream &errors) { +LinkRead readLink(llvm::ArrayRef inputs, const LinkWanted &want, + llvm::raw_ostream &errors) { + const bool compare = want.compare; + const bool counts = want.counts; + const llvm::StringRef allocator = want.allocator; // Each input read once, on its own (in parallel: reading is the cost), // then their entries in the link's order. - const Wanted wanted{.compare = compare, .allocator = allocator}; + const Wanted wanted{.allocator = allocator}; std::vector each(inputs.size()); llvm::parallelFor(0, inputs.size(), [&](std::size_t i) { readInput(inputs[i], wanted, each[i]); @@ -807,13 +962,187 @@ LinkRead readLink(llvm::ArrayRef inputs, bool compare, read.allocator = inputs[i]; break; } - if (!compare) - return read; - read.definitions = compareRecords(each, errors); + read.definitions = compareRecords(each, compare, errors); + read.foreign = checkForeignUses(each, counts, want.partial, errors); + if (want.join) + for (const Records &one : each) + for (const llvm::StringRef section : one.sections) + read.joined += section; return read; } +/// The symbols of `file` that are defined and global, each without the +/// `_` Mach-O puts before a C name, given to `defined`. +static void definedSymbols(const llvm::object::SymbolicFile &file, + llvm::function_ref defined) { + bool underscore = false; + if (const auto *object = llvm::dyn_cast(&file)) + underscore = object->isMachO(); + else if (const auto *ir = llvm::dyn_cast(&file)) + underscore = llvm::Triple(ir->getTargetTriple()).isOSBinFormatMachO(); + std::string name; + for (const llvm::object::BasicSymbolRef &each : file.symbols()) { + llvm::Expected flags = each.getFlags(); + if (!flags) { + llvm::consumeError(flags.takeError()); + continue; + } + if ((*flags & llvm::object::BasicSymbolRef::SF_Undefined) != 0 || + (*flags & llvm::object::BasicSymbolRef::SF_Global) == 0) + continue; + name.clear(); + llvm::raw_string_ostream os(name); + if (llvm::Error error = each.printName(os)) { + llvm::consumeError(std::move(error)); + continue; + } + llvm::StringRef symbol = name; + if (underscore) + symbol.consume_front("_"); + // (An ELF symbol's version is not part of the name a unit uses.) + defined(symbol.split('@').first); + } +} + +static ForeignChecked checkForeignUses(const std::vector &each, + bool counts, bool partial, + llvm::raw_ostream &errors) { + ForeignChecked checked; + // The uses by symbol, in the link's order; the first names the input. + struct Use { + const Recorded *first = nullptr; + llvm::StringRef input; + std::uint64_t places = 0; + bool defined = false; + /// What a unit's code that is not checked for it says of the symbol: + /// nothing crosses (`N`), or a pointer does and it is called from code + /// that is not safe (`U`). + bool uncrossed = false; + bool unchecked = false; + }; + llvm::StringMap uses; + std::vector order; + llvm::StringSet<> contracts; + unsigned foreign = 0; + std::size_t ours = 0; + // (The comparison made each entry's `from` an index into the inputs' + // names joined in the link's order.) + std::vector names; + for (const Records &one : each) + names.insert(names.end(), one.names.begin(), one.names.end()); + for (const Records &one : each) { + foreign += one.foreign; + ours += one.ours.size(); + for (const Recorded &entry : one.entries) { + const llvm::StringRef name = entry.text(entry.name); + if (entry.kind == 'K') { + contracts.insert(name); + } else if (entry.kind == 'N' || entry.kind == 'U') { + // (Counted only for the summary line: another unit of the link may + // define the function, which its symbols say.) + if (counts) + (entry.kind == 'N' ? uses[name].uncrossed : uses[name].unchecked) = + true; + } else if (entry.kind == 'X') { + const auto [found, added] = uses.try_emplace(name); + if (found->second.first == nullptr) { + found->second.first = &entry; + found->second.input = + entry.from < names.size() ? names[entry.from] : ""; + order.push_back(found->first()); + } + llvm::SmallVector fields; + entry.text(entry.users).split(fields, '\t'); + std::uint64_t places = 1; + if (fields.size() > 2) + (void)fields[2].getAsInteger(10, places); + found->second.places += places; + } + } + } + checked.expected = static_cast(order.size()); + checked.contracts = contracts.size(); + checked.whole = foreign == 0 && ours != 0; + // (A partial link's object carries its inputs' records: the link of the + // image looks for what they use.) + if (uses.empty() || partial) + return checked; + // Only now are symbols read, and only those of the inputs WeaveC + // compiled: a definition anywhere else is foreign, as none is. + std::vector files; + for (const Records &one : each) + files.insert(files.end(), one.ours.begin(), one.ours.end()); + std::vector> definedBy(files.size()); + llvm::parallelFor(0, files.size(), [&](std::size_t i) { + definedSymbols(*files[i], [&](llvm::StringRef symbol) { + const auto found = uses.find(symbol); + if (found != uses.end()) + definedBy[i].push_back(found->first()); + }); + }); + for (const std::vector &symbols : definedBy) + for (const llvm::StringRef symbol : symbols) + uses[symbol].defined = true; + for (const auto &use : uses) { + if (use.second.defined || use.second.first != nullptr) + continue; + if (use.second.unchecked) + ++checked.unchecked; + else if (use.second.uncrossed) + ++checked.uncrossed; + } + for (const llvm::StringRef symbol : order) { + const Use &use = uses[symbol]; + if (use.defined) + continue; + ++checked.missing; + const Recorded &entry = *use.first; + llvm::SmallVector fields; + entry.text(entry.users).split(fields, '\t'); + const llvm::StringRef kind = !fields.empty() ? fields[0] : "call"; + const llvm::StringRef caller = fields.size() > 1 ? fields[1] : ""; + const llvm::StringRef shown = fields.size() > 3 ? fields[3] : symbol; + const llvm::StringRef place = entry.text(entry.place); + const llvm::StringRef proposal = entry.text(entry.description); + errors << use.input << ": error: "; + if (kind == "global") + errors << "'" << shown << "' is named by safe code"; + else if (kind == "address") + errors << "the address of '" << shown << "' is taken by safe code"; + else + errors << "'" << shown << "' is called by safe code"; + errors << " and no code WeaveC compiled defines it " + "[weavec-safe:foreign-call]\n"; + llvm::StringRef done = "called"; + llvm::StringRef verb = "call"; + if (kind == "global") { + done = "named"; + verb = "name"; + } else if (kind == "address") { + done = "taken"; + verb = "take"; + } + errors << place << ": note: " << done << " here"; + if (!caller.empty()) + errors << ", in '" << caller << "'"; + if (use.places > 1) + errors << " (and " << (use.places - 1) << " more place" + << (use.places == 2 ? "" : "s") << ")"; + errors << "\n" + << place << ": note: " + << (kind == "global" ? "say what it points to" + : "say what it does with what it is given") + << ": '" << proposal + << "'; or compile its library with weavec-cc; or " << verb + << " it from a function that is not safe\n"; + errors << "note: 'weavec-cc --weavec-explain foreign-call' explains " + "this rule\n"; + } + return checked; +} + static DefinitionsCompared compareRecords(std::vector &each, + bool compare, llvm::raw_ostream &errors) { // The entries stay where each input's read put them: the comparison // walks them in the link's order, naming their inputs from `names`. @@ -839,8 +1168,14 @@ static DefinitionsCompared compareRecords(std::vector &each, llvm::DenseMap> more; llvm::DenseSet reported; llvm::SmallVector seen; + if (!compare) + return found; for (const Records &one : each) for (const Recorded &entry : one.entries) { + // (RFC 0057: the foreign uses are the link check's.) + if (entry.kind != 'T' && entry.kind != 'F' && entry.kind != 'G' && + entry.kind != 'C') + continue; const auto [met, inserted] = first.try_emplace(entry.key, &entry); if (inserted) { if (entry.kind == 'T' || entry.kind == 'C') diff --git a/lib/Frontend/Driver.cpp b/lib/Frontend/Driver.cpp index 5b87822..67b5061 100644 --- a/lib/Frontend/Driver.cpp +++ b/lib/Frontend/Driver.cpp @@ -90,9 +90,9 @@ static std::string invalidValue(llvm::StringRef arg, llvm::StringRef value, /// then says what is wrong with it, if anything. static bool consumeValueFlag(DriverOptions &options, llvm::StringRef arg, std::string &error) { - static constexpr std::array Names{ - "-fweavec-checks", "-fweavec-ledger", "-fweavec-safe-checks", - "-fweavec-fix-wants", "-fweavec-safe-bounds"}; + static constexpr std::array Names{ + "-fweavec-checks", "-fweavec-ledger", "-fweavec-safe-checks", + "-fweavec-fix-wants", "-fweavec-safe-bounds", "-fweavec-contracts"}; const auto [flag, value] = arg.split('='); if (!llvm::is_contained(Names, flag)) return false; @@ -125,6 +125,8 @@ static bool consumeValueFlag(DriverOptions &options, llvm::StringRef arg, error = invalidValue(arg, value, "found or declared"); } else if (flag == "-fweavec-fix-wants") { options.fixWants = value.str(); + } else if (flag == "-fweavec-contracts") { + options.contracts.push_back(value.str()); } else { options.ledger = value.str(); } @@ -230,6 +232,11 @@ llvm::StringRef driverFlagsHelp() { it (found, the default; RFC 0056): the ledger and --weavec-audit list these bounds. With declared such a use is an error ('index-single', 'call-args') and every bound is written. + -fweavec-contracts=
+ Include
in every C and C++ unit, after the command line's + own -include files: the contracts (WEAVEC_FOREIGN declarations) of a + library WeaveC did not compile, for a build whose sources are not + edited (RFC 0057). May be given more than once. -fweavec-safe-survey, -fno-weavec-safe-survey Also run the rules over the functions that are not safe, without printing or failing on their errors: the ledger counts them by rule, @@ -677,6 +684,21 @@ static int runCc1Job(llvm::ArrayRef argv, const char *argv0) { buffer->FlushDiagnostics(compiler->getDiagnostics()); if (!success) return 1; + // RFC 0057 §3.1: the contracts' headers, in every unit of C or C++ that + // is preprocessed here, after the command line's own `-include` files. + if (weavec.enabled && !weavec.contracts.empty()) { + const auto &inputs = compiler->getFrontendOpts().Inputs; + const bool source = llvm::all_of(inputs, [](const auto &input) { + const clang::InputKind kind = input.getKind(); + return !kind.isPreprocessed() && + kind.getFormat() == clang::InputKind::Source && + (kind.getLanguage() == clang::Language::C || + kind.getLanguage() == clang::Language::CXX); + }); + if (source && !inputs.empty()) + for (const std::string &header : weavec.contracts) + compiler->getPreprocessorOpts().Includes.push_back(header); + } // RFC 0051 §4.4 (D5): four of Clang's warnings are errors in a safe unit, // under Clang's own names and words. if (weavec.enabled && weavec.safe) @@ -775,6 +797,11 @@ static int runCc1Job(llvm::ArrayRef argv, const char *argv0) { target.errors = std::move(safe->errors); target.evidence = std::move(safe->evidence); target.found = safe->boundsFound; + target.foreign = safe->foreign; + target.expects = safe->expects; + target.uncrossed = safe->uncrossed; + target.unchecked = safe->unchecked; + target.defines = safe->definedGlobals; target.files = std::move(safe->files); for (const SafeUnit::Field &field : safe->fields) target.fields.push_back({.record = field.record, @@ -1250,14 +1277,242 @@ static bool addRuntimeLibraries(clang::driver::Compilation &compilation, return true; } +/// RFC 0057 §7.2: the libraries a link names with `-l` that the command +/// line's own `-L` directories hold, as the linker would find them (a +/// directory's shared library before its archive, but in a static link): +/// they may be code WeaveC compiled. One the toolchain's directories hold +/// is the system's, and foreign. +static std::vector +namedLibraries(llvm::ArrayRef args, const llvm::Triple &target, + bool linkStatic) { + std::vector directories; + std::vector names; + for (std::size_t i = 0; i < args.size(); ++i) { + const llvm::StringRef arg(args[i]); + if (arg == "-L" || arg == "-l") { + if (i + 1 < args.size()) + (arg == "-L" ? directories : names).emplace_back(args[++i]); + } else if (arg.starts_with("-L")) { + directories.push_back(arg.drop_front(2).str()); + } else if (arg.starts_with("-l") && arg != "-lto_library") { + names.push_back(arg.drop_front(2).str()); + } + } + std::vector found; + for (const std::string &name : names) { + std::vector files; + if (llvm::StringRef(name).starts_with(":")) { + files.push_back(name.substr(1)); + } else { + if (!linkStatic || target.isOSDarwin()) { + if (target.isOSDarwin()) { + files.push_back("lib" + name + ".dylib"); + files.push_back("lib" + name + ".tbd"); + } + files.push_back("lib" + name + ".so"); + } + files.push_back("lib" + name + ".a"); + } + bool settled = false; + for (const std::string &directory : directories) { + for (const std::string &file : files) { + llvm::SmallString<256> path(directory); + llvm::sys::path::append(path, file); + if (!llvm::sys::fs::exists(path)) + continue; + // (A text stub names a system library's symbols: foreign.) + if (!llvm::StringRef(file).ends_with(".tbd")) + found.emplace_back(path.str()); + settled = true; + break; + } + if (settled) + break; + } + } + return found; +} + +/// A relocatable ELF object of one section with `contents` (and an empty +/// `.note.GNU-stack`, so that the image's stack stays non-executable), for +/// the 64-bit little-endian targets whose objects need no flags; empty for +/// another target. +static std::string elfObject(const llvm::Triple &target, llvm::StringRef name, + std::uint32_t type, std::uint64_t flags, + llvm::StringRef contents) { + if (!target.isOSBinFormatELF() || !target.isLittleEndian() || + (target.getArch() != llvm::Triple::x86_64 && + target.getArch() != llvm::Triple::aarch64)) + return {}; + std::string bytes; + const auto put = [&bytes](std::uint64_t value, unsigned count) { + for (unsigned i = 0; i < count; ++i) + bytes.push_back(static_cast((value >> (8 * i)) & 0xFFU)); + }; + std::string names(1, '\0'); + const auto named = [&names](llvm::StringRef text) { + const auto at = static_cast(names.size()); + names += text; + names.push_back('\0'); + return at; + }; + const std::uint32_t own = named(name); + const std::uint32_t stack = named(".note.GNU-stack"); + const std::uint32_t strings = named(".shstrtab"); + constexpr std::uint64_t Header = 64; + const std::uint64_t contentsAt = Header; + const std::uint64_t namesAt = contentsAt + contents.size(); + const std::uint64_t sectionsAt = (namesAt + names.size() + 7) & ~7ULL; + bytes.append("\x7f" + "ELF\2\1\1", + 7); + bytes.append(9, '\0'); + put(1, 2); // ET_REL + put(target.getArch() == llvm::Triple::x86_64 ? 62 : 183, 2); + put(1, 4); + put(0, 8); + put(0, 8); + put(sectionsAt, 8); + put(0, 4); + put(Header, 2); + put(0, 2); + put(0, 2); + put(64, 2); + put(4, 2); + put(3, 2); + bytes += contents; + bytes += names; + bytes.resize(sectionsAt, '\0'); + const auto section = [&](std::uint32_t label, std::uint32_t kind, + std::uint64_t sectionFlags, std::uint64_t offset, + std::uint64_t size, std::uint64_t align) { + put(label, 4); + put(kind, 4); + put(sectionFlags, 8); + put(0, 8); + put(offset, 8); + put(size, 8); + put(0, 4); + put(0, 4); + put(align, 8); + put(0, 8); + }; + section(0, 0, 0, 0, 0, 0); + section(own, type, flags, contentsAt, contents.size(), 4); + section(stack, 1 /*SHT_PROGBITS*/, 0, namesAt, 0, 1); + section(strings, 3 /*SHT_STRTAB*/, 0, namesAt, names.size(), 1); + return bytes; +} + +/// A temporary file of the compilation with `bytes`, or null. +static const char *temporaryFile(clang::driver::Compilation &compilation, + llvm::StringRef suffix, + llvm::StringRef bytes) { + llvm::SmallString<128> path; + int descriptor = -1; + if (llvm::sys::fs::createTemporaryFile("weavec-link", suffix, descriptor, + path)) + return nullptr; + { + llvm::raw_fd_ostream out(descriptor, /*shouldClose=*/true); + out << bytes; + } + return compilation.addTempFile( + compilation.getArgs().MakeArgString(path.str())); +} + +/// RFC 0057 §7.3: the mark of an image whose every object carries a +/// record, as arguments for its link: on Darwin a section of its own (an +/// empty one with Apple's linker, which needs no file and so costs the +/// link nothing: the image's dependency on the runtime's library already +/// says the ABI; with another linker, one made from a file that holds the +/// ABI), on ELF an object that holds a note. Empty where it cannot be +/// made: the image is then foreign to another's safe code, which reaches +/// it through contracts. +static llvm::opt::ArgStringList +imageMark(clang::driver::Compilation &compilation, const llvm::Triple &target) { + llvm::opt::ArgStringList added; + std::string abi; + for (unsigned i = 0; i < 4; ++i) + abi.push_back(static_cast( + (static_cast(WEAVEC_RUNTIME_ABI) >> (8 * i)) & 0xFFU)); + if (target.isOSDarwin()) { + const llvm::opt::ArgList &arguments = compilation.getArgs(); + if (!arguments.hasArg(clang::options::OPT_fuse_ld_EQ, + clang::options::OPT_ld_path_EQ)) { + added.push_back("-add_empty_section"); + added.push_back(arguments.MakeArgString(ImageMarkSegmentMachO)); + added.push_back(arguments.MakeArgString(ImageMarkSectionMachO)); + return added; + } + if (const char *file = temporaryFile(compilation, "bin", abi)) { + added.push_back("-sectcreate"); + added.push_back(arguments.MakeArgString(ImageMarkSegmentMachO)); + added.push_back(arguments.MakeArgString(ImageMarkSectionMachO)); + added.push_back(file); + } + return added; + } + // A note of the owner `WeaveC`, type 1, whose description is the ABI. + std::string note; + note.append("\7\0\0\0\4\0\0\0\1\0\0\0WeaveC\0\0", 20); + note += abi; + const std::string object = elfObject(target, ImageMarkSectionELF, + 7 /*SHT_NOTE*/, 2 /*SHF_ALLOC*/, note); + if (!object.empty()) + if (const char *file = temporaryFile(compilation, "o", object)) + added.push_back(file); + return added; +} + +/// RFC 0057 (amendment): what a partial link (`-r`) is given so that its +/// object says what its inputs did. Mach-O's linker drops the inputs' +/// records, so the object gets them joined, in a section made from a +/// file; ELF's joins them itself. Where an input carries no record, the +/// object gets one more record that says so: its definitions are then not +/// taken for WeaveC's. +static llvm::opt::ArgStringList +partialRecords(clang::driver::Compilation &compilation, + const llvm::Triple &target, const LinkRead &read) { + llvm::opt::ArgStringList added; + const bool mixed = !read.foreign.whole; + if (target.isOSDarwin()) { + const std::string records = + read.joined + (mixed ? mixedRecord() : std::string()); + if (records.empty()) + return added; + if (const char *file = temporaryFile(compilation, "bin", records)) { + added.push_back("-sectcreate"); + added.push_back("__DWARF"); + added.push_back( + compilation.getArgs().MakeArgString(DefinitionsSectionName)); + added.push_back(file); + } + return added; + } + if (!mixed || read.joined.empty()) + return added; + const std::string object = + elfObject(target, DefinitionsSectionELF, 1 /*SHT_PROGBITS*/, + 0x80000000ULL /*SHF_EXCLUDE*/, mixedRecord()); + if (!object.empty()) + if (const char *file = temporaryFile(compilation, "o", object)) + added.push_back(file); + return added; +} + /// The checks a link's inputs get before the linker runs, from one read of /// each (RFC 0051 §5.2): a program that defines the allocator keeps it (the /// loader binds `malloc` to the program's definition before the runtime's), /// which is said once, naming the first input, an object or an archive, /// that defines `malloc` strongly; and the records of the link's safe units -/// are compared. False when two disagree, and the link does not run. -static bool checkLinkInputs(const clang::driver::Command &link, +/// are compared. RFC 0057 §7.2: and what safe code uses that its unit does +/// not define is found among the inputs WeaveC compiled. False when two +/// units disagree or a use is foreign, and the link does not run. +static bool checkLinkInputs(clang::driver::Compilation &compilation, + clang::driver::Command &link, const DriverOptions &weavec, + llvm::ArrayRef commandLine, const llvm::Triple &target) { if (!weavec.definitions) llvm::errs() << "weavec-cc: note: -fno-weavec-definitions: the safe units " @@ -1266,9 +1521,24 @@ static bool checkLinkInputs(const clang::driver::Command &link, for (const clang::driver::InputInfo &input : link.getInputInfos()) if (input.isFilename()) inputs.emplace_back(input.getFilename()); + for (std::string &library : + namedLibraries(commandLine, target, linksStatically(commandLine))) + inputs.push_back(std::move(library)); + const llvm::opt::ArgStringList &old = link.getArguments(); + const auto has = [&old](llvm::StringRef flag) { + return llvm::is_contained(old, flag); + }; + const bool partial = has("-r"); const LinkRead read = - readLink(inputs, weavec.definitions, - target.isOSDarwin() ? "_malloc" : "malloc", llvm::errs()); + readLink(inputs, + {.compare = weavec.definitions, + .counts = weavec.summary.value_or(false), + // (Mach-O's partial link carries the joined records; ELF's + // reads them only to know that an input has one.) + .join = partial, + .partial = partial, + .allocator = target.isOSDarwin() ? "_malloc" : "malloc"}, + llvm::errs()); if (!read.allocator.empty()) llvm::errs() << "weavec-cc: note: '" << read.allocator << "' defines the allocator, which serves the program " @@ -1276,17 +1546,43 @@ static bool checkLinkInputs(const clang::driver::Command &link, "untracked, guards pass on it and releases are not " "validated\n"; const DefinitionsCompared &found = read.definitions; + const ForeignChecked &foreign = read.foreign; if (found.safe != 0 && weavec.summary.value_or(false) && - found.mismatches == 0) { + found.mismatches == 0 && foreign.missing == 0) { const std::string output = link.getOutputFilenames().empty() ? std::string("a.out") : link.getOutputFilenames().front(); llvm::errs() << "weavec: " << output << ": " << found.objects - << " objects, " << found.safe << " safe; " << found.types - << " types, " << found.functions << " functions and " - << found.globals << " globals agree\n"; + << " objects, " << found.safe << " safe; "; + if (weavec.definitions) + llvm::errs() << found.types << " types, " << found.functions + << " functions and " << found.globals << " globals agree; "; + // RFC 0057 §9: what leaves the code WeaveC compiled. + llvm::errs() << foreign.contracts << " foreign function" + << (foreign.contracts == 1 ? "" : "s") << " by contract, " + << foreign.uncrossed << " with nothing crossing; "; + if (foreign.unchecked == 0) + llvm::errs() << "closed\n"; + else + llvm::errs() << foreign.unchecked + << " called from code that is not safe with no contract\n"; } - return found.mismatches == 0; + if (found.mismatches != 0 || foreign.missing != 0) + return false; + // RFC 0057 §7.3: a shared library whose every object WeaveC compiled says + // so, for the links that name it; and a partial link's object carries + // its inputs' records. + llvm::opt::ArgStringList more; + if (partial) + more = partialRecords(compilation, target, read); + else if (foreign.whole && (has("-shared") || has("-dylib") || has("-bundle"))) + more = imageMark(compilation, target); + if (!more.empty()) { + llvm::opt::ArgStringList args(old.begin(), old.end()); + args.append(more.begin(), more.end()); + link.replaceArguments(args); + } + return true; } int runCc1(llvm::ArrayRef argv, const char *argv0) { @@ -1555,7 +1851,7 @@ int runDriver(llvm::ArrayRef commandLine, void *mainAddress) { } int status = 0; - for (const clang::driver::Command &job : compilation->getJobs()) { + for (clang::driver::Command &job : compilation->getJobs()) { // After a failure the other inputs are still compiled, as Clang's driver // does (an agent's round sees every file's errors); nothing else runs. const bool compile = !job.getArguments().empty() && @@ -1566,7 +1862,7 @@ int runDriver(llvm::ArrayRef commandLine, void *mainAddress) { // and a program-defined allocator is visible. if (job.getSource().getKind() == clang::driver::Action::LinkJobClass && weavec.enforces() && - !checkLinkInputs(job, weavec, + !checkLinkInputs(*compilation, job, weavec, clangArgs, compilation->getDefaultToolChain().getTriple())) { status = 1; continue; diff --git a/lib/Frontend/EnforcementLedger.cpp b/lib/Frontend/EnforcementLedger.cpp index c68b7ef..e48e53e 100644 --- a/lib/Frontend/EnforcementLedger.cpp +++ b/lib/Frontend/EnforcementLedger.cpp @@ -256,6 +256,64 @@ bool readFound(const llvm::json::Value &value, FoundBound &found) { return true; } +llvm::json::Value foreignJson(const ForeignFunction &function) { + return llvm::json::Object{{.K = "function", .V = function.function}, + {.K = "contract", .V = function.contract}, + {.K = "file", .V = function.file}, + {.K = "line", .V = function.line}, + {.K = "column", .V = function.column}, + {.K = "row", .V = function.row}, + {.K = "safeCalls", .V = function.safeCalls}, + {.K = "guardedCalls", .V = function.guardedCalls}, + {.K = "global", .V = function.global}}; +} + +bool readForeign(const llvm::json::Value &value, ForeignFunction &function) { + const llvm::json::Object *object = value.getAsObject(); + if (object == nullptr) + return false; + function.function = text(*object, "function"); + function.contract = text(*object, "contract"); + function.file = text(*object, "file"); + function.line = number(*object, "line"); + function.column = number(*object, "column"); + function.row = text(*object, "row"); + function.safeCalls = number(*object, "safeCalls"); + function.guardedCalls = number(*object, "guardedCalls"); + function.global = object->getBoolean("global").value_or(false); + return !function.function.empty(); +} + +llvm::json::Value foreignUseJson(const ForeignUse &use) { + return llvm::json::Object{{.K = "function", .V = use.function}, + {.K = "symbol", .V = use.symbol}, + {.K = "use", .V = use.use}, + {.K = "file", .V = use.file}, + {.K = "line", .V = use.line}, + {.K = "column", .V = use.column}, + {.K = "caller", .V = use.caller}, + {.K = "places", .V = use.places}, + {.K = "proposal", .V = use.proposal}, + {.K = "surveyed", .V = use.surveyed}}; +} + +bool readForeignUse(const llvm::json::Value &value, ForeignUse &use) { + const llvm::json::Object *object = value.getAsObject(); + if (object == nullptr) + return false; + use.function = text(*object, "function"); + use.symbol = text(*object, "symbol"); + use.use = text(*object, "use"); + use.file = text(*object, "file"); + use.line = number(*object, "line"); + use.column = number(*object, "column"); + use.caller = text(*object, "caller"); + use.places = number(*object, "places"); + use.proposal = text(*object, "proposal"); + use.surveyed = object->getBoolean("surveyed").value_or(false); + return !use.function.empty(); +} + bool isLedgerDirectory(llvm::StringRef value) { if (value.empty()) return false; @@ -378,6 +436,16 @@ bool writeEnforcementLedger(const EnforcementLedger &ledger, llvm::json::Array found; for (const FoundBound &each : ledger.found) found.push_back(foundJson(each)); + // RFC 0057 §9. + llvm::json::Array foreign; + for (const ForeignFunction &each : ledger.foreign) + foreign.push_back(foreignJson(each)); + const auto usesOf = [](const std::vector &uses) { + llvm::json::Array list; + for (const ForeignUse &each : uses) + list.push_back(foreignUseJson(each)); + return list; + }; llvm::json::Array files; for (const ReadFile &file : ledger.files) files.push_back(llvm::json::Object{{.K = "path", .V = file.path}, @@ -477,6 +545,11 @@ bool writeEnforcementLedger(const EnforcementLedger &ledger, {.K = "errors", .V = std::move(errors)}, {.K = "evidence", .V = std::move(evidence)}, {.K = "found", .V = std::move(found)}, + {.K = "foreign", .V = std::move(foreign)}, + {.K = "expects", .V = usesOf(ledger.expects)}, + {.K = "defines", .V = llvm::json::Array(ledger.defines)}, + {.K = "uncrossed", .V = usesOf(ledger.uncrossed)}, + {.K = "unchecked", .V = usesOf(ledger.unchecked)}, {.K = "library", .V = std::move(library)}, {.K = "rows", .V = std::move(rows)}, }}}, @@ -561,6 +634,13 @@ std::string enforcementSummary(const EnforcementLedger &ledger, if (!ledger.found.empty()) os << "; " << ledger.found.size() << (ledger.found.size() == 1 ? " bound found" : " bounds found"); + // RFC 0057 §7.1. + const auto expected = llvm::count_if( + ledger.expects, [](const ForeignUse &use) { return !use.surveyed; }); + if (expected != 0) + os << "; " << expected + << (expected == 1 ? " call the link must find" + : " calls the link must find"); return text; } @@ -631,6 +711,15 @@ struct Audit { /// header's is listed by each unit that includes it), with every unit's /// functions that need it and what any unit proposes. std::map found; + /// RFC 0057 §9: the functions the program calls by a contract or a row, + /// by name; what its units use and do not define, by symbol; and the + /// names every unit defines (a function another unit of the program + /// defines is not foreign). + std::map foreign; + std::map expects; + std::map uncrossed; + std::map foreignUnchecked; + std::set defined; }; } // namespace @@ -689,6 +778,7 @@ static bool auditLedger(llvm::StringRef path, Audit &audit) { const std::string tier = function->getString("tier").value_or("").str(); tiers[name] = tier; ++audit.functions; + audit.defined.insert(name); { Audit::Surveyed &entry = audit.converted[{ function->getString("file").value_or("").str(), @@ -756,6 +846,39 @@ static bool auditLedger(llvm::StringRef path, Audit &audit) { error.rule + " " + error.message, std::move(error)); } + // RFC 0057 §9. + if (const llvm::json::Array *foreign = unit->getArray("foreign")) + for (const llvm::json::Value &value : *foreign) { + ForeignFunction entry; + if (!readForeign(value, entry)) + continue; + const auto [at, added] = + audit.foreign.try_emplace(entry.function, entry); + if (added) + continue; + at->second.safeCalls += entry.safeCalls; + at->second.guardedCalls += entry.guardedCalls; + } + const auto uses = [&](llvm::StringRef list, + std::map &into) { + if (const llvm::json::Array *entries = unit->getArray(list)) + for (const llvm::json::Value &value : *entries) { + ForeignUse entry; + if (!readForeignUse(value, entry)) + continue; + const auto [at, added] = into.try_emplace( + entry.symbol.empty() ? entry.function : entry.symbol, entry); + if (!added) + at->second.places += entry.places; + } + }; + uses("expects", audit.expects); + if (const llvm::json::Array *defines = unit->getArray("defines")) + for (const llvm::json::Value &value : *defines) + if (const auto name = value.getAsString()) + audit.defined.insert(name->str()); + uses("uncrossed", audit.uncrossed); + uses("unchecked", audit.foreignUnchecked); if (const llvm::json::Array *found = unit->getArray("found")) for (const llvm::json::Value &value : *found) { FoundBound entry; @@ -965,6 +1088,35 @@ int runAudit(llvm::ArrayRef operands) { std::ranges::stable_sort(found, [](const FoundBound *a, const FoundBound *b) { return a->functions.size() > b->functions.size(); }); + // RFC 0057 §9: what leaves the code WeaveC compiled. A function a unit + // of these ledgers defines is the program's own; the ledgers do not say + // what a library compiled by weavec-cc defines, which the link knows. + const auto leaves = [&](const std::map &uses) { + std::vector left; + for (const auto &[symbol, use] : uses) + if (!audit.defined.contains(use.function) && + !audit.defined.contains(symbol)) + left.push_back(&use); + return left; + }; + const std::vector expects = leaves(audit.expects); + const std::vector foreignUnchecked = + leaves(audit.foreignUnchecked); + const std::vector uncrossed = leaves(audit.uncrossed); + unsigned declared = 0; + unsigned tabled = 0; + std::map headers; + for (const auto &[name, function] : audit.foreign) { + if (function.contract == "declared") { + ++declared; + continue; + } + ++tabled; + ++headers[function.file.empty() + ? std::string("(no header)") + : llvm::sys::path::filename(function.file).str()]; + } + const bool closed = expects.empty() && foreignUnchecked.empty(); if (json) { llvm::json::Array files; for (FilePlan &plan : plans) @@ -987,12 +1139,35 @@ int runAudit(llvm::ArrayRef operands) { llvm::json::Array foundList; for (const FoundBound *entry : found) foundList.push_back(foundJson(*entry)); + llvm::json::Array contracts; + for (const auto &[name, function] : audit.foreign) + if (function.contract == "declared") + contracts.push_back(foreignJson(function)); + llvm::json::Object byHeader; + for (const auto &[header, count] : headers) + byHeader[header] = count; + const auto usesJson = [](const std::vector &uses) { + llvm::json::Array list; + for (const ForeignUse *use : uses) + list.push_back(foreignUseJson(*use)); + return list; + }; + llvm::json::Object foreignObject{ + {.K = "closed", .V = closed}, + {.K = "declared", .V = declared}, + {.K = "table", .V = tabled}, + {.K = "contracts", .V = std::move(contracts)}, + {.K = "tableByHeader", .V = std::move(byHeader)}, + {.K = "expects", .V = usesJson(expects)}, + {.K = "unchecked", .V = usesJson(foreignUnchecked)}, + {.K = "uncrossed", .V = static_cast(uncrossed.size())}}; llvm::outs() << llvm::formatv( "{0:2}", llvm::json::Value(llvm::json::Object{ {.K = "schema", .V = "weavec-audit"}, - {.K = "version", .V = 11}, + {.K = "version", .V = 12}, + {.K = "foreign", .V = std::move(foreignObject)}, {.K = "undefined", .V = llvm::json::Object{{.K = "units", .V = llvm::json::Value( @@ -1050,6 +1225,26 @@ int runAudit(llvm::ArrayRef operands) { out << '\n'; } }; + // RFC 0057 §9: the program's edge, first. + if (closed) { + out << "closed: every call that leaves the code WeaveC compiled has a " + "contract (" + << declared << " declared, " << tabled << " of the table)\n"; + } else { + out << "not closed:"; + if (!expects.empty()) + out << ' ' << expects.size() + << (expects.size() == 1 ? " function" : " functions") + << " safe code uses with no contract, which no unit of these " + "ledgers defines (the link reports each as foreign-call unless " + "a library weavec-cc compiled defines it)"; + if (!foreignUnchecked.empty()) + out << (expects.empty() ? " " : "; ") << foreignUnchecked.size() + << (foreignUnchecked.size() == 1 ? " foreign function" + : " foreign functions") + << " called from code that is not safe with no contract"; + out << " (" << declared << " declared, " << tabled << " of the table)\n"; + } out << audit.safe << " of " << audit.functions << " functions safe\n"; // RFC 0051 §8: what the guarantee that nothing is undefined rests on. if (audit.safe == audit.functions && audit.functions != 0 && @@ -1146,9 +1341,49 @@ int runAudit(llvm::ArrayRef operands) { out << '\n'; } } - list("functions that are not safe (safe code trusts them; 'owns': a " - "parameter or the result is WEAVEC_OWNED)", + list("guarded functions (safe code that calls them trusts them; 'owns': " + "a parameter or the result is WEAVEC_OWNED)", audit.trusted, "function", "tier"); + // RFC 0057 §9: the contracts, and what has none. + out << "\ncontracts (what the program promises of code WeaveC did not " + "compile):\n"; + for (const auto &[name, function] : audit.foreign) + if (function.contract == "declared") + out << " " << function.file << ':' << function.line << ':' + << function.column << ": " << llvm::StringRef(function.row).rtrim(';') + << "; " << function.safeCalls << " safe and " << function.guardedCalls + << " guarded " << (function.global ? "uses" : "calls") << "\n"; + if (tabled != 0) { + out << " rows of the library table: " << tabled << " ("; + bool first = true; + for (const auto &[header, count] : headers) { + out << (first ? "" : ", ") << header << ' ' << count; + first = false; + } + out << ")\n"; + } + const auto listUses = [&](llvm::StringRef title, + const std::vector &uses) { + out << '\n' << title << ":\n"; + for (const ForeignUse *use : uses) { + out << " " << use->file << ':' << use->line << ':' << use->column << ": " + << use->function << " (" << use->places + << (use->places == 1 ? " place" : " places"); + if (!use->caller.empty()) + out << ", first in " << use->caller; + out << ")"; + if (!use->proposal.empty()) + out << ": '" << use->proposal << "'"; + out << '\n'; + } + }; + listUses("foreign calls with no contract (from code that is not safe; " + "each with the contract proposed)", + foreignUnchecked); + if (!expects.empty()) + listUses("what safe code uses with no contract (the link must find a " + "definition WeaveC compiled)", + expects); list("accesses of safe functions that keep a guard", audit.guarded, "operation", "reason"); list("library calls of safe functions that keep a checked wrapper", diff --git a/lib/Frontend/GuardExpand.cpp b/lib/Frontend/GuardExpand.cpp index 4b863f8..8ed6d8a 100644 --- a/lib/Frontend/GuardExpand.cpp +++ b/lib/Frontend/GuardExpand.cpp @@ -382,6 +382,29 @@ static bool plainCall(const ModuleContext &module, const llvm::CallBase &call) { callee->getName().ends_with(".weavec.safe"); } +/// RFC 0057 §5.1: whether `use` is an argument of `call` for a pointer +/// parameter that the declared contract of the function called borrows +/// and does not keep. +static bool lentByContract(const ModuleContext &module, + const llvm::CallBase &call, const llvm::Use &use) { + const llvm::Function *callee = call.getCalledFunction(); + if (callee == nullptr || !callee->isDeclarationForLinker() || + !call.isArgOperand(&use)) + return false; + const llvm::StringRef name = libraryName(callee->getName()); + if (contractOf(module, name) == nullptr) + return false; + const std::optional match = + libraryRow(module, name, call.arg_size()); + if (!match || match->entry == nullptr || match->alias != nullptr) + return false; + const core::LibraryParam *param = + match->entry->param(call.getArgOperandNo(&use)); + return param != nullptr && param->type == core::LibraryParam::Type::Pointer && + !param->kept && !param->handle && + param->effect == core::LibraryParam::Effect::Borrow; +} + static bool escapes(const ModuleContext &module, const llvm::AllocaInst &alloca, bool typed, bool plain) { llvm::SmallVector work{&alloca}; @@ -426,6 +449,12 @@ static bool escapes(const ModuleContext &module, const llvm::AllocaInst &alloca, continue; if (plain && !call->isCallee(&use) && plainCall(module, *call)) continue; + // RFC 0057 §5.1: a function with a declared contract is given the + // local's bytes for the call and no longer, unless the parameter + // says it is kept. + if (plain && !call->isCallee(&use) && + lentByContract(module, *call, use)) + continue; if (const auto *intrinsic = llvm::dyn_cast(call); intrinsic && (intrinsic->isLifetimeStartOrEnd() || @@ -938,6 +967,53 @@ static void reportLibraryTraps(ModuleContext &module, } } +/// RFC 0057 §8: the monitor's two calls are made only where the bytes the +/// contract gives end at a redzone. `before` is called if the granule the +/// byte after them lies in is not wholly addressable (inside an object, and +/// in memory with no record, it is); its answer, or zero, is what decides +/// `after`. +static void gateWatches(FunctionContext &context) { + ModuleContext &module = context.module; + llvm::SmallVector befores; + llvm::SmallVector afters; + for (llvm::BasicBlock &block : context.function) + for (llvm::Instruction &instruction : block) + if (auto *call = llvm::dyn_cast(&instruction)) + if (const llvm::Function *callee = call->getCalledFunction()) { + if (callee->getName() == "__weavec_rt_foreign_before") + befores.push_back(call); + else if (callee->getName() == "__weavec_rt_foreign_after") + afters.push_back(call); + } + for (llvm::CallInst *before : befores) { + llvm::IRBuilder<> builder(before); + llvm::Value *end = builder.CreateAdd( + builder.CreatePtrToInt(before->getArgOperand(0), module.i64), + before->getArgOperand(1)); + llvm::Value *granule = + builder.CreateLoad(module.i8, context.shadowAddress(builder, end)); + llvm::Value *redzone = + builder.CreateICmpUGT(granule, llvm::ConstantInt::get(module.i8, 0x7F)); + llvm::BasicBlock *skipped = before->getParent(); + llvm::Instruction *then = llvm::SplitBlockAndInsertIfThen( + redzone, before, false, + llvm::MDBuilder(module.context).createUnlikelyBranchWeights()); + llvm::PHINode *watched = llvm::PHINode::Create(module.i32, 2, ""); + watched->insertBefore(before->getIterator()); + before->replaceAllUsesWith(watched); + before->moveBefore(then->getIterator()); + watched->addIncoming(before, then->getParent()); + watched->addIncoming(llvm::ConstantInt::get(module.i32, 0), skipped); + } + for (llvm::CallInst *after : afters) { + llvm::IRBuilder<> builder(after); + llvm::Instruction *then = llvm::SplitBlockAndInsertIfThen( + builder.CreateIsNotNull(after->getArgOperand(2)), after, false, + llvm::MDBuilder(module.context).createUnlikelyBranchWeights()); + after->moveBefore(then->getIterator()); + } +} + void expandGuards(ModuleContext &module, llvm::Function &function, llvm::FunctionAnalysisManager &analyses) { const llvm::DataLayout &layout = module.layout; @@ -1103,6 +1179,7 @@ void expandGuards(ModuleContext &module, llvm::Function &function, for (const Access &access : accesses) if (access.kind == Access::Kind::String) expand(context, access); + gateWatches(context); unpoisonBeforeNoReturn(context); } diff --git a/lib/Frontend/GuardLibrary.cpp b/lib/Frontend/GuardLibrary.cpp index 4ef8a8c..c7948e9 100644 --- a/lib/Frontend/GuardLibrary.cpp +++ b/lib/Frontend/GuardLibrary.cpp @@ -38,6 +38,7 @@ #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/CFG.h" #include "llvm/IR/IntrinsicInst.h" +#include "llvm/Support/xxhash.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include @@ -261,6 +262,21 @@ struct LibraryCall { return stringLength(builder, pointer, bound, nullOk(term.arg) ? MarkerNullOk : 0); } + case Kind::Pointee: + return pointee(term.arg, builder); + // RFC 0057 amendment 4: the bytes from one pointer argument to + // another; an end before its start is more than any object has. + case Kind::Distance: { + llvm::Value *end = argument(term.arg); + llvm::Value *start = argument(static_cast(term.value)); + if (end == nullptr || start == nullptr || + !end->getType()->isPointerTy() || !start->getType()->isPointerTy()) + return nullptr; + end = builder.CreatePtrToInt(end, i64); + start = builder.CreatePtrToInt(start, i64); + return builder.CreateSelect(builder.CreateICmpULT(end, start), max, + builder.CreateSub(end, start)); + } case Kind::Product: case Kind::Sum: { llvm::Value *left = evaluate(term.operands[0], builder, bound); @@ -307,6 +323,53 @@ struct LibraryCall { return nullptr; } + /// RFC 0057 §3.2, §4.2: `*aN`, the unsigned integer row argument `index` + /// points to when the call is made, of the width its `bytes(W)` gives, + /// read once behind its own guard; zero when the pointer is null. + llvm::Value *pointee(unsigned index, llvm::IRBuilder<> &builder) const { + llvm::Value *pointer = argument(index); + const core::LibraryParam *param = match.entry->param(index); + if (pointer == nullptr || !pointer->getType()->isPointerTy() || + pointer->getType()->getPointerAddressSpace() != 0 || param == nullptr || + !param->bytes || param->bytes->kind != core::LibTerm::Kind::Constant) + return nullptr; + const auto found = pointees.find(index); + if (found != pointees.end()) + return found->second; + const auto width = static_cast(param->bytes->value); + llvm::Type *type = llvm::IntegerType::get(module().context, width * 8); + llvm::Value *zero = llvm::ConstantInt::get(module().i64, 0); + llvm::Value *value = nullptr; + if (llvm::isa(pointer)) { + value = zero; + } else { + llvm::BasicBlock *before = call.getParent(); + llvm::Instruction *read = llvm::SplitBlockAndInsertIfThen( + builder.CreateIsNotNull(pointer), call.getIterator(), + /*Unreachable=*/false); + module().insertGuard(read, pointer, width, llvm::Align(1), 0, nullptr, + record("range", width)); + llvm::IRBuilder<> at(read); + at.SetCurrentDebugLocation(call.getDebugLoc()); + llvm::Value *loaded = at.CreateZExt( + at.CreateAlignedLoad(type, pointer, llvm::Align(1)), module().i64); + llvm::PHINode *joined = + llvm::PHINode::Create(module().i64, 2, "", call.getParent()->begin()); + joined->addIncoming(zero, before); + joined->addIncoming(loaded, read->getParent()); + value = joined; + // The builder's block was split under it. + builder.SetInsertPoint(&call); + } + pointees[index] = value; + return value; + } + /// The `*aN` values read for this call, each once. + // (An aggregate with a designated initializer: the member is named last + // and takes no initializer of its own.) + // NOLINTNEXTLINE(readability-redundant-member-init) + mutable std::map pointees = {}; + /// Guards `bytes` (an i64) at `pointer` before the call. void guardBytes(llvm::Value *pointer, llvm::Value *bytes, bool write) const { const unsigned flags = write ? MarkerWrite : 0; @@ -327,6 +390,43 @@ struct LibraryCall { /// Guards each pointer argument the row reads or writes. void guardArguments() const; + /// RFC 0057 §8: in a checked safe unit, and in verify mode, the runtime + /// watches the redzone after the `bytes` the row lets the callee write + /// through `pointer` (the row's argument `index`) while the call runs; + /// for a contract the program declares, after the bytes it reads too. + /// Only a function with no body in the unit is watched (a library's + /// inline function, or one the optimizer may inline from the body its + /// header gives, is code WeaveC compiles where it lands), and only a call + /// that returns to the next instruction. `after` names the watch by the + /// pointer and the argument alone: a site made before inlining is made + /// again after it (`resiteInlinedCalls`), and the optimizer merges the + /// `after` calls of two paths. `before` answers whether it watches, and + /// `after` is given the answer, so that the expansion can make both calls + /// only where the bytes end at a redzone (`gateWatches`). + void monitor(llvm::Value *pointer, llvm::Value *bytes, unsigned index) const { + const SafeUnit *unit = module().options.safe.get(); + const bool checked = unit != nullptr && unit->full && + (unit->defined || !unit->definedSafe.empty()); + if (!module().verify() && !checked) + return; + const llvm::Function *callee = call.getCalledFunction(); + if (callee == nullptr || !callee->isDeclaration() || + !llvm::isa(call) || call.doesNotReturn() || + call.isMustTailCall()) + return; + llvm::Constant *at = site(true); + llvm::Constant *argument = llvm::ConstantInt::get(module().i32, index + 1); + llvm::IRBuilder<> before(&call); + llvm::Value *watched = before.CreateCall( + module().foreignBeforeFunction(), + {pointer, before.CreateZExtOrTrunc(bytes, module().i64), at, + module().text(name), argument}); + llvm::IRBuilder<> after(call.getNextNode()); + after.SetCurrentDebugLocation(call.getDebugLoc()); + after.CreateCall(module().foreignAfterFunction(), + {pointer, argument, watched}); + } + /// RFC 0038 §2: before the call, a `scan` argument's null check and its /// first byte, which every search reads (none when its count is zero). void guardScanStart(unsigned index) const; @@ -443,6 +543,10 @@ void LibraryCall::guardArguments() const { const core::LibraryEntry &entry = *match.entry; llvm::Value *const limit = objectSize(); const std::optional limited = firstWritten(); + // RFC 0057 §8: the table's rows are held to the platform's headers; a + // contract the program declares is checked by nothing, so the monitor + // watches what it says is only read too (a `const` that is wrong). + const bool declared = contractOf(module(), entry.name) != nullptr; llvm::SmallVector scans; for (unsigned index = 0; index < entry.params.size(); ++index) { const core::LibraryParam ¶m = entry.params[index]; @@ -472,11 +576,20 @@ void LibraryCall::guardArguments() const { const bool write = param.access == core::LibraryParam::Access::Write || param.access == core::LibraryParam::Access::ReadWrite; llvm::IRBuilder<> builder(&call); - if (param.string) - (void)stringLength(builder, pointer, nullptr, - nullOk(index) ? MarkerNullOk : 0); const std::optional &term = param.bytes ? param.bytes : param.count; + if (param.string) { + llvm::Value *length = stringLength(builder, pointer, nullptr, + nullOk(index) ? MarkerNullOk : 0); + // A string the program's contract says is only read is watched past + // its terminator. + if (declared && !term && length != nullptr) + monitor( + pointer, + builder.CreateAdd(builder.CreateZExtOrTrunc(length, module().i64), + llvm::ConstantInt::get(module().i64, 1)), + index); + } // `min(t, strlen(a) + 1)`: the bytes a bounded scan of the string // reads, which its string guard checks. if (term && term->kind == core::LibTerm::Kind::Min && @@ -508,6 +621,8 @@ void LibraryCall::guardArguments() const { builder.CreateSelect(builder.CreateIsNull(pointer), llvm::ConstantInt::get(module().i64, 0), bytes); guardBytes(pointer, bytes, write); + if (write || declared) + monitor(pointer, bytes, index); // The object a fortified form writes is the first it writes; its bytes // are addressable by now, so a failure is within an object. (A first // written argument whose bytes are not known here, `strtok_r`'s string, @@ -863,9 +978,28 @@ static bool callsLibrary(const llvm::Function &callee) { (callee.getName().starts_with("_Z") && callee.hasLinkOnceODRLinkage()); } +std::optional +libraryRow(const ModuleContext &module, llvm::StringRef name, + std::optional arguments) { + std::optional match = + core::LibrarySpec::shipped().lookup(name, arguments); + if ((!match || match->entry == nullptr) && module.options.safe && + module.options.safe->contractRows) + match = module.options.safe->contractRows->lookup(name, arguments); + return match; +} + +const SafeUnit::Contract *contractOf(const ModuleContext &module, + llvm::StringRef name) { + if (!module.options.safe) + return nullptr; + const auto found = module.options.safe->contracts.find(name); + return found == module.options.safe->contracts.end() ? nullptr + : &found->second; +} + void guardLibraryCalls(ModuleContext &module, llvm::Function &function, bool late) { - const core::LibrarySpec &spec = core::LibrarySpec::shipped(); std::vector calls; for (llvm::BasicBlock &block : function) for (llvm::Instruction &instruction : block) @@ -892,9 +1026,13 @@ void guardLibraryCalls(ModuleContext &module, llvm::Function &function, continue; } const std::optional match = - spec.lookup(name, call->arg_size()); + libraryRow(module, name, call->arg_size()); if (!match || match->entry == nullptr) continue; + // RFC 0057 §5.1: a report at the call names its declared contract. + if (const SafeUnit::Contract *contract = + contractOf(module, match->entry->name)) + module.contractAt(call->getDebugLoc(), *contract); LibraryCall library{.context = module, .function = function, .call = *call, @@ -956,14 +1094,13 @@ void guardLibraryCalls(ModuleContext &module, llvm::Function &function, } void thunkLibraryAddresses(ModuleContext &module, llvm::Module &ir) { - const core::LibrarySpec &spec = core::LibrarySpec::shipped(); for (llvm::Function &function : llvm::make_early_inc_range(ir)) { if (!function.isDeclaration() || function.isIntrinsic() || function.isVarArg() || ModuleContext::isRuntimeName(function.getName())) continue; const llvm::StringRef name = libraryName(function.getName()); const std::optional match = - spec.lookup(name, function.arg_size()); + libraryRow(module, name, function.arg_size()); if (!match || match->entry == nullptr || !guardsAnArgument(*match->entry)) continue; // The uses that take the address: any but the callee of a call. @@ -975,7 +1112,12 @@ void thunkLibraryAddresses(ModuleContext &module, llvm::Module &ir) { continue; // One thunk per function, the same in every unit (`linkonce_odr`), so // that its address compares equal across units built by weavec-cc. - const std::string thunkName = (ThunkPrefix + name).str(); + // RFC 0057 §5.3: a contract's thunk is named for its row too, so that + // units that declare the same contract share it and no other does. + std::string thunkName = (ThunkPrefix + name).str(); + if (const SafeUnit::Contract *contract = contractOf(module, name)) + thunkName += + "." + llvm::utohexstr(llvm::xxh3_64bits(contract->row), true); llvm::Function *thunk = ir.getFunction(thunkName); if (thunk == nullptr) { thunk = llvm::Function::Create(function.getFunctionType(), diff --git a/lib/Frontend/GuardPass.cpp b/lib/Frontend/GuardPass.cpp index a76d75d..a25f9bf 100644 --- a/lib/Frontend/GuardPass.cpp +++ b/lib/Frontend/GuardPass.cpp @@ -544,6 +544,14 @@ llvm::Constant *ModuleContext::site(const llvm::DebugLoc &location, column = at->getColumn(); file = text(at->getFilename()); } + // RFC 0057 §5.1: a site at a call of a function with a declared contract + // is followed by the place of the contract. + const SafeUnit::Contract *contract = nullptr; + if (const auto found = contractSites.find({file, line, column}); + found != contractSites.end()) { + contract = found->second; + flags |= SiteContract; + } llvm::Constant *&record = sites[{file, line, column, flags}]; if (record != nullptr) return record; @@ -552,23 +560,62 @@ llvm::Constant *ModuleContext::site(const llvm::DebugLoc &location, llvm::Type *i16 = llvm::Type::getInt16Ty(context); if (siteType == nullptr) siteType = llvm::StructType::get(context, {i64, i32, i16, i16}); - auto *global = new llvm::GlobalVariable(module, siteType, /*isConstant=*/true, + llvm::Type *type = siteType; + if (contract != nullptr) + type = llvm::ArrayType::get(siteType, 2); + auto *global = new llvm::GlobalVariable(module, type, /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, nullptr, "__weavec.site"); - llvm::Constant *offset = - file->isNullValue() ? llvm::ConstantInt::get(i64, 0) - : llvm::ConstantExpr::getSub( - llvm::ConstantExpr::getPtrToInt(file, i64), - llvm::ConstantExpr::getPtrToInt(global, i64)); - global->setInitializer(llvm::ConstantStruct::get( - siteType, {offset, llvm::ConstantInt::get(i32, line), - llvm::ConstantInt::get(i16, std::min(column, 0xFFFFU)), - llvm::ConstantInt::get(i16, flags)})); + const auto recordOf = [&](llvm::Constant *name, unsigned atLine, + unsigned atColumn, unsigned atFlags, + unsigned index) { + // (The second record's file is an offset from that record.) + llvm::Constant *self = + llvm::ConstantExpr::getAdd(llvm::ConstantExpr::getPtrToInt(global, i64), + llvm::ConstantInt::get(i64, index * 16ULL)); + llvm::Constant *offset = + name->isNullValue() + ? llvm::ConstantInt::get(i64, 0) + : llvm::ConstantExpr::getSub( + llvm::ConstantExpr::getPtrToInt(name, i64), self); + return llvm::ConstantStruct::get( + siteType, {offset, llvm::ConstantInt::get(i32, atLine), + llvm::ConstantInt::get(i16, std::min(atColumn, 0xFFFFU)), + llvm::ConstantInt::get(i16, atFlags)}); + }; + llvm::Constant *own = recordOf(file, line, column, flags, 0); + if (contract != nullptr) + global->setInitializer(llvm::ConstantArray::get( + llvm::ArrayType::get(siteType, 2), + {own, recordOf(text(contract->file), contract->line, contract->column, + 0, 1)})); + else + global->setInitializer(own); global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); record = global; return record; } +void ModuleContext::contractAt(const llvm::DebugLoc &location, + const SafeUnit::Contract &contract) { + if (!location) + return; + const llvm::DILocation *at = reportedAt(location.get()); + contractSites[{text(at->getFilename()), at->getLine(), at->getColumn()}] = + &contract; +} + +llvm::FunctionCallee ModuleContext::foreignBeforeFunction() { + return runtime("foreign_before", llvm::FunctionType::get( + i32, {ptr, i64, ptr, ptr, i32}, false)); +} + +llvm::FunctionCallee ModuleContext::foreignAfterFunction() { + return runtime("foreign_after", + llvm::FunctionType::get(llvm::Type::getVoidTy(context), + {ptr, i32, i32}, false)); +} + unsigned ModuleContext::row(const llvm::Function &function, const llvm::DebugLoc &location, llvm::StringRef operation, std::uint64_t bytes, diff --git a/lib/Frontend/GuardPassImpl.h b/lib/Frontend/GuardPassImpl.h index 41b1bb3..fbc6f50 100644 --- a/lib/Frontend/GuardPassImpl.h +++ b/lib/Frontend/GuardPassImpl.h @@ -18,6 +18,7 @@ #ifndef WEAVEC_LIB_FRONTEND_GUARDPASSIMPL_H #define WEAVEC_LIB_FRONTEND_GUARDPASSIMPL_H +#include "weavec/Core/LibrarySpec.h" #include "weavec/Frontend/GuardPass.h" #include "weavec/Frontend/SafeCheck.h" @@ -55,6 +56,9 @@ inline constexpr unsigned SiteBelieved = 32; /// RFC 0056 §5: a found bound's comparison where a pointer is stored, /// passed or returned (`bounds-conversion`), not at an access. inline constexpr unsigned SiteConvert = 64; +/// RFC 0057 §5.1: a call of a function with a declared contract; a second +/// record follows the site's, the place the contract is declared at. +inline constexpr unsigned SiteContract = 128; /// The markers GuardInsert puts before accesses and GuardExpand turns into /// checks: @@ -274,6 +278,14 @@ class ModuleContext { /// The site record of an access at `location` (section 2.3), with the /// mode's flags added to `flags`. llvm::Constant *site(const llvm::DebugLoc &location, unsigned flags); + /// RFC 0057 §5.1: says that the call at `location` is of a function with + /// the declared contract `contract`: every site made there afterwards + /// names it (SiteContract). + void contractAt(const llvm::DebugLoc &location, + const SafeUnit::Contract &contract); + /// RFC 0057 §8: the monitor of a checked build. + llvm::FunctionCallee foreignBeforeFunction(); + llvm::FunctionCallee foreignAfterFunction(); /// The source location of an instruction, for the ledger and the unsafe /// regions: its file (absolute where the debug information says), line @@ -320,6 +332,10 @@ class ModuleContext { llvm::Constant *> sites; llvm::StructType *siteType = nullptr; + /// The calls of functions with declared contracts, by place. + std::map, + const SafeUnit::Contract *> + contractSites; llvm::GlobalVariable *descriptor = nullptr; }; @@ -520,6 +536,16 @@ inline constexpr llvm::StringLiteral ThunkPrefix = "__weavec_thunk_"; /// RFC 0037 §5: replaces each address the unit takes of a library function /// whose calls guard an argument with that of a thunk that calls it. void thunkLibraryAddresses(ModuleContext &module, llvm::Module &ir); +/// RFC 0057 §4.1: the row of the callee `name`: the table's, or the row a +/// contract the unit declares was lowered to (a function has one or the +/// other: a contract for a function of the table is `bad-annotation`). +std::optional +libraryRow(const ModuleContext &module, llvm::StringRef name, + std::optional arguments = std::nullopt); +/// The contract `name`'s row was lowered from, or null for a row of the +/// table. +const SafeUnit::Contract *contractOf(const ModuleContext &module, + llvm::StringRef name); void guardLibraryCalls(ModuleContext &module, llvm::Function &function, bool late); diff --git a/lib/Frontend/GuardSafe.cpp b/lib/Frontend/GuardSafe.cpp index 2e7d72d..99789ca 100644 --- a/lib/Frontend/GuardSafe.cpp +++ b/lib/Frontend/GuardSafe.cpp @@ -3129,6 +3129,28 @@ class SafeBounds { } case Kind::StringLength: return all; + // RFC 0057 §4.2: read where the call's own guards are made. + case Kind::Pointee: + return nullptr; + // RFC 0057 amendment 4: an end before its start is more than any + // bound. + case Kind::Distance: { + const auto pointerAt = [&](std::uint64_t index) -> llvm::Value * { + const int at = index < use.arguments.size() ? use.arguments[index] : -1; + if (at < 0) + return nullptr; + llvm::Value *value = call.getArgOperand(static_cast(at)); + return value->getType()->isPointerTy() + ? builder.CreatePtrToInt(value, module.i64) + : nullptr; + }; + llvm::Value *end = pointerAt(term.arg); + llvm::Value *start = pointerAt(static_cast(term.value)); + if (end == nullptr || start == nullptr) + return nullptr; + return builder.CreateSelect(builder.CreateICmpULT(end, start), all, + builder.CreateSub(end, start)); + } case Kind::Sum: { llvm::Value *left = operand(0); llvm::Value *right = operand(1); @@ -3309,8 +3331,7 @@ class SafeBounds { if (callee != nullptr && (ModuleContext::isRuntimeName(callee->getName()) || (callee->isDeclarationForLinker() && - core::LibrarySpec::shipped() - .lookup(libraryName(callee->getName()), call->arg_size()) + libraryRow(module, libraryName(callee->getName()), call->arg_size()) .has_value()))) continue; const FunctionBounds *bounds = calleeBounds(module, *call); diff --git a/lib/Frontend/SafeCheck.cpp b/lib/Frontend/SafeCheck.cpp index 30a8384..b64d76e 100644 --- a/lib/Frontend/SafeCheck.cpp +++ b/lib/Frontend/SafeCheck.cpp @@ -502,6 +502,41 @@ class Declarations { bounds.constant = constant; continue; } + // RFC 0057 §3.2: `*p`, the integer a parameter of a contract points + // to when the call is made. + if (llvm::StringRef pointed = annotation.argument; + pointed.consume_front("*")) { + const int pointer = parameterNamed(function, pointed.trim()); + const clang::QualType counted = + pointer < 0 ? clang::QualType() + : function.getParamDecl(static_cast(pointer)) + ->getType(); + const bool contract = contractDeclaration(function) != nullptr && + type != function.getReturnType(); + if (!contract || counted.isNull() || !counted->isPointerType() || + !counted->getPointeeType()->isIntegerType()) { + report(at, rule::BadAnnotation, + !contract + ? "'" + annotation.argument + + "' in the bound is a count read through a pointer, " + "which only a parameter of a contract (a " + "WEAVEC_FOREIGN declaration with no body) may have" + : "'" + annotation.argument + + "' in the bound names no parameter of '" + + function.getName().str() + + "' that points to an integer", + !contract ? "take the count by value: a function of the " + "program reads it where its caller can see it" + : "name a parameter of the declaration whose type " + "is a pointer to an integer"); + bounds.kind = PointerBounds::Kind::Single; + continue; + } + bounds.countPointee = pointer; + bounds.pointeeWidth = + static_cast(sizeOf(counted->getPointeeType())); + continue; + } if (parameter < 0) { if (ambiguousMacro(annotation.argument)) { reportAmbiguous(at, annotation.argument); @@ -739,6 +774,22 @@ class Declarations { return f->getType()->isPointerType() && counted(f->getType()); })) return; + for (clang::FieldDecl *field : record.fields()) + annotateField(record, field, cxx); + } + + /// One field of `annotateFields`: `field` of `record`, whose bound its + /// type states (RFC 0057 §3.3: a type a contract gave it). + void annotateField(clang::RecordDecl &record, clang::FieldDecl *field, + bool cxx) { + const auto counted = [&](clang::QualType type) { + return llvm::any_of(annotationsOf(type, ast), [](const auto &each) { + return each.name == CountedByAnnotation || + each.name == CountedByOrNullAnnotation || + each.name == SizedByAnnotation || + each.name == SizedByOrNullAnnotation; + }); + }; const clang::ASTRecordLayout &layout = ast.getASTRecordLayout(&record); auto offsetOf = [&](const clang::FieldDecl &field) { return static_cast( @@ -747,94 +798,192 @@ class Declarations { layout.getFieldOffset(field.getFieldIndex()))) .getQuantity()); }; - for (clang::FieldDecl *field : record.fields()) { - if (field->isBitField() || field->isInvalidDecl()) + if (field->isBitField() || field->isInvalidDecl()) + return; + clang::QualType type = field->getType(); + FieldBounds bounds; + if (const auto *array = ast.getAsConstantArrayType(type)) { + type = array->getElementType(); + bounds.flags |= FieldBounds::Array; + } + // A reference member is a pointer to one object that is never null. + const bool reference = + ast.getLangOpts().CPlusPlus && type->isReferenceType(); + if ((!type->isPointerType() && !reference) || + (cxx && ((bounds.flags & FieldBounds::Array) != 0 || !counted(type)))) + return; + bounds.elementSize = + static_cast(sizeOf(type->getPointeeType())); + clang::FieldDecl *count = nullptr; + bool known = true; + for (const TypeAnnotation &annotation : annotationsOf(type, ast)) { + const llvm::StringRef name = annotation.name; + if (name == OwnedAnnotation) + bounds.flags |= FieldBounds::Owner; + if (name == BorrowedAnnotation) + bounds.flags |= FieldBounds::Borrowed; + if (name == EscapesAnnotation || name == BorrowedAnnotation || + name == OwnedAnnotation || name == DropsAnnotation) + continue; + if (name == NullTerminatedAnnotation || + name == NullTerminatedOrNullAnnotation) { + bounds.kind = FieldBounds::Kind::NullTerminated; + if (name == NullTerminatedOrNullAnnotation) + bounds.flags |= FieldBounds::OrNull; continue; - clang::QualType type = field->getType(); - FieldBounds bounds; - if (const auto *array = ast.getAsConstantArrayType(type)) { - type = array->getElementType(); - bounds.flags |= FieldBounds::Array; } - // A reference member is a pointer to one object that is never null. - const bool reference = - ast.getLangOpts().CPlusPlus && type->isReferenceType(); - if ((!type->isPointerType() && !reference) || - (cxx && ((bounds.flags & FieldBounds::Array) != 0 || !counted(type)))) + if (name == EndedByAnnotation || + (bounds.flags & FieldBounds::Array) != 0) { + known = false; + continue; + } + bounds.kind = FieldBounds::Kind::Counted; + if (name == SizedByAnnotation || name == SizedByOrNullAnnotation) + bounds.elementSize = 1; + if (name == CountedByOrNullAnnotation || name == SizedByOrNullAnnotation) + bounds.flags |= FieldBounds::OrNull; + unsigned long long literal = 0; + if (!llvm::StringRef(annotation.argument).getAsInteger(0, literal)) { + bounds.countOffset = static_cast(literal); continue; - bounds.elementSize = - static_cast(sizeOf(type->getPointeeType())); - clang::FieldDecl *count = nullptr; - bool known = true; - for (const TypeAnnotation &annotation : annotationsOf(type, ast)) { - const llvm::StringRef name = annotation.name; - if (name == OwnedAnnotation) - bounds.flags |= FieldBounds::Owner; - if (name == BorrowedAnnotation) - bounds.flags |= FieldBounds::Borrowed; - if (name == EscapesAnnotation || name == BorrowedAnnotation || - name == OwnedAnnotation || name == DropsAnnotation) - continue; - if (name == NullTerminatedAnnotation || - name == NullTerminatedOrNullAnnotation) { - bounds.kind = FieldBounds::Kind::NullTerminated; - if (name == NullTerminatedOrNullAnnotation) - bounds.flags |= FieldBounds::OrNull; - continue; - } - if (name == EndedByAnnotation || - (bounds.flags & FieldBounds::Array) != 0) { - known = false; - continue; - } - bounds.kind = FieldBounds::Kind::Counted; - if (name == SizedByAnnotation || name == SizedByOrNullAnnotation) - bounds.elementSize = 1; - if (name == CountedByOrNullAnnotation || - name == SizedByOrNullAnnotation) - bounds.flags |= FieldBounds::OrNull; - unsigned long long literal = 0; - if (!llvm::StringRef(annotation.argument).getAsInteger(0, literal)) { - bounds.countOffset = static_cast(literal); - continue; - } - if (const auto value = macroConstant(annotation.argument)) { - bounds.countOffset = static_cast(*value); - continue; - } - count = nullptr; - for (clang::FieldDecl *other : record.fields()) - if (other->getName() == annotation.argument && !other->isBitField() && - other->getType()->isIntegerType()) - count = other; - if (count == nullptr) { - known = false; - continue; - } - bounds.countOffset = offsetOf(*count) - offsetOf(*field); - bounds.countWidth = static_cast(sizeOf(count->getType())); - if (count->getType()->isSignedIntegerType()) - bounds.flags |= FieldBounds::CountSigned; } - if (!known || (bounds.kind == FieldBounds::Kind::Counted && - bounds.elementSize == 0)) + if (const auto value = macroConstant(annotation.argument)) { + bounds.countOffset = static_cast(*value); continue; - // A pointee completed later: its size is the end of the unit's. - if (bounds.kind == FieldBounds::Kind::Single && bounds.elementSize == 0 && - type->getPointeeType()->isIncompleteType() && - type->getPointeeType()->isRecordType()) { - laterPointees.push_back(type->getPointeeType()); - bounds.pointee = static_cast(laterPointees.size()); } - addAnnotation(*field, FieldAnnotation, - {static_cast(bounds.kind), bounds.elementSize, - bounds.countOffset, bounds.countWidth, - static_cast(bounds.flags), bounds.pointee}); - if (count != nullptr) - addAnnotation(*count, CountAnnotation, - {offsetOf(*field) - offsetOf(*count), bounds.elementSize, - static_cast(bounds.flags)}); + count = nullptr; + for (clang::FieldDecl *other : record.fields()) + if (other->getName() == annotation.argument && !other->isBitField() && + other->getType()->isIntegerType()) + count = other; + if (count == nullptr) { + known = false; + continue; + } + bounds.countOffset = offsetOf(*count) - offsetOf(*field); + bounds.countWidth = static_cast(sizeOf(count->getType())); + if (count->getType()->isSignedIntegerType()) + bounds.flags |= FieldBounds::CountSigned; + } + if (!known || + (bounds.kind == FieldBounds::Kind::Counted && bounds.elementSize == 0)) + return; + // A pointee completed later: its size is the end of the unit's. + if (bounds.kind == FieldBounds::Kind::Single && bounds.elementSize == 0 && + type->getPointeeType()->isIncompleteType() && + type->getPointeeType()->isRecordType()) { + laterPointees.push_back(type->getPointeeType()); + bounds.pointee = static_cast(laterPointees.size()); + } + addAnnotation(*field, FieldAnnotation, + {static_cast(bounds.kind), bounds.elementSize, + bounds.countOffset, bounds.countWidth, + static_cast(bounds.flags), bounds.pointee}); + if (count != nullptr) + addAnnotation(*count, CountAnnotation, + {offsetOf(*field) - offsetOf(*count), bounds.elementSize, + static_cast(bounds.flags)}); + } + + /// RFC 0057 §3.3: `WEAVEC_FOREIGN_FIELD(type, field, annotations)`, a + /// typedef of the member's type with the annotations: from here the + /// member's type is the typedef's, so that every rule and the passes + /// read the annotations as if the member's declaration carried them. + /// With `annotate`, the member gets its implicit annotation for the + /// passes too. + void foreignField(const clang::TypedefNameDecl &contract, bool annotate, + bool fast) { + if (contract.isInvalidDecl()) + return; + const clang::QualType stated = contract.getUnderlyingType(); + clang::FieldDecl *field = nullptr; + clang::QualType current = stated; + for (unsigned depth = 0; depth < 16 && field == nullptr; ++depth) { + if (const auto *of = + llvm::dyn_cast(current.getTypePtr())) { + if (const auto *member = llvm::dyn_cast( + of->getUnderlyingExpr()->IgnoreParens())) + field = llvm::dyn_cast(member->getMemberDecl()); + break; + } + const clang::QualType next = current.getSingleStepDesugaredType(ast); + if (next == current) + break; + current = next; } + std::string named = "the member"; + for (const auto *attribute : contract.specific_attrs()) + if (attribute->getAnnotation() == ForeignFieldAnnotation && + attribute->args_size() == 2) { + const auto *record = llvm::dyn_cast( + (*attribute->args_begin())->IgnoreParenCasts()); + const auto *member = llvm::dyn_cast( + (*(attribute->args_begin() + 1))->IgnoreParenCasts()); + if (record != nullptr && member != nullptr) + named = "'" + member->getString().str() + "' of '" + + record->getString().str() + "'"; + } + // (The typedef's name is the macro's own text: the errors are at the + // line that uses the macro.) + const clang::SourceLocation at = + ast.getSourceManager().getExpansionLoc(contract.getLocation()); + if (field == nullptr || field->isBitField() || + !field->getType()->isPointerType()) { + report(at, rule::BadAnnotation, + "WEAVEC_FOREIGN_FIELD names " + named + + ", which is no pointer member of a struct or a union", + "name a member whose type is a pointer: WEAVEC_FOREIGN_FIELD(" + "struct iovec, iov_base, WEAVEC_SIZED_BY(iov_len))"); + return; + } + std::string text; + for (const TypeAnnotation &annotation : annotationsOf(stated, ast)) { + const llvm::StringRef name = annotation.name; + if (name == EscapesAnnotation || name == DropsAnnotation || + name == SendsAnnotation) { + report(at, rule::BadAnnotation, + "WEAVEC_FOREIGN_FIELD gives " + named + + " an annotation that is a parameter's", + "a member's contract is a bound (WEAVEC_COUNTED_BY, " + "WEAVEC_SIZED_BY, WEAVEC_NULL_TERMINATED), WEAVEC_OWNED or " + "WEAVEC_BORROWED"); + return; + } + text += (name + "(" + annotation.argument + ")").str(); + } + const auto earlier = foreignFields.find(field); + if (earlier != foreignFields.end()) { + if (earlier->second != text) + report(at, rule::BadAnnotation, + "a second WEAVEC_FOREIGN_FIELD for " + named + + " says something else than the first", + "keep one contract for the member, in one header"); + return; + } + if (!annotationsOf(field->getType(), ast).empty()) { + report(at, rule::BadAnnotation, + "WEAVEC_FOREIGN_FIELD names " + named + + ", whose own declaration has an annotation", + "a member of a struct the program defines is annotated where " + "it is declared"); + return; + } + foreignFields.try_emplace(field, text); + field->setType(stated); + clang::RecordDecl *record = field->getParent(); + if (record != nullptr) + record = record->getDefinition(); + if (!annotate || record == nullptr || record->isInvalidDecl() || + record->isDependentType()) + return; + // What the struct's own definition gave the member (one object) goes. + if (field->hasAttrs()) + llvm::erase_if(field->getAttrs(), [](const clang::Attr *attribute) { + const auto *annotation = llvm::dyn_cast(attribute); + return annotation != nullptr && + annotation->getAnnotation() == FieldAnnotation; + }); + annotateField(*record, field, ast.getLangOpts().CPlusPlus && !fast); } /// The sizes of the pointees `annotateFields` left to the end of the @@ -849,6 +998,8 @@ class Declarations { private: std::vector laterPointees; + /// RFC 0057 §3.3: the members a contract gave annotations, with them. + llvm::DenseMap foreignFields; clang::ASTContext * [[maybe_unused]] clang::DiagnosticsEngine &diagnostics; const clang::Preprocessor *preprocessor; @@ -919,6 +1070,12 @@ class Declarations { static int parameterNamed(const clang::FunctionDecl &function, llvm::StringRef name) { + // RFC 0057 §3.1: a declaration that took its contract's types names + // parameters as the contract does. + if (const clang::FunctionDecl *contract = contractDeclaration(function); + contract != nullptr && contract != &function && + contract->getNumParams() == function.getNumParams()) + return parameterNamed(*contract, name); for (unsigned i = 0; i < function.getNumParams(); ++i) if (function.getParamDecl(i)->getName() == name) return static_cast(i); @@ -1226,7 +1383,11 @@ class FunctionCheck final : public clang::RecursiveASTVisitor { passesString(*call->getArg(i), *callee->getParamDecl(i), *callee); const auto *prototype = callee->getType()->getAs(); + // RFC 0057 §3.6: a variadic function with no body in the unit is the + // foreign rules' (SafeForeign.cpp): what its call passes through `...` + // decides. if (prototype != nullptr && prototype->isVariadic() && + callee->isDefined() && !core::LibrarySpec::shipped() .lookup(callee->getName().str(), call->getNumArgs()) .has_value()) @@ -1327,6 +1488,26 @@ class FunctionCheck final : public clang::RecursiveASTVisitor { return true; } + /// RFC 0057 amendment 22: an initializer stores a member with a bound + /// without naming it, and a checked C++ unit compares that store too (a + /// contract may give the struct to foreign code, which believes the + /// member's bound). + void storesBounded(const clang::RecordDecl *record) { + if (record == nullptr) + return; + usedBounds = + usedBounds || + llvm::any_of(record->fields(), [&](const clang::FieldDecl *field) { + return boundedBy(annotationsOf(field->getType(), ast)); + }); + } + + bool VisitCXXParenListInitExpr(clang::CXXParenListInitExpr *list) { + if (cxx) + storesBounded(list->getType()->getAsRecordDecl()); + return true; + } + bool VisitInitListExpr(clang::InitListExpr *visited) { // A local aggregate's WEAVEC_BORROWED fields may take borrowed pointers. const clang::InitListExpr *list = @@ -1336,8 +1517,10 @@ class FunctionCheck final : public clang::RecursiveASTVisitor { const clang::RecordDecl *record = list->getType()->getAsRecordDecl(); if (record != nullptr && list == visited) checkCountedInit(ast, *list, *record, report); - if (cxx) + if (cxx) { + storesBounded(record); return true; + } const bool local = initializesLocal(*list) || initializesLocal(*visited); unsigned index = 0; llvm::SmallVector fields; @@ -3207,6 +3390,8 @@ class SafeChecker final : public clang::ASTConsumer { /// A function, or those of a namespace, made as the namespace closes. void markIn(clang::Decl &declaration) { if (auto *function = llvm::dyn_cast(&declaration)) { + // RFC 0057 §3.1: before the code of any function that follows. + adoptContract(*function); markPlaced(*function); markTypes(*function); } else if (llvm::isa(declaration).decls()) markIn(*each); + } else if (const auto *contract = + llvm::dyn_cast(&declaration); + contract != nullptr && + hasAnnotateAttr(*contract, ForeignFieldAnnotation)) { + // RFC 0057 §3.3: before the code of any function that follows. + clang::ASTContext &ast = contract->getASTContext(); + declarationsFor(ast).foreignField( + *contract, + out->annotates && + ast.getTargetInfo().getPointerWidth(clang::LangAS::Default) == 64, + out->fast); } } void HandleInlineFunctionDefinition(clang::FunctionDecl *function) override { @@ -3750,6 +3946,27 @@ class SafeChecker final : public clang::ASTConsumer { << printedFixes << printed << (compiler.getLangOpts().CPlusPlus ? "weavec-c++" : "weavec-cc"); } + // RFC 0057: the unit's contracts, as rows for the passes, and what its + // code calls that it does not define. + if (compiler.hasASTContext()) { + ForeignRules foreign; + foreign.tableOf = [this](const clang::FunctionDecl &function) { + return declarationsFor(compiler.getASTContext()).tableOf(function); + }; + foreign.report = [this](clang::SourceLocation at, llvm::StringRef rule, + llvm::StringRef message, llvm::StringRef fix) { + report(at, rule, message, fix); + }; + foreign.owner = [this](const clang::FunctionDecl *function, + bool surveyed) { + owner = function == nullptr + ? std::nullopt + : std::optional(ownerOf(*function, surveyed)); + }; + foreign.fixes = &fixes(); + checkForeign(compiler.getASTContext(), *out, foreign); + owner.reset(); + } fixes().evidence(out->wants, out->evidence); if (out->survey) fixes().files(out->files); @@ -3829,6 +4046,11 @@ class SafeChecker final : public clang::ASTConsumer { const auto *function = llvm::dyn_cast(declaration); if (function == nullptr || function->getName().empty()) continue; + // RFC 0057 §3.1: a function with a contract is what its contract + // says, read once, where the contract is. + if (const clang::FunctionDecl *contract = contractDeclaration(*function); + contract != nullptr && contract != function) + continue; const FunctionBounds table = declarations.tableOf(*function); const bool annotated = table.result.bounded() || diff --git a/lib/Frontend/SafeCheckImpl.h b/lib/Frontend/SafeCheckImpl.h index c7cbfa2..ff7d178 100644 --- a/lib/Frontend/SafeCheckImpl.h +++ b/lib/Frontend/SafeCheckImpl.h @@ -184,6 +184,52 @@ struct BoundsRules { FixPlanner *fixes = nullptr; }; +/// RFC 0057 (SafeForeign.cpp): what the unit's checker gives the rules of +/// foreign code. +struct ForeignRules { + /// The bounds a declaration's annotations give (a contract's `*p` counts + /// with them). + std::function tableOf; + std::function + report; + /// Whose code the errors reported until the next call are in; null ends + /// that. + std::function owner; + FixPlanner *fixes = nullptr; +}; +/// RFC 0057 §3, §4.1, §7.1, §9: reads the unit's contracts (the +/// declarations marked `WEAVEC_FOREIGN`), lowers each function's to a row +/// (`SafeUnit::contractRows`), and lists what the unit's functions call, +/// take the address of or name that the unit does not define: with a row or +/// a contract (`foreign`), with neither where a pointer crosses (`expects` +/// from safe code, `unchecked` from other code) and where nothing crosses +/// (`uncrossed`). Reports `bad-annotation` for a contract that says what it +/// cannot, `foreign-call` for a pointer passed through `...` (§3.6), and +/// `call-args` for a callback that does not declare the bound its +/// contract's function-pointer type declares (§3.5). +void checkForeign(clang::ASTContext &ast, SafeUnit &unit, + const ForeignRules &rules); +/// RFC 0057 §3.1: the declaration that is `function`'s contract (the first +/// that wrote WEAVEC_FOREIGN and has no body), or null when it has none or +/// the unit defines it. +[[nodiscard]] const clang::FunctionDecl * +contractDeclaration(const clang::FunctionDecl &function); +/// RFC 0057 §3.1: makes every declaration of a function with a contract say +/// what the contract says, whichever came first and whichever a call names: +/// the library's own prototype then has the contract's types (in C a later +/// declaration takes the type of the earlier one, which would drop what a +/// contract says of the result) and its `lifetimebound` parameters. +void adoptContract(const clang::FunctionDecl &function); +/// RFC 0057 §10 (E10): the contract the planner proposes for `function`, +/// from its prototype: the declaration's text. +[[nodiscard]] std::string proposeContract(const clang::FunctionDecl &function); +/// RFC 0057 §2: whether a pointer crosses a value of `type` (it is, or +/// holds, a pointer; in C++ a reference to a complete object type and a +/// class that is no C struct do not need a contract). +[[nodiscard]] bool pointerCrosses(clang::QualType type, + const clang::ASTContext &ast); + /// RFC 0048 §2.2, §4: the local pointer an expression names; the values /// each local pointer of a statement is given, and those stepped in place. using LocalValues = diff --git a/lib/Frontend/SafeCxxFlow.cpp b/lib/Frontend/SafeCxxFlow.cpp index c320177..c488678 100644 --- a/lib/Frontend/SafeCxxFlow.cpp +++ b/lib/Frontend/SafeCxxFlow.cpp @@ -1488,6 +1488,19 @@ class CxxFlow { if (hasAnnotation(annotationsOf(type, ast), EscapesAnnotation) || hasAnnotation(annotationsOf(type, ast), SendsAnnotation)) return true; + // RFC 0057 §4.2: a row of the table says the C library keeps it + // (`kept`: the value given to pthread_setspecific). + if (const auto *declared = + llvm::dyn_cast(parameter->getDeclContext()); + declared != nullptr && declared->getIdentifier() != nullptr && + declared->isExternC() && !declared->hasBody()) + if (const auto row = core::LibrarySpec::shipped().lookup( + declared->getName(), declared->getNumParams()); + row && row->entry != nullptr && row->alias == nullptr) + if (const core::LibraryParam *kept = + row->entry->param(parameter->getFunctionScopeIndex()); + kept != nullptr && kept->kept) + return true; if (type->isLValueReferenceType() || !kinds.erased(type)) return false; // A template's parameter that an instantiation gave such a type was diff --git a/lib/Frontend/SafeForeign.cpp b/lib/Frontend/SafeForeign.cpp new file mode 100644 index 0000000..a1a6626 --- /dev/null +++ b/lib/Frontend/SafeForeign.cpp @@ -0,0 +1,1365 @@ +//===- SafeForeign.cpp - Foreign code by contract +//--------------------------===// +// +// Part of WeaveC, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// RFC 0057. Code WeaveC did not compile is foreign: the C library, a unit +// compiled with `-fno-weavec`, another language's archive. A safe function +// reaches it only through a contract: a row of the library table, or the +// function's prototype redeclared `WEAVEC_FOREIGN` with the annotations a +// function of the program has (§3). This file +// +// - reads the unit's contracts and lowers each function's to a row of the +// table's language (§4.1), so that the passes that read the table guard +// a guarded caller's arguments and compare a safe caller's bounds with +// no code of their own (`SafeUnit::contractRows`); +// - lists what the unit's functions call, take the address of or name that +// the unit does not define (§7.1, §9): with a row or a contract +// (`foreign`), with neither where a pointer crosses (`expects` from safe +// code: the link decides whether code WeaveC compiled defines it; +// `unchecked` from code that is not safe) and where nothing crosses +// (`uncrossed`); +// - reports what a contract cannot say (`bad-annotation`), a pointer +// passed through `...` where no format describes it (`foreign-call`, +// §3.6), and a callback that does not declare the bound its contract's +// function-pointer type declares (`call-args`, §3.5); +// - proposes a contract from a prototype (§10, evidence E10). +// +// What is foreign is the link's to decide (Definitions.cpp reads the +// entries this file lists); nothing here depends on where a declaration is +// written. +// +//===----------------------------------------------------------------------===// + +#include "SafeCheckImpl.h" +#include "weavec/Core/LibrarySpec.h" + +#include "clang/AST/ASTContext.h" +#include "clang/AST/Attr.h" +#include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" +#include "clang/AST/Expr.h" +#include "clang/AST/ExprCXX.h" +#include "clang/AST/Mangle.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/AST/TypeLoc.h" +#include "clang/Basic/Builtins.h" +#include "clang/Basic/SourceManager.h" +#include "clang/Basic/TargetInfo.h" + +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/StringExtras.h" + +#include +#include +#include + +namespace weavec::frontend { + +namespace { +namespace rule { +constexpr llvm::StringLiteral ForeignCall = "foreign-call"; +constexpr llvm::StringLiteral Escape = "escape"; +constexpr llvm::StringLiteral BadAnnotation = "bad-annotation"; +constexpr llvm::StringLiteral CallArgs = "call-args"; +constexpr llvm::StringLiteral Variadic = "variadic"; +} // namespace rule +} // namespace + +static bool marked(const clang::Decl &declaration, llvm::StringRef name) { + return llvm::any_of(declaration.specific_attrs(), + [&](const clang::AnnotateAttr *attribute) { + return attribute->getAnnotation() == name; + }); +} + +/// Whether this declaration itself carries the mark (a later declaration +/// inherits its attributes from the earlier ones). +static bool markedHere(const clang::Decl &declaration, llvm::StringRef name) { + return llvm::any_of(declaration.specific_attrs(), + [&](const clang::AnnotateAttr *attribute) { + return attribute->getAnnotation() == name && + !attribute->isInherited(); + }); +} + +const clang::FunctionDecl * +contractDeclaration(const clang::FunctionDecl &function) { + // (A later declaration inherits the mark; an earlier one has none.) + if (!function.getMostRecentDecl()->hasAttr() || + function.isDefined()) + return nullptr; + const clang::SourceManager &sources = + function.getASTContext().getSourceManager(); + const clang::FunctionDecl *contract = nullptr; + for (const clang::FunctionDecl *each : function.redecls()) + if (markedHere(*each, ForeignAnnotation) && + (contract == nullptr || + sources.isBeforeInTranslationUnit(each->getLocation(), + contract->getLocation()))) + contract = each; + return contract; +} + +void adoptContract(const clang::FunctionDecl &function) { + const clang::FunctionDecl *contract = contractDeclaration(function); + if (contract == nullptr) + return; + // What the declaration wrote: in C its type may already be an earlier + // declaration's. + const clang::QualType written = contract->getTypeSourceInfo() != nullptr + ? contract->getTypeSourceInfo()->getType() + : contract->getType(); + for (clang::FunctionDecl *each : function.redecls()) { + if (!clang::ASTContext::hasSameType(each->getType(), written)) + continue; + each->setType(written); + if (each == contract || each->getNumParams() != contract->getNumParams()) + continue; + for (unsigned i = 0; i < each->getNumParams(); ++i) { + clang::ParmVarDecl *parameter = each->getParamDecl(i); + const clang::ParmVarDecl *stated = contract->getParamDecl(i); + if (clang::ASTContext::hasSameType(parameter->getType(), + stated->getType())) + parameter->setType(stated->getType()); + if (const auto *bound = stated->getAttr(); + bound != nullptr && !parameter->hasAttr()) + parameter->addAttr(bound->clone(function.getASTContext())); + } + } +} + +//===----------------------------------------------------------------------===// +// What crosses (§2) +//===----------------------------------------------------------------------===// + +static bool crosses(clang::QualType type, const clang::ASTContext &ast, + llvm::SmallPtrSetImpl &seen) { + const clang::QualType canonical = type.getCanonicalType(); + const clang::Type *of = canonical.getTypePtr(); + if (of->isReferenceType()) { + // C++: a reference to a complete object type says its bound. + const clang::QualType pointee = of->getPointeeType(); + return pointee->isIncompleteType() || pointee->isFunctionType(); + } + if (of->isAnyPointerType() || of->isBlockPointerType() || + of->isMemberPointerType() || of->isFunctionType()) + return true; + if (const auto *array = llvm::dyn_cast(of)) + return crosses(array->getElementType(), ast, seen); + if (const auto *atomic = llvm::dyn_cast(of)) + return crosses(atomic->getValueType(), ast, seen); + const clang::RecordDecl *record = of->getAsRecordDecl(); + if (record == nullptr || !seen.insert(of).second) + return false; + record = record->getDefinition(); + if (record == nullptr) + return false; + // C++: a class whose kind RFC 0044 derives (an owner, a view, a value) + // says what it reaches; a C struct's pointer members are raw pointers. + if (const auto *cxx = llvm::dyn_cast(record); + cxx != nullptr && !cxx->isCLike()) + return false; + return llvm::any_of(record->fields(), [&](const clang::FieldDecl *field) { + const clang::QualType member = field->getType(); + // (An array member is held by value: its elements decide.) + if (const auto *array = ast.getAsArrayType(member)) + return crosses(ast.getBaseElementType(array), ast, seen); + return crosses(member, ast, seen); + }); +} + +bool pointerCrosses(clang::QualType type, const clang::ASTContext &ast) { + if (type.isNull() || type->isDependentType()) + return false; + llvm::SmallPtrSet seen; + return crosses(type, ast, seen); +} + +/// Whether a pointer crosses a call of `function` by its declared result +/// or parameters (its variadic arguments are each call's: §3.6). +static bool crossesFunction(const clang::FunctionDecl &function, + const clang::ASTContext &ast) { + if (pointerCrosses(function.getReturnType(), ast)) + return true; + return llvm::any_of(function.parameters(), + [&](const clang::ParmVarDecl *parameter) { + return pointerCrosses(parameter->getType(), ast); + }); +} + +//===----------------------------------------------------------------------===// +// Proposals (§10, E10) +//===----------------------------------------------------------------------===// + +/// Whether `name` is a count's name beside the pointer `pointer`: `len`, +/// `n`, `size`, `count`, `length`, or the pointer's name with such a suffix +/// (`buf` and `buflen`, `dest` and `destLen`). +static bool countName(llvm::StringRef name, llvm::StringRef pointer) { + const std::string lower = name.lower(); + llvm::StringRef text = lower; + for (const llvm::StringRef word : + {"len", "n", "size", "count", "length", "nbytes", "num", "cnt", "sz", + "cap", "capacity", "nmemb", "nitems", "nelem", "bytes"}) + if (text == word) + return true; + const std::string lowerPointer = pointer.lower(); + if (!lowerPointer.empty() && text.consume_front(lowerPointer)) + text = text.ltrim('_'); + else + return llvm::StringRef(lower).ends_with("len") || + llvm::StringRef(lower).ends_with("size") || + llvm::StringRef(lower).ends_with("count") || + llvm::StringRef(lower).ends_with("length"); + return text == "len" || text == "size" || text == "count" || + text == "length" || text == "n" || text == "sz" || text == "cap"; +} + +std::string proposeContract(const clang::FunctionDecl &function) { + const clang::ASTContext &ast = function.getASTContext(); + clang::PrintingPolicy policy(ast.getPrintingPolicy()); + policy.SuppressTagKeyword = false; + policy.Bool = true; + const unsigned count = function.getNumParams(); + std::vector names(count); + for (unsigned i = 0; i < count; ++i) { + names[i] = function.getParamDecl(i)->getName().str(); + if (names[i].empty()) + names[i] = "a" + std::to_string(i); + } + const auto type = [&](unsigned i) { + return function.getParamDecl(i)->getType(); + }; + const auto functionPointer = [&](unsigned i) { + const clang::QualType each = type(i); + return each->isFunctionPointerType() || each->isBlockPointerType(); + }; + std::string text = "WEAVEC_FOREIGN " + + function.getReturnType().getAsString(policy) + " " + + function.getQualifiedNameAsString() + "("; + for (unsigned i = 0; i < count; ++i) { + if (i != 0) + text += ", "; + const clang::QualType each = type(i); + std::string annotation; + if (each->isPointerType() && !functionPointer(i)) { + const clang::QualType pointee = each->getPointeeType(); + const bool handle = pointee->isIncompleteType() && + !pointee->isVoidType() && !pointee->isArrayType(); + // A count beside the pointer, by value or through a pointer. + std::string counted; + for (const int near : + {static_cast(i) + 1, static_cast(i) - 1}) { + if (near < 0 || std::cmp_greater_equal(near, count) || !counted.empty()) + continue; + const auto at = static_cast(near); + if (!countName(names[at], names[i])) + continue; + if (type(at)->isIntegerType()) + counted = names[at]; + else if (type(at)->isPointerType() && + type(at)->getPointeeType()->isIntegerType() && + !type(at)->getPointeeType()->isAnyCharacterType()) + counted = "*" + names[at]; + } + const bool nextToCallback = + pointee->isVoidType() && ((i > 0 && functionPointer(i - 1)) || + (i + 1 < count && functionPointer(i + 1))); + if (handle) { + annotation.clear(); + } else if (nextToCallback) { + annotation = "WEAVEC_ESCAPES"; + } else if (!counted.empty()) { + annotation = (pointee->isVoidType() ? "WEAVEC_SIZED_BY(" + : "WEAVEC_COUNTED_BY(") + + counted + ")"; + } else if (pointee->isCharType() && pointee.isConstQualified()) { + annotation = "WEAVEC_NULL_TERMINATED"; + } + if (!annotation.empty() && !pointee->isFunctionType() && + !pointee->isArrayType()) { + std::string spelled = pointee.getAsString(policy); + text += spelled; + text += llvm::StringRef(spelled).ends_with("*") ? "*" : " *"; + text += annotation; + text += ' '; + text += names[i]; + continue; + } + } + std::string declarator = names[i]; + each.getAsStringInternal(declarator, policy); + text += declarator; + } + if (function.isVariadic()) + text += count == 0 ? "..." : ", ..."; + else if (count == 0 && !ast.getLangOpts().CPlusPlus) + text += "void"; + return text + ");"; +} + +//===----------------------------------------------------------------------===// +// The unit's contracts and uses +//===----------------------------------------------------------------------===// + +namespace { + +class Foreign { +public: + Foreign(clang::ASTContext &ast, SafeUnit &unit, const ForeignRules &rules) + : ast(ast), sources(ast.getSourceManager()), unit(unit), rules(rules), + names(ast), cxx(ast.getLangOpts().CPlusPlus) {} + + void run() { + contractsIn(ast.getTranslationUnitDecl()); + lowerContracts(); + usesIn(ast.getTranslationUnitDecl()); + finish(); + } + +private: + clang::ASTContext * + const clang::SourceManager &sources; + SafeUnit &unit; + const ForeignRules &rules; + clang::ASTNameGenerator names; + bool cxx; + + /// A function's contract: the declaration that carries the mark. + struct FunctionContract { + const clang::FunctionDecl *declaration = nullptr; + std::string key; + bool format = false; + }; + llvm::DenseMap contracts; + llvm::DenseMap globals; + std::string rowsText; + + /// The lists, by symbol, in the order met. + std::map foreignAt; + std::map expectsAt; + std::map uncrossedAt; + std::map uncheckedAt; + + //===--------------------------------------------------------------------===// + // Names + //===--------------------------------------------------------------------===// + + /// The linker's symbol, without the target's label prefix (Mach-O's `_`). + std::string symbolOf(const clang::NamedDecl &declaration) { + if (llvm::isa( + declaration)) { + const std::vector all = names.getAllManglings(&declaration); + if (all.empty()) + return {}; + llvm::StringRef name = all.front(); + name.consume_front(ast.getTargetInfo().getUserLabelPrefix()); + return name.str(); + } + const std::string symbol = names.getName(&declaration); + llvm::StringRef name = symbol; + // (An `asm` label is the linker's name whole, after Clang's mark.) + name.consume_front("\1"); + name.consume_front(ast.getTargetInfo().getUserLabelPrefix()); + return name.str(); + } + + /// The name a row for `function` has: the C name, or for a function with + /// C++ linkage its symbol, as the passes read a callee's (`libraryName`). + std::string rowName(const clang::FunctionDecl &function) { + if (function.getIdentifier() != nullptr && + (!cxx || function.isExternC() || function.getBuiltinID() != 0)) + return function.getName().str(); + return llvm::StringRef(symbolOf(function)).split('$').first.str(); + } + + /// Whether `function`'s code is safe (RFC 0051 §2's list of the unit's + /// safe functions, by symbol). + bool isSafe(const clang::FunctionDecl &function) { + if (!cxx) + return unit.definedSafe.contains(function.getName()); + const llvm::StringRef prefix = ast.getTargetInfo().getUserLabelPrefix(); + if (llvm::isa( + function)) { + for (const std::string &each : names.getAllManglings(&function)) { + llvm::StringRef name = each; + name.consume_front(prefix); + if (unit.definedSafe.contains(name)) + return true; + } + return false; + } + return unit.definedSafe.contains(symbolOf(function)); + } + + /// Whether `declaration` is the C++ library's, which is not foreign + /// (§11): what is trusted of it is RFC 0044's and RFC 0050's. + static bool inCxxLibrary(const clang::Decl &declaration) { + for (const clang::DeclContext *context = declaration.getDeclContext(); + context != nullptr; context = context->getParent()) + if (const auto *space = llvm::dyn_cast(context)) { + if (space->isStdNamespace()) + return true; + if (const clang::IdentifierInfo *name = space->getIdentifier(); + name != nullptr && + (name->isStr("__gnu_cxx") || name->isStr("__cxxabiv1") || + name->isStr("__gnu_debug") || name->isStr("__detail"))) + return true; + } + return false; + } + + struct Place { + std::string file; + unsigned line = 0; + unsigned column = 0; + }; + Place placeOf(clang::SourceLocation at) const { + const clang::PresumedLoc presumed = + sources.getPresumedLoc(sources.getFileLoc(at)); + if (presumed.isInvalid()) + return {}; + return {.file = presumed.getFilename(), + .line = presumed.getLine(), + .column = presumed.getColumn()}; + } + + //===--------------------------------------------------------------------===// + // Contracts (§3) + //===--------------------------------------------------------------------===// + + void contractsIn(const clang::DeclContext *context) { + for (const clang::Decl *declaration : context->decls()) { + // A class is entered for the mark on a member, which is an error. + if (llvm::isa(declaration)) { + contractsIn(llvm::cast(declaration)); + continue; + } + if (const auto *function = + llvm::dyn_cast(declaration)) { + if (markedHere(*function, ForeignAnnotation)) + functionContract(*function); + continue; + } + if (const auto *variable = llvm::dyn_cast(declaration); + variable != nullptr && markedHere(*variable, ForeignAnnotation)) + globalContract(*variable); + } + } + + void bad(clang::SourceLocation at, const std::string &message, + const std::string ¬e) { + rules.owner(nullptr, false); + rules.report(at, rule::BadAnnotation, message, note); + } + + void functionContract(const clang::FunctionDecl &function) { + const std::string name = function.getNameAsString(); + if (function.doesThisDeclarationHaveABody()) { + bad(function.getLocation(), + "WEAVEC_FOREIGN is on the definition of '" + name + + "': a contract is the declaration of a function that code " + "WeaveC did not compile defines", + "remove it: the rules check this function's code"); + return; + } + // In a unit that defines the function the mark is ignored: a contract + // header may be included by the library's own units. + if (function.isDefined()) + return; + const clang::FunctionDecl *canonical = function.getCanonicalDecl(); + if (contracts.contains(canonical)) + return; + if (llvm::isa(function)) { + bad(function.getLocation(), + "WEAVEC_FOREIGN is on the member function '" + name + + "': a contract is a function's own declaration, and a member " + "is declared in its class", + "call a foreign class's member that passes a raw pointer from a " + "function that is not safe"); + return; + } + const std::string key = rowName(function); + if (function.getBuiltinID() != 0 || + core::LibrarySpec::shipped().lookup(key).has_value()) { + bad(function.getLocation(), + "'" + name + + "' has a row of the library table, which is its contract", + "remove the declaration; if the row is wrong for this function, " + "that is a bug in the table to report"); + return; + } + contracts[canonical] = {.declaration = &function, + .key = key, + .format = function.hasAttr()}; + } + + void globalContract(const clang::VarDecl &variable) { + if (variable.isThisDeclarationADefinition() != + clang::VarDecl::DeclarationOnly || + !variable.hasGlobalStorage()) { + bad(variable.getLocation(), + "WEAVEC_FOREIGN is on the definition of '" + + variable.getNameAsString() + + "': a contract is the 'extern' declaration of a global that " + "code WeaveC did not compile defines", + "remove it, or declare the global 'extern' with no initializer"); + return; + } + if (variable.hasDefinition() != clang::VarDecl::DeclarationOnly) + return; + if (core::LibrarySpec::shipped().global(variable.getName())) { + bad(variable.getLocation(), + "'" + variable.getNameAsString() + + "' has a row of the library table, which is its contract", + "remove the declaration"); + return; + } + globals.try_emplace(variable.getCanonicalDecl(), &variable); + } + + /// A term's text for a bound: the count and the element's bytes. + static std::string product(const std::string &count, std::uint64_t element) { + return element == 1 ? count : count + "*" + std::to_string(element); + } + + /// §4.1: the row a contract's annotations state. + std::string lower(const FunctionContract &contract) { + const clang::FunctionDecl &function = *contract.declaration; + const FunctionBounds bounds = rules.tableOf(function); + std::string row = contract.key + " ("; + for (unsigned i = 0; i < function.getNumParams(); ++i) { + if (i != 0) + row += ", "; + const clang::QualType type = + function.getParamDecl(i)->getType().getCanonicalType(); + const PointerBounds &bound = bounds.parameters[i]; + if (type->isFunctionPointerType() || type->isBlockPointerType() || + type->isMemberPointerType() || type->isFunctionReferenceType()) { + row += "fn"; + continue; + } + if (type->isReferenceType()) { + const clang::QualType pointee = type->getPointeeType(); + if (pointee->isIncompleteType()) { + row += "handle"; + } else { + row += (pointee.isConstQualified() ? "r:bytes(" : "rw:bytes(") + + std::to_string(ast.getTypeSizeInChars(pointee).getQuantity()) + + ")"; + } + if (bound.escapes) + row += ":kept"; + continue; + } + if (!type->isPointerType()) { + row += type->isIntegralOrEnumerationType() ? "int" : "other"; + continue; + } + const std::string access = + type->getPointeeType().isConstQualified() ? "r" : "rw"; + std::string text; + switch (bound.kind) { + case PointerBounds::Kind::Counted: { + std::string count; + if (bound.countPointee >= 0) + count = "*a" + std::to_string(bound.countPointee); + else if (bound.count >= 0) + count = "a" + std::to_string(bound.count); + if (count.empty()) { + // A constant count: the bytes, or (a member's count, which a + // contract's parameter cannot have) the first byte. + text = bound.memberOffset >= 0 + ? access + : access + ":bytes(" + + std::to_string(bound.constant * bound.elementSize) + + ")" + (bound.orNull ? ":null-ok" : ""); + break; + } + const std::string term = product(count, bound.elementSize); + text = access; + text += ":bytes("; + text += term; + text += bound.orNull ? "):null-ok" : "):null-if-zero(" + term + ")"; + break; + } + case PointerBounds::Kind::NullTerminated: + text = access + ":str" + (bound.orNull ? ":null-ok" : ""); + break; + case PointerBounds::Kind::Ended: { + // The bytes from the pointer to its end (amendment 4). + const std::string term = + "a" + std::to_string(bound.end) + "-a" + std::to_string(i); + text = access; + text += ":bytes("; + text += term; + text += bound.orNull ? "):null-ok" : "):null-if-zero(" + term + ")"; + break; + } + case PointerBounds::Kind::Single: + text = bound.pointeeSize == 0 + ? "handle" + : access + ":bytes(" + std::to_string(bound.pointeeSize) + + "):null-ok"; + break; + case PointerBounds::Kind::None: + text = "handle"; + break; + } + if (bound.escapes && !bound.owned) + text += ":kept"; + row += text; + } + if (function.isVariadic()) + row += function.getNumParams() == 0 ? "..." : ", ..."; + row += ") -> "; + const clang::QualType result = function.getReturnType().getCanonicalType(); + if (result->isVoidType()) { + row += "void"; + } else if (result->isPointerType() || result->isReferenceType()) { + row += "ptr"; + if (bounds.result.owned) + row += ":owned"; + if (bounds.result.kind == PointerBounds::Kind::NullTerminated) + row += ":str"; + else if (bounds.result.kind == PointerBounds::Kind::Counted && + bounds.result.memberOffset < 0) + row += ":bytes(" + + (bounds.result.count >= 0 + ? product("a" + std::to_string(bounds.result.count), + bounds.result.elementSize) + : std::to_string(bounds.result.constant * + bounds.result.elementSize)) + + ")"; + if (!bounds.result.owned) + for (unsigned i = 0; i < bounds.parameters.size(); ++i) + if (bounds.parameters[i].lifetimeBound && + (function.getParamDecl(i)->getType()->isPointerType() || + function.getParamDecl(i)->getType()->isReferenceType())) { + row += ":of(a" + std::to_string(i) + ")"; + break; + } + } else { + row += "int"; + } + if (const auto *format = function.getAttr()) { + const llvm::StringRef kind = + format->getType() != nullptr ? format->getType()->getName() : ""; + // printf's archetypes, the logs' included (os_log, syslog). + const bool printf = kind.contains("printf") || kind.ends_with("log"); + const int formatIndex = format->getFormatIdx() - 1; + // The first variadic argument, or a `v` function's `va_list`. + const int first = format->getFirstArg() != 0 ? format->getFirstArg() - 1 + : formatIndex + 1; + if ((printf || kind.contains("scanf")) && formatIndex >= 0 && + std::cmp_less(formatIndex, function.getNumParams()) && + (function.isVariadic() || + std::cmp_less(first, function.getNumParams()))) + row += (printf ? " printf(" : " scanf(") + std::to_string(formatIndex) + + ", " + std::to_string(first) + ")"; + } + if (function.isNoReturn()) + row += " exits"; + return row + ";"; + } + + /// A member bounded by its end in what a value of `type` gives foreign + /// code. Typed memory keeps a count beside its pointer and no end (RFC + /// 0042 amendment 2: an end's loads keep their guards), so nothing holds + /// the bound foreign code would believe of such a member. + const clang::FieldDecl * + endedMember(clang::QualType type, + llvm::SmallPtrSetImpl &seen) const { + const clang::Type *of = type.getCanonicalType().getTypePtr(); + if (of->isAnyPointerType() || of->isReferenceType()) + return endedMember(of->getPointeeType(), seen); + if (const auto *array = llvm::dyn_cast(of)) + return endedMember(array->getElementType(), seen); + const clang::RecordDecl *record = of->getAsRecordDecl(); + if (record == nullptr || !seen.insert(of).second) + return nullptr; + record = record->getDefinition(); + if (record == nullptr) + return nullptr; + if (const auto *cxxRecord = llvm::dyn_cast(record); + cxxRecord != nullptr && !cxxRecord->isCLike()) + return nullptr; + for (const clang::FieldDecl *field : record->fields()) { + if (llvm::any_of(annotationsOf(field->getType(), ast), + [](const TypeAnnotation &annotation) { + return annotation.name == EndedByAnnotation; + })) + return field; + if (const clang::FieldDecl *inner = endedMember(field->getType(), seen)) + return inner; + } + return nullptr; + } + + /// Whether a contract's types give foreign code such a member + /// (`bad-annotation`). + bool givesEnded(const clang::DeclaratorDecl &contract, + llvm::ArrayRef types) { + for (const clang::QualType type : types) { + llvm::SmallPtrSet seen; + const clang::FieldDecl *field = endedMember(type, seen); + if (field == nullptr) + continue; + bad(contract.getLocation(), + "the contract of '" + contract.getNameAsString() + + "' gives foreign code '" + field->getNameAsString() + "' of '" + + clang::QualType(ast.getCanonicalTagType(field->getParent())) + .getAsString(ast.getPrintingPolicy()) + + "', which WEAVEC_ENDED_BY bounds: typed memory keeps a count " + "beside its pointer, and no end", + "state the member's bound as a count (WEAVEC_COUNTED_BY or " + "WEAVEC_SIZED_BY), or make the call from a function that is not " + "safe"); + return true; + } + return false; + } + + void lowerContracts() { + // (Once every WEAVEC_FOREIGN_FIELD of the unit is read.) + for (const auto &[canonical, variable] : globals) + givesEnded(*variable, {variable->getType()}); + // In the unit's order, so that the rows' text is the same each compile. + std::vector ordered; + for (const auto &[function, contract] : contracts) + ordered.push_back(&contract); + llvm::sort(ordered, [&](const FunctionContract *a, + const FunctionContract *b) { + return sources.isBeforeInTranslationUnit(a->declaration->getLocation(), + b->declaration->getLocation()); + }); + std::vector failed; + for (const FunctionContract *contract : ordered) { + const clang::FunctionDecl &function = *contract->declaration; + const clang::SourceLocation at = function.getLocation(); + std::vector types = {function.getReturnType()}; + for (const clang::ParmVarDecl *parameter : function.parameters()) + types.push_back(parameter->getType()); + if (givesEnded(function, types)) { + failed.push_back(function.getCanonicalDecl()); + continue; + } + // A result counted through a pointer would be read before the call + // stores it. + const std::string row = lower(*contract); + std::string error; + if (!core::LibrarySpec::parse(row, error)) { + bad(at, + "the contract of '" + function.getNameAsString() + + "' says what no row can: " + + llvm::StringRef(error).rsplit(": ").second.str(), + "state each pointer's bound with a parameter of the declaration, " + "a constant, or '*p' for a parameter that points to an integer"); + failed.push_back(function.getCanonicalDecl()); + continue; + } + const Place place = placeOf(at); + unit.contracts[contract->key] = {.file = place.file, + .line = place.line, + .column = place.column, + .row = row}; + rowsText += row + "\n"; + } + for (const clang::FunctionDecl *function : failed) + contracts.erase(function); + if (rowsText.empty()) + return; + std::string error; + if (auto rows = core::LibrarySpec::parse(rowsText, error)) + unit.contractRows = + std::make_shared(std::move(*rows)); + } + + //===--------------------------------------------------------------------===// + // Uses (§7.1, §9) + //===--------------------------------------------------------------------===// + + enum class Use : std::uint8_t { Call, Address, Global }; + + struct Within { + const clang::FunctionDecl *function = nullptr; + bool safe = false; + bool surveyed = false; + }; + + /// The functions of the unit whose code is the program's. + void usesIn(const clang::DeclContext *context) { + struct Functions final : clang::RecursiveASTVisitor { + std::vector found; + std::vector globals; + // NOLINTBEGIN(readability-identifier-naming,bugprone-derived-method-shadowing-base-method,readability-make-member-function-const) + [[nodiscard]] static bool shouldVisitTemplateInstantiations() { + return true; + } + bool VisitFunctionDecl(clang::FunctionDecl *function) { + if (function->doesThisDeclarationHaveABody() && + !function->isDependentContext()) + found.push_back(function); + return true; + } + bool VisitVarDecl(clang::VarDecl *variable) { + if (variable->hasGlobalStorage() && variable->isExternallyVisible() && + !variable->isStaticLocal() && + variable->isThisDeclarationADefinition() != + clang::VarDecl::DeclarationOnly && + !variable->getDeclContext()->isDependentContext()) + globals.push_back(variable); + return true; + } + // NOLINTEND(readability-identifier-naming,bugprone-derived-method-shadowing-base-method,readability-make-member-function-const) + } functions; + // NOLINTBEGIN(cppcoreguidelines-pro-type-const-cast) + functions.TraverseDecl( + const_cast(llvm::cast(context))); + // NOLINTEND(cppcoreguidelines-pro-type-const-cast) + // What another unit's safe code may name: the audit resolves its + // `expects` against these, as the link does against the objects. + std::set defined; + for (const clang::VarDecl *variable : functions.globals) + if (!sources.isInSystemHeader(variable->getLocation())) + if (std::string symbol = symbolOf(*variable); !symbol.empty()) + defined.insert(std::move(symbol)); + unit.definedGlobals.assign(defined.begin(), defined.end()); + llvm::SmallPtrSet seen; + for (const clang::FunctionDecl *function : functions.found) { + if (!seen.insert(function).second || + sources.isInSystemHeader(function->getLocation()) || + function->getBody() == nullptr) + continue; + Within within; + within.function = function; + within.safe = isSafe(*function); + within.surveyed = + !within.safe && unit.survey && !marked(*function, "weavec.unsafe"); + usesOf(within); + } + } + + void usesOf(const Within &within) { + struct Body final : clang::RecursiveASTVisitor { + Foreign *self = nullptr; + const Within *within = nullptr; + llvm::SmallPtrSet callees; + // NOLINTBEGIN(readability-identifier-naming,bugprone-derived-method-shadowing-base-method,readability-make-member-function-const) + bool TraverseDecl(clang::Decl *declaration) { + // A local class's functions are functions of their own. + if (declaration != nullptr && + llvm::isa(declaration)) + return true; + return clang::RecursiveASTVisitor::TraverseDecl(declaration); + } + bool VisitCallExpr(clang::CallExpr *call) { + callees.insert(call->getCallee()->IgnoreParenImpCasts()); + if (const clang::FunctionDecl *callee = call->getDirectCallee()) + self->use(*within, *callee, call->getExprLoc(), Use::Call, call); + return true; + } + bool VisitCXXConstructExpr(clang::CXXConstructExpr *construct) { + if (const clang::CXXConstructorDecl *callee = + construct->getConstructor()) + self->use(*within, *callee, construct->getExprLoc(), Use::Call, + nullptr); + return true; + } + bool VisitDeclRefExpr(clang::DeclRefExpr *reference) { + if (const auto *function = + llvm::dyn_cast(reference->getDecl())) { + if (!callees.contains(reference)) + self->use(*within, *function, reference->getExprLoc(), Use::Address, + nullptr); + } else if (const auto *variable = + llvm::dyn_cast(reference->getDecl())) { + self->global(*within, *variable, reference->getExprLoc()); + } + return true; + } + // NOLINTEND(readability-identifier-naming,bugprone-derived-method-shadowing-base-method,readability-make-member-function-const) + } body; + body.self = this; + body.within = &within; + body.TraverseStmt(within.function->getBody()); + } + + /// One more place of a list's entry. + void list(std::vector &into, + std::map &at, const Within &within, + const std::string &name, const std::string &symbol, + llvm::StringRef use, clang::SourceLocation where, + const std::string &proposal) { + const std::string key = + symbol + (within.surveyed ? "\nsurveyed" : "") + "\n" + use.str(); + const auto [found, added] = at.try_emplace(key, into.size()); + if (added) { + const Place place = placeOf(where); + into.push_back({.function = name, + .symbol = symbol, + .use = use.str(), + .file = place.file, + .line = place.line, + .column = place.column, + .caller = within.function->getNameAsString(), + .places = 0, + .proposal = proposal, + .surveyed = within.surveyed}); + } + ++into[found->second].places; + } + + /// One more call of a function with a row or a contract. + void covered(const Within &within, const std::string &name, + llvm::StringRef kind, const Place &place, const std::string &row, + bool isGlobal) { + const auto [found, added] = + foreignAt.try_emplace(name, unit.foreign.size()); + if (added) + unit.foreign.push_back({.function = name, + .contract = kind.str(), + .file = place.file, + .line = place.line, + .column = place.column, + .row = row, + .safeCalls = 0, + .guardedCalls = 0, + .global = isGlobal}); + ++(within.safe ? unit.foreign[found->second].safeCalls + : unit.foreign[found->second].guardedCalls); + } + + /// Whether a pointer passes through the `...` of `call`. + bool variadicPointer(const clang::FunctionDecl &callee, + const clang::CallExpr *call) const { + if (call == nullptr || !callee.isVariadic()) + return false; + for (unsigned i = callee.getNumParams(); i < call->getNumArgs(); ++i) { + const clang::Expr *argument = call->getArg(i); + // (A null pointer constant is no pointer to anything.) + if (argument->isNullPointerConstant( + ast, clang::Expr::NPC_ValueDependentIsNotNull) != + clang::Expr::NPCK_NotNull) + continue; + if (pointerCrosses(argument->IgnoreParenImpCasts()->getType(), ast) || + pointerCrosses(argument->getType(), ast)) + return true; + } + return false; + } + + void use(const Within &within, const clang::FunctionDecl &callee, + clang::SourceLocation at, Use kind, const clang::CallExpr *call) { + if (callee.isDefined() || callee.isImplicit() || callee.isDeleted() || + callee.isDefaulted() || callee.isPureVirtual() || + callee.isDependentContext() || + llvm::isa(callee)) + return; + if (cxx && (inCxxLibrary(callee) || + callee.isReplaceableGlobalAllocationFunction())) + return; + const std::string name = callee.getQualifiedNameAsString(); + const std::string key = rowName(callee); + const unsigned arguments = + call != nullptr ? call->getNumArgs() : callee.getNumParams(); + const std::optional row = + core::LibrarySpec::shipped().lookup(key, arguments); + // A builtin with no row is the compiler's own (`__builtin_expect`). + if (const unsigned builtin = callee.getBuiltinID(); builtin != 0 && !row) { + const llvm::StringRef spelled = + callee.getIdentifier() != nullptr ? callee.getName() : ""; + if (spelled.starts_with("__builtin_") || spelled.starts_with("__sync_") || + spelled.starts_with("__atomic_") || spelled.starts_with("_mm") || + !(ast.BuiltinInfo.isLibFunction(builtin) || + ast.BuiltinInfo.isPredefinedLibFunction(builtin))) + return; + } + const auto contract = contracts.find(callee.getCanonicalDecl()); + const bool through = variadicPointer(callee, call); + // §3.6: no contract can say what the pointer is. The function is + // foreign as far as the unit can tell when a contract or a system + // header declares it; one the program's own headers declare may be + // another unit's, and in C its call is `variadic`'s as it was (RFC + // 0041): the link still asks for a contract if no unit defines it. + if (through && !row && + (contract == contracts.end() || !contract->second.format) && + !callee.hasAttr() && + (within.safe || within.surveyed)) { + const bool foreign = + cxx || contract != contracts.end() || + ast.getSourceManager().isInSystemHeader(callee.getLocation()); + rules.owner(within.function, within.surveyed); + if (foreign) + rules.report(at, rule::ForeignCall, + "a pointer is passed to '" + name + + "' through '...', where no contract says what is " + "done with it", + "make the call in a function that is not safe " + "(WEAVEC_GUARDED), which the audit lists"); + else + rules.report(at, rule::Variadic, + "a pointer is passed to '" + name + + "' through '...', and nothing says how it is read", + "give the declaration a format attribute if it reads a " + "printf or scanf format, call a variant that takes its " + "arguments by type, or make the call in a function " + "that is not safe (WEAVEC_GUARDED)"); + rules.owner(nullptr, false); + return; + } + if (row && row->entry != nullptr) { + Place place = placeOf(callee.getLocation()); + place.line = row->entry->line; + place.column = 0; + covered(within, row->entry->name, "table", place, "", false); + if (call != nullptr) + keptLocals(within, callee, nullptr, row->entry, *call); + return; + } + if (contract != contracts.end()) { + const auto stated = unit.contracts.find(contract->second.key); + covered(within, name, "declared", + placeOf(contract->second.declaration->getLocation()), + stated != unit.contracts.end() ? stated->second.row : "", false); + if (within.safe && call != nullptr) + callbacks(within, *contract->second.declaration, *call); + if (call != nullptr) + keptLocals(within, callee, contract->second.declaration, nullptr, + *call); + return; + } + const std::string symbol = symbolOf(callee); + const llvm::StringRef how = kind == Use::Call ? "call" : "address"; + if (!crossesFunction(callee, ast) && !through) { + if (within.safe) + list(unit.uncrossed, uncrossedAt, within, name, symbol, how, at, ""); + return; + } + if (within.safe || within.surveyed) + list(unit.expects, expectsAt, within, name, symbol, how, at, + proposeContract(callee)); + else + list(unit.unchecked, uncheckedAt, within, name, symbol, how, at, + proposeContract(callee)); + } + + void global(const Within &within, const clang::VarDecl &variable, + clang::SourceLocation at) { + if (!variable.hasGlobalStorage() || !variable.isExternallyVisible() || + variable.hasDefinition() != clang::VarDecl::DeclarationOnly || + variable.getDeclContext()->isDependentContext() || + (cxx && inCxxLibrary(variable))) + return; + const std::string name = variable.getQualifiedNameAsString(); + if (variable.getIdentifier() != nullptr && + core::LibrarySpec::shipped().global(variable.getName())) { + covered(within, name, "table", placeOf(variable.getLocation()), "", true); + return; + } + if (const auto contract = globals.find(variable.getCanonicalDecl()); + contract != globals.end()) { + covered(within, name, "declared", + placeOf(contract->second->getLocation()), "", true); + return; + } + const std::string symbol = symbolOf(variable); + if (!pointerCrosses(variable.getType(), ast)) { + if (within.safe) + list(unit.uncrossed, uncrossedAt, within, name, symbol, "global", at, + ""); + return; + } + clang::PrintingPolicy policy(ast.getPrintingPolicy()); + std::string declarator = name; + variable.getType().getAsStringInternal(declarator, policy); + const std::string proposal = "WEAVEC_FOREIGN extern " + declarator + ";"; + if (within.safe || within.surveyed) + list(unit.expects, expectsAt, within, name, symbol, "global", at, + proposal); + else + list(unit.unchecked, uncheckedAt, within, name, symbol, "global", at, + proposal); + } + + //===--------------------------------------------------------------------===// + // Callbacks (§3.5) + //===--------------------------------------------------------------------===// + + /// The prototype a function-pointer parameter's declarator writes, with + /// its parameters' names. + static clang::FunctionProtoTypeLoc prototypeOf(clang::TypeLoc at) { + for (unsigned depth = 0; depth < 8 && !at.isNull(); ++depth) { + at = at.getUnqualifiedLoc(); + if (const auto found = at.getAs()) + return found; + if (const auto pointer = at.getAs()) { + at = pointer.getPointeeLoc(); + } else if (const auto paren = at.getAs()) { + at = paren.getInnerLoc(); + } else if (const auto attributed = at.getAs()) { + at = attributed.getModifiedLoc(); + } else if (const auto named = at.getAs()) { + const clang::TypeSourceInfo *written = + named.getDecl()->getTypeSourceInfo(); + if (written == nullptr) + break; + at = written->getTypeLoc(); + } else if (const auto elaborated = at.getNextTypeLoc(); + !elaborated.isNull() && elaborated != at) { + at = elaborated; + } else { + break; + } + } + return {}; + } + + /// A bound annotation of `type` as `name(index of the parameter it + /// names)`, or with the argument's text when it names none. + template + std::string boundOf(clang::QualType type, const Names &indexOf) const { + for (const TypeAnnotation &annotation : annotationsOf(type, ast)) { + const llvm::StringRef name = annotation.name; + if (name == EscapesAnnotation || name == BorrowedAnnotation || + name == OwnedAnnotation || name == DropsAnnotation || + name == SendsAnnotation) + continue; + const int index = indexOf(annotation.argument); + return (name + "(" + + (index >= 0 ? "#" + std::to_string(index) : annotation.argument) + + ")") + .str(); + } + return {}; + } + + /// The macro an annotation is written with, and its argument. + static std::string spelled(llvm::StringRef annotation, + llvm::StringRef argument) { + std::string macro = "WEAVEC_" + annotation.drop_front(7).upper(); + if (annotation == NullTerminatedAnnotation || + annotation == NullTerminatedOrNullAnnotation) + return macro; + return macro + "(" + argument.str() + ")"; + } + + /// The local whose address `argument` is, as the error names it: `&local`, + /// `&local.member`, `&local.array[i]`, a local array (or an array member + /// of a local) where it becomes a pointer, or a compound literal written + /// in a function, which is a local with no name. A static local outlives + /// the function. Empty for anything else. + static std::string localAddressed(const clang::Expr *argument) { + argument = argument->IgnoreParenCasts(); + if (const auto *address = llvm::dyn_cast(argument)) { + if (address->getOpcode() != clang::UO_AddrOf) + return {}; + argument = address->getSubExpr()->IgnoreParenCasts(); + } else if (!argument->getType()->isArrayType()) { + return {}; + } + for (unsigned depth = 0; depth < 32; ++depth) { + if (const auto *member = llvm::dyn_cast(argument)) { + if (member->isArrow()) + return {}; + argument = member->getBase()->IgnoreParenCasts(); + } else if (const auto *element = + llvm::dyn_cast(argument)) { + const clang::Expr *base = element->getBase()->IgnoreParenImpCasts(); + if (!base->getType()->isArrayType()) + return {}; + argument = base; + } else { + break; + } + } + if (const auto *literal = + llvm::dyn_cast(argument)) + return literal->isFileScope() ? std::string() : "a compound literal"; + const auto *reference = llvm::dyn_cast(argument); + const auto *variable = + reference != nullptr + ? llvm::dyn_cast(reference->getDecl()) + : nullptr; + return variable != nullptr && variable->hasLocalStorage() + ? "'" + variable->getNameAsString() + "'" + : std::string(); + } + + /// §5.1, (F3): a foreign function that keeps a pointer (a contract's + /// `WEAVEC_ESCAPES` parameter, a row's `kept`) is not given the address + /// of a local. At a call of the program's own function Safe C places + /// such a local in typed memory for its scope (RFC 0048), and the code + /// that uses the pointer later is checked; what foreign code does with + /// it after the scope ends nothing checks, so here it is `escape`. Safe + /// C++'s flow rules say the same of every kept parameter. + void keptLocals(const Within &within, const clang::FunctionDecl &callee, + const clang::FunctionDecl *contract, + const core::LibraryEntry *row, const clang::CallExpr &call) { + if (cxx || !(within.safe || within.surveyed)) + return; + for (unsigned i = 0; i < call.getNumArgs(); ++i) { + bool keeps = false; + if (contract != nullptr && i < contract->getNumParams()) + keeps = hasAnnotation( + annotationsOf(contract->getParamDecl(i)->getType(), ast), + EscapesAnnotation); + else if (row != nullptr) + if (const core::LibraryParam *parameter = row->param(i)) + keeps = parameter->kept; + if (!keeps) + continue; + const std::string local = localAddressed(call.getArg(i)); + if (local.empty()) + continue; + rules.owner(within.function, within.surveyed); + rules.report(call.getArg(i)->getExprLoc(), rule::Escape, + "the address of " + local + " is given to '" + + callee.getNameAsString() + "', which keeps it, and " + + (local.front() == '\'' ? local : "the literal") + + " ends with its scope", + "code WeaveC did not compile is not checked when it uses " + "the pointer later: give it an object that outlives the " + "call (a global, a static local, a block the program " + "allocates and releases after the library lets go)"); + rules.owner(nullptr, false); + } + } + + void callbacks(const Within &within, const clang::FunctionDecl &contract, + const clang::CallExpr &call) { + for (unsigned i = 0; i < contract.getNumParams() && i < call.getNumArgs(); + ++i) { + const clang::ParmVarDecl *parameter = contract.getParamDecl(i); + if (!parameter->getType()->isFunctionPointerType() || + parameter->getTypeSourceInfo() == nullptr) + continue; + const clang::FunctionProtoTypeLoc prototype = + prototypeOf(parameter->getTypeSourceInfo()->getTypeLoc()); + if (prototype.isNull()) + continue; + const clang::Expr *argument = call.getArg(i)->IgnoreParenImpCasts(); + if (const auto *address = llvm::dyn_cast(argument); + address != nullptr && address->getOpcode() == clang::UO_AddrOf) + argument = address->getSubExpr()->IgnoreParenImpCasts(); + const auto *reference = llvm::dyn_cast(argument); + const auto *passed = + reference != nullptr + ? llvm::dyn_cast(reference->getDecl()) + : nullptr; + if (passed == nullptr || + passed->getNumParams() != prototype.getNumParams()) + continue; + const auto statedIndex = [&](llvm::StringRef name) { + for (unsigned j = 0; j < prototype.getNumParams(); ++j) + if (prototype.getParam(j) != nullptr && + prototype.getParam(j)->getName() == name) + return static_cast(j); + return -1; + }; + // The declaration of the function passed that says most. + const clang::FunctionDecl *declared = passed; + const auto passedIndex = [&](llvm::StringRef name) { + for (unsigned j = 0; j < declared->getNumParams(); ++j) + if (declared->getParamDecl(j)->getName() == name) + return static_cast(j); + return -1; + }; + for (unsigned j = 0; j < prototype.getNumParams(); ++j) { + if (prototype.getParam(j) == nullptr) + continue; + const clang::QualType statedType = prototype.getParam(j)->getType(); + const std::string stated = boundOf(statedType, statedIndex); + if (stated.empty()) + continue; + bool agrees = false; + for (const clang::FunctionDecl *each : passed->redecls()) { + declared = each; + if (boundOf(each->getParamDecl(j)->getType(), passedIndex) == stated) + agrees = true; + } + if (agrees) + continue; + declared = passed->getFirstDecl(); + // What to write on the function's parameter: the contract's + // annotation, naming the function's own parameter. + std::string written; + if (const std::vector annotations = + annotationsOf(statedType, ast); + !annotations.empty()) { + const TypeAnnotation &annotation = annotations.front(); + const int index = statedIndex(annotation.argument); + std::string named = annotation.argument; + if (index >= 0 && std::cmp_less(index, declared->getNumParams()) && + !declared->getParamDecl(static_cast(index)) + ->getName() + .empty()) + named = declared->getParamDecl(static_cast(index)) + ->getName() + .str(); + written = spelled(annotation.name, named); + } + const clang::ParmVarDecl *target = declared->getParamDecl(j); + if (rules.fixes != nullptr && target->getLocation().isValid() && + !target->getName().empty()) { + Want wanted; + wanted.kind = Want::Kind::Write; + wanted.declaration = target; + wanted.level = "certain"; + wanted.aspect = "bound"; + wanted.fact = written; + wanted.macros = true; + wanted.insertions.emplace_back(target->getLocation(), written + " "); + wanted.description = written + " " + target->getNameAsString(); + rules.fixes->want(call.getArg(i)->getExprLoc(), std::move(wanted)); + } + rules.owner(within.function, false); + rules.report(call.getArg(i)->getExprLoc(), rule::CallArgs, + "'" + passed->getNameAsString() + "' is passed where '" + + contract.getNameAsString() + "' declares '" + written + + "' for parameter " + std::to_string(j + 1) + + ", and declares none", + "declare '" + written + "' on parameter " + + std::to_string(j + 1) + " of '" + + passed->getNameAsString() + + "': foreign code calls it with what the contract " + "says"); + rules.owner(nullptr, false); + } + } + } + + void finish() { + // A contract nothing in the unit calls is listed too: the audit counts + // the program's contracts, not only those a unit happens to use. + for (const auto &[key, contract] : unit.contracts) + if (!foreignAt.contains(key.str()) && + llvm::none_of(unit.foreign, [&](const ForeignFunction &each) { + return each.contract == "declared" && each.file == contract.file && + each.line == contract.line; + })) + unit.foreign.push_back({.function = key.str(), + .contract = "declared", + .file = contract.file, + .line = contract.line, + .column = contract.column, + .row = contract.row, + .safeCalls = 0, + .guardedCalls = 0, + .global = false}); + } +}; + +} // namespace + +void checkForeign(clang::ASTContext &ast, SafeUnit &unit, + const ForeignRules &rules) { + Foreign(ast, unit, rules).run(); +} + +} // namespace weavec::frontend diff --git a/lib/Frontend/SafeTypes.cpp b/lib/Frontend/SafeTypes.cpp index 68e9c01..ac8c2f2 100644 --- a/lib/Frontend/SafeTypes.cpp +++ b/lib/Frontend/SafeTypes.cpp @@ -1095,7 +1095,8 @@ class Marker final : public clang::RecursiveASTVisitor { // conversion through a pointer variable. // (In C++ only an address that becomes a `void *`, or a local seen as // its base: a typed pointer converts down only by a class's rules.) - if (op->getOpcode() == clang::UO_AddrOf && !ast.getLangOpts().CPlusPlus) + if (op->getOpcode() == clang::UO_AddrOf && !ast.getLangOpts().CPlusPlus && + !lent.contains(op)) record(*op->getSubExpr()); return true; } @@ -1109,7 +1110,8 @@ class Marker final : public clang::RecursiveASTVisitor { case clang::CK_ArrayToPointerDecay: // (In C++ an array given as a typed pointer stays in its plain frame: // one that becomes a `void *` is recorded there.) - if (!subscripted.contains(cast) && !ast.getLangOpts().CPlusPlus) + if (!subscripted.contains(cast) && !lent.contains(cast) && + !ast.getLangOpts().CPlusPlus) record(*cast->getSubExpr()); break; case clang::CK_DerivedToBase: @@ -1127,6 +1129,7 @@ class Marker final : public clang::RecursiveASTVisitor { /// from (without virtual functions: those are checked by their vtable), /// bound to a reference or given as a pointer, may be converted down. bool VisitCallExpr(clang::CallExpr *call) { + lends(*call); recordsPassed(*call); // (In C every address taken is recorded where it is taken.) if (!ast.getLangOpts().CPlusPlus) @@ -1158,6 +1161,8 @@ class Marker final : public clang::RecursiveASTVisitor { clang::ASTContext * llvm::DenseSet writes; llvm::DenseSet subscripted; + /// RFC 0057 §5.1: the arguments lent to a function with a contract. + llvm::DenseSet lent; /// Whether a class the unit has parsed derives from `type`, a class /// without virtual functions (a downcast's source). @@ -1248,6 +1253,43 @@ class Marker final : public clang::RecursiveASTVisitor { }); } + /// RFC 0057 §5.1: the contract of the function called, when the argument + /// at `index` is lent to it for the call: a typed pointer its parameter + /// does not keep. Code WeaveC did not compile asks for no bound and + /// makes no checked conversion. + [[nodiscard]] bool lentTo(const clang::FunctionDecl *contract, + unsigned index) const { + if (contract == nullptr || index >= contract->getNumParams()) + return false; + const clang::QualType type = contract->getParamDecl(index)->getType(); + return type->isPointerType() && !type->isVoidPointerType() && + !type->isFunctionPointerType() && + !hasAnnotation(annotationsOf(type, ast), EscapesAnnotation); + } + + /// (Visited before its arguments: an address lent for the call is none + /// that §1.2 records.) + void lends(const clang::CallExpr &call) { + const clang::FunctionDecl *callee = call.getDirectCallee(); + const clang::FunctionDecl *contract = + callee != nullptr ? contractDeclaration(*callee) : nullptr; + if (contract == nullptr) + return; + for (unsigned i = 0; i < call.getNumArgs(); ++i) { + if (!lentTo(contract, i)) + continue; + const clang::Expr *argument = call.getArg(i)->IgnoreParens(); + // (A conversion that only adds `const`.) + while (const auto *cast = + llvm::dyn_cast(argument)) { + if (cast->getCastKind() != clang::CK_NoOp) + break; + argument = cast->getSubExpr()->IgnoreParens(); + } + lent.insert(argument); + } + } + /// RFC 0056 §4: a local array, or a local that holds one, whose address /// is passed to a function of the program (which may hand it to code /// that asks for its bound and holds none): recorded for its scope. @@ -1299,8 +1341,17 @@ class Marker final : public clang::RecursiveASTVisitor { holdsArray(variable->getType())) record(*object); }; - for (const clang::Expr *argument : call.arguments()) + // RFC 0057 §5.1: what a function with a contract is lent for the call + // needs no record (what it keeps may come back through a callback). + const clang::FunctionDecl *contract = + callee != nullptr ? contractDeclaration(*callee) : nullptr; + unsigned index = 0; + for (const clang::Expr *argument : call.arguments()) { + const unsigned at = index++; + if (lentTo(contract, at)) + continue; passed(*argument); + } // (A member function is passed its object.) if (const auto *member = llvm::dyn_cast(&call)) if (const clang::Expr *object = member->getImplicitObjectArgument(); diff --git a/resources/include/weavec.h b/resources/include/weavec.h index 99fb11a..092b8d6 100644 --- a/resources/include/weavec.h +++ b/resources/include/weavec.h @@ -28,7 +28,7 @@ #define WEAVEC_H #define WEAVEC_H_VERSION_MAJOR 3 -#define WEAVEC_H_VERSION_MINOR 5 +#define WEAVEC_H_VERSION_MINOR 6 #if defined(__has_attribute) #if __has_attribute(annotate) @@ -223,4 +223,50 @@ * member is for. A member without one is never used by safe code. */ #define WEAVEC_WHEN(...) WEAVEC_ANNOTATE_ARGS_("weavec.when", __VA_ARGS__) +/** + * Before the declaration of a function WeaveC does not compile (a library + * the program links): the declaration is the function's contract, what it + * does with what it is given, said with the annotations above. A safe + * function may call a function no code WeaveC compiled defines only with + * a contract (or a row of the library table), and every caller's + * arguments are checked against it. In a contract a count may also be + * `*p`, the integer a pointer parameter `p` points to when the call is + * made (`WEAVEC_SIZED_BY(*destLen)`). Before the declaration of a global + * such code defines, it says the same of the global's type. + * + * WEAVEC_FOREIGN int compress( + * unsigned char *WEAVEC_SIZED_BY(*destLen) dest, unsigned long *destLen, + * const unsigned char *WEAVEC_SIZED_BY(sourceLen) source, + * unsigned long sourceLen); + */ +#define WEAVEC_FOREIGN WEAVEC_ANNOTATE_("weavec.foreign") + +/** + * At file scope, as a declaration of its own: the contract of a pointer + * member of a struct a foreign header defines, which the program cannot + * annotate where it is declared. The annotations are a member's (a bound + * that names another member, WEAVEC_OWNED, WEAVEC_BORROWED): + * + * WEAVEC_FOREIGN_FIELD(struct iovec, iov_base, WEAVEC_SIZED_BY(iov_len)); + */ +#if defined(__clang__) && defined(__has_attribute) +#if __has_attribute(annotate) +/* Two declarations, since C++ takes no attribute after `__typeof__(...)`: + * the member's type under a name, then that name with the annotations. */ +#define WEAVEC_FOREIGN_FIELD_2_(type, field, n, ...) \ + typedef __typeof__(((type *)0)->field) weavec_foreign_member_##n##_; \ + typedef weavec_foreign_member_##n##_ __VA_ARGS__ \ + weavec_foreign_field_##n##_ WEAVEC_ANNOTATE_ARGS_( \ + "weavec.foreign_field", #type, #field) +#define WEAVEC_FOREIGN_FIELD_1_(type, field, n, ...) \ + WEAVEC_FOREIGN_FIELD_2_(type, field, n, __VA_ARGS__) +#define WEAVEC_FOREIGN_FIELD(type, field, ...) \ + WEAVEC_FOREIGN_FIELD_1_(type, field, __COUNTER__, __VA_ARGS__) +#endif +#endif +#ifndef WEAVEC_FOREIGN_FIELD +#define WEAVEC_FOREIGN_FIELD(type, field, ...) \ + typedef int weavec_foreign_field_unused_ +#endif + #endif /* WEAVEC_H */ diff --git a/resources/safe/rules.md b/resources/safe/rules.md index 0ce9a58..0fc2597 100644 --- a/resources/safe/rules.md +++ b/resources/safe/rules.md @@ -452,6 +452,28 @@ void keep(struct holder *h, int *WEAVEC_ESCAPES p) { h->kept = p; } `WEAVEC_ESCAPES` after the `*` if the function keeps a reference (callers then cannot pass a stack address); `WEAVEC_LIFETIMEBOUND` after the parameter's name if the function returns it; `WEAVEC_OWNED` if the function takes the block and is responsible for releasing it (see `owner-source`); a `WEAVEC_BORROWED` field of a local struct to carry it down a call tree. +A local whose address a function of the program keeps is placed in typed memory for its scope, and the code that uses the pointer later is checked. Code WeaveC did not compile is not, so the address of a local is not given to a parameter a foreign function keeps: a `WEAVEC_ESCAPES` parameter of a contract, or one a row of the library table says is kept ([`foreign-call`](#foreign-call)). Give the library a global, a static local, or a block the program allocates and releases after the library lets go. + +```c rejected +struct app { int events; }; +WEAVEC_FOREIGN void lib_listen(void (*callback)(void *user), void *WEAVEC_ESCAPES user); +void seen(void *user) { (void)user; } +void listen(void) { + struct app app = {0}; + lib_listen(seen, &app); +} +``` + +```c accepted +struct app { int events; }; +WEAVEC_FOREIGN void lib_listen(void (*callback)(void *user), void *WEAVEC_ESCAPES user); +void seen(void *user) { (void)user; } +void listen(void) { + static struct app app; + lib_listen(seen, &app); +} +``` + _Fix_ ([`fix`](#fix)): `WEAVEC_ESCAPES` on the parameter, or after the parameter list for `this`, on every declaration (certain); a returned parameter that every return gives, `WEAVEC_LIFETIMEBOUND` (likely); a pointer member of a class of plain values, `WEAVEC_BORROWED` first (likely). ### In C++ @@ -775,7 +797,23 @@ void copy(char *WEAVEC_COUNTED_BY(n) out, const char *WEAVEC_COUNTED_BY(n) in, ``` -_Fix_ ([`fix`](#fix)): the argument's bound, from its uses, on its declaration; for a stored or returned end of its own bound (`data_ + size_`), `WEAVEC_COUNTED_BY(0)` on where it goes (certain). +A function passed where a contract's function-pointer type declares a bound ([`foreign-call`](#foreign-call), [RFC 0057](/rfcs/0057-foreign-code-by-contract/) §3.5) declares the same bound for that parameter: the library calls it with memory WeaveC has no record of, and the declaration is what says how much of it there is. + +```c rejected +typedef void (*on_data)(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n); +WEAVEC_FOREIGN void lib_listen(on_data callback, void *user); +void seen(void *user, const char *data, size_t n) { (void)user; (void)data; (void)n; } +void listen(void) { lib_listen(seen, NULL); } +``` + +```c accepted +typedef void (*on_data)(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n); +WEAVEC_FOREIGN void lib_listen(on_data callback, void *user); +void seen(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n) { (void)user; (void)data; (void)n; } +void listen(void) { lib_listen(seen, NULL); } +``` + +_Fix_ ([`fix`](#fix)): the argument's bound, from its uses, on its declaration; for a stored or returned end of its own bound (`data_ + size_`), `WEAVEC_COUNTED_BY(0)` on where it goes (certain); for a function passed to a contract, the bound the contract's type declares, on the function's parameter (certain). ### In C++ The same for a function's, a constructor's or a member function's parameters with a bound (a pointer with no declared bound passes the bound found for it, under the default), and for the library's that take a pointer and a count, or two pointers: `std::span(p, n)`, `std::string_view(p, n)`, `std::string(p, n)`, `append(p, n)`, `assign(p, n)`, `std::vector(first, last)`. Their pointer has a bound that covers the count, checked when it runs; in a fast unit a `std::span` or a `std::string_view` made from a pointer, or from an iterator, is checked once where it is made, since its index is checked by the library alone (RFC 0050 §2.3). @@ -819,15 +857,28 @@ void copy(char *WEAVEC_COUNTED_BY(n) out, const char *WEAVEC_COUNTED_BY(n) in, s ## variadic -A variadic call is only to a function of the library table whose row describes its format (`printf` is described); `va_start` is not used, nor `va_arg` of a type that holds pointers. +A safe function reads no variadic arguments: `va_start` is not used, nor `va_arg` of a type that holds pointers. So a variadic function the unit defines is not called from safe code, since it could not read what it is given. ```c rejected -int total(int count, ...); +int total(int count, ...) { return count; } int call(void) { return total(2, 1, 2); } ``` Take the arguments by type: a counted array and its length. +A variadic function the unit only declares is another's code ([RFC 0057](/rfcs/0057-foreign-code-by-contract/) §3.6). Its call is accepted when the library table's row or a `format` attribute describes its format (`printf` is described, and the arguments are checked against it), and when no variadic argument is or holds a pointer (`open(path, flags, 0644)`). A pointer through `...` with no format is rejected: nothing says how the function reads it. The error is this rule's when the program's own header declares the function, and [`foreign-call`](#foreign-call)'s when a system header or a contract does. + +```c rejected +int report(int level, const char *WEAVEC_NULL_TERMINATED text, ...); +int call(const char *WEAVEC_NULL_TERMINATED name) { return report(2, "%s", name); } +``` + +```c accepted +int total(int count, ...); +int report(int level, const char *WEAVEC_NULL_TERMINATED text, ...) __attribute__((format(printf, 2, 3))); +int call(const char *WEAVEC_NULL_TERMINATED name) { return total(2, 1, 2) + report(2, "%s", name); } +``` + ### In C++ A safe function does not read variadic arguments with `va_start` and `va_arg`; a parameter pack, a `std::initializer_list` or a `std::span` carries them with their types. Calling `printf` is allowed, and its format is checked as in C. @@ -966,6 +1017,16 @@ int sum(const int *WEAVEC_COUNTED_BY(count) v, size_t n); int sum(const int *WEAVEC_COUNTED_BY(n) v, size_t n); ``` +A contract ([`foreign-call`](#foreign-call)) is a declaration of code WeaveC did not compile, and nothing else: `WEAVEC_FOREIGN` is not written on a definition (a function's or a global's) or on a member function, nor for a function or a global the library table has a row for (the table is WeaveC's contract for the C library; a row that is wrong is a bug to report). A count `*p` names a parameter that points to an integer, bounds a parameter and not the result, and is written only in a contract. `WEAVEC_FOREIGN_FIELD` names a pointer member that has no annotation of its own, and two for one member say the same. A contract gives foreign code no struct with a member that `WEAVEC_ENDED_BY` bounds (as a parameter, a result or a global, directly or through a pointer): typed memory keeps a count beside a member's pointer and no end, so the member takes `WEAVEC_COUNTED_BY` or `WEAVEC_SIZED_BY` instead. On a parameter of the contract itself an end is fine: the call compares the bytes from the pointer to it. + +```c rejected +WEAVEC_FOREIGN char *getenv(const char *WEAVEC_NULL_TERMINATED name); +``` + +```c rejected +int fill(char *WEAVEC_COUNTED_BY(*n) out, size_t *n) { return out != NULL && n != NULL; } +``` + _Fix_ ([`fix`](#fix)): what one declaration of a function says, written on the other (certain). ### In C++ @@ -1966,3 +2027,175 @@ weavec-cc: note: a program has one definition of each name: put a type only one ``` Put a type only one file uses in an unnamed namespace (C: give it a name of its own), and compile a header every unit includes with the same macros. `-fno-weavec-definitions` links without comparing, and says so; it is for bisecting a build. + +## foreign-call + +A safe function reaches code WeaveC did not compile only through a contract ([RFC 0057](/rfcs/0057-foreign-code-by-contract/)). Code is _foreign_ when no object, archive member or shared library of the link that `weavec-cc` compiled defines it: the C library, a system library, a unit built with `-fno-weavec` or by another compiler, assembly, another language's archive. A foreign function through which a pointer crosses (a pointer, function-pointer or array parameter or result, or a struct passed by value that holds one), and a foreign global that holds a pointer, needs one of: + +- a row of the library table, which WeaveC ships for the C library and the POSIX headers it covers (`fclose`, `memcpy`, `getenv`, `pthread_create` and about a thousand more need nothing from the program); +- a contract the program declares: the function's prototype again, marked `WEAVEC_FOREIGN`, with the annotations that say what the function does with what it is given; +- nothing, when no pointer crosses (`int helper(int)`). + +A unit that calls a function with none of these compiles, since another unit of the program may define it; its summary line counts the calls (`2 calls the link must find`). The link looks for the definition before the linker runs, and stops when code WeaveC did not compile, or no input at all, defines it: + +```text +main.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +main.c:10:24: note: called here, in 'main' +main.c:10:24: note: say what it does with what it is given: 'WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);'; or compile its library with weavec-cc; or call it from a function that is not safe +note: 'weavec-cc --weavec-explain foreign-call' explains this rule +``` + +There are three ways out, and no flag that turns the rule off: + +1. **Write the contract**, in a header of the program's own that includes the library's header (the language then checks the contract against the library's prototype), and include it where the function is called, or give it to every unit with `-fweavec-contracts=
`. +2. **Compile the library with `weavec-cc`.** Its functions are then guarded code, which safe code calls as it calls the program's own. +3. **Make the call from a function that is not safe** (`WEAVEC_GUARDED`). The call is not checked, and `weavec-cc --weavec-audit` lists it with the contract it lacks. + +The note proposes a contract from the prototype's names and types. It is a guess about code the compiler cannot see: read the library's documentation and correct it. It never proposes the two annotations that matter most, because nothing in a prototype shows them: who owns a handle, and what a result points into. + +**A contract says what the function does with each pointer.** The annotations mean what they mean on a function of the program: + +- _Access._ Through a pointer parameter the function reads, and writes unless the pointee is `const`, at most what the bound gives: `WEAVEC_COUNTED_BY(n)` elements, `WEAVEC_SIZED_BY(n)` bytes, up to `WEAVEC_ENDED_BY(end)`, the string of a `WEAVEC_NULL_TERMINATED`, and with no annotation one object of the pointee's type. A pointer to an incomplete type or to `void` with no bound is a _handle_: the function is given no bytes of the caller's through it. +- _Keeping._ The function keeps no pointer past its return unless the parameter is `WEAVEC_ESCAPES`. +- _Owning._ The function releases only what a `WEAVEC_OWNED` parameter gives it, and the caller owns only a `WEAVEC_OWNED` result, or what the function stores through a pointer to an owner (`struct stmt *WEAVEC_OWNED *out`). +- _Results._ A pointer result has the bound its declaration states, and points to memory that lives until the parameter it is bound to (`WEAVEC_LIFETIMEBOUND`, after the parameter's name) is changed, moved or released. + +With those, the rules of ownership and borrows hold for a library's handles as for the program's own blocks: a statement used after it is finalized is [`stale-borrow`](#stale-borrow), one never finalized is [`owner-leak`](#owner-leak), a second release is [`owner-moved`](#owner-moved). + +```c accepted +struct db; +struct stmt; +WEAVEC_FOREIGN int db_prepare(struct db *db, const char *WEAVEC_NULL_TERMINATED sql, + struct stmt *WEAVEC_OWNED *out); +WEAVEC_FOREIGN const char *WEAVEC_NULL_TERMINATED_OR_NULL +db_text(struct stmt *stmt WEAVEC_LIFETIMEBOUND, int column); +WEAVEC_FOREIGN int db_finalize(struct stmt *WEAVEC_OWNED stmt); + +int first(struct db *db) { + struct stmt *WEAVEC_OWNED stmt = NULL; + int result = -1; + if (db_prepare(db, "select name from t", &stmt) == 0 && stmt != NULL) { + const char *text = db_text(stmt, 0); + result = text != NULL ? text[0] : 0; + } + db_finalize(stmt); + return result; +} +``` + +**A count the function is given by reference.** Many C functions take a capacity through a pointer and store the length back. In a contract, and only there, a count may be `*p`, where `p` is a parameter that points to an integer: the count is what `p` points to when the call is made. + +```c accepted +WEAVEC_FOREIGN int pack(unsigned char *WEAVEC_COUNTED_BY(*out_len) out, unsigned long *out_len, + const unsigned char *WEAVEC_COUNTED_BY(in_len) in, unsigned long in_len); + +unsigned long packed(const unsigned char *WEAVEC_COUNTED_BY(n) in, unsigned long n) { + unsigned char out[64]; + unsigned long len = sizeof(out); + return pack(out, &len, in, n) == 0 ? len : 0; +} +``` + +**Members of the library's struct, and its globals.** `WEAVEC_FOREIGN_FIELD(type, member, annotations)`, at file scope, gives a member of a struct the program does not define the bound or the owner its declaration would carry; from there it is a member of typed memory ([`counted-pair`](#counted-pair)). A foreign global that holds a pointer is declared again with `WEAVEC_FOREIGN extern`. + +```c accepted +struct stream { const unsigned char *next_in; unsigned avail_in; unsigned char *next_out; unsigned avail_out; }; +WEAVEC_FOREIGN_FIELD(struct stream, next_in, WEAVEC_COUNTED_BY(avail_in)); +WEAVEC_FOREIGN_FIELD(struct stream, next_out, WEAVEC_COUNTED_BY(avail_out)); +WEAVEC_FOREIGN int stream_step(struct stream *s); +WEAVEC_FOREIGN extern const char *WEAVEC_NULL_TERMINATED lib_version; + +unsigned fill(struct stream *s) { + unsigned char out[256]; + s->next_out = out; + s->avail_out = sizeof(out); + int status = stream_step(s); + s->next_out = NULL; + s->avail_out = 0; + return status == 0 && lib_version[0] == '1' ? out[0] : 0; +} +``` + +**Callbacks.** A function-pointer parameter's type says the bounds of what the library passes; the function the program passes declares the same ([`call-args`](#call-args), with a fix that writes them), and the `void *` that travels with it is `WEAVEC_ESCAPES` when the library keeps it. + +```c accepted +struct loop; +struct app { int events; }; +typedef void (*on_data)(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n); +WEAVEC_FOREIGN void loop_listen(struct loop *loop, on_data callback, void *WEAVEC_ESCAPES user); + +void count(void *user, const char *WEAVEC_COUNTED_BY(n) data, size_t n) { + struct app *app = (struct app *)user; + if (n != 0 && data[n - 1] == '\n') + app->events++; +} +void listen(struct loop *loop, struct app *WEAVEC_ESCAPES app) { loop_listen(loop, count, app); } +``` + +**What the contract buys when the program runs.** Before the call, the bytes the contract lets the function use through each pointer are compared with the bound the caller holds, and a count past it stops at the call (`pointer-out-of-bounds`; in a guarded caller the guard's own kind), with a line that names the contract's declaration. A result arrives with the bound the contract declares, compared with the memory's record where WeaveC has one. A contract is trusted: nothing proves the library does no more than it says. The checked build (`-fweavec-safe-checks=full`) watches the bytes after each buffer the function may write and stops with `foreign-overflow` when the call returns and they have changed. `weavec-cc --weavec-audit` lists every contract with its callers; that list is what a review of the program reads. + +**A pointer through `...`** is the one case reported when the unit compiles. No contract can say what a variadic function does with a pointer it has no format for. A variadic call is accepted when the declaration has a `format` attribute (its arguments are checked as `printf`'s are) or when no variadic argument is or holds a pointer. (In C, the same call of a function the program's own header declares with no contract is [`variadic`](#variadic)'s error: it may be another unit's function.) + +```c rejected +struct device; +WEAVEC_FOREIGN int device_control(struct device *device, int request, ...); +int name(struct device *device, char *WEAVEC_COUNTED_BY(n) out, size_t n) { + return device_control(device, 7, out, n); +} +``` + +```c accepted +struct device; +WEAVEC_FOREIGN int device_control(struct device *device, int request, ...); +int mode(struct device *device, int flags) { return device_control(device, 3, flags); } +WEAVEC_GUARDED int name(struct device *device, char *WEAVEC_COUNTED_BY(n) out, size_t n) { + return device_control(device, 7, out, n); +} +``` + +A contract for a function or a global the library table has a row for, `WEAVEC_FOREIGN` on a definition or on a member function, and `*p` outside a contract are [`bad-annotation`](#bad-annotation). + +### In C++ + +An `extern "C"` function, and a function with C++ linkage that is not a member, is declared again with `WEAVEC_FOREIGN` as in C (in its namespace). A reference to a complete object type and a class whose kind the rules derive (an owner, a view, a value) need no contract: the type says its bound and its kind. A raw pointer crosses as in C, and a container's `data()` has the bound of its `size()`. + +```cpp accepted +extern "C" { +WEAVEC_FOREIGN int pack(unsigned char *WEAVEC_COUNTED_BY(*out_len) out, unsigned long *out_len, + const unsigned char *WEAVEC_COUNTED_BY(in_len) in, unsigned long in_len); +} +std::vector packed(const std::vector &in) { + std::vector out(in.size() + 16); + unsigned long len = out.size(); + if (pack(out.data(), &len, in.data(), in.size()) != 0) + len = 0; + out.resize(len); + return out; +} +``` + +Safe C++ has no `WEAVEC_OWNED` ([`raw-owner`](#raw-owner)): a C handle is owned by a `std::unique_ptr` whose deleter makes the releasing call, and the deleter, and the function that first takes the handle from the library, are `WEAVEC_GUARDED`. Everything else uses the owner, and a result bound to the handle is a borrow of it. + +```cpp accepted +struct stmt; +extern "C" { +WEAVEC_FOREIGN const char *WEAVEC_NULL_TERMINATED_OR_NULL db_text(stmt *statement WEAVEC_LIFETIMEBOUND, int column); +WEAVEC_FOREIGN int db_finalize(stmt *statement); +} +struct Finalize { + WEAVEC_GUARDED void operator()(stmt *statement) const { db_finalize(statement); } +}; +using Statement = std::unique_ptr; +std::string first(Statement &statement) { + const char *text = db_text(statement.get(), 0); + return text != nullptr ? std::string(text) : std::string(); +} +``` + +A member function of a foreign class cannot be declared again outside its class. Where a raw pointer crosses one, call it from a function that is not safe, or compile the class's library with `weavec-c++`. The C++ standard library is not foreign: what is trusted of it is the library table's class rows and [`safe-cxx`](#safe-cxx). + +```cpp rejected +struct device; +extern "C" int device_control(device *d, int request, ...); +int name(device *d, std::span out) { return device_control(d, 7, out.data(), out.size()); } +``` diff --git a/runtime/test/rt_test.c b/runtime/test/rt_test.c index f54f52f..8d29cc7 100644 --- a/runtime/test/rt_test.c +++ b/runtime/test/rt_test.c @@ -2900,6 +2900,187 @@ static void testBoundReports(void) { "released\n") != NULL); } +/*===-- RFC 0057: the monitor of foreign calls -----------------------------===*/ + +static char *volatile watchedBlock; +static char watchedFunction[] = "lib_fill"; +/* What a foreign function does between the two calls: writes `past` bytes + * after the `bytes` its contract gives argument 1. */ +static void foreignCall(char *block, uint64_t bytes, unsigned past) { + volatile char *out = block; + unsigned i; + (void)__weavec_rt_foreign_before(block, bytes, &trapSite, watchedFunction, 1); + for (i = 0; i < past; ++i) + out[bytes + i] = 'y'; + __weavec_rt_foreign_after(block, 1, 1); +} +static void foreignWritesPast(void) { foreignCall(watchedBlock, 24, 1); } +static void foreignWritesFar(void) { foreignCall(watchedBlock, 32, 3); } +static void foreignNestedPast(void) { + /* The callee called back, and the code it reached made a call of its + * own that kept its contract; the outer one did not. */ + volatile char *out = watchedBlock; + char *inner = (char *)opaque(malloc(40)); + (void)__weavec_rt_foreign_before(watchedBlock, 24, &trapSite, watchedFunction, 1); + foreignCall(inner, 40, 0); + out[24] = 'y'; + __weavec_rt_foreign_after(watchedBlock, 1, 1); +} +/* Nine calls that never came back (each left by a `longjmp`): the ninth + * finds the stack of watches full and empties it, putting back the bytes + * of the eight, and is watched itself. */ +static void foreignNine(char *blocks[9]) { + unsigned i; + for (i = 0; i < 9; ++i) { + blocks[i] = (char *)opaque(malloc(24)); + memset(blocks[i] + 24, 0, 8); + (void)__weavec_rt_foreign_before(blocks[i], 24, &trapSite, watchedFunction, 1); + } +} +static void foreignAfterFull(void) { + char *blocks[9]; + volatile char *out; + foreignNine(blocks); + out = blocks[8]; + out[24] = 'y'; + __weavec_rt_foreign_after(blocks[8], 1, 1); +} +static void foreignAfterStale(void) { + /* A call that never came back, and then the call under it returns: the + * stale watch is dropped with no report though its bytes changed (the + * memory may be another object's by then), and the bytes stay. */ + char *stale = (char *)opaque(malloc(24)); + volatile char *out = stale; + (void)__weavec_rt_foreign_before(watchedBlock, 24, &trapSite, watchedFunction, 1); + (void)__weavec_rt_foreign_before(stale, 24, &trapSite, watchedFunction, 2); + out[24] = 'y'; + __weavec_rt_foreign_after(watchedBlock, 1, 1); + if (out[24] != 'y') + abort(); + /* Nothing is left of either: an `after` with no watch does nothing. */ + __weavec_rt_foreign_after(stale, 2, 1); + free(stale); +} + +/* A callback grows the watched block in its slot while the call runs: the + * bytes `before` watched are the block's now, and its own. */ +static void foreignCallbackGrows(void) { + char *block = (char *)opaque(malloc(40)); + volatile char *out; + (void)__weavec_rt_foreign_before(block, 40, &trapSite, watchedFunction, 1); + if ((char *)realloc(block, 44) != block) + abort(); + out = block; + out[40] = 'z'; + __weavec_rt_foreign_after(block, 1, 1); + if (out[40] != 'z' || out[41] != 0) + abort(); + free(block); +} +/* A callback releases the watched block while the call runs. */ +static void foreignCallbackReleases(void) { + char *block = (char *)opaque(malloc(40)); + unsigned char saved[8]; + memcpy(saved, block + 40, sizeof saved); + (void)__weavec_rt_foreign_before(block, 40, &trapSite, watchedFunction, 1); + free(block); + __weavec_rt_foreign_after(block, 1, 1); + /* (The pattern is taken back out of the released slot.) */ + if (memcmp(saved, block + 40, sizeof saved) != 0) + abort(); +} + +static void testForeignWatchChanges(void) { + /* A watch of no bytes stays in its slot: the slot after a `malloc(0)` + * block, whose shadow is a tail too when it was never handed out, is not + * touched. */ + char *empty = (char *)opaque(malloc(0)); + const uintptr_t end = weavecRtHeapSlotEnd((uintptr_t)empty); + unsigned char next[32]; + CHECK(end > (uintptr_t)empty); + memcpy(next, (const void *)end, sizeof next); + (void)__weavec_rt_foreign_before(empty, 0, &trapSite, watchedFunction, 1); + CHECK(memcmp(next, (const void *)end, sizeof next) == 0); + __weavec_rt_foreign_after(empty, 1, 1); + CHECK(memcmp(next, (const void *)end, sizeof next) == 0); + free(empty); + /* Bytes that stopped being a redzone during the call are not compared: + * no report, and the program's bytes stay. */ + CHECK(!stopsIn(foreignCallbackGrows)); + CHECK(!stopsIn(foreignCallbackReleases)); +} + +static void testForeignWatch(void) { + /* A call that keeps its contract leaves the bytes after the block, and + * the block's shadow, as they were; one that writes the byte after what + * the contract gives stops when it returns, at the call. */ + char text[4096]; + unsigned char before[8]; + char *block = (char *)opaque(malloc(24)); + watchedBlock = block; + memcpy(before, block + 24, sizeof before); + CHECK(weavecRtShadowBytes(shadowAt(block + 16)) == 8); + foreignCall(block, 24, 0); + CHECK(memcmp(before, block + 24, sizeof before) == 0); + CHECK(weavecRtShadowBytes(shadowAt(block + 16)) == 8); + CHECK(shadowAt(block + 32) == WeavecRtShadowHeapTail); + CHECK(trapsIn(foreignWritesPast)); + outputOf(foreignWritesPast, text, sizeof text); + CHECK(strstr(text, "weavec: foreign-overflow at rt_test.c:1:2: 'lib_fill' " + "wrote past the 24 bytes its contract gives argument 1, " + "at 0x") == text); + CHECK(strstr(text, " is 0 bytes after the 24-byte heap object at 0x") != + NULL); + CHECK(strstr(text, "weavec: the contract is a row of the library table\n") != + NULL); + CHECK(strstr(text, "weavec: summary: foreign-overflow at rt_test.c:1:2") != + NULL); + free(block); + /* A block that ends on a granule: the redzone that follows is watched. */ + block = (char *)opaque(malloc(32)); + watchedBlock = block; + foreignCall(block, 32, 0); + CHECK(trapsIn(foreignWritesFar)); + /* A count that ends inside the object watches nothing: the bytes after + * it are the program's, and a write to them is no report. */ + foreignCall(block, 8, 4); + CHECK(block[8] == 'y' && block[11] == 'y'); + /* Nothing to watch: a null pointer, memory with no shadow record. */ + (void)__weavec_rt_foreign_before(NULL, 8, &trapSite, watchedFunction, 1); + __weavec_rt_foreign_after(NULL, 1, 1); + free(block); +} + +static void testForeignWatchNested(void) { + char *block = (char *)opaque(malloc(24)); + watchedBlock = block; + char *blocks[9]; + unsigned char zeros[8] = {0}; + unsigned i; + CHECK(trapsIn(foreignNestedPast)); + CHECK(trapsIn(foreignAfterFull)); + CHECK(!trapsIn(foreignAfterStale)); + foreignNine(blocks); + for (i = 0; i < 8; ++i) + CHECK(memcmp(blocks[i] + 24, zeros, sizeof zeros) == 0); + CHECK(memcmp(blocks[8] + 24, zeros, sizeof zeros) != 0); + __weavec_rt_foreign_after(blocks[8], 1, 1); + CHECK(memcmp(blocks[8] + 24, zeros, sizeof zeros) == 0); + __weavec_rt_foreign_after(blocks[0], 1, 1); + for (i = 0; i < 9; ++i) + free(blocks[i]); + /* The same pointer watched twice, as when a call is inlined into a + * watched one: each `after` takes the newest. */ + memset(block + 24, 0, 8); + (void)__weavec_rt_foreign_before(block, 24, &trapSite, watchedFunction, 1); + (void)__weavec_rt_foreign_before(block, 24, &trapSite, watchedFunction, 1); + __weavec_rt_foreign_after(block, 1, 1); + CHECK((unsigned char)block[24] == 0xA5); + __weavec_rt_foreign_after(block, 1, 1); + CHECK(memcmp(block + 24, zeros, sizeof zeros) == 0); + free(block); +} + static const struct { const char *name; void (*run)(void); @@ -2983,6 +3164,9 @@ static const struct { {"bound-shared-frames", testBoundSharedFrames}, {"bound-empty-element", testBoundEmptyElement}, {"bound-reports", testBoundReports}, + {"foreign-watch", testForeignWatch}, + {"foreign-watch-nested", testForeignWatchNested}, + {"foreign-watch-changes", testForeignWatchChanges}, }; int main(int argc, char **argv) { diff --git a/runtime/weavec_alloc.c b/runtime/weavec_alloc.c index d004ba4..433f34b 100644 --- a/runtime/weavec_alloc.c +++ b/runtime/weavec_alloc.c @@ -3001,6 +3001,14 @@ int weavecRtInLiveBlock(uintptr_t address) { address - ref.base <= weavecRtLiveSize(word); } +uintptr_t weavecRtHeapSlotEnd(uintptr_t address) { + if (inArena(address)) { + const SlotRef ref = slotOf(address); + return ref.base + __weavec_rt_heap.table[ref.region].size; + } + return 0; +} + struct weavecRtHeapObject weavecRtHeapObjectAt(uintptr_t address) { struct weavecRtHeapObject object = {0, 0, 0, 0, 0, 0, 0, 0}; if (inArena(address)) { diff --git a/runtime/weavec_guard.c b/runtime/weavec_guard.c index 2dcdd0b..9192013 100644 --- a/runtime/weavec_guard.c +++ b/runtime/weavec_guard.c @@ -942,6 +942,195 @@ __weavec_rt_found_fail(uintptr_t address, uint64_t width, uintptr_t lo, weavecRtFailFound(address, width, lo, hi, site, question); } +/*===-- The monitor of foreign calls (RFC 0057 section 8) -------------------===*/ + +/* A contract is what nothing checks: the checked build tests the bytes + * that follow what a foreign function may write. The watches of a thread + * are a short stack, since a foreign function may call back into code that + * calls another: `before` pushes one for every call (an empty one when the + * bytes have no redzone after them) and `after` takes the newest of its + * pointer and argument, which is the top unless a call above it never came + * back (a `longjmp` or an exception out of it). The site is no part of the + * name: the compiler makes a call's site again after inlining, and joins + * the `after` calls of two paths. A watch a call never came back to is + * dropped without a report; its bytes are put back only if they are still + * the pattern in a redzone (the memory may be another object's by then). A + * full stack is emptied the same way before the next watch. */ +enum { ForeignWatches = 8, ForeignBytes = 32 }; + +struct ForeignWatch { + uintptr_t pointer; + /* The first byte after the bytes the contract gives. */ + uintptr_t end; + uint64_t bytes; + const struct __weavec_rt_site *site; + const char *function; + uint32_t argument; + /* The redzone bytes watched, and whether they hold the pattern (a + * global's are only remembered: its memory may be read-only). */ + uint8_t count; + uint8_t patterned; + unsigned char saved[ForeignBytes]; +}; + +/* (One thread-local object: a call finds its thread's state once.) */ +struct ForeignState { + unsigned depth; + struct ForeignWatch watch[ForeignWatches]; +}; +static __thread struct ForeignState foreignState; + +/* The pattern: byte i is 0xA5 ^ (i * 29). */ +static const unsigned char foreignPattern[ForeignBytes] = { + 0xA5, 0xB8, 0x9F, 0xF2, 0xD1, 0x34, 0x0B, 0x6E, 0x4D, 0xA0, 0x87, + 0x9A, 0xF9, 0xDC, 0x33, 0x16, 0x75, 0x48, 0xAF, 0x82, 0xE1, 0xC4, + 0xDB, 0x3E, 0x1D, 0x70, 0x57, 0xAA, 0x89, 0xEC, 0xC3, 0x26}; + +/* The bytes from `end` that belong to no object and are the runtime's: the + * rest of the granule an object ends in, and the redzone that follows (a + * heap slot's tail, a frame's, a global's); 0 when `end` is not where an + * object ends. `*writable`: a heap's or a frame's. */ +static unsigned foreignRedzone(uintptr_t end, uint64_t bytes, int *writable) { + const unsigned offset = (unsigned)(end & 15U); + unsigned count = 0; + uintptr_t slot; + uintptr_t at; + *writable = 1; + if (!weavecRtShadowReady() || !weavecRtInWindow(end) || end < 16) + return 0; + if (offset != 0) { + const unsigned char last = *weavecRtShadowOf(end); + if (weavecRtShadowFull(last) || weavecRtShadowPoison(last) || + weavecRtShadowBytes(last) != offset) + return 0; + count = 16 - offset; + } else if (bytes != 0 && !weavecRtShadowFull(*weavecRtShadowOf(end - 1))) { + return 0; + } + for (at = end + count; count < ForeignBytes; at += 16) { + const unsigned char next = *weavecRtShadowOf(at); + if (next == WeavecRtShadowGlobal) + *writable = 0; + else if (next != WeavecRtShadowHeapTail && next != WeavecRtShadowStackMid && + next != WeavecRtShadowStackRight && + next != WeavecRtShadowStackDynamic) + break; + count += 16; + } + if (count == 0) + return 0; + /* A slot of the arena ends where the next begins, and a slot not handed + * out yet has a tail's shadow: the bytes past this one's end are not + * its redzone (another thread may allocate them while the call runs). + * With no bytes the slot is `end`'s own: a pointer into an object (or + * past its last byte, which is never its slot's last) lies in its slot, + * and so does a `malloc(0)` block's. */ + slot = weavecRtHeapSlotEnd(bytes != 0 ? end - 1 : end); + if (slot != 0) { + if (end + count > slot) + count = slot > end ? (unsigned)(slot - end) : 0; + return count > ForeignBytes ? ForeignBytes : count; + } + /* (The granule's rest alone says nothing of whose it is: a global's + * padding may be read-only.) */ + if (count != 0 && count < 16 && weavecRtHeapObjectAt(end - 1).found == 0) + *writable = 0; + return count > ForeignBytes ? ForeignBytes : count; +} + +/* The first byte of the watch that is not what `before` left, or 0. */ +static uintptr_t foreignChanged(const struct ForeignWatch *watch) { + const unsigned char *at = (const unsigned char *)watch->end; + const unsigned char *left = watch->patterned ? foreignPattern : watch->saved; + unsigned i; + if (memcmp(at, left, watch->count) == 0) + return 0; + for (i = 0; at[i] == left[i]; ++i) + ; + return watch->end + i; +} + +/* Drops the watches from `depth` up, which belong to calls that did not + * return to their `after`. */ +static __attribute__((noinline)) void foreignDrop(struct ForeignState *state, + unsigned depth) { + while (state->depth > depth) { + const struct ForeignWatch *watch = &state->watch[--state->depth]; + int writable = 0; + if (watch->count != 0 && watch->patterned && + foreignRedzone(watch->end, watch->bytes, &writable) >= watch->count && + writable && foreignChanged(watch) == 0) + memcpy((void *)watch->end, watch->saved, watch->count); + } +} + +uint32_t __weavec_rt_foreign_before(const void *pointer, uint64_t bytes, + const struct __weavec_rt_site *site, + const char *function, uint32_t argument) { + struct ForeignState *state = &foreignState; + const uintptr_t end = (uintptr_t)pointer + (uintptr_t)bytes; + struct ForeignWatch *watch; + int writable = 0; + unsigned count; + if (state->depth >= ForeignWatches) + foreignDrop(state, 0); + count = pointer == NULL || end < (uintptr_t)pointer + ? 0 + : foreignRedzone(end, bytes, &writable); + watch = &state->watch[state->depth++]; + watch->pointer = (uintptr_t)pointer; + watch->argument = argument; + watch->count = (uint8_t)count; + if (count == 0) + return 1; + watch->end = end; + watch->bytes = bytes; + watch->site = site; + watch->function = function; + watch->patterned = (uint8_t)writable; + memcpy(watch->saved, (const void *)end, count); + if (writable) + memcpy((void *)end, foreignPattern, count); + return 1; +} + +void __weavec_rt_foreign_after(const void *pointer, uint32_t argument, + uint32_t watched) { + struct ForeignState *state; + unsigned depth; + const struct ForeignWatch *watch; + uintptr_t changed; + int writable = 0; + int still; + if (watched == 0) + return; + state = &foreignState; + depth = state->depth; + /* The call's watch: the newest of this argument. */ + while (depth != 0 && (state->watch[depth - 1].pointer != (uintptr_t)pointer || + state->watch[depth - 1].argument != argument)) + --depth; + if (depth == 0) + return; + if (depth != state->depth) + foreignDrop(state, depth); + watch = &state->watch[--state->depth]; + if (watch->count == 0) + return; + changed = foreignChanged(watch); + /* Code the call ran may have changed whose the bytes are (a callback + * that grew the block in its slot with `realloc`, or released it): they + * are compared only while they are still the redzone `before` watched, + * and put back only then or while they still hold the pattern. */ + still = foreignRedzone(watch->end, watch->bytes, &writable) >= watch->count && + writable == watch->patterned; + if (watch->patterned && (still || changed == 0)) + memcpy((void *)watch->end, watch->saved, watch->count); + if (still && changed != 0) + weavecRtFailForeign(watch->function, watch->bytes, watch->argument, + changed, watch->site); +} + WEAVEC_RT_SLOW void __weavec_rt_convert_fail(uintptr_t address, uint64_t width, uintptr_t lo, uintptr_t hi, const struct __weavec_rt_site *site) { diff --git a/runtime/weavec_report.c b/runtime/weavec_report.c index 4207042..0b96291 100644 --- a/runtime/weavec_report.c +++ b/runtime/weavec_report.c @@ -293,6 +293,12 @@ static struct Report { uintptr_t foundHi; const char *foundDeclaration; const char *message; + /* RFC 0057: the place the contract of the call at the site is declared + * at (a second record after the site's), and whether the report is of a + * contract at all (`foreign-overflow`, whose contract may be a row of + * the library table). */ + const struct __weavec_rt_site *contract; + int foreign; struct Stack stack; /* The object paragraphs. */ int memory; @@ -849,6 +855,18 @@ static void writeText(struct Line *line) { } else if (report.memory == StackMemory) { putFrameLocals(line); } + /* RFC 0057: what the callee was promised to do, and where. */ + if (report.contract != NULL) { + const char *file = weavecRtSiteFile(report.contract); + put(line, "weavec: the contract is declared at "); + put(line, file != NULL ? file : ""); + putNumber(line, ":", report.contract->line); + if (report.contract->column != 0) + putNumber(line, ":", report.contract->column); + put(line, "\n"); + } else if (report.foreign) { + put(line, "weavec: the contract is a row of the library table\n"); + } put(line, "weavec: summary: "); put(line, report.kind); put(line, " at "); @@ -899,6 +917,16 @@ static void writeJson(struct Line *line) { putJson(line, report.foundDeclaration); put(line, "}"); } + /* RFC 0057: the contract of the call at the site. */ + if (report.contract != NULL) { + put(line, ",\"contract\":{\"file\":"); + putJson(line, weavecRtSiteFile(report.contract)); + putNumber(line, ",\"line\":", report.contract->line); + putNumber(line, ",\"column\":", report.contract->column); + put(line, "}"); + } else if (report.foreign) { + put(line, ",\"contract\":\"table\""); + } if (report.memory == HeapMemory) { putJsonHex(line, ",\"object\":{\"memory\":\"heap\",\"base\":", report.heap.base); putNumber(line, ",\"size\":", report.heap.size); @@ -983,6 +1011,8 @@ static int begin(const char *kind, const struct __weavec_rt_site *site) { report.file = weavecRtSiteFile(site); report.line = site->line; report.column = site->column; + if ((site->flags & WeavecRtSiteContract) != 0) + report.contract = site + 1; } return 1; } @@ -1267,6 +1297,38 @@ void weavecRtFailFound(uintptr_t address, uint64_t width, uintptr_t lo, stop(site); } +/* RFC 0057 section 8: a foreign function wrote past what its contract + * gives an argument; the paragraph is the object the bytes are in. */ +void weavecRtFailForeign(const char *function, uint64_t bytes, + uint32_t argument, uintptr_t address, + const struct __weavec_rt_site *site) { + static const char kind[] = "foreign-overflow"; + if (reportsOnce(site) && seenSite(kind, site)) + return; + if (begin(kind, site)) { + struct Line line = {report.what, report.what + sizeof report.what - 1}; + report.foreign = 1; + report.address = address; + report.width = bytes; + report.op = "write"; + put(&line, "'"); + putFunction(&line, function != NULL ? function : "?"); + put(&line, "' wrote past the "); + putUnsigned(&line, bytes, 10); + put(&line, bytes == 1 ? " byte" : " bytes"); + put(&line, " its contract gives argument "); + putUnsigned(&line, argument, 10); + put(&line, ", at "); + putHex(&line, address); + *line.at = 0; + captureAccess(); + if (!describeHeap(address) && !describeGlobal(address)) + (void)describeFrame(address); + finish(); + } + stop(site); +} + /* RFC 0037 section 8.3: a color mismatch names the root the access was * computed from, and the object the access landed in. */ void weavecRtFailJump(const char *kind, uintptr_t address, uint64_t width, diff --git a/runtime/weavec_rt.exports b/runtime/weavec_rt.exports index fef85fa..27da383 100644 --- a/runtime/weavec_rt.exports +++ b/runtime/weavec_rt.exports @@ -36,6 +36,8 @@ __weavec_rt_escape_check __weavec_rt_extents_register __weavec_rt_extents_unregister __weavec_rt_fast_program +__weavec_rt_foreign_after +__weavec_rt_foreign_before __weavec_rt_found_fail __weavec_rt_fprintf __weavec_rt_frame_escape diff --git a/runtime/weavec_rt.h b/runtime/weavec_rt.h index c8b5cbb..0bdfa98 100644 --- a/runtime/weavec_rt.h +++ b/runtime/weavec_rt.h @@ -476,6 +476,9 @@ struct weavecRtHeapObject { uint32_t type; }; struct weavecRtHeapObject weavecRtHeapObjectAt(uintptr_t address); +/* The end of the arena slot `address` lies in (the bytes after it are + * another slot's, whatever their shadow says), or 0 outside the arena. */ +uintptr_t weavecRtHeapSlotEnd(uintptr_t address); /* RFC 0054 section 1: the block's type (index + 1 in the table of types), * set once an allocation or a conversion gives it one. */ void weavecRtSetBlockType(uintptr_t base, uint32_t type); @@ -509,7 +512,11 @@ enum { WeavecRtSiteBelieved = 32, /* RFC 0056 section 5: a found bound's conversion to a declared one * (`bounds-conversion`). */ - WeavecRtSiteConvert = 64 + WeavecRtSiteConvert = 64, + /* RFC 0057 section 5.1: the site is a call of a function with a declared + * contract, and a second record follows it: the place the contract is + * declared at, which a report at the site names. */ + WeavecRtSiteContract = 128 }; /* RFC 0037 section 11: the file name lies `file` bytes from the record (0: * none), so that the records and the names are read-only data without a @@ -533,7 +540,8 @@ static inline void weavecRtSiteSet(struct __weavec_rt_site *site, site->file = file != NULL ? (int64_t)((intptr_t)file - (intptr_t)site) : 0; site->line = line; site->column = (unsigned short)(column > 0xFFFF ? 0xFFFF : column); - site->flags = (unsigned short)flags; + /* (A copy is one record: the contract's place does not follow it.) */ + site->flags = (unsigned short)(flags & ~(unsigned)WeavecRtSiteContract); } /* The slow path of an inline guard of `width` bytes at `address`: returns @@ -966,6 +974,33 @@ WEAVEC_RT_API WEAVEC_RT_SLOW void __weavec_rt_found_fail(uintptr_t address, uint64_t width, uintptr_t lo, uintptr_t hi, const struct __weavec_rt_site *site, const struct __weavec_rt_question *question); +/* RFC 0057 section 8, the monitor of a checked build: around a call of a + * function WeaveC did not compile, for each argument its contract (or row) + * lets it write `bytes` bytes through. `before` looks at what follows the + * bytes: where they end at their object's end (a heap block's, a guarded + * frame's local's, a global's), the redzone after it, which is the + * runtime's own memory, gets a pattern in its first bytes (at most 32; a + * global's is only remembered). `after`, given the same pointer and + * argument, compares them: a changed byte is `foreign-overflow`, a report + * at the call's `site` that names `function` and the argument (`argument`, + * from 1), made only while the bytes are still the redzone `before` + * watched (a callback may grow or release the block during the call). + * Bytes that end inside their object, memory with no redzone and a fast + * unit's plain frames are not monitored. `before` answers 1, and + * `after` does nothing when its `watched` is 0: compiled code calls + * `before` only where the byte after the bytes is in no whole granule of + * an object, and gives `after` its answer, or 0 where it made no call. */ +WEAVEC_RT_API uint32_t +__weavec_rt_foreign_before(const void *pointer, uint64_t bytes, + const struct __weavec_rt_site *site, + const char *function, uint32_t argument); +WEAVEC_RT_API void __weavec_rt_foreign_after(const void *pointer, + uint32_t argument, + uint32_t watched); +/* The report (weavec_report.c): the first byte changed is at `address`. */ +void weavecRtFailForeign(const char *function, uint64_t bytes, + uint32_t argument, uintptr_t address, + const struct __weavec_rt_site *site); /* Section 3.1: the objects a unit defines that have no redzone (a string * literal, a constant the linker may merge, a global with a section): each * record is the object's address as an offset from the record, and its @@ -1114,7 +1149,7 @@ void weavecRtSymbolize(const uintptr_t *pcs, unsigned count, /* The library's interface version (libweavec_rt.so., * libweavec_rt..dylib), raised whenever an entry point, the shadow * encoding or a site record changes. */ -#define WEAVEC_RT_ABI 52 +#define WEAVEC_RT_ABI 53 /*===-- Internal -----------------------------------------------------------===*/ diff --git a/scripts/check-hygiene.py b/scripts/check-hygiene.py index 5eebcb3..34021ef 100755 --- a/scripts/check-hygiene.py +++ b/scripts/check-hygiene.py @@ -42,6 +42,11 @@ WEAVEC_RT_REPLACEABLE, WEAVEC_RT_WEAK or WEAVEC_ASAN_API: a name on one side only is a violation, and so is a missing list when such declarations exist. + table-row the table has a row for every function, and a global row + for every global, through which a pointer crosses that + ISO C's and POSIX's headers declare on this platform (RFC + 0057 section 4.3): what scripts/check-table.py lists. + Skipped where no compiler can read the headers. It also counts the lines of the library (lib/, include/ and tools/, without lib/Core/LibrarySpec.txt, a declarative table) and of the C runtime @@ -123,6 +128,7 @@ RUNTIME_PREFIX = "__weavec_rt_" # runtime-export (RFC 0038, section 1) RUNTIME_EXPORTS = "runtime/weavec_rt.exports" +TABLE_CHECK = "scripts/check-table.py" EXPORT_MACROS = ("WEAVEC_RT_API", "WEAVEC_RT_WEAK", "WEAVEC_ASAN_API", "WEAVEC_RT_REPLACEABLE") # Macros whose first argument names an exported definition (RFC 0039 §4: # the C++ allocation functions of weavec_cxx.c). @@ -141,6 +147,7 @@ ("runtime-include", "a WeaveC header other than weavec_rt.h included by runtime/"), ("runtime-entry", "a runtime entry point the passes name that runtime/weavec_rt.h does not declare"), ("runtime-export", "runtime/weavec_rt.exports and the runtime's WEAVEC_RT_API declarations differ"), + ("table-row", "a function or global of the platform's C headers through which a pointer crosses, with no row"), ) # --------------------------------------------------------------------------- @@ -706,8 +713,31 @@ def count_runtime_lines(tree: Tree, result: Result) -> None: result.runtime_code += file.code_lines +def check_table_rows(tree: Tree, result: Result) -> None: + """RFC 0057 section 4.3: scripts/check-table.py over the platform's + headers. A tree without the script or the table, or a machine without a + compiler to read the headers, has nothing to compare.""" + script = tree.root / TABLE_CHECK + if not script.is_file() or not (tree.root / LIBRARY_SPEC).is_file(): + return + try: + ran = subprocess.run([sys.executable, str(script), "--if-available", "--table", + str(tree.root / LIBRARY_SPEC)], + capture_output=True, text=True, check=False, timeout=600) + except (OSError, subprocess.TimeoutExpired) as error: + result.add("table-row", TABLE_CHECK, None, f"could not run: {error}") + return + for line in ran.stdout.splitlines(): + if line.startswith(("check-table: no row: ", "check-table: no global row: ")): + result.add("table-row", LIBRARY_SPEC, None, line.removeprefix("check-table: ")) + if ran.returncode != 0 and result.count("table-row") == 0: + result.add("table-row", TABLE_CHECK, None, + (ran.stderr.strip() or ran.stdout.strip() or "failed").splitlines()[-1]) + + CHECK_FUNCTIONS = (check_library_name_tests, check_corpus_words, check_core_includes, check_runtime_includes, - check_runtime_entries, check_runtime_exports, count_library_lines, count_runtime_lines) + check_runtime_entries, check_runtime_exports, check_table_rows, count_library_lines, + count_runtime_lines) # --------------------------------------------------------------------------- diff --git a/scripts/check-table.py b/scripts/check-table.py new file mode 100755 index 0000000..f731517 --- /dev/null +++ b/scripts/check-table.py @@ -0,0 +1,500 @@ +#!/usr/bin/env python3 +# Part of WeaveC, under the Apache License v2.0 with LLVM Exceptions. +# See LICENSE for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Compares the library table with the platform's headers (RFC 0057 §4.3). + +Safe code calls a function no code WeaveC compiled defines only where a +contract says what crosses: for the C library that contract is a row of +`lib/Core/LibrarySpec.txt`. This script reads the declarations of ISO C's +headers, and of the POSIX headers the table covers, as the platform's +compiler sees them, and lists every function through which a pointer +crosses (a parameter or a result that is, or holds, a pointer) that the +table has no row for, and every such global it has no `global` row for. + + scripts/check-table.py [--cc CLANG] [--table FILE] [--list] [--propose] + +`--list` prints what is covered too, by header; `--propose` prints a row +for each function with none, for a person to review (a pointer to an +incomplete type or to `void` is a handle, a `const char *` a string, any +other pointer is read or written at its first byte). The exit status is 1 +when a function or a global has no row. + +Names the table leaves out on purpose are in `ABSENT` below, each with its +reason. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + +# ISO C (C23 §7), then the POSIX headers the table has rows for. +HEADERS = [ + "assert.h", + "complex.h", + "ctype.h", + "errno.h", + "fenv.h", + "inttypes.h", + "locale.h", + "math.h", + "setjmp.h", + "signal.h", + "stdarg.h", + "stdio.h", + "stdlib.h", + "string.h", + "time.h", + "uchar.h", + "wchar.h", + "wctype.h", + "threads.h", + "strings.h", + "unistd.h", + "fcntl.h", + "sys/stat.h", + "dirent.h", + "sys/mman.h", + "dlfcn.h", + "libgen.h", + "pthread.h", + "sys/socket.h", + "netdb.h", + "arpa/inet.h", + "netinet/in.h", + "sys/time.h", + "sys/select.h", + "sys/uio.h", + "sys/wait.h", + "sys/resource.h", + "sys/utsname.h", + "poll.h", + "pwd.h", + "grp.h", + "termios.h", + "sys/ioctl.h", + "getopt.h", + "langinfo.h", + "iconv.h", + "regex.h", + "glob.h", + "fnmatch.h", + "semaphore.h", + "sched.h", + "spawn.h", + "syslog.h", + "utime.h", + "wordexp.h", + "search.h", + "ftw.h", + "sys/file.h", + "sys/statvfs.h", + "sys/times.h", + "sys/un.h", + "net/if.h", + "ifaddrs.h", + "execinfo.h", + "malloc.h", + "malloc/malloc.h", + "alloca.h", + "err.h", + "sys/random.h", + "sys/epoll.h", + "sys/eventfd.h", + "sys/inotify.h", + "sys/sendfile.h", + "sys/event.h", + "sys/timerfd.h", + "sys/signalfd.h", +] + +# The view of the headers the check holds the table to: what ISO C and +# POSIX.1-2008 with XSI declare. `--extensions` reads the platform's own +# additions too (BSD's, GNU's), which have a row where a program was found +# to call them and a `foreign-call` proposal at the link otherwise. +STANDARD = ["-std=c23", "-D_POSIX_C_SOURCE=200809L", "-D_XOPEN_SOURCE=700"] +EXTENDED = ["-std=gnu23", "-D_GNU_SOURCE", "-D_DARWIN_C_SOURCE"] + +# Headers the listed ones include that are not theirs: the kernel's and the +# linker's interfaces, which no row covers. +OUTSIDE = ("/uuid/", "/mach/", "/mach-o/", "/libkern/", "/os/", "/bsm/") + +# Deliberately absent (RFC 0057 §3.6): no row can say what the pointer a +# call passes through `...` is, or what the memory an integer names is. +ABSENT = { + "ioctl": "its third argument is whatever the request says", + "syscall": "its arguments are whatever the call number says", + "__syscall": "its arguments are whatever the call number says", + "prctl": "its arguments are whatever the option says", + "sysctl": "its buffers are whatever the name says", + "sysctlbyname": "its buffers are whatever the name says", + "va_start": "the compiler's", + "va_end": "the compiler's", + "va_copy": "the compiler's", + "va_arg": "the compiler's", + "alloca": "the compiler's", +} + + +def compiler(given: str | None) -> str | None: + """The compiler whose view of the headers is read: a plain Clang, so + that the answer does not depend on what a build of WeaveC adds.""" + if given: + return given + prefix = os.environ.get("WEAVEC_LLVM_PREFIX") + if prefix and (Path(prefix) / "bin" / "clang").exists(): + return str(Path(prefix) / "bin" / "clang") + found = shutil.which("clang") + if found: + return found + built = ROOT / "build" / "dev" / "bin" / "weavec-cc" + return str(built) if built.exists() else None + + +def table_names(path: Path) -> tuple[set[str], set[str]]: + """The names with a row (their `chk` aliases too) and the globals.""" + text = path.read_text() + functions: set[str] = set() + globals_: set[str] = set() + logical = re.sub(r"\\\n", " ", text) + for line in logical.splitlines(): + line = line.split("#", 1)[0].strip() + if not line: + continue + match = re.match(r"global\s+([A-Za-z_][A-Za-z0-9_]*)\s*:", line) + if match: + globals_.add(match.group(1)) + continue + if line.startswith(("class ", "function ")): + continue + match = re.match(r"([A-Za-z_][A-Za-z0-9_]*)\s*\(", line) + if match: + functions.add(match.group(1)) + for alias in re.findall(r"chk\(([A-Za-z_][A-Za-z0-9_]*)\s*:", line): + functions.add(alias) + return functions, globals_ + + +class Declarations: + """The functions and globals a set of headers declares.""" + + def __init__(self) -> None: + self.file = "" + self.typedefs: dict[str, str] = {} + self.records: dict[str, list[str]] = {} + # name -> (header, result, [(type, name)], variadic, has a body) + self.functions: dict[str, tuple[str, str, list[tuple[str, str]], bool, bool]] = {} + self.globals: dict[str, tuple[str, str]] = {} + self._memo: dict[str, bool] = {} + + def read(self, node: object, top: bool = True) -> None: + if isinstance(node, list): + for each in node: + self.read(each, top) + return + if not isinstance(node, dict): + return + kind = node.get("kind") + # Clang prints a location's file only where it changes. + for key in ("loc", "range"): + self._place(node.get(key)) + if kind == "TypedefDecl": + kind_type = node.get("type", {}) + self.typedefs[node.get("name", "")] = kind_type.get( + "desugaredQualType", kind_type.get("qualType", "") + ) + elif kind == "RecordDecl" and node.get("name") and "inner" in node: + self.records[node["tagUsed"] + " " + node["name"]] = self._fields(node) + elif kind == "FunctionDecl" and top and node.get("name"): + self._function(node) + elif kind == "VarDecl" and top and node.get("storageClass") == "extern": + self.globals.setdefault(node["name"], (self.file, self._type(node))) + for key, value in node.items(): + if key in ("loc", "range"): + continue + if key == "inner": + self.read(value, kind == "TranslationUnitDecl") + elif isinstance(value, (dict, list)): + self._places(value) + + def _places(self, node: object) -> None: + if isinstance(node, list): + for each in node: + self._places(each) + elif isinstance(node, dict): + self._place(node) + for value in node.values(): + if isinstance(value, (dict, list)): + self._places(value) + + def _place(self, at: object) -> None: + if not isinstance(at, dict): + return + if "file" in at: + self.file = at["file"] + for key in ("spellingLoc", "expansionLoc", "begin", "end"): + self._place(at.get(key)) + + def _fields(self, node: dict) -> list[str]: + """The types of a record's fields, an unnamed member's with them.""" + fields: list[str] = [] + for each in node.get("inner", []): + if each.get("kind") == "RecordDecl" and not each.get("name"): + fields += self._fields(each) + elif each.get("kind") == "FieldDecl": + text = self._type(each) + if "(unnamed" not in text and "(anonymous" not in text: + fields.append(text) + return fields + + @staticmethod + def _type(node: dict) -> str: + kind_type = node.get("type", {}) + return kind_type.get("qualType", "") + + def _function(self, node: dict) -> None: + text = self._type(node) + result = text.split("(", 1)[0].strip() + params = [ + (self._type(each), each.get("name", "")) + for each in node.get("inner", []) + if each.get("kind") == "ParmVarDecl" + ] + body = any( + each.get("kind") == "CompoundStmt" for each in node.get("inner", []) + ) + earlier = self.functions.get(node["name"]) + self.functions[node["name"]] = ( + earlier[0] if earlier else self.file, + result, + params, + bool(node.get("variadic")) or text.rstrip().endswith("...)"), + body or (earlier[4] if earlier else False), + ) + + def pointer(self, text: str, depth: int = 0) -> bool: + """Whether a value of the type is, or holds, a pointer.""" + # An array of what holds no pointer holds none (a parameter Clang + # prints is already a pointer). + text = re.sub(r"\[[^\]]*\]", "", text) + if "*" in text or "(" in text or "va_list" in text: + return True + if depth > 8: + return False + if text in self._memo: + return self._memo[text] + self._memo[text] = False + found = False + for tag in re.findall(r"\b(?:struct|union) [A-Za-z_][A-Za-z0-9_]*", text): + found = found or any( + self.pointer(field, depth + 1) for field in self.records.get(tag, []) + ) + for word in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", text): + if word in self.typedefs and self.typedefs[word] != text: + found = found or self.pointer(self.typedefs[word], depth + 1) + self._memo[text] = found + return found + + def handle(self, text: str) -> bool: + """A pointer to `void`, to a function or to a type with no fields.""" + pointee = text.rsplit("*", 1)[0].replace("const", "").strip() + if "*" in pointee: + return False + if pointee in ("void", "FILE", "DIR") or "(" in text: + return True + resolved = self.typedefs.get(pointee, pointee) + tag = re.search(r"\b(?:struct|union) [A-Za-z_][A-Za-z0-9_]*", resolved) + return bool(tag) and tag.group(0) not in self.records + + +COUNT = re.compile(r"^(n|len|length|size|count|nbytes|buflen|bufsize|siz|nitems|nel|nelem|nmemb|maxlen|max|namelen|nbyte|bufsiz|.*_len|.*len|.*size)$") + + +def propose(name: str, entry: tuple, declarations: Declarations) -> str: + """A row for a person to review.""" + _, result, params, variadic, _ = entry + parts = [] + for index, (text, _) in enumerate(params): + resolved = text + for _ in range(4): + word = resolved.replace("const", "").strip() + if word in declarations.typedefs: + resolved = declarations.typedefs[word] + if "(*" in resolved or "(^" in resolved: + parts.append("fn") + elif "*" in resolved or "[" in resolved: + const = "const" in resolved.rsplit("*", 1)[0] + neighbor = None + for near in (index + 1, index - 1): + if 0 <= near < len(params) and COUNT.match(params[near][1] or ""): + if not declarations.pointer(params[near][0]): + neighbor = near + break + if declarations.handle(resolved): + if neighbor is not None and "void" in resolved: + parts.append( + f"{'r' if const else 'w'}:bytes(a{neighbor})" + f":null-if-zero(a{neighbor})" + ) + else: + parts.append("handle") + elif const and re.search(r"\bchar\b", resolved) and resolved.count("*") == 1: + parts.append("r:str") + elif neighbor is not None and resolved.count("*") == 1 and re.search(r"\bchar\b", resolved): + parts.append( + f"{'r' if const else 'w'}:bytes(a{neighbor})" + f":null-if-zero(a{neighbor})" + ) + else: + parts.append("r" if const else "rw") + elif declarations.pointer(resolved): + parts.append("other") + elif re.search(r"\b(float|double)\b", resolved) or re.search( + r"\b(struct|union)\b", resolved + ): + parts.append("other") + else: + parts.append("int") + if variadic: + parts.append("...") + if result == "void": + out = "void" + elif declarations.pointer(result): + out = "ptr" + else: + out = "int" + return f"{name} ({', '.join(parts)}) -> {out};" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--cc", help="the compiler whose headers are read") + parser.add_argument( + "--table", default=str(ROOT / "lib" / "Core" / "LibrarySpec.txt") + ) + parser.add_argument("--list", action="store_true") + parser.add_argument("--propose", action="store_true") + parser.add_argument( + "--extensions", + action="store_true", + help="read the platform's own additions to the headers too", + ) + parser.add_argument("--if-available", action="store_true", + help="succeed when no compiler can read the headers") + args = parser.parse_args() + + cc = compiler(args.cc) + if cc is None: + if args.if_available: + print("check-table: no compiler; skipped") + return 0 + sys.exit("check-table: no compiler: pass --cc") + view = EXTENDED if args.extensions else STANDARD + rows, global_rows = table_names(Path(args.table)) + declarations = Declarations() + read = [] + with tempfile.TemporaryDirectory() as scratch: + probe = Path(scratch) / "probe.c" + # The headers the platform has. + for header in HEADERS: + probe.write_text(f"#include <{header}>\n") + if ( + subprocess.run( + [cc, "-fsyntax-only", "-w", *view, str(probe)], + capture_output=True, + check=False, + ).returncode + == 0 + ): + read.append(header) + probe.write_text( + "".join(f"#include <{header}>\n" for header in read) + ) + dump = subprocess.run( + [ + cc, + "-fsyntax-only", + "-w", + *view, + "-Xclang", + "-ast-dump=json", + str(probe), + ], + capture_output=True, + check=False, + ) + if dump.returncode != 0: + sys.stderr.write(dump.stderr.decode(errors="replace")) + sys.exit("check-table: the headers do not compile") + declarations.read(json.loads(dump.stdout)) + + missing = [] + covered = 0 + uncrossed = 0 + for name, entry in sorted(declarations.functions.items()): + header, result, params, variadic, body = entry + # A vector variant of a function takes and returns values. + if name in ABSENT or name.startswith(("__builtin_", "_ZGV")): + continue + if any(part in header for part in OUTSIDE): + continue + crosses = declarations.pointer(result) and result != "void" + crosses = crosses or any(declarations.pointer(text) for text, _ in params) + if not crosses: + uncrossed += 1 + continue + # An inline function of a header is compiled with the unit. + if body: + continue + if name in rows: + covered += 1 + if args.list: + print(f"row {name} ({header})") + continue + missing.append((name, entry)) + missing_globals = [] + for name, (header, text) in sorted(declarations.globals.items()): + if not declarations.pointer(text) or name in ABSENT: + continue + if any(part in header for part in OUTSIDE): + continue + if name in global_rows: + if args.list: + print(f"global {name} ({header})") + continue + missing_globals.append((name, header, text)) + + for name, entry in missing: + if args.propose: + print(f"{propose(name, entry, declarations)} # {entry[0]}") + else: + params = ", ".join(text for text, _ in entry[2]) + print( + f"check-table: no row: {entry[1]} {name}({params}" + f"{', ...' if entry[3] else ''}) ({entry[0]})" + ) + for name, header, text in missing_globals: + if args.propose: + print(f"global {name} : handle; # {text}, {header}") + else: + print(f"check-table: no global row: {text} {name} ({header})") + print( + f"check-table: {len(read)} headers, {covered} functions with a row, " + f"{uncrossed} through which nothing crosses, {len(missing)} with no " + f"row, {len(missing_globals)} globals with no row" + ) + return 1 if missing or missing_globals else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/corpus-gate.py b/scripts/corpus-gate.py index f9ca309..70bb109 100755 --- a/scripts/corpus-gate.py +++ b/scripts/corpus-gate.py @@ -118,7 +118,7 @@ INJECTIONS_VERSION = 2 # The enforcement ledger (RFC 0035, section 9). LEDGER_SCHEMA = "weavec-ledger" -LEDGER_VERSION = 16 +LEDGER_VERSION = 17 LEDGER_COUNTS = ("accesses", "proven", "guarded", "unguarded") # The per-file compiles: the optimization real builds use (a config's own # -O in compile.args comes later and wins). diff --git a/scripts/run-cases.py b/scripts/run-cases.py index 2b25796..8ce2a49 100755 --- a/scripts/run-cases.py +++ b/scripts/run-cases.py @@ -60,7 +60,7 @@ # --------------------------------------------------------------------------- # The `version` of the enforcement ledger this runner reads. -LEDGER_VERSION = 16 +LEDGER_VERSION = 17 # Run-time report kinds (runtime/weavec_report.c). KINDS = ( "heap-buffer-overflow", "heap-use-after-free", "stack-buffer-overflow", @@ -75,6 +75,8 @@ "stack-exhaustion", # RFC 0054: one of several types, checked where it is chosen. "bad-cast", "union-member", + # RFC 0057 section 6: a foreign function wrote past what its contract gives. + "foreign-overflow", ) LEDGER_REASONS = { "GUARDED": ("access", "range", "string", "checked-call", "loop-range", diff --git a/scripts/test_corpus_gate.py b/scripts/test_corpus_gate.py index 637e5a2..d4e5e18 100644 --- a/scripts/test_corpus_gate.py +++ b/scripts/test_corpus_gate.py @@ -41,7 +41,7 @@ def proc(returncode=0, stdout="", stderr="", timed_out=False, error=""): return gate.ProcResult("cmd", returncode, stdout, stderr, 0.1, timed_out=timed_out, error=error) -def ledger_document(*summaries, version=16, rows=()): +def ledger_document(*summaries, version=17, rows=()): return {"schema": "weavec-ledger", "version": version, "producer": {"name": "weavec-cc"}, "units": [{"source": "a.c", "object": "a.o", "summary": s, "rows": list(rows)} for s in summaries]} @@ -165,7 +165,7 @@ def test_invalid_ledgers(self): for data, message in ((ledger_document({"accesses": 1}, version=2), "version 2"), ({"schema": "other"}, "not a weavec-ledger"), (ledger_document(), "no units"), - ({"schema": "weavec-ledger", "version": 16, "units": [{}]}, "no summary")): + ({"schema": "weavec-ledger", "version": 17, "units": [{}]}, "no summary")): with self.assertRaisesRegex(ValueError, message): gate.read_ledger(self.write(directory, data)) with self.assertRaisesRegex(ValueError, "x.ledger.json"): @@ -825,7 +825,7 @@ def test_verify(self): summary = {"accesses": lines, "proven": proven, "guarded": lines - proven, "unguarded": 0} rows = [{"file": sources[0], "line": 1, "column": 1, "function": "f", "operation": "load", "bytes": 4, "outcome": "proven", "reason": "in-bounds"}] * proven - json.dump({"schema": "weavec-ledger", "version": 16, "units": [ + json.dump({"schema": "weavec-ledger", "version": 17, "units": [ {"source": sources[0], "object": out, "config": {"checks": checks}, "summary": summary, "rows": rows}]}, open(ledger, "w")) sys.exit(0) @@ -992,7 +992,7 @@ def test_a_tool_failure_is_not_recorded(self): (self.root / "bin" / "fake-weavec-cc").write_text(f"#!{sys.executable}\nimport sys; sys.exit(3)\n") status, output = self.run_gate("--quick", "--update") self.assertEqual(status, 2, output) # the probe sees it first - self.assertIn("does not write a weavec-ledger version 16 ledger", output) + self.assertIn("does not write a weavec-ledger version 17 ledger", output) self.assertFalse(self.expected.exists()) def test_a_failed_compile_is_not_recorded(self): diff --git a/scripts/test_run_cases.py b/scripts/test_run_cases.py index b443ccf..3b5d8fe 100755 --- a/scripts/test_run_cases.py +++ b/scripts/test_run_cases.py @@ -532,7 +532,7 @@ def test_a_proven_report_is_a_wrong_proof(self): class JudgeLedgerTest(Workspace): - def ledger(self, path, rows, version=16, summary=None): + def ledger(self, path, rows, version=17, summary=None): return {"schema": "weavec-ledger", "version": version, "units": [{ "source": str(path), "config": {"checks": "trap", "zeroInit": True}, "summary": summary or {"accesses": len(rows), "proven": 0, "guarded": len(rows), "unguarded": 0}, @@ -563,7 +563,7 @@ def test_missing_or_old_ledger(self): case = self.case("s/l.c", "int main(void) { return 0; } // GUARDED\n") self.assertEqual(self.judge(case, None), ["no enforcement ledger was written"]) self.assertEqual(self.judge(case, self.ledger(case.path, [], version=2)), - ["ledger version 2, expected 16"]) + ["ledger version 2, expected 17"]) plain = self.case("s/p.c", "int main(void) { return 0; } // TRAP\n") self.assertEqual(self.judge(plain, None), []) # no ledger marker, no ledger needed @@ -644,7 +644,7 @@ def test_clean_case_fails_on_a_stop_and_an_asan_report(self): def test_ledger_is_requested_only_when_read(self): case = self.case("s/l.c", "int main(void) { return 0; } // GUARDED\n") - self.ledger = {"version": 16, "units": [{"rows": [{"file": str(case.path), "line": 1, + self.ledger = {"version": 17, "units": [{"rows": [{"file": str(case.path), "line": 1, "outcome": "guarded", "reason": "access"}]}]} self.assertEqual(rc.run_case(case, self.config())["status"], "pass") self.assertEqual(self.builds, [("build", (), True)]) diff --git a/test/Driver/Inputs/foreign/contracts.h b/test/Driver/Inputs/foreign/contracts.h new file mode 100644 index 0000000..9bb46e1 --- /dev/null +++ b/test/Driver/Inputs/foreign/contracts.h @@ -0,0 +1,3 @@ +#include +WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n); +WEAVEC_FOREIGN int lib_sum(const int *WEAVEC_COUNTED_BY(count) values, int count); diff --git a/test/Driver/Inputs/foreign/helper.c b/test/Driver/Inputs/foreign/helper.c new file mode 100644 index 0000000..baccb9b --- /dev/null +++ b/test/Driver/Inputs/foreign/helper.c @@ -0,0 +1 @@ +int helper(int x) { return x + 1; } diff --git a/test/Driver/Inputs/foreign/lib.c b/test/Driver/Inputs/foreign/lib.c new file mode 100644 index 0000000..14c9f4b --- /dev/null +++ b/test/Driver/Inputs/foreign/lib.c @@ -0,0 +1,3 @@ +#include "lib.h" +int lib_fill(char *out, int n) { for (int i = 0; i < n; ++i) out[i] = 'x'; return n; } +int lib_sum(const int *values, int count) { int s = 0; for (int i = 0; i < count; ++i) s += values[i]; return s; } diff --git a/test/Driver/Inputs/foreign/lib.h b/test/Driver/Inputs/foreign/lib.h new file mode 100644 index 0000000..6a76382 --- /dev/null +++ b/test/Driver/Inputs/foreign/lib.h @@ -0,0 +1,2 @@ +int lib_fill(char *out, int n); +int lib_sum(const int *values, int count); diff --git a/test/Driver/Inputs/foreign/main.c b/test/Driver/Inputs/foreign/main.c new file mode 100644 index 0000000..d7d30d1 --- /dev/null +++ b/test/Driver/Inputs/foreign/main.c @@ -0,0 +1,12 @@ +#include +#include "lib.h" +#ifdef CONTRACTS +#include "contracts.h" +#endif +int helper(int x); +int main(void) { + char text[8]; + int values[3] = {1, 2, 3}; + printf("%d %d %d\n", lib_fill(text, 8), lib_sum(values, 3), helper(4)); + return 0; +} diff --git a/test/Driver/Inputs/foreign/names.c b/test/Driver/Inputs/foreign/names.c new file mode 100644 index 0000000..02d0b42 --- /dev/null +++ b/test/Driver/Inputs/foreign/names.c @@ -0,0 +1 @@ +const char *const lib_names[2] = {"one", "two"}; diff --git a/test/Driver/Inputs/foreign/through.c b/test/Driver/Inputs/foreign/through.c new file mode 100644 index 0000000..fb207c9 --- /dev/null +++ b/test/Driver/Inputs/foreign/through.c @@ -0,0 +1,2 @@ +#include "lib.h" +int through(char *out) { return lib_fill(out, 4); } diff --git a/test/Driver/Inputs/foreign/uses-names.c b/test/Driver/Inputs/foreign/uses-names.c new file mode 100644 index 0000000..a54d551 --- /dev/null +++ b/test/Driver/Inputs/foreign/uses-names.c @@ -0,0 +1,2 @@ +extern const char *const lib_names[2]; +const char *first(void) { return lib_names[0]; } diff --git a/test/Driver/contracts-flag.c b/test/Driver/contracts-flag.c new file mode 100644 index 0000000..06b38a5 --- /dev/null +++ b/test/Driver/contracts-flag.c @@ -0,0 +1,42 @@ +// RFC 0057 §3.1: -fweavec-contracts=
includes a header of +// contracts in every C and C++ unit, after the command line's own -include +// files, so a build system gives a program its contracts in one flag: the +// call below has none without it and its contract with it, which is +// compared at run time. The flag may be repeated, reaches each unit of a +// compile of several, leaves an assembly input alone, and a header that is +// not there is Clang's error. +// RUN: rm -rf %t && mkdir -p %t && cp %S/Inputs/foreign/* %t/ +// RUN: cd %t && %weavec_cc -O1 -fno-weavec -c lib.c -o lib.o +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -c %s -o plain.o +// RUN: cd %t && not %weavec_cc plain.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=OPEN +// OPEN: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -fweavec-contracts=contracts.h %s lib.o -o prog +// RUN: %t/prog 8 | FileCheck %s --check-prefix=OK +// RUN: not --crash %t/prog 9 2>&1 | FileCheck %s --check-prefix=PAST +// OK: 8 +// PAST: weavec: pointer-out-of-bounds at {{.*}}contracts-flag.c:40:18: write of 9 bytes +// PAST: weavec: the contract is declared at {{.*}}contracts.h:2:20 +// +// Twice, with -include, and for two units at once. +// RUN: cd %t && echo '#define FROM_SECOND 1' > second.h +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -include %S/Inputs/foreign/lib.h -fweavec-contracts=contracts.h -fweavec-contracts=second.h -DNEEDS_SECOND -c %s helper.c +// RUN: cd %t && %weavec_cc -E -fweavec-contracts=contracts.h %s | FileCheck %s --check-prefix=TEXT +// TEXT: __attribute__((annotate("weavec.foreign"))) int lib_fill(char *{{.*}}"weavec.counted_by", "n"{{.*}} out, int n); +// +// RUN: cd %t && %weavec_cc -fweavec-contracts=contracts.h -c %S/Inputs/empty.S -o empty.o +// RUN: cd %t && not %weavec_cc -fweavec-contracts=missing.h -c %s -o none.o 2>&1 | FileCheck %s --check-prefix=MISSING +// MISSING: fatal error: 'missing.h' file not found +#include +#include +#include "Inputs/foreign/lib.h" +#if defined(NEEDS_SECOND) && !defined(FROM_SECOND) +#error "the second contracts header was not included" +#endif + +int main(int argc, char **argv) { + char text[8]; + int n = argc > 1 ? atoi(argv[1]) : 0; + printf("%d\n", lib_fill(text, n)); + return 0; +} diff --git a/test/Driver/flags.c b/test/Driver/flags.c index ec3f7fb..1ba5957 100644 --- a/test/Driver/flags.c +++ b/test/Driver/flags.c @@ -38,6 +38,7 @@ // HELP: -fweavec-ledger= // HELP: -fweavec-asan-compat // HELP: -fweavec-colors +// HELP: -fweavec-contracts=
// HELP-NOT: -fweavec-diagnose // JOBS: "-cc1" // JOBS-SAME: "-fweavec-checks=verify" "-fno-weavec-zero-init" "-fweavec-ledger={{.*}}ledgers/" "-fno-weavec-asan-compat" diff --git a/test/Driver/foreign-audit.c b/test/Driver/foreign-audit.c new file mode 100644 index 0000000..e88e3b4 --- /dev/null +++ b/test/Driver/foreign-audit.c @@ -0,0 +1,103 @@ +// RFC 0057 §7: the ledger (version 17) lists, for each unit, the contracts +// its calls use (`foreign`: declared ones with the row they lower to, and +// the library table's), the functions its safe code calls with no contract +// (`expects`, which the link must find compiled by WeaveC) and the ones its +// other code calls (`unchecked`), each with the contract the compiler +// proposes. The audit (version 12) says first whether the program is +// closed: every call that leaves the code WeaveC compiled has a contract. +// A function another unit of the ledgers defines is not foreign. +// RUN: rm -rf %t && mkdir -p %t/open %t/closed %t/mixed && cp %S/Inputs/foreign/* %t/ +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -fweavec-summary -fweavec-ledger=open/ -c main.c -o open.o 2>&1 | FileCheck %s --check-prefix=SUMMARY +// RUN: cd %t && %weavec_cc -O1 -fweavec-ledger=open/ -c helper.c -o open-helper.o +// SUMMARY: weavec: main.c: {{.*}}1 of 1 functions safe; {{.*}}; 2 calls the link must find +// +// RUN: FileCheck %s --check-prefix=LEDGER --input-file=%t/open/open.o.ledger.json +// LEDGER: "expects": [ +// LEDGER: "caller": "main" +// LEDGER: "column": 24 +// LEDGER: "file": "main.c" +// LEDGER: "function": "lib_fill" +// LEDGER: "line": 10 +// LEDGER: "places": 1 +// LEDGER: "proposal": "WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);" +// LEDGER: "use": "call" +// LEDGER: "function": "lib_sum" +// LEDGER: "foreign": [ +// LEDGER: "contract": "table" +// LEDGER: "function": "printf" +// LEDGER: "safeCalls": 1 +// LEDGER: "unchecked": [] +// LEDGER: "version": 17 +// +// RUN: cd %t && %weavec_cc --weavec-audit open/ | FileCheck %s --check-prefix=OPEN +// OPEN: not closed: 2 functions safe code uses with no contract, which no unit of these ledgers defines (the link reports each as foreign-call unless a library weavec-cc compiled defines it) (0 declared, 1 of the table) +// OPEN-NEXT: 1 of 2 functions safe +// OPEN: contracts (what the program promises of code WeaveC did not compile): +// OPEN-NEXT: rows of the library table: 1 ({{.*}} 1) +// OPEN: what safe code uses with no contract (the link must find a definition WeaveC compiled): +// OPEN-NEXT: main.c:10:24: lib_fill (1 place, first in main): 'WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);' +// OPEN-NEXT: main.c:10:43: lib_sum (1 place, first in main): 'WEAVEC_FOREIGN int lib_sum(const int *WEAVEC_COUNTED_BY(count) values, int count);' +// +// With the contracts: closed, each contract with the row it lowers to and +// the calls that use it. +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -DCONTRACTS -fweavec-ledger=closed/ -c main.c -o closed.o +// RUN: cd %t && %weavec_cc -O1 -fweavec-ledger=closed/ -c helper.c -o closed-helper.o +// RUN: FileCheck %s --check-prefix=DECLARED --input-file=%t/closed/closed.o.ledger.json +// DECLARED: "expects": [] +// DECLARED: "contract": "declared" +// DECLARED: "function": "lib_fill" +// DECLARED: "row": "lib_fill (rw:bytes(a1):null-if-zero(a1), int) -> int;" +// DECLARED: "row": "lib_sum (r:bytes(a1*4):null-if-zero(a1*4), int) -> int;" +// RUN: cd %t && %weavec_cc --weavec-audit closed/ | FileCheck %s --check-prefix=CLOSED +// CLOSED: closed: every call that leaves the code WeaveC compiled has a contract (2 declared, 1 of the table) +// CLOSED: contracts (what the program promises of code WeaveC did not compile): +// CLOSED-NEXT: contracts.h:2:20: lib_fill (rw:bytes(a1):null-if-zero(a1), int) -> int; 1 safe and 0 guarded calls +// CLOSED-NEXT: contracts.h:3:20: lib_sum (r:bytes(a1*4):null-if-zero(a1*4), int) -> int; 1 safe and 0 guarded calls +// CLOSED-NEXT: rows of the library table: 1 ({{.*}} 1) +// CLOSED: foreign calls with no contract (from code that is not safe; each with the contract proposed): +// CLOSED-EMPTY: +// +// The library's own ledger beside the first ones: its functions are +// defined by a unit of the ledgers, and the program is closed with no +// contract. +// RUN: cd %t && %weavec_cc -O1 -fweavec-ledger=open/ -c lib.c -o open-lib.o +// RUN: cd %t && %weavec_cc --weavec-audit open/ | FileCheck %s --check-prefix=DEFINED +// DEFINED: closed: every call that leaves the code WeaveC compiled has a contract (0 declared, 1 of the table) +// DEFINED: lib.c:2: lib_fill (guarded) +// +// A global is found the same way: the unit that defines it lists it +// (`defines`), and the audit resolves the use against the list. +// RUN: mkdir -p %t/names && cd %t && %weavec_cc -O1 -fweavec-safe -fweavec-ledger=names/ -c uses-names.c -o uses-names.o +// RUN: cd %t && %weavec_cc --weavec-audit names/ | FileCheck %s --check-prefix=NAMES-OPEN +// NAMES-OPEN: not closed: 1 function safe code uses with no contract, which no unit of these ledgers defines +// NAMES-OPEN: uses-names.c:2:34: lib_names (1 place, first in first): 'WEAVEC_FOREIGN extern const char *const lib_names[2];' +// RUN: cd %t && %weavec_cc -O1 -fweavec-ledger=names/ -c names.c -o names.o +// RUN: FileCheck %s --check-prefix=NAMES-LEDGER --input-file=%t/names/names.o.ledger.json +// NAMES-LEDGER: "defines": [ +// NAMES-LEDGER-NEXT: "lib_names" +// RUN: cd %t && %weavec_cc --weavec-audit names/ | FileCheck %s --check-prefix=NAMES +// NAMES: closed: every call that leaves the code WeaveC compiled has a contract (0 declared, 0 of the table) +// +// A guarded function that calls with no contract compiles and links; the +// audit lists the call, and the program is not closed. +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -DCONTRACTS -fweavec-ledger=mixed/ -c main.c -o mixed.o +// RUN: cd %t && %weavec_cc -O1 -fweavec-ledger=mixed/ -c through.c -o through.o +// RUN: cd %t && %weavec_cc --weavec-audit mixed/ | FileCheck %s --check-prefix=MIXED +// MIXED: not closed: 1 foreign function called from code that is not safe with no contract (2 declared, 1 of the table) +// MIXED: foreign calls with no contract (from code that is not safe; each with the contract proposed): +// MIXED-NEXT: through.c:2:33: lib_fill (1 place, first in through): 'WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);' +// +// RUN: cd %t && %weavec_cc --weavec-audit --format=json mixed/ | FileCheck %s --check-prefix=JSON +// JSON: "foreign": { +// JSON: "closed": false +// JSON: "contracts": [ +// JSON: "contract": "declared" +// JSON: "function": "lib_fill" +// JSON: "declared": 2 +// JSON: "expects": [] +// JSON: "table": 1 +// JSON: "unchecked": [ +// JSON: "caller": "through" +// JSON: "proposal": "WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);" +// JSON: "schema": "weavec-audit" +// JSON: "version": 12 diff --git a/test/Driver/foreign-link.c b/test/Driver/foreign-link.c new file mode 100644 index 0000000..8595fa0 --- /dev/null +++ b/test/Driver/foreign-link.c @@ -0,0 +1,86 @@ +// RFC 0057 §4: a link is closed. Each safe unit records the functions it +// calls with no contract, and the driver looks, before the linker runs, for +// code WeaveC compiled that defines each: an object, an archive's member +// (named or found by -l in the command line's own -L directories), a shared +// library weavec-cc linked (it carries a mark), a partial link of such +// objects. A function nothing of the kind defines is `foreign-call`, with +// the call, the contract the compiler proposes from the call's own +// arguments, and the two other ways out. The contracts' header, the +// library compiled by weavec-cc, and a guarded shared library each close +// the link; a function through which no pointer crosses needs nothing; and +// -fweavec-summary counts what the link rests on. +// RUN: rm -rf %t && mkdir -p %t && cp %S/Inputs/foreign/* %t/ +// RUN: cd %t && %weavec_cc -O1 -fno-weavec -c lib.c -o lib.o +// RUN: cd %t && %weavec_cc -O1 -c lib.c -o guarded.o +// RUN: cd %t && %weavec_cc -O1 -c helper.c -o helper.o +// RUN: cd %t && %weavec_cc -O1 -fno-weavec -c helper.c -o helper-foreign.o +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -c main.c -o main.o +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -DCONTRACTS -c main.c -o contracts.o +// +// No contract: the link stops, and no program is written. +// RUN: cd %t && not %weavec_cc main.o helper.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=OPEN +// (The error names the input that makes the call wherever it is in the link.) +// RUN: cd %t && not %weavec_cc helper.o lib.o main.o -o prog 2>&1 | FileCheck %s --check-prefix=OPEN +// RUN: cd %t && not ls prog +// OPEN: main.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// OPEN-NEXT: main.c:10:24: note: called here, in 'main' +// OPEN-NEXT: main.c:10:24: note: say what it does with what it is given: 'WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, int n);'; or compile its library with weavec-cc; or call it from a function that is not safe +// OPEN-NEXT: note: 'weavec-cc --weavec-explain foreign-call' explains this rule +// OPEN-NEXT: main.o: error: 'lib_sum' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// OPEN-NEXT: main.c:10:43: note: called here, in 'main' +// OPEN-NEXT: main.c:10:43: note: say what it does with what it is given: 'WEAVEC_FOREIGN int lib_sum(const int *WEAVEC_COUNTED_BY(count) values, int count);'; or compile its library with weavec-cc; or call it from a function that is not safe +// OPEN-NOT: helper +// +// The same from an archive, named and through -l, and from a shared +// library weavec-cc did not make; -fno-weavec-definitions skips RFC 0051's +// comparison and not this one. +// RUN: cd %t && rm -f liblib.a && llvm-ar rc liblib.a lib.o 2>/dev/null || ar rc liblib.a lib.o +// RUN: cd %t && not %weavec_cc main.o helper.o liblib.a -o prog 2>&1 | FileCheck %s --check-prefix=STOP +// RUN: cd %t && not %weavec_cc main.o helper.o -L. -llib -o prog 2>&1 | FileCheck %s --check-prefix=STOP +// RUN: cd %t && %weavec_cc -fno-weavec %shared lib.c -o libplain%so +// RUN: cd %t && not %weavec_cc main.o helper.o libplain%so -o prog 2>&1 | FileCheck %s --check-prefix=STOP +// RUN: cd %t && not %weavec_cc -fno-weavec-definitions main.o helper.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=STOP +// RUN: cd %t && not ls prog +// STOP: main.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// STOP: main.o: error: 'lib_sum' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// +// The contracts close it: three functions by contract (the two and the +// library table's printf). +// RUN: cd %t && %weavec_cc -fweavec-summary contracts.o helper.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=CONTRACTS +// RUN: %t/prog | FileCheck %s --check-prefix=OUT +// CONTRACTS: weavec: prog: 3 objects, 1 safe; {{[0-9]+}} types, {{[0-9]+}} functions and {{[0-9]+}} globals agree; 3 foreign functions by contract, 0 with nothing crossing; closed +// OUT: 8 6 5 +// +// -fweavec-contracts gives every unit the header. +// RUN: cd %t && %weavec_cc -O1 -fweavec-safe -fweavec-contracts=contracts.h -c main.c -o flag.o +// RUN: cd %t && %weavec_cc -fweavec-summary flag.o helper.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=CONTRACTS +// +// The library compiled by weavec-cc, as an object, an archive's member and +// a shared library, needs no contract. +// RUN: cd %t && %weavec_cc -fweavec-summary main.o helper.o guarded.o -o prog 2>&1 | FileCheck %s --check-prefix=COMPILED +// RUN: cd %t && rm -f libguarded.a && llvm-ar rc libguarded.a guarded.o 2>/dev/null || ar rc libguarded.a guarded.o +// RUN: cd %t && %weavec_cc -fweavec-summary main.o helper.o -L. -lguarded -o prog 2>&1 | FileCheck %s --check-prefix=COMPILED +// RUN: cd %t && %weavec_cc %shared lib.c -o libmarked%so +// RUN: cd %t && %weavec_cc -fweavec-summary main.o helper.o libmarked%so -Wl,-rpath,%t -o prog 2>&1 | FileCheck %s --check-prefix=COMPILED +// RUN: %t/prog | FileCheck %s --check-prefix=OUT +// COMPILED: weavec: prog: 3 objects, 1 safe; {{[0-9]+}} types, {{[0-9]+}} functions and {{[0-9]+}} globals agree; 1 foreign function by contract, 0 with nothing crossing; closed +// +// `helper` takes an int and returns one: nothing crosses, and code WeaveC +// did not compile may define it. +// RUN: cd %t && %weavec_cc -fweavec-summary contracts.o helper-foreign.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=NOTHING +// NOTHING: 3 foreign functions by contract, 1 with nothing crossing; closed +// +// An LTO object's record is its bitcode's. +// RUN: cd %t && %weavec_cc -O1 -flto -fweavec-safe -c main.c -o lto.o +// RUN: cd %t && not %weavec_cc -flto lto.o helper.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=LTO +// LTO: lto.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// +// A partial link carries its objects' records; one that joins an object +// WeaveC did not compile defines nothing a safe caller may rely on. +// RUN: cd %t && %weavec_cc -r main.o helper.o -o part.o 2>/dev/null +// RUN: cd %t && not %weavec_cc part.o lib.o -o prog 2>&1 | FileCheck %s --check-prefix=PARTIAL +// RUN: cd %t && %weavec_cc part.o guarded.o -o prog && %t/prog | FileCheck %s --check-prefix=OUT +// RUN: cd %t && %weavec_cc -r main.o helper.o lib.o -o mixed.o 2>/dev/null +// RUN: cd %t && not %weavec_cc mixed.o -o prog 2>&1 | FileCheck %s --check-prefix=MIXED +// PARTIAL: part.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] +// MIXED: mixed.o: error: 'lib_fill' is called by safe code and no code WeaveC compiled defines it [weavec-safe:foreign-call] diff --git a/test/Driver/found-bounds.c b/test/Driver/found-bounds.c index c5bb445..d3f94e4 100644 --- a/test/Driver/found-bounds.c +++ b/test/Driver/found-bounds.c @@ -1,9 +1,9 @@ // RFC 0056 §8: what a unit that finds bounds tells its author. The summary // line counts the declarations whose bounds are found; -Rpass=weavec-safe // names each arrival and the declaration that would compare with a count -// instead; the ledger (version 16) lists each declaration once, with the +// instead; the ledger (version 17) lists each declaration once, with the // functions that need it and the fixes the planner proposes, and counts the -// questions placed in the code; the audit (version 11) prints the list, +// questions placed in the code; the audit (version 12) prints the list, // most needed first. `--weavec-fix-bounds` writes the certain declarations // (none here), `=likely` the likely ones too, after which only the bound with no // proposal is found; @@ -61,7 +61,7 @@ // LEDGER: "summary": { // LEDGER: "boundQuestions": {{[1-9][0-9]*}}, // LEDGER: "foundBounds": 5, -// LEDGER: "version": 16 +// LEDGER: "version": 17 // AUDIT: bounds found when safe functions run (a declared bound compares with a count instead; 'weavec-cc --weavec-fix-bounds ' writes the certain ones), most needed first: // AUDIT-NEXT: {{.*}}list.c:8: member 'buffer::data', needed by 2 functions; likely: 'int *WEAVEC_COUNTED_BY(count) data' @@ -73,7 +73,7 @@ // JSON: "declaration": "{{.*}}list.c|buffer::data", // JSON: "level": "likely", // JSON: "text": "int *WEAVEC_COUNTED_BY(count) data" -// JSON: "version": 11 +// JSON: "version": 12 // BAD: error: '--weavec-fix-bounds=some': expected '--weavec-fix-bounds', '--weavec-fix-bounds=certain' or '--weavec-fix-bounds=likely' diff --git a/test/Driver/safe-cxx-threads.cpp b/test/Driver/safe-cxx-threads.cpp index cccb079..fe46b33 100644 --- a/test/Driver/safe-cxx-threads.cpp +++ b/test/Driver/safe-cxx-threads.cpp @@ -121,7 +121,7 @@ int main() { // LEDGER-NEXT: "owns": false // LEDGER-NEXT: "sends": false // LEDGER-NEXT: "starts": 1 -// LEDGER: "version": 16 +// LEDGER: "version": 17 // AUDIT: functions that are not safe and start threads or use locks // AUDIT-NEXT: safe-cxx-threads.cpp:{{[0-9]+}}: spawn (guarded) @@ -130,6 +130,6 @@ int main() { // AUDIT: globals of code that is not safe that safe code names // AUDIT-NEXT: safe-cxx-threads.cpp:{{[0-9]+}}: main.counter // JSON-DAG: "schema": "weavec-audit" -// JSON-DAG: "version": 11 +// JSON-DAG: "version": 12 // JSON-DAG: "threads": [ // JSON-DAG: "sends": [ diff --git a/test/Driver/safe-cxx-units.cpp b/test/Driver/safe-cxx-units.cpp index 7a58aa5..007dd77 100644 --- a/test/Driver/safe-cxx-units.cpp +++ b/test/Driver/safe-cxx-units.cpp @@ -93,9 +93,9 @@ int main() { // LEDGER: "tier": "safe" // LEDGER: "function": "main" // LEDGER: "tier": "safe" -// LEDGER: "version": 16 +// LEDGER: "version": 17 // AUDIT: 4 of 5 functions safe -// AUDIT: functions that are not safe +// AUDIT: guarded functions (safe code that calls them trusts them // AUDIT-NEXT: safe-cxx-units.cpp:{{[0-9]+}}: raw (guarded) // AUDIT: reference fields // AUDIT-NEXT: safe-cxx-units.cpp:{{[0-9]+}}: Cache.last @@ -104,7 +104,7 @@ int main() { // AUDIT: erased members // AUDIT-NEXT: safe-cxx-units.cpp:{{[0-9]+}}: Cache.onChange // JSON-DAG: "schema": "weavec-audit" -// JSON-DAG: "version": 11 +// JSON-DAG: "version": 12 // JSON-DAG: "shared": [ // JSON-DAG: "erased": [ // REPORT: weavec: heap-use-after-free at {{.*}}safe-cxx-units.cpp:{{[0-9]+}}: diff --git a/test/Driver/safe-survey.cpp b/test/Driver/safe-survey.cpp index e303d1b..dbec735 100644 --- a/test/Driver/safe-survey.cpp +++ b/test/Driver/safe-survey.cpp @@ -48,7 +48,7 @@ int hits = 0; // a global that is not safe to share: its error is in the plan // LEDGER: "function": "first" // LEDGER: "surveyed": true // LEDGER: "partial": false -// LEDGER: "version": 16 +// LEDGER: "version": 17 // AUDIT: conversion: 3 of 7 functions safe (43%); 2 more have no error // AUDIT-NEXT: fixes: 0 certain, 1 likely ('weavec-cc --weavec-fix ' applies them) @@ -63,7 +63,7 @@ int hits = 0; // a global that is not safe to share: its error is in the plan // AUDIT: aliased classes // AUDIT-NEXT: survey-slice.h:{{[0-9]+}}: Slice -// JSON-DAG: "version": 11 +// JSON-DAG: "version": 12 // JSON-DAG: "conversion": { // JSON-DAG: "choices": [] // JSON-DAG: "likely": 1 diff --git a/test/Driver/typed-units.c b/test/Driver/typed-units.c index f05498e..e06935c 100644 --- a/test/Driver/typed-units.c +++ b/test/Driver/typed-units.c @@ -60,10 +60,13 @@ int viewed(const struct view *w) { return total(w->of); } // RFC 0055 §2 (D2): a fast unit tests no reference (O4 is the checked // build's). // LEDGER-NOT: "reason": "reference" -// LEDGER: "version": 16 +// LEDGER: "version": 17 +// RFC 0057 §9: the callee's ledger is not among these, so the audit cannot +// say the program is closed. +// AUDIT: not closed: 1 function safe code uses with no contract, which no unit of these ledgers defines // AUDIT: 2 of 3 functions safe -// AUDIT: functions that are not safe (safe code trusts them +// AUDIT: guarded functions (safe code that calls them trusts them // AUDIT-NEXT: typed-units.c:{{[0-9]+}}: main (guarded) // AUDIT: reference fields (tested where checked safe code loads them): // AUDIT-NEXT: typed-units.c:{{[0-9]+}}: view.of @@ -73,7 +76,7 @@ int viewed(const struct view *w) { return total(w->of); } // TWICE-NOT: view.of // JSON-DAG: "schema": "weavec-audit" // JSON-DAG: "safe": 2 -// JSON-DAG: "version": 11 +// JSON-DAG: "version": 12 // TYPED: '-fweavec-typed' was removed: -fweavec-safe makes a unit safe, with typed memory and ownership (RFC 0043) WEAVEC_GUARDED int main(void) { diff --git a/test/Guards/Inputs/foreign-lib-contracts.h b/test/Guards/Inputs/foreign-lib-contracts.h new file mode 100644 index 0000000..5a00ea5 --- /dev/null +++ b/test/Guards/Inputs/foreign-lib-contracts.h @@ -0,0 +1,20 @@ +// The contracts of foreign-lib.h (RFC 0057 §3), in a header of their own: +// a unit includes it, or the build names it with -fweavec-contracts=. +#ifndef FOREIGN_LIB_CONTRACTS_H +#define FOREIGN_LIB_CONTRACTS_H +#include "foreign-lib.h" +#include + +WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, size_t n); +WEAVEC_FOREIGN int lib_fill_past(char *WEAVEC_COUNTED_BY(n) out, size_t n, size_t extra); +WEAVEC_FOREIGN int lib_pack(unsigned char *WEAVEC_COUNTED_BY(*out_len) out, unsigned long *out_len, + const unsigned char *WEAVEC_COUNTED_BY(in_len) in, unsigned long in_len); +WEAVEC_FOREIGN size_t lib_measure(const char *WEAVEC_NULL_TERMINATED text); +WEAVEC_FOREIGN char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED lib_block(size_t n, int honest); +WEAVEC_FOREIGN_FIELD(struct lib_record, data, WEAVEC_COUNTED_BY(len) WEAVEC_OWNED); +WEAVEC_FOREIGN void lib_record_make(struct lib_record *record, size_t n); +WEAVEC_FOREIGN size_t lib_sum_past(const char *WEAVEC_COUNTED_BY(n) in, size_t n, size_t extra); +WEAVEC_FOREIGN int lib_fill_to(char *WEAVEC_ENDED_BY(end) begin, char *end); +WEAVEC_FOREIGN_FIELD(struct lib_slice, data, WEAVEC_COUNTED_BY(len)); +WEAVEC_FOREIGN int lib_slice_sum(const struct lib_slice *slice); +#endif diff --git a/test/Guards/Inputs/foreign-lib.c b/test/Guards/Inputs/foreign-lib.c new file mode 100644 index 0000000..ea91b3c --- /dev/null +++ b/test/Guards/Inputs/foreign-lib.c @@ -0,0 +1,56 @@ +// The library of foreign-lib.h, compiled with -fno-weavec. +#include "foreign-lib.h" +#include +#include + +int lib_fill(char *out, size_t n) { + memset(out, 'x', n); + return (int)n; +} + +int lib_fill_past(char *out, size_t n, size_t extra) { + volatile char *bytes = out; + for (size_t i = 0; i < n + extra; ++i) + bytes[i] = 'y'; + return (int)n; +} + +int lib_pack(unsigned char *out, unsigned long *out_len, const unsigned char *in, unsigned long in_len) { + unsigned long n = in_len < *out_len ? in_len : *out_len; + memcpy(out, in, n); + *out_len = n; + return 0; +} + +size_t lib_measure(const char *text) { return strlen(text); } + +char *lib_block(size_t n, int honest) { return calloc(honest ? n : n / 2, 1); } + +void lib_record_make(struct lib_record *record, size_t n) { + record->data = calloc(n, 1); + record->len = n; +} + +size_t lib_sum_past(const char *in, size_t n, size_t extra) { + size_t sum = 0; + for (size_t i = 0; i < n; ++i) + sum += (unsigned char)in[i]; + volatile char *bytes = (char *)in; + for (size_t i = n; i < n + extra; ++i) + bytes[i] = 0; + return sum; +} + +int lib_fill_to(char *begin, char *end) { + int written = 0; + for (volatile char *at = begin; at != end; ++at, ++written) + *at = 'e'; + return written; +} + +int lib_slice_sum(const struct lib_slice *slice) { + int sum = 0; + for (int i = 0; i < slice->len; ++i) + sum += slice->data[i]; + return sum; +} diff --git a/test/Guards/Inputs/foreign-lib.h b/test/Guards/Inputs/foreign-lib.h new file mode 100644 index 0000000..92fead5 --- /dev/null +++ b/test/Guards/Inputs/foreign-lib.h @@ -0,0 +1,28 @@ +// A library WeaveC did not compile (the tests build foreign-lib.c with +// -fno-weavec): its own header, with no annotation. +#ifndef FOREIGN_LIB_H +#define FOREIGN_LIB_H +#include + +struct lib_record { char *data; size_t len; }; + +// Writes `n` bytes of `out`. +int lib_fill(char *out, size_t n); +// Writes `n` + `extra` bytes of `out`: more than it says when extra > 0. +int lib_fill_past(char *out, size_t n, size_t extra); +// Writes at most `*out_len` bytes of `out`, and how many into `*out_len`. +int lib_pack(unsigned char *out, unsigned long *out_len, const unsigned char *in, unsigned long in_len); +// Reads the string `text`. +size_t lib_measure(const char *text); +// A block of `n` bytes the caller frees; `honest` zero returns half of it. +char *lib_block(size_t n, int honest); +// Fills `record` with a block of `n` bytes the caller frees. +void lib_record_make(struct lib_record *record, size_t n); +// Sums n bytes, then (wrongly, for its `const`) clears `extra` bytes after them. +size_t lib_sum_past(const char *in, size_t n, size_t extra); +// Writes the bytes from `begin` to `end`. +int lib_fill_to(char *begin, char *end); +// Sums the `len` bytes at `data`. +struct lib_slice { const char *data; int len; }; +int lib_slice_sum(const struct lib_slice *slice); +#endif diff --git a/test/Guards/foreign-contract.c b/test/Guards/foreign-contract.c new file mode 100644 index 0000000..78a85f5 --- /dev/null +++ b/test/Guards/foreign-contract.c @@ -0,0 +1,117 @@ +// RFC 0057 §5: a call of a function with a declared contract is checked +// before it is made. A safe caller compares the bound it holds for each +// pointer argument with the bytes the contract gives the call's arguments +// (pointer-out-of-bounds), in a fast and in a checked build; a guarded +// caller guards the same bytes against the shadow; a count read through a +// pointer ('*out_len') is read when the call is made, and a bound that is +// an end ('WEAVEC_ENDED_BY') gives the bytes from the pointer to it. Each +// report names the contract. +// RUN: rm -rf %t && mkdir -p %t +// RUN: %weavec_cc -fno-weavec -O1 -c %S/Inputs/foreign-lib.c -o %t/lib.o +// RUN: %weavec_cc -O2 -g -fweavec-safe %s %t/lib.o -o %t/fast +// RUN: %weavec_cc -O2 -g -fweavec-safe -fweavec-safe-checks=full %s %t/lib.o -o %t/full +// RUN: %weavec_cc -O2 -g %s %t/lib.o -o %t/guarded +// RUN: %t/fast | FileCheck %s --check-prefix=OK +// RUN: %t/full | FileCheck %s --check-prefix=OK +// RUN: %t/guarded | FileCheck %s --check-prefix=OK +// RUN: not --crash %t/fast count 2>&1 | FileCheck %s --check-prefix=COUNT +// RUN: not --crash %t/full count 2>&1 | FileCheck %s --check-prefix=COUNT +// RUN: not --crash %t/guarded count 2>&1 | FileCheck %s --check-prefix=GUARDED +// RUN: not --crash %t/fast pointee 2>&1 | FileCheck %s --check-prefix=POINTEE +// RUN: not --crash %t/full pointee 2>&1 | FileCheck %s --check-prefix=POINTEE +// RUN: not --crash %t/guarded pointee 2>&1 | FileCheck %s --check-prefix=GUARDED-POINTEE +// RUN: not --crash %t/fast read 2>&1 | FileCheck %s --check-prefix=READ +// RUN: not --crash %t/guarded heap 2>&1 | FileCheck %s --check-prefix=GUARDED-HEAP +// RUN: not --crash %t/fast end 2>&1 | FileCheck %s --check-prefix=END +// RUN: not --crash %t/full end 2>&1 | FileCheck %s --check-prefix=END +// RUN: not --crash %t/guarded end 2>&1 | FileCheck %s --check-prefix=GUARDED-END +#include "Inputs/foreign-lib-contracts.h" +#include +#include +#include + +static int fills(size_t n) { + char buffer[16]; + return lib_fill(buffer, n) + buffer[0]; +} + +static int packs(unsigned long room) { + unsigned char out[8]; + unsigned char in[32] = {1, 2, 3}; + unsigned long length = room; + return lib_pack(out, &length, in, sizeof(in)) + (int)length + out[0]; +} + +static int reads(unsigned long n) { + unsigned char out[64]; + unsigned char in[16] = {7}; + unsigned long length = sizeof(out); + return lib_pack(out, &length, in, n) + out[0]; +} + +static int heap(size_t n) { + char *WEAVEC_COUNTED_BY(24) WEAVEC_OWNED block = malloc(24); + if (block == NULL) + return 1; + int result = lib_fill(block, n); + free(block); + return result; +} + +// An end in another object: more bytes than the first has, or (when the +// other object lies before it) no range at all. +static char first[16]; +static char second[16]; + +static int spans(int other) { + return lib_fill_to(first, other ? &second[8] : &first[16]); +} + +int main(int argc, char **argv) { + const char *mode = argc > 1 ? argv[1] : "ok"; + if (strcmp(mode, "end") == 0) + return spans(1); + if (strcmp(mode, "count") == 0) + return fills(17); + if (strcmp(mode, "pointee") == 0) + return packs(9); + if (strcmp(mode, "read") == 0) + return reads(17); + if (strcmp(mode, "heap") == 0) + return heap(25); + printf("%d %d %d %d %zu %d\n", fills(16), packs(8), reads(16), heap(24), + lib_measure("contract"), spans(0)); + return 0; +} +// OK: 136 9 7 24 8 16 + +// COUNT: weavec: pointer-out-of-bounds at {{.*}}foreign-contract.c:35:10: write of 17 bytes at 0x{{[0-9a-f]+}} +// COUNT: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 16-byte bounds of the pointer at 0x{{[0-9a-f]+}} +// COUNT-NEXT: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:8:20 +// COUNT-NEXT: weavec: summary: pointer-out-of-bounds at {{.*}}foreign-contract.c:{{[0-9]+}}:10 in + +// The count is the integer 'length' holds when the call is made. +// POINTEE: weavec: pointer-out-of-bounds at {{.*}}foreign-contract.c:42:10: write of 9 bytes at 0x{{[0-9a-f]+}} +// POINTEE: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 8-byte bounds of the pointer at 0x{{[0-9a-f]+}} +// POINTEE-NEXT: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:10:20 + +// READ: weavec: pointer-out-of-bounds at {{.*}}foreign-contract.c:49:10: read of 17 bytes at 0x{{[0-9a-f]+}} +// READ: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:10:20 + +// A guarded caller has no bound to compare: the bytes are guarded against +// the shadow, as a library call's are. +// GUARDED: weavec: stack-buffer-overflow at {{.*}}foreign-contract.c:35:10: write of 17 bytes at 0x{{[0-9a-f]+}} +// GUARDED: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside 'buffer' (16 bytes +// GUARDED: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:8:20 +// GUARDED-NEXT: weavec: summary: stack-buffer-overflow at {{.*}}foreign-contract.c:{{[0-9]+}}:10 in +// GUARDED-POINTEE: weavec: stack-buffer-overflow at {{.*}}foreign-contract.c:42:10: write of 9 bytes at 0x{{[0-9a-f]+}} +// GUARDED-POINTEE: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:10:20 +// GUARDED-HEAP: weavec: heap-buffer-overflow at {{.*}}foreign-contract.c:56:16: write of 25 bytes at 0x{{[0-9a-f]+}} +// GUARDED-HEAP: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 24-byte heap object +// GUARDED-HEAP: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:8:20 + +// END: weavec: pointer-out-of-bounds at {{.*}}foreign-contract.c:67:10: write of {{[0-9]+}} bytes at 0x{{[0-9a-f]+}} +// END: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 16-byte bounds of the pointer at 0x{{[0-9a-f]+}} +// END-NEXT: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:17:20 +// GUARDED-END: weavec: global-buffer-overflow at {{.*}}foreign-contract.c:{{[0-9]+}}:10: write of {{[0-9]+}} bytes at 0x{{[0-9a-f]+}} +// GUARDED-END: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:17:20 diff --git a/test/Guards/foreign-member.cpp b/test/Guards/foreign-member.cpp new file mode 100644 index 0000000..68e0b70 --- /dev/null +++ b/test/Guards/foreign-member.cpp @@ -0,0 +1,53 @@ +// RFC 0057 §3.3, amendment 22: a foreign struct's member with a contract +// (WEAVEC_FOREIGN_FIELD) is one of typed memory, and foreign code that is +// given the struct believes the member's bound. Safe C++ that fills the +// struct by an initializer, which names no member, stores the checked pair +// in a fast unit, in a checked one and without optimization: a count the +// pointer's object does not have stops where the struct is made. +// RUN: rm -rf %t && mkdir -p %t +// RUN: %weavec_cc -fno-weavec -O1 -c %S/Inputs/foreign-lib.c -o %t/lib.o +// RUN: %weavec_cxx -std=c++20 -O2 -g -fweavec-safe %s %t/lib.o -o %t/fast +// RUN: %weavec_cxx -std=c++20 -O2 -g -fweavec-safe -fweavec-safe-checks=full %s %t/lib.o -o %t/full +// RUN: %weavec_cxx -std=c++20 -O0 -g -fweavec-safe %s %t/lib.o -o %t/plain +// RUN: %t/fast | FileCheck %s --check-prefix=OK +// RUN: %t/full | FileCheck %s --check-prefix=OK +// RUN: %t/plain | FileCheck %s --check-prefix=OK +// RUN: not --crash %t/fast braces 2>&1 | FileCheck %s --check-prefix=BRACES +// RUN: not --crash %t/full braces 2>&1 | FileCheck %s --check-prefix=BRACES +// RUN: not --crash %t/plain braces 2>&1 | FileCheck %s --check-prefix=BRACES +// RUN: not --crash %t/fast parens 2>&1 | FileCheck %s --check-prefix=PARENS +// RUN: not --crash %t/full parens 2>&1 | FileCheck %s --check-prefix=PARENS +// RUN: not --crash %t/plain parens 2>&1 | FileCheck %s --check-prefix=PARENS +extern "C" { +#include "Inputs/foreign-lib-contracts.h" +} +#include +#include +#include + +static int braces(const std::vector &bytes, int count) { + lib_slice slice{bytes.data(), count}; + return lib_slice_sum(&slice); +} + +static int parens(const std::vector &bytes, int count) { + lib_slice slice(bytes.data(), count); + return lib_slice_sum(&slice); +} + +int main(int argc, char **argv) { + const std::string_view mode = argc > 1 ? argv[1] : "ok"; + const std::vector bytes(8, 1); + if (mode == "braces") + return braces(bytes, 40); + if (mode == "parens") + return parens(bytes, 40); + std::printf("%d %d\n", braces(bytes, 8), parens(bytes, 8)); + return 0; +} +// OK: 8 8 + +// BRACES: weavec: heap-buffer-overflow at {{.*}}foreign-member.cpp:29:18: read of 40 bytes at 0x{{[0-9a-f]+}} +// BRACES: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 8-byte heap object +// PARENS: weavec: heap-buffer-overflow at {{.*}}foreign-member.cpp:34:18: read of 40 bytes at 0x{{[0-9a-f]+}} +// PARENS: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 8-byte heap object diff --git a/test/Guards/foreign-overflow.c b/test/Guards/foreign-overflow.c new file mode 100644 index 0000000..187babd --- /dev/null +++ b/test/Guards/foreign-overflow.c @@ -0,0 +1,89 @@ +// RFC 0057 §5.3: in a checked build (and under -fweavec-checks=verify) a +// call by contract is monitored: the bytes after each argument the +// contract says is written are watched across the call, and a callee that +// wrote past what its contract gives it stops the program when it returns, +// with the function, the argument, the contract and the object. What a +// contract the program declares says is only read is watched too: its +// `const` may be wrong. A fast build does not monitor (the call is made +// directly), and a callee that keeps its contract changes nothing. +// RUN: rm -rf %t && mkdir -p %t +// RUN: %weavec_cc -fno-weavec -O1 -c %S/Inputs/foreign-lib.c -o %t/lib.o +// RUN: %weavec_cc -O2 -g -fweavec-safe -fweavec-safe-checks=full %s %t/lib.o -o %t/full +// RUN: %weavec_cc -O0 -g -fweavec-safe %s %t/lib.o -o %t/debug +// RUN: %weavec_cc -O2 -g -fweavec-checks=verify %s %t/lib.o -o %t/verify +// RUN: %weavec_cc -O2 -g -fweavec-safe %s %t/lib.o -o %t/fast +// RUN: %t/full | FileCheck %s --check-prefix=OK +// RUN: %t/debug | FileCheck %s --check-prefix=OK +// RUN: %t/verify | FileCheck %s --check-prefix=OK +// RUN: %t/fast | FileCheck %s --check-prefix=OK +// RUN: not --crash %t/full stack 2>&1 | FileCheck %s --check-prefix=STACK +// RUN: not --crash %t/debug stack 2>&1 | FileCheck %s --check-prefix=STACK +// RUN: not --crash %t/verify stack 2>&1 | FileCheck %s --check-prefix=STACK +// RUN: not --crash %t/full heap 2>&1 | FileCheck %s --check-prefix=HEAP +// RUN: not --crash %t/verify heap 2>&1 | FileCheck %s --check-prefix=HEAP +// RUN: not --crash %t/full const 2>&1 | FileCheck %s --check-prefix=CONST +// RUN: not --crash %t/verify const 2>&1 | FileCheck %s --check-prefix=CONST +// RUN: %t/fast const | FileCheck %s --check-prefix=FAST +// RUN: env WEAVEC_RT_REPORT_FORMAT=json not --crash %t/full heap 2>&1 | FileCheck %s --check-prefix=JSON +#include "Inputs/foreign-lib-contracts.h" +#include +#include +#include + +static int stack(size_t extra) { + char buffer[16]; + return lib_fill_past(buffer, sizeof(buffer), extra) + buffer[0]; +} + +static int heap(size_t extra) { + char *WEAVEC_COUNTED_BY(24) WEAVEC_OWNED block = malloc(24); + if (block == NULL) + return 1; + int result = lib_fill_past(block, 24, extra) + block[23]; + free(block); + return result; +} + +static int reads(size_t extra) { + char *WEAVEC_COUNTED_BY(8) WEAVEC_OWNED block = malloc(8); + if (block == NULL) + return 1; + memset(block, 2, 8); + int result = (int)lib_sum_past(block, 8, extra); + free(block); + return result; +} + +int main(int argc, char **argv) { + const char *mode = argc > 1 ? argv[1] : "ok"; + if (strcmp(mode, "const") == 0) { + printf("%d\n", reads(2)); + return 0; + } + if (strcmp(mode, "stack") == 0) + return stack(3); + if (strcmp(mode, "heap") == 0) + return heap(1); + printf("%d %d %d\n", stack(0), heap(0), reads(0)); + return 0; +} +// OK: 137 145 16 +// FAST: 16 + +// STACK: weavec: foreign-overflow at {{.*}}foreign-overflow.c:35:10: 'lib_fill_past' wrote past the 16 bytes its contract gives argument 1, at 0x{{[0-9a-f]+}} +// STACK-NEXT: {{^ #0 0x[0-9a-f]+ in stack}} +// STACK: weavec: 0x{{[0-9a-f]+}} is 0 bytes after 'buffer' (16 bytes at offset {{[0-9]+}}) in the frame of +// STACK: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:9:20 +// STACK-NEXT: weavec: summary: foreign-overflow at {{.*}}foreign-overflow.c:35:10 in stack (thread T0) + +// HEAP: weavec: foreign-overflow at {{.*}}foreign-overflow.c:42:16: 'lib_fill_past' wrote past the 24 bytes its contract gives argument 1, at 0x{{[0-9a-f]+}} +// HEAP: weavec: 0x{{[0-9a-f]+}} is 0 bytes after the 24-byte heap object of type 'char' at 0x{{[0-9a-f]+}} +// HEAP: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:9:20 +// HEAP-NEXT: weavec: summary: foreign-overflow at {{.*}}foreign-overflow.c:42:16 in heap (thread T0) + +// JSON: {"weavec":{{[0-9]+}},"kind":"foreign-overflow","proven":false,"site":{"file":"{{.*}}foreign-overflow.c","line":42,"column":16},"what":"'lib_fill_past' wrote past the 24 bytes its contract gives argument 1, at 0x{{[0-9a-f]+}}" +// JSON-SAME: "contract":{"file":"{{.*}}foreign-lib-contracts.h","line":9,"column":20} + +// CONST: weavec: foreign-overflow at {{.*}}foreign-overflow.c:52:21: 'lib_sum_past' wrote past the 8 bytes its contract gives argument 1, at 0x{{[0-9a-f]+}} +// CONST: weavec: 0x{{[0-9a-f]+}} is 0 bytes after the 8-byte heap object of type 'char' at 0x{{[0-9a-f]+}} +// CONST: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:16:23 diff --git a/test/Guards/foreign-result.c b/test/Guards/foreign-result.c new file mode 100644 index 0000000..3da36d6 --- /dev/null +++ b/test/Guards/foreign-result.c @@ -0,0 +1,63 @@ +// RFC 0057 §6: what a foreign function returns arrives with the bound its +// contract declares, and is believed no further than the memory shows: a +// result, and a member the callee filled, whose block is smaller than the +// contract says stops where the result arrives, in a fast and in a checked +// build, and the report names the contract; a member the callee filled +// (WEAVEC_FOREIGN_FIELD) has the bound its contract gives it. +// RUN: rm -rf %t && mkdir -p %t +// RUN: %weavec_cc -fno-weavec -O1 -c %S/Inputs/foreign-lib.c -o %t/lib.o +// RUN: %weavec_cc -O2 -g -fweavec-safe %s %t/lib.o -o %t/fast +// RUN: %weavec_cc -O2 -g -fweavec-safe -fweavec-safe-checks=full %s %t/lib.o -o %t/full +// RUN: %t/fast | FileCheck %s --check-prefix=OK +// RUN: %t/full | FileCheck %s --check-prefix=OK +// RUN: not --crash %t/fast short 2>&1 | FileCheck %s --check-prefix=SHORT +// RUN: not --crash %t/full short 2>&1 | FileCheck %s --check-prefix=SHORT +// RUN: not --crash %t/fast member 2>&1 | FileCheck %s --check-prefix=MEMBER +#include "Inputs/foreign-lib-contracts.h" +#include +#include +#include + +static int last(size_t n, int honest) { + char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED block = lib_block(n, honest); + if (block == NULL) + return -1; + block[n - 1] = 5; + int result = block[n - 1]; + free(block); + return result; +} + +static int member(size_t n, size_t at) { + struct lib_record record = {0}; + lib_record_make(&record, n); + if (record.data == NULL) + return -1; + record.data[at] = 6; + int result = record.data[at]; + free(record.data); + record.data = NULL; + return result; +} + +int main(int argc, char **argv) { + const char *mode = argc > 1 ? argv[1] : "ok"; + if (strcmp(mode, "short") == 0) + return last(32, 0); + if (strcmp(mode, "member") == 0) + return member(8, 8); + printf("%d %d\n", last(32, 1), member(8, 7)); + return 0; +} +// OK: 5 6 + +// The block is half of what the contract says: the result is checked +// against the memory as it arrives. +// SHORT: weavec: heap-buffer-overflow at {{.*}}foreign-result.c:22:51: read of 32 bytes at 0x{{[0-9a-f]+}} +// SHORT: weavec: 0x{{[0-9a-f]+}} is 0 bytes inside the 16-byte heap object at 0x{{[0-9a-f]+}} +// SHORT: weavec: the contract is declared at {{.*}}foreign-lib-contracts.h:13:56 +// SHORT-NEXT: weavec: summary: heap-buffer-overflow at {{.*}}foreign-result.c:22:51 in + +// MEMBER: weavec: pointer-out-of-bounds at {{.*}}foreign-result.c:36:19: write of 1 bytes at 0x{{[0-9a-f]+}} +// MEMBER-NEXT: {{^ #0 }} +// MEMBER: weavec: 0x{{[0-9a-f]+}} is 0 bytes after the 8-byte bounds of the pointer at 0x{{[0-9a-f]+}} diff --git a/test/Guards/ir-foreign.c b/test/Guards/ir-foreign.c new file mode 100644 index 0000000..bc0dc3d --- /dev/null +++ b/test/Guards/ir-foreign.c @@ -0,0 +1,124 @@ +// RFC 0057 §5, §6: what a call through a contract compiles to. In a fast +// safe unit the caller holds the argument's bound, so the contract's count +// is compared with it before a direct call, with nothing after it; a local +// lent to the call stays in a plain frame (the contract says the library +// keeps no pointer to it). A checked unit also watches what the library writes +// (`__weavec_rt_foreign_before`, `__weavec_rt_foreign_after`), with both +// calls made only where the byte after the contract's bytes is in no whole +// granule of an object (a redzone, or an object's last granule). A guarded +// unit guards the range the contract states, as it does for a row of the +// library table. A contract function whose address is taken is called +// through a thunk that makes the same checks, named with a hash of the +// contract so that two units that declare it alike share one. +// RUN: %weavec_cc -O2 -fweavec-safe -S -emit-llvm %s -o - | FileCheck %s --check-prefix=FAST +// RUN: %weavec_cc -O2 -fweavec-safe -fweavec-safe-checks=full -S -emit-llvm %s -o - | FileCheck %s --check-prefix=FULL +// RUN: %weavec_cc -O2 -S -emit-llvm %s -o - | FileCheck %s --check-prefix=GUARDED +#include +#include + +struct lib_ctx; +WEAVEC_FOREIGN int lib_write(struct lib_ctx *ctx, char *WEAVEC_COUNTED_BY(n) out, size_t n); +typedef int (*writer)(struct lib_ctx *, char *WEAVEC_COUNTED_BY(n), size_t n); + +// FAST-LABEL: define {{.*}}i32 @fills.weavec.safe(ptr {{.*}}%ctx, ptr {{.*}}%out, i64 {{.*}}%n, i64 {{.*}}%m) +// FAST-NOT: __weavec_rt_guard +// FAST: icmp ugt i64 %{{.*}}, %m +// FAST: call preserve_allcc void @__weavec_rt_bounds_fail( +// FAST-NEXT: unreachable +// FAST-NOT: __weavec_rt_foreign +// FAST: call i32 @lib_write(ptr {{.*}}%ctx, ptr {{.*}}%out, i64 {{.*}}%m) +// FAST-NOT: __weavec_rt_foreign +// FAST: ret i32 + +// FULL-LABEL: define {{.*}}i32 @fills.weavec.safe( +// FULL: call preserve_allcc void @__weavec_rt_bounds_fail( +// FULL: [[GRANULE:%.*]] = load i8, ptr +// FULL-NEXT: [[REDZONE:%.*]] = icmp ugt i8 [[GRANULE]], 127 +// FULL-NEXT: br i1 [[REDZONE]], +// FULL: [[ANSWER:%.*]] = {{.*}}call i32 @__weavec_rt_foreign_before(ptr %out, i64 %m, ptr {{.*}}@__weavec.site{{.*}}, ptr {{.*}}@__weavec.file{{.*}}, i32 2) +// FULL: [[WATCHED:%.*]] = phi i32 [ [[ANSWER]], %{{.*}} ], [ 0, %{{.*}} ] +// FULL-NEXT: call i32 @lib_write(ptr {{.*}}%ctx, ptr {{.*}}%out, i64 {{.*}}%m) +// FULL-NEXT: icmp ne i32 [[WATCHED]], 0 +// FULL: call void @__weavec_rt_foreign_after(ptr %out, i32 2, i32 [[WATCHED]]) + +// GUARDED-LABEL: define {{.*}}i32 @fills(ptr {{.*}}%ctx, ptr {{.*}}%out, i64 {{.*}}%n, i64 {{.*}}%m) +// GUARDED: call preserve_allcc void @__weavec_rt_guard(i64 %{{.*}}, i64 %m, ptr @__weavec.site +// GUARDED-NOT: __weavec_rt_foreign +// GUARDED: call i32 @lib_write(ptr {{.*}}%ctx, ptr {{.*}}%out, i64 {{.*}}%m) +int fills(struct lib_ctx *ctx, char *WEAVEC_COUNTED_BY(n) out, size_t n, size_t m) { + return lib_write(ctx, out, m); +} + +// A lent local: a plain frame and no record of it in a fast unit. +// FAST-LABEL: define {{.*}}i32 @local.weavec.safe( +// FAST-NEXT: entry: +// FAST-NEXT: %buffer = alloca [32 x i8], align {{[0-9]+}} +// FAST-NOT: weavec.frame +// FAST-NOT: __weavec_rt_frame +// FAST-NOT: __weavec_rt_guard +// FAST: call i32 @lib_write(ptr {{.*}}%ctx, ptr {{.*}}%buffer, i64 noundef 32) +// FAST: ret i32 + +// FULL-LABEL: define {{.*}}i32 @local.weavec.safe( +// FULL: %weavec.frame = alloca [128 x i8], align 32 +// FULL: [[ANSWER:%.*]] = {{.*}}call i32 @__weavec_rt_foreign_before(ptr {{.*}}%buffer, i64 32, ptr +// FULL: [[WATCHED:%.*]] = phi i32 [ [[ANSWER]], %{{.*}} ], [ 0, %{{.*}} ] +// FULL-NEXT: call i32 @lib_write( +// FULL: call void @__weavec_rt_foreign_after(ptr {{.*}}%buffer, i32 2, i32 [[WATCHED]]) + +// GUARDED-LABEL: define {{.*}}i32 @local( +// GUARDED: %weavec.frame = alloca [128 x i8], align 32 +// GUARDED: call i32 @lib_write( +int local(struct lib_ctx *ctx) { + char buffer[32]; + return lib_write(ctx, buffer, sizeof(buffer)) + buffer[0]; +} + +// What the program's contract says is only read is watched too in a +// checked unit (its `const` may be wrong), and not in a fast one. +WEAVEC_FOREIGN int lib_sum(const char *WEAVEC_COUNTED_BY(n) in, size_t n); +// FAST-LABEL: define {{.*}}i32 @sums.weavec.safe( +// FAST-NOT: __weavec_rt_foreign +// FAST: call i32 @lib_sum( +// FULL-LABEL: define {{.*}}i32 @sums.weavec.safe( +// FULL: [[ANSWER:%.*]] = {{.*}}call i32 @__weavec_rt_foreign_before(ptr %in, i64 %m, ptr {{.*}}, ptr {{.*}}, i32 1) +// FULL: call i32 @lib_sum(ptr {{.*}}%in, i64 {{.*}}%m) +// FULL: call void @__weavec_rt_foreign_after(ptr %in, i32 1, i32 +int sums(const char *WEAVEC_COUNTED_BY(n) in, size_t n, size_t m) { return lib_sum(in, m); } + +// A bound that is an end gives the bytes from the pointer to it, and an +// end before the pointer more than any bound has. +WEAVEC_FOREIGN int lib_span(char *WEAVEC_ENDED_BY(end) begin, char *end); +// FAST-LABEL: define {{.*}}i32 @spans.weavec.safe(ptr {{.*}}%out, i64 {{.*}}%n, ptr {{.*}}%end +// FAST: [[BEFORE:%.*]] = icmp ult ptr %end, %out +// FAST: [[BYTES:%.*]] = sub i64 %{{.*}}, %{{.*}} +// FAST: [[SPAN:%.*]] = select i1 [[BEFORE]], i64 -1, i64 [[BYTES]] +// FAST: icmp ugt i64 %{{.*}}, [[SPAN]] +// FAST: call preserve_allcc void @__weavec_rt_bounds_fail( +// FAST: call i32 @lib_span(ptr {{.*}}%out, ptr {{.*}}%end) +// GUARDED-LABEL: define {{.*}}i32 @spans(ptr {{.*}}%out, i64 {{.*}}%n, ptr {{.*}}%end) +// GUARDED: [[BEFORE:%.*]] = icmp ult ptr %end, %out +// GUARDED: [[SPAN:%.*]] = select i1 [[BEFORE]], i64 -1, i64 %{{.*}} +// GUARDED: call void @__weavec_rt_range(i64 %{{.*}}, i64 [[SPAN]], ptr @__weavec.site +// GUARDED: call i32 @lib_span(ptr {{.*}}%out, ptr {{.*}}%end) +int spans(char *WEAVEC_COUNTED_BY(n) out, size_t n, char *end) { return lib_span(out, end); } + +// FAST-LABEL: define {{.*}}ptr @address.weavec.safe() +// FAST: ret ptr @__weavec_thunk_lib_write.[[HASH:[0-9a-f]+]] +// FAST: define linkonce_odr i32 @__weavec_thunk_lib_write.[[HASH]](ptr noundef %0, ptr noundef %1, i64 noundef %2) +// FAST: call preserve_allcc void @__weavec_rt_guard(i64 %{{.*}}, i64 %2, ptr @__weavec.site +// FAST-NOT: __weavec_rt_foreign +// FAST: call i32 @lib_write(ptr %0, ptr %1, i64 %2) + +// FULL: define linkonce_odr i32 @__weavec_thunk_lib_write.{{[0-9a-f]+}}( +// FULL: [[ANSWER:%.*]] = {{.*}}call i32 @__weavec_rt_foreign_before(ptr %1, i64 %2, ptr +// FULL: [[WATCHED:%.*]] = phi i32 [ [[ANSWER]], %{{.*}} ], [ 0, %{{.*}} ] +// FULL-NEXT: call i32 @lib_write(ptr %0, ptr %1, i64 %2) +// FULL: call void @__weavec_rt_foreign_after(ptr %1, i32 2, i32 [[WATCHED]]) + +// GUARDED-LABEL: define {{.*}}ptr @address() +// GUARDED: ret ptr @__weavec_thunk_lib_write.[[HASH:[0-9a-f]+]] +// GUARDED: define linkonce_odr i32 @__weavec_thunk_lib_write.[[HASH]]( +// GUARDED: call preserve_allcc void @__weavec_rt_guard(i64 %{{.*}}, i64 %2, ptr @__weavec.site +// GUARDED: call i32 @lib_write(ptr %0, ptr %1, i64 %2) +writer address(void) { return lib_write; } diff --git a/test/Guards/ledger.c b/test/Guards/ledger.c index 800cdee..59b012a 100644 --- a/test/Guards/ledger.c +++ b/test/Guards/ledger.c @@ -6,7 +6,7 @@ // SUMMARY: weavec: {{.*}}ledger.c: 2 accesses: 1 proven, 1 guarded, 0 unguarded // CHECK-DAG: "schema": "weavec-ledger" -// CHECK-DAG: "version": 16 +// CHECK-DAG: "version": 17 // CHECK-DAG: "checks": "trap" // CHECK-DAG: "accesses": 2 // CHECK-DAG: "outcome": "guarded" diff --git a/test/Guards/report-json.c b/test/Guards/report-json.c index e79e876..1fbca48 100644 --- a/test/Guards/report-json.c +++ b/test/Guards/report-json.c @@ -12,6 +12,6 @@ int main(void) { free(p); return sink[2]; } -// CHECK: {"weavec":52,"kind":"heap-use-after-free","proven":false,"site":{"file":"{{.*}}report-json.c","line":13,"column":{{[0-9]+}}},"what":"read of 1 bytes at 0x{{[0-9a-f]+}}","access":{"op":"read","width":1,"address":"0x{{[0-9a-f]+}}"},"thread":{"id":0},"stack":[{"pc":"0x{{[0-9a-f]+}}","module":"{{.*}}","offset":"0x{{[0-9a-f]+}}","function":"main","file":"{{.*}}report-json.c","line":13, +// CHECK: {"weavec":53,"kind":"heap-use-after-free","proven":false,"site":{"file":"{{.*}}report-json.c","line":13,"column":{{[0-9]+}}},"what":"read of 1 bytes at 0x{{[0-9a-f]+}}","access":{"op":"read","width":1,"address":"0x{{[0-9a-f]+}}"},"thread":{"id":0},"stack":[{"pc":"0x{{[0-9a-f]+}}","module":"{{.*}}","offset":"0x{{[0-9a-f]+}}","function":"main","file":"{{.*}}report-json.c","line":13, // CHECK-SAME: "object":{"memory":"heap","base":"0x{{[0-9a-f]+}}","size":8{{(,"type":"[^"]*")?}},"state":"released","released":[{"pc":"0x{{[0-9a-f]+}}",{{.*}}"line":12, // CHECK-SAME: "allocated":[{"pc":"0x{{[0-9a-f]+}}",{{.*}}"line":10, diff --git a/test/Guards/unsafe-region.c b/test/Guards/unsafe-region.c index 1eafc28..d839bf5 100644 --- a/test/Guards/unsafe-region.c +++ b/test/Guards/unsafe-region.c @@ -17,6 +17,6 @@ int both(const int *p, int i) { // SUMMARY: weavec: {{.*}}unsafe-region.c: 3 accesses: 0 proven, 1 guarded, 2 unguarded // LEDGER-DAG: "schema": "weavec-ledger" -// LEDGER-DAG: "version": 16 +// LEDGER-DAG: "version": 17 // LEDGER-DAG: "outcome": "unguarded" // LEDGER-DAG: "reason": "unsafe" diff --git a/test/Safe/calls.c b/test/Safe/calls.c index e9e7b0b..75f8504 100644 --- a/test/Safe/calls.c +++ b/test/Safe/calls.c @@ -1,6 +1,7 @@ // RFC 0041 §3, rules call-args and variadic: a bounded parameter takes a -// pointer with bounds; a variadic call is to a function the library table -// describes, and a safe function reads no variadic arguments. +// pointer with bounds; a variadic call of a function the unit defines is to +// one the library table describes (one it does not define is RFC 0057's: +// foreign-call.c), and a safe function reads no variadic arguments. // The rules below are those of -fweavec-safe-bounds=declared (RFC 0056 §9), // where a pointer with no declared bound is one object. // RUN: %weavec_cc -fsyntax-only -fweavec-safe-bounds=declared -Xclang -verify -Xclang -verify-ignore-unexpected=note %s @@ -10,7 +11,7 @@ #include int total(const int *WEAVEC_COUNTED_BY(n) v, size_t n); -int logf_(const char *format, ...); +int logf_(const char *format, ...) { return format != 0; } WEAVEC_SAFE int args(const int *one, const int *WEAVEC_COUNTED_BY(n) v, size_t n) { diff --git a/test/Safe/cxx-foreign-call.cpp b/test/Safe/cxx-foreign-call.cpp new file mode 100644 index 0000000..7c479c1 --- /dev/null +++ b/test/Safe/cxx-foreign-call.cpp @@ -0,0 +1,92 @@ +// RFC 0057 in Safe C++: a contract is a free function's declaration +// (extern "C" or not); a member function has none; the borrow rules follow +// the contract's annotations at its calls; a pointer through '...' with no +// format is foreign-call when the unit compiles; and a row of the table +// that keeps its argument is a kept parameter to the rules. +// RUN: %weavec_cxx -std=c++20 -fsyntax-only -fweavec-safe -Xclang -verify -Xclang -verify-ignore-unexpected=note %s +#include +#include +#include +#include +#include +#include + +extern "C" { +struct lib_db; +WEAVEC_FOREIGN lib_db *WEAVEC_OWNED lib_db_open(const char *WEAVEC_NULL_TERMINATED path); +WEAVEC_FOREIGN void lib_db_close(lib_db *WEAVEC_OWNED db); +WEAVEC_FOREIGN const char *WEAVEC_NULL_TERMINATED lib_db_text(lib_db *db WEAVEC_LIFETIMEBOUND); +WEAVEC_FOREIGN int lib_db_step(lib_db *db); +WEAVEC_FOREIGN int lib_db_put(lib_db *db, const unsigned char *WEAVEC_COUNTED_BY(n) blob, std::size_t n); +WEAVEC_FOREIGN void lib_db_watch(lib_db *db, int *WEAVEC_ESCAPES flag); +int lib_db_config(lib_db *db, int option, ...); +} +WEAVEC_FOREIGN int lib_cxx_sum(const int *WEAVEC_COUNTED_BY(n) values, std::size_t n); + +// A member of the library's struct (WEAVEC_FOREIGN_FIELD is two typedefs, +// since C++ takes no attribute after `__typeof__(...)`), in a linkage +// specification and in a namespace. +extern "C" { +struct lib_stream { const unsigned char *next_in; unsigned avail_in; int *owner; }; +WEAVEC_FOREIGN_FIELD(lib_stream, next_in, WEAVEC_COUNTED_BY(avail_in)); +WEAVEC_FOREIGN_FIELD(lib_stream, avail_in, WEAVEC_COUNTED_BY(4)); // expected-error {{WEAVEC_FOREIGN_FIELD names 'avail_in' of 'lib_stream', which is no pointer member of a struct or a union [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN int lib_stream_step(lib_stream *stream); +} +namespace lib { +struct Span { const int *first; unsigned count; }; +WEAVEC_FOREIGN_FIELD(Span, first, WEAVEC_COUNTED_BY(count)); +WEAVEC_FOREIGN_FIELD(lib::Span, first, WEAVEC_COUNTED_BY(8)); // expected-error {{a second WEAVEC_FOREIGN_FIELD for 'first' of 'lib::Span' says something else than the first [weavec-safe:bad-annotation]}} +} + +int feeds(const std::vector &in) { + lib_stream stream{}; + const unsigned char *data = in.data(); + const unsigned size = static_cast(in.size()); + stream.next_in = data; + stream.avail_in = size; + int status = lib_stream_step(&stream); + lib::Span span{}; + return status + (span.count != 0 ? span.first[span.count - 1] : 0); +} + +struct Widget { + WEAVEC_FOREIGN int measure(const char *text); // expected-error {{WEAVEC_FOREIGN is on the member function 'measure': a contract is a function's own declaration, and a member is declared in its class [weavec-safe:bad-annotation]}} +}; + +// Safe C++ takes no raw owner (raw-owner, RFC 0044): the two functions +// that move the handle between the library and the unique_ptr are guarded, +// and the audit lists them. +struct Closer { + WEAVEC_GUARDED void operator()(lib_db *db) const { lib_db_close(db); } +}; + +class Database { +public: + WEAVEC_GUARDED explicit Database(const std::string &path) + : db(lib_db_open(path.c_str())) {} + int put(const std::vector &blob) { + return lib_db_put(db.get(), blob.data(), blob.size()); + } + int step() { return lib_db_step(db.get()); } + std::string text() { return std::string(lib_db_text(db.get())); } + +private: + std::unique_ptr db; +}; + +int uses(const std::string &path, const std::vector &values) { + Database database(path); + std::vector blob{1, 2, 3}; + return database.put(blob) + database.step() + + static_cast(database.text().size()) + + lib_cxx_sum(values.data(), values.size()); +} + +int stores(lib_db *db, pthread_key_t key) { + int local = 0; + lib_db_watch(db, &local); // expected-error {{a borrow of 'local' is stored in what 'lib_db_watch' keeps, which outlives it [weavec-safe:escape]}} + pthread_setspecific(key, &local); // expected-error {{a borrow of 'local' is stored in what 'pthread_setspecific' keeps, which outlives it [weavec-safe:escape]}} + char name[8] = "name"; + return lib_db_config(db, 1, 2) + + lib_db_config(db, 2, name); // expected-error {{a pointer is passed to 'lib_db_config' through '...', where no contract says what is done with it [weavec-safe:foreign-call]}} +} diff --git a/test/Safe/foreign-call.c b/test/Safe/foreign-call.c new file mode 100644 index 0000000..4777ccc --- /dev/null +++ b/test/Safe/foreign-call.c @@ -0,0 +1,74 @@ +// RFC 0057 §3.6, rule foreign-call: what a safe function's call reaches +// that no code WeaveC compiled defines is the link's to refuse +// (test/Driver/foreign-link.c); when the unit compiles, the one error is a +// pointer passed through '...' to such a function with no contract that +// says what is done with it (a format). The function is foreign for that +// error when a contract or a system header declares it; one the program's +// own header declares may be another unit's, and its call is `variadic`'s. +// A row of the table, a declared contract with a format, and a call that +// passes no pointer are accepted, and so is any call made by a function +// that is not safe. §5.1, rule +// escape: a foreign function that keeps a pointer (a contract's +// WEAVEC_ESCAPES parameter, a row's `kept`) is not given the address of a +// local, which nothing would check when the library used it later; a +// static local, a global and a block of the heap are accepted, and so is +// a local lent to a parameter the library does not keep. +// RUN: %weavec_cc -fsyntax-only -fweavec-safe -Xclang -verify -Xclang -verify-ignore-unexpected=note %s +#include +#include +#include + +int lib_log(int level, const char *format, ...); +int lib_control(int fd, unsigned long request, ...); +int lib_plain(const char *name); +WEAVEC_FOREIGN int lib_trace(const char *WEAVEC_NULL_TERMINATED format, ...) + __attribute__((format(printf, 1, 2))); +WEAVEC_FOREIGN int lib_option(int handle, int option, ...); + +WEAVEC_SAFE int calls(int fd, const char *WEAVEC_NULL_TERMINATED name) { + char buffer[16]; + int n = printf("%s\n", name); // a row of the table + n += lib_trace("%s %d\n", name, fd); // a contract with a format + n += lib_control(fd, 7UL, 1); // no pointer crosses + n += lib_plain(name); // the link's to find + n += ioctl(fd, 7UL, 1); // no pointer crosses + n += ioctl(fd, 9UL, buffer); // expected-error {{a pointer is passed to 'ioctl' through '...', where no contract says what is done with it [weavec-safe:foreign-call]}} + n += lib_log(2, "%s", name); // expected-error {{a pointer is passed to 'lib_log' through '...', and nothing says how it is read [weavec-safe:variadic]}} + n += lib_control(fd, 9UL, buffer); // expected-error {{a pointer is passed to 'lib_control' through '...', and nothing says how it is read [weavec-safe:variadic]}} + n += lib_option(fd, 3, buffer); // expected-error {{a pointer is passed to 'lib_option' through '...', where no contract says what is done with it [weavec-safe:foreign-call]}} + return n + lib_option(fd, 4, 1); +} + +WEAVEC_GUARDED int adapter(int fd, char *WEAVEC_COUNTED_BY(16) buffer) { + return lib_control(fd, 9UL, buffer); // guarded: the audit lists it +} + +struct app { int events; char name[16]; }; +WEAVEC_FOREIGN void lib_listen(void (*callback)(void *user), void *WEAVEC_ESCAPES user); +WEAVEC_FOREIGN void lib_name(const char *WEAVEC_ESCAPES WEAVEC_NULL_TERMINATED name); +WEAVEC_FOREIGN void lib_read(const struct app *app); +int pthread_setspecific(unsigned long key, const void *value); +void seen(void *user); +static struct app shared; + +WEAVEC_SAFE void keeps(struct app *WEAVEC_ESCAPES given, unsigned long key) { + struct app local = {0}; + static struct app kept; + char text[8] = "name"; + lib_listen(seen, &local); // expected-error {{the address of 'local' is given to 'lib_listen', which keeps it, and 'local' ends with its scope [weavec-safe:escape]}} + lib_listen(seen, &local.events); // expected-error {{the address of 'local' is given to 'lib_listen', which keeps it, and 'local' ends with its scope [weavec-safe:escape]}} + lib_listen(seen, local.name); // expected-error {{the address of 'local' is given to 'lib_listen', which keeps it, and 'local' ends with its scope [weavec-safe:escape]}} + lib_name(text); // expected-error {{the address of 'text' is given to 'lib_name', which keeps it, and 'text' ends with its scope [weavec-safe:escape]}} + pthread_setspecific(key, &local); // expected-error {{the address of 'local' is given to 'pthread_setspecific', which keeps it, and 'local' ends with its scope [weavec-safe:escape]}} + lib_name((char[8]){"name"}); // expected-error {{the address of a compound literal is given to 'lib_name', which keeps it, and the literal ends with its scope [weavec-safe:escape]}} + lib_listen(seen, &kept); + lib_listen(seen, &shared); + lib_listen(seen, given); + lib_name("literal"); + lib_read(&local); // lent for the call +} + +WEAVEC_GUARDED void keeps_guarded(void) { + struct app local = {0}; + lib_listen(seen, &local); // guarded: not checked by the rules +} diff --git a/test/Safe/foreign-callback.c b/test/Safe/foreign-callback.c new file mode 100644 index 0000000..427449f --- /dev/null +++ b/test/Safe/foreign-callback.c @@ -0,0 +1,47 @@ +// RFC 0057 §3.5: a function the program gives a foreign function to call +// back is called with what the contract's parameter type says, so its own +// parameters say the same: a bound the contract declares and the function +// does not is call-args, with the fix that writes it. A function that +// declares what the contract does, and a callback of a row of the table, +// are accepted. +// RUN: %weavec_cc -fsyntax-only -fweavec-safe -Xclang -verify -Xclang -verify-ignore-unexpected=note %s +// RUN: not %weavec_cc -fsyntax-only -fweavec-safe -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s --check-prefix=FIXIT +#include +#include +#include + +struct lib_parser; +typedef int lib_on_data(void *user, const char *WEAVEC_COUNTED_BY(len) data, size_t len); +WEAVEC_FOREIGN void lib_set_handler(struct lib_parser *p, lib_on_data *handler, void *user); +WEAVEC_FOREIGN int lib_each(struct lib_parser *p, + int (*visit)(const char *WEAVEC_NULL_TERMINATED key, void *user), + void *user); + +WEAVEC_SAFE int counted(void *user, const char *WEAVEC_COUNTED_BY(len) data, size_t len) { + return len > 0 ? data[0] + (user != NULL) : 0; +} +WEAVEC_SAFE int bare(void *user, const char *data, size_t len) { + return len > 0 && user != NULL ? data[0] : 0; +} +WEAVEC_SAFE int key_string(const char *WEAVEC_NULL_TERMINATED key, void *user) { + return key[0] + (user != NULL); +} +WEAVEC_SAFE int key_bare(const char *key, void *user) { + return key[0] + (user != NULL); +} +WEAVEC_SAFE int by_value(const void *a, const void *b) { + return *(const int *)a - *(const int *)b; +} + +WEAVEC_SAFE int gives(struct lib_parser *p, int *WEAVEC_COUNTED_BY(n) v, size_t n) { + lib_set_handler(p, counted, NULL); + lib_set_handler(p, bare, NULL); // expected-error {{'bare' is passed where 'lib_set_handler' declares 'WEAVEC_COUNTED_BY(len)' for parameter 2, and declares none [weavec-safe:call-args]}} + qsort(v, n, sizeof(int), by_value); // a row of the table + return lib_each(p, key_string, NULL) + + lib_each(p, key_bare, NULL); // expected-error {{'key_bare' is passed where 'lib_each' declares 'WEAVEC_NULL_TERMINATED' for parameter 1, and declares none [weavec-safe:call-args]}} +} +// The fix writes what the contract declares on the function's parameter. +// FIXIT: note: fix (certain): declare it 'WEAVEC_COUNTED_BY(len) data' +// FIXIT: fix-it:"{{.*}}foreign-callback.c":{23:46-23:46}:"WEAVEC_COUNTED_BY(len) " +// FIXIT: note: fix (certain): declare it 'WEAVEC_NULL_TERMINATED key' +// FIXIT: fix-it:"{{.*}}foreign-callback.c":{29:38-29:38}:"WEAVEC_NULL_TERMINATED " diff --git a/test/Safe/foreign-contract.c b/test/Safe/foreign-contract.c new file mode 100644 index 0000000..e2b0f35 --- /dev/null +++ b/test/Safe/foreign-contract.c @@ -0,0 +1,104 @@ +// RFC 0057 §3: a contract is the prototype of a function that code WeaveC +// did not compile defines, declared again WEAVEC_FOREIGN with the +// annotations a function of the program has. Each form is accepted here, +// and each wrong one is bad-annotation. +// RUN: %weavec_cc -fsyntax-only -fweavec-safe -Xclang -verify -Xclang -verify-ignore-unexpected=note %s +#include +#include +#include +#include + +// §3.1: bounds from parameters, a constant, a string; a handle (a pointer +// to a type the library keeps to itself); an owner made and released. +struct z_handle; +struct lib_entry { const char *name; char *data; size_t len; }; + +WEAVEC_FOREIGN int lib_read(struct z_handle *h, char *WEAVEC_COUNTED_BY(n) out, size_t n); +WEAVEC_FOREIGN int lib_sum(const int *WEAVEC_COUNTED_BY(4) four); +WEAVEC_FOREIGN size_t lib_length(const char *WEAVEC_NULL_TERMINATED text); +WEAVEC_FOREIGN struct z_handle *WEAVEC_OWNED lib_open(const char *WEAVEC_NULL_TERMINATED path); +WEAVEC_FOREIGN void lib_close(struct z_handle *WEAVEC_OWNED h); +WEAVEC_FOREIGN const char *WEAVEC_NULL_TERMINATED lib_name(struct z_handle *h WEAVEC_LIFETIMEBOUND); +WEAVEC_FOREIGN void lib_keep(struct z_handle *h, int *WEAVEC_ESCAPES slot); + +// §3.2: a count read through a pointer when the call is made. +WEAVEC_FOREIGN int lib_pack(unsigned char *WEAVEC_COUNTED_BY(*out_len) out, unsigned long *out_len, + const unsigned char *WEAVEC_COUNTED_BY(in_len) in, unsigned long in_len); + +// §3.3: a member of a struct the library's header defines. +WEAVEC_FOREIGN_FIELD(struct lib_entry, data, WEAVEC_COUNTED_BY(len)); +WEAVEC_FOREIGN_FIELD(struct lib_entry, name, WEAVEC_NULL_TERMINATED); +WEAVEC_FOREIGN int lib_next(struct z_handle *h, struct lib_entry *entry); + +// §3.4: a global the library defines. +WEAVEC_FOREIGN extern const char *WEAVEC_NULL_TERMINATED lib_version; + +WEAVEC_SAFE int uses(const char *WEAVEC_NULL_TERMINATED path) { + char line[64]; + unsigned char packed[32]; + unsigned long room = sizeof(packed); + int four[4] = {1, 2, 3, 4}; + struct lib_entry entry = {0}; + struct z_handle *WEAVEC_OWNED h = lib_open(path); + if (h == NULL) + return -1; + int n = lib_read(h, line, sizeof(line)) + lib_sum(four) + + (int)lib_length(lib_name(h)) + (int)lib_length(lib_version); + n += lib_pack(packed, &room, (const unsigned char *)line, sizeof(line)); + if (lib_next(h, &entry) == 0 && entry.len > 2) + n += entry.data[2] + entry.name[0]; + lib_close(h); + return n; +} + +// What a contract cannot be. +WEAVEC_FOREIGN int defined_here(int *p) { return *p; } // expected-error {{WEAVEC_FOREIGN is on the definition of 'defined_here': a contract is the declaration of a function that code WeaveC did not compile defines [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN char *getenv(const char *name); // expected-error {{'getenv' has a row of the library table, which is its contract [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN int lib_global = 3; // expected-error {{WEAVEC_FOREIGN is on the definition of 'lib_global': a contract is the 'extern' declaration of a global that code WeaveC did not compile defines [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN extern char *optarg; // expected-error {{'optarg' has a row of the library table, which is its contract [weavec-safe:bad-annotation]}} + +// A count read through a pointer is a contract's alone, names a pointer to +// an integer, and bounds no result. +int program_fill(char *WEAVEC_COUNTED_BY(*n) out, size_t *n); // expected-error {{'*n' in the bound is a count read through a pointer, which only a parameter of a contract (a WEAVEC_FOREIGN declaration with no body) may have [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN int lib_bad_count(char *WEAVEC_COUNTED_BY(*what) out, char **what); // expected-error {{'*what' in the bound names no parameter of 'lib_bad_count' that points to an integer [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN char *WEAVEC_COUNTED_BY(*n) lib_bad_result(size_t *n); // expected-error {{'*n' in the bound is a count read through a pointer, which only a parameter of a contract (a WEAVEC_FOREIGN declaration with no body) may have [weavec-safe:bad-annotation]}} + +// A member's contract names a pointer member, once, with a member's +// annotations, of a struct that does not annotate it itself. +struct own_entry { char *WEAVEC_COUNTED_BY(len) data; size_t len; }; +WEAVEC_FOREIGN_FIELD(struct lib_entry, len, WEAVEC_COUNTED_BY(len)); // expected-error {{WEAVEC_FOREIGN_FIELD names 'len' of 'struct lib_entry', which is no pointer member of a struct or a union [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN_FIELD(struct lib_entry, data, WEAVEC_COUNTED_BY(4)); // expected-error {{a second WEAVEC_FOREIGN_FIELD for 'data' of 'struct lib_entry' says something else than the first [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN_FIELD(struct own_entry, data, WEAVEC_COUNTED_BY(len)); // expected-error {{WEAVEC_FOREIGN_FIELD names 'data' of 'struct own_entry', whose own declaration has an annotation [weavec-safe:bad-annotation]}} +struct other_entry { char *data; }; +WEAVEC_FOREIGN_FIELD(struct other_entry, data, WEAVEC_ESCAPES); // expected-error {{WEAVEC_FOREIGN_FIELD gives 'data' of 'struct other_entry' an annotation that is a parameter's [weavec-safe:bad-annotation]}} + +// A bound that is an end is a parameter's (the call compares the bytes from +// the pointer to it); typed memory keeps a count beside a member's pointer +// and no end, so a struct with such a member is not given to foreign code. +WEAVEC_FOREIGN int lib_span(char *WEAVEC_ENDED_BY(end) begin, char *end); +struct own_range { char *WEAVEC_ENDED_BY(end) begin; char *end; }; +struct lib_range { char *begin; char *end; }; +WEAVEC_FOREIGN_FIELD(struct lib_range, begin, WEAVEC_ENDED_BY(end)); +struct lib_ranges { struct lib_range *first; size_t count; }; +WEAVEC_FOREIGN int lib_range_fill(struct own_range *range); // expected-error {{the contract of 'lib_range_fill' gives foreign code 'begin' of 'struct own_range', which WEAVEC_ENDED_BY bounds: typed memory keeps a count beside its pointer, and no end [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN int lib_range_sum(struct lib_range range); // expected-error {{the contract of 'lib_range_sum' gives foreign code 'begin' of 'struct lib_range', which WEAVEC_ENDED_BY bounds: typed memory keeps a count beside its pointer, and no end [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN struct lib_ranges *lib_ranges_all(void); // expected-error {{the contract of 'lib_ranges_all' gives foreign code 'begin' of 'struct lib_range', which WEAVEC_ENDED_BY bounds: typed memory keeps a count beside its pointer, and no end [weavec-safe:bad-annotation]}} +WEAVEC_FOREIGN extern struct lib_range lib_whole; // expected-error {{the contract of 'lib_whole' gives foreign code 'begin' of 'struct lib_range', which WEAVEC_ENDED_BY bounds: typed memory keeps a count beside its pointer, and no end [weavec-safe:bad-annotation]}} + +// The library's own prototype may come before the contract or after it (a +// build that names the contracts' header with -fweavec-contracts): every +// declaration of the function says what the contract says. +char *lib_early(size_t n); +WEAVEC_FOREIGN char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED lib_early(size_t n); +WEAVEC_FOREIGN char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED lib_late(size_t n); +char *lib_late(size_t); + +WEAVEC_SAFE int orders(size_t n) { + char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED early = lib_early(n); + char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED late = lib_late(n); + int result = (early != NULL && n > 1 ? early[1] : 0) + + (late != NULL && n > 1 ? late[1] : 0); + free(early); + free(late); + return result; +} diff --git a/test/cases/README.md b/test/cases/README.md index ea91694..c23877e 100644 --- a/test/cases/README.md +++ b/test/cases/README.md @@ -25,6 +25,7 @@ messages; these cases pin what must be reported and what must stop. | `detection/cxx/` | RFC 0039's C++ detection probes, one class per file, each with a `-DFIX` twin | | `sum/` | RFC 0054's values of one of several types: tagged unions and checked conversions, each bug with a `_ok` twin | | `bounds/` | RFC 0056's found bounds: code with no bounds declarations compiled with `-fweavec-safe`, one bug per kind of object a bound is found for (heap, member, global, local, string, range), each with a `_ok` twin | +| `foreign/` | RFC 0057's foreign code by contract: a library built with `-fno-weavec` (`Inputs/lib.c`) called through contracts (`Inputs/contracts.h`): a count past the caller's bound, an in-out count, a foreign struct's member, a short result, a guarded caller, and a library that writes past its contract in the checked build (`foreign-overflow`), each with a `_ok` twin | A file under an `Inputs/` directory is never a case: it holds units, headers and input files that cases share. @@ -114,7 +115,7 @@ Report kinds are those of the runtime (`runtime/weavec_report.c`, RFC 0035 `stack-use-after-return` and `memory-fault`, RFC 0039's `container-overflow` and `library-assertion`, and RFC 0040's bad releases, `double-free`, `invalid-free` and `alloc-release-mismatch`, which replace -`invalid-release`. +`invalid-release`, and RFC 0057's `foreign-overflow`. Rules the grammar leaves implicit, as the runner enforces them: diff --git a/test/cases/foreign/Inputs/contracts.h b/test/cases/foreign/Inputs/contracts.h new file mode 100644 index 0000000..44042b7 --- /dev/null +++ b/test/cases/foreign/Inputs/contracts.h @@ -0,0 +1,15 @@ +// The contracts of Inputs/lib.h (RFC 0057 §3). +#ifndef CASES_FOREIGN_CONTRACTS_H +#define CASES_FOREIGN_CONTRACTS_H +#include "lib.h" +#include + +WEAVEC_FOREIGN int lib_fill(char *WEAVEC_COUNTED_BY(n) out, size_t n); +WEAVEC_FOREIGN int lib_fill_past(char *WEAVEC_COUNTED_BY(n) out, size_t n, size_t extra); +WEAVEC_FOREIGN int lib_pack(unsigned char *WEAVEC_COUNTED_BY(*out_len) out, unsigned long *out_len, + const unsigned char *WEAVEC_COUNTED_BY(in_len) in, unsigned long in_len); +WEAVEC_FOREIGN char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED lib_block(size_t n, int honest); +WEAVEC_FOREIGN_FIELD(struct lib_record, data, WEAVEC_COUNTED_BY(len) WEAVEC_OWNED); +WEAVEC_FOREIGN void lib_record_make(struct lib_record *record, size_t n); +WEAVEC_FOREIGN int lib_fill_to(char *WEAVEC_ENDED_BY(end) begin, char *end); +#endif diff --git a/test/cases/foreign/Inputs/lib.c b/test/cases/foreign/Inputs/lib.c new file mode 100644 index 0000000..909b1a2 --- /dev/null +++ b/test/cases/foreign/Inputs/lib.c @@ -0,0 +1,37 @@ +// FLAGS: -fno-weavec +#include "lib.h" +#include +#include + +int lib_fill(char *out, size_t n) { + memset(out, 'x', n); + return (int)n; +} + +int lib_fill_past(char *out, size_t n, size_t extra) { + volatile char *bytes = out; + for (size_t i = 0; i < n + extra; ++i) + bytes[i] = 'y'; + return (int)n; +} + +int lib_pack(unsigned char *out, unsigned long *out_len, const unsigned char *in, unsigned long in_len) { + unsigned long n = in_len < *out_len ? in_len : *out_len; + memcpy(out, in, n); + *out_len = n; + return 0; +} + +char *lib_block(size_t n, int honest) { return calloc(honest ? n : n / 2, 1); } + +void lib_record_make(struct lib_record *record, size_t n) { + record->data = calloc(n, 1); + record->len = n; +} + +int lib_fill_to(char *begin, char *end) { + int written = 0; + for (volatile char *at = begin; at != end; ++at, ++written) + *at = 'e'; + return written; +} diff --git a/test/cases/foreign/Inputs/lib.h b/test/cases/foreign/Inputs/lib.h new file mode 100644 index 0000000..8f2a4ca --- /dev/null +++ b/test/cases/foreign/Inputs/lib.h @@ -0,0 +1,21 @@ +// A library WeaveC did not compile (Inputs/lib.c is built with +// -fno-weavec): its header as it ships, with no annotation. +#ifndef CASES_FOREIGN_LIB_H +#define CASES_FOREIGN_LIB_H +#include + +struct lib_record { char *data; size_t len; }; + +// Writes `n` bytes of `out`. +int lib_fill(char *out, size_t n); +// Writes `n` + `extra` bytes of `out`: more than it says when extra > 0. +int lib_fill_past(char *out, size_t n, size_t extra); +// Writes at most `*out_len` bytes of `out`, and how many into `*out_len`. +int lib_pack(unsigned char *out, unsigned long *out_len, const unsigned char *in, unsigned long in_len); +// A block of `n` bytes the caller frees; `honest` zero returns half of it. +char *lib_block(size_t n, int honest); +// Fills `record` with a block of `n` bytes the caller frees. +void lib_record_make(struct lib_record *record, size_t n); +// Writes the bytes from `begin` to `end`. +int lib_fill_to(char *begin, char *end); +#endif diff --git a/test/cases/foreign/count-past.c b/test/cases/foreign/count-past.c new file mode 100644 index 0000000..06d9ef1 --- /dev/null +++ b/test/cases/foreign/count-past.c @@ -0,0 +1,21 @@ +// RFC 0057 §6: safe code passes a count one past the buffer it holds; the +// contract's count is compared with the bound before the library runs. +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int fill(size_t n) { + char *WEAVEC_COUNTED_BY(16) WEAVEC_OWNED text = calloc(16, 1); + if (text == NULL) + return -1; + int written = lib_fill(text, n); // TRAP: pointer-out-of-bounds + free(text); + return written; +} + +int main(void) { + printf("%d\n", fill(17)); + return 0; +} diff --git a/test/cases/foreign/count-past_ok.c b/test/cases/foreign/count-past_ok.c new file mode 100644 index 0000000..5b833f5 --- /dev/null +++ b/test/cases/foreign/count-past_ok.c @@ -0,0 +1,22 @@ +// RFC 0057 §6: the twin of count-past.c: the count is the buffer's, and +// the call goes to the library directly. +// CLEAN +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int fill(size_t n) { + char *WEAVEC_COUNTED_BY(16) WEAVEC_OWNED text = calloc(16, 1); + if (text == NULL) + return -1; + int written = lib_fill(text, n); + free(text); + return written; +} + +int main(void) { + printf("%d\n", fill(16)); + return 0; +} diff --git a/test/cases/foreign/end-past.c b/test/cases/foreign/end-past.c new file mode 100644 index 0000000..31a1890 --- /dev/null +++ b/test/cases/foreign/end-past.c @@ -0,0 +1,19 @@ +// RFC 0057 amendment 4: a contract's WEAVEC_ENDED_BY gives the bytes from +// the pointer to its end; safe code passes an end that lies in another +// object, and the span is compared with the bound before the library runs. +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +static char text[16]; +static char other[16]; + +__attribute__((noinline)) static int fill(char *WEAVEC_COUNTED_BY(16) from, char *WEAVEC_COUNTED_BY(0) end) { + return lib_fill_to(from, end); // TRAP: pointer-out-of-bounds +} + +int main(void) { + printf("%d %d\n", fill(text, &other[8]), other[0]); + return 0; +} diff --git a/test/cases/foreign/end-past_ok.c b/test/cases/foreign/end-past_ok.c new file mode 100644 index 0000000..f7c9892 --- /dev/null +++ b/test/cases/foreign/end-past_ok.c @@ -0,0 +1,19 @@ +// RFC 0057 amendment 4: the twin of end-past.c: the end is the object's +// own, and the call goes to the library directly. +// CLEAN +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +static char text[16]; +static char other[16]; + +__attribute__((noinline)) static int fill(char *WEAVEC_COUNTED_BY(16) from, char *WEAVEC_COUNTED_BY(0) end) { + return lib_fill_to(from, end); +} + +int main(void) { + printf("%d %d\n", fill(text, &text[16]), other[0]); + return 0; +} diff --git a/test/cases/foreign/guarded-caller.c b/test/cases/foreign/guarded-caller.c new file mode 100644 index 0000000..d76b2b0 --- /dev/null +++ b/test/cases/foreign/guarded-caller.c @@ -0,0 +1,18 @@ +// RFC 0057 §5: a guarded function's call through a contract is guarded as +// a library call is: the range the contract states is tested against the +// shadow before the library runs. +// FLAGS: -O2 +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((noinline)) static int fill(size_t n) { + char text[16]; + int written = lib_fill(text, n); // TRAP: stack-buffer-overflow + return written + text[0]; +} + +int main(void) { + printf("%d\n", fill(17)); + return 0; +} diff --git a/test/cases/foreign/guarded-caller_ok.c b/test/cases/foreign/guarded-caller_ok.c new file mode 100644 index 0000000..93b018c --- /dev/null +++ b/test/cases/foreign/guarded-caller_ok.c @@ -0,0 +1,17 @@ +// RFC 0057 §5: the twin of guarded-caller.c: the count is the buffer's. +// CLEAN +// FLAGS: -O2 +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((noinline)) static int fill(size_t n) { + char text[16]; + int written = lib_fill(text, n); + return written + text[0]; +} + +int main(void) { + printf("%d\n", fill(16)); + return 0; +} diff --git a/test/cases/foreign/in-out-count.c b/test/cases/foreign/in-out-count.c new file mode 100644 index 0000000..b0d705c --- /dev/null +++ b/test/cases/foreign/in-out-count.c @@ -0,0 +1,21 @@ +// RFC 0057 §3.3: a count the library reads and writes through a pointer +// (`WEAVEC_COUNTED_BY(*out_len)`): what it holds at the call is compared +// with the buffer's bound, here 8 bytes more than the buffer. +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((noinline)) static unsigned long pack(unsigned long room) { + unsigned char out[24]; + static const unsigned char in[32] = {1, 2, 3}; + unsigned long len = room; + if (lib_pack(out, &len, in, sizeof(in)) != 0) // TRAP: pointer-out-of-bounds + return 0; + return len + out[0]; +} + +int main(void) { + printf("%lu\n", pack(32)); + return 0; +} diff --git a/test/cases/foreign/in-out-count_ok.c b/test/cases/foreign/in-out-count_ok.c new file mode 100644 index 0000000..9833912 --- /dev/null +++ b/test/cases/foreign/in-out-count_ok.c @@ -0,0 +1,21 @@ +// RFC 0057 §3.3: the twin of in-out-count.c: the count is the room the +// buffer has, and the library says how much it used. +// CLEAN +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((noinline)) static unsigned long pack(unsigned long room) { + unsigned char out[24]; + static const unsigned char in[32] = {1, 2, 3}; + unsigned long len = room; + if (lib_pack(out, &len, in, sizeof(in)) != 0) + return 0; + return len + out[0]; +} + +int main(void) { + printf("%lu\n", pack(24)); + return 0; +} diff --git a/test/cases/foreign/inlined-caller.c b/test/cases/foreign/inlined-caller.c new file mode 100644 index 0000000..e6d5bf3 --- /dev/null +++ b/test/cases/foreign/inlined-caller.c @@ -0,0 +1,33 @@ +// RFC 0057 §8: a watched call inside a function that is inlined at two +// places, whose paths the optimizer joins, is still the call the report +// names when the library writes past what its contract gives. +// FLAGS: -O2 -fweavec-safe -fweavec-safe-checks=full +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((always_inline)) static inline int put(char *WEAVEC_COUNTED_BY(n) out, size_t n, int both, + size_t extra) { + int written = 0; + if (both) + written += lib_fill_past(out, n, 0); + written += lib_fill_past(out, n, extra); // TRAP: foreign-overflow + return written; +} + +__attribute__((noinline)) static int fill(int both, size_t extra) { + char text[16]; + char more[16]; + int written = put(text, sizeof(text), both, 0); + if (both) + written += put(more, sizeof(more), 0, extra); + else + written += put(text, sizeof(text), 1, extra); + return written + text[0]; +} + +int main(int argc, char **argv) { + (void)argv; + printf("%d %d\n", fill(argc > 1, 0), fill(argc == 1, 1)); + return 0; +} diff --git a/test/cases/foreign/inlined-caller_ok.c b/test/cases/foreign/inlined-caller_ok.c new file mode 100644 index 0000000..4516cfb --- /dev/null +++ b/test/cases/foreign/inlined-caller_ok.c @@ -0,0 +1,34 @@ +// RFC 0057 §8: the twin of inlined-caller.c: a watched call inside a +// function that is inlined at two places, whose paths the optimizer joins, +// keeps its contract on every path. +// CLEAN +// FLAGS: -O2 -fweavec-safe -fweavec-safe-checks=full +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((always_inline)) static inline int put(char *WEAVEC_COUNTED_BY(n) out, size_t n, int both, + size_t extra) { + int written = 0; + if (both) + written += lib_fill_past(out, n, 0); + written += lib_fill_past(out, n, extra); + return written; +} + +__attribute__((noinline)) static int fill(int both, size_t extra) { + char text[16]; + char more[16]; + int written = put(text, sizeof(text), both, 0); + if (both) + written += put(more, sizeof(more), 0, extra); + else + written += put(text, sizeof(text), 1, extra); + return written + text[0]; +} + +int main(int argc, char **argv) { + (void)argv; + printf("%d %d\n", fill(argc > 1, 0), fill(argc == 1, 0)); + return 0; +} diff --git a/test/cases/foreign/member-bound.c b/test/cases/foreign/member-bound.c new file mode 100644 index 0000000..bfcb945 --- /dev/null +++ b/test/cases/foreign/member-bound.c @@ -0,0 +1,24 @@ +// RFC 0057 §3.4: a member of the library's struct has the bound its +// contract gives it (WEAVEC_FOREIGN_FIELD); an index at the count stops. +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int member(size_t n, size_t at) { + struct lib_record record = {0}; + lib_record_make(&record, n); + if (record.data == NULL) + return -1; + record.data[at] = 6; // TRAP: pointer-out-of-bounds + int result = record.data[at]; + free(record.data); + record.data = NULL; + return result; +} + +int main(void) { + printf("%d\n", member(8, 8)); + return 0; +} diff --git a/test/cases/foreign/member-bound_ok.c b/test/cases/foreign/member-bound_ok.c new file mode 100644 index 0000000..a01ec1c --- /dev/null +++ b/test/cases/foreign/member-bound_ok.c @@ -0,0 +1,24 @@ +// RFC 0057 §3.4: the twin of member-bound.c: the index is inside the count. +// CLEAN +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int member(size_t n, size_t at) { + struct lib_record record = {0}; + lib_record_make(&record, n); + if (record.data == NULL) + return -1; + record.data[at] = 6; + int result = record.data[at]; + free(record.data); + record.data = NULL; + return result; +} + +int main(void) { + printf("%d\n", member(8, 7)); + return 0; +} diff --git a/test/cases/foreign/result-short.c b/test/cases/foreign/result-short.c new file mode 100644 index 0000000..44ddfff --- /dev/null +++ b/test/cases/foreign/result-short.c @@ -0,0 +1,24 @@ +// RFC 0057 §6: a result arrives with the bound its contract declares and +// is believed no further than the memory shows: the library returns half +// of the block the contract states, and the program stops where the result +// arrives. +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int last(size_t n, int honest) { + char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED block = lib_block(n, honest); // TRAP: heap-buffer-overflow + if (block == NULL) + return -1; + block[n - 1] = 5; + int result = block[n - 1]; + free(block); + return result; +} + +int main(void) { + printf("%d\n", last(32, 0)); + return 0; +} diff --git a/test/cases/foreign/result-short_ok.c b/test/cases/foreign/result-short_ok.c new file mode 100644 index 0000000..7627c75 --- /dev/null +++ b/test/cases/foreign/result-short_ok.c @@ -0,0 +1,23 @@ +// RFC 0057 §6: the twin of result-short.c: the block is what the contract +// states. +// CLEAN +// FLAGS: -O2 -fweavec-safe +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int last(size_t n, int honest) { + char *WEAVEC_COUNTED_BY(n) WEAVEC_OWNED block = lib_block(n, honest); + if (block == NULL) + return -1; + block[n - 1] = 5; + int result = block[n - 1]; + free(block); + return result; +} + +int main(void) { + printf("%d\n", last(32, 1)); + return 0; +} diff --git a/test/cases/foreign/wrote-past-local.c b/test/cases/foreign/wrote-past-local.c new file mode 100644 index 0000000..0043a87 --- /dev/null +++ b/test/cases/foreign/wrote-past-local.c @@ -0,0 +1,17 @@ +// RFC 0057 §6: as wrote-past.c for a local: the library writes past the 16 +// bytes its contract gives the argument, into the frame's redzone. +// FLAGS: -O2 -fweavec-safe -fweavec-safe-checks=full +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((noinline)) static int fill(size_t extra) { + char text[16]; + int written = lib_fill_past(text, sizeof(text), extra); // TRAP: foreign-overflow + return written + text[0]; +} + +int main(void) { + printf("%d\n", fill(1)); + return 0; +} diff --git a/test/cases/foreign/wrote-past-local_ok.c b/test/cases/foreign/wrote-past-local_ok.c new file mode 100644 index 0000000..d2b1e42 --- /dev/null +++ b/test/cases/foreign/wrote-past-local_ok.c @@ -0,0 +1,17 @@ +// RFC 0057 §6: the twin of wrote-past-local.c: nothing past the 16 bytes. +// CLEAN +// FLAGS: -O2 -fweavec-safe -fweavec-safe-checks=full +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include + +__attribute__((noinline)) static int fill(size_t extra) { + char text[16]; + int written = lib_fill_past(text, sizeof(text), extra); + return written + text[0]; +} + +int main(void) { + printf("%d\n", fill(0)); + return 0; +} diff --git a/test/cases/foreign/wrote-past.c b/test/cases/foreign/wrote-past.c new file mode 100644 index 0000000..0ab8463 --- /dev/null +++ b/test/cases/foreign/wrote-past.c @@ -0,0 +1,22 @@ +// RFC 0057 §6: a contract that is wrong. The library writes four bytes +// past the count its contract states; a checked build watches the bytes +// after what the contract gives and stops when the call returns. +// FLAGS: -O2 -fweavec-safe -fweavec-safe-checks=full +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int fill(size_t extra) { + char *WEAVEC_COUNTED_BY(24) WEAVEC_OWNED text = calloc(24, 1); + if (text == NULL) + return -1; + int written = lib_fill_past(text, 24, extra); // TRAP: foreign-overflow + free(text); + return written; +} + +int main(void) { + printf("%d\n", fill(4)); + return 0; +} diff --git a/test/cases/foreign/wrote-past_ok.c b/test/cases/foreign/wrote-past_ok.c new file mode 100644 index 0000000..5aa13d8 --- /dev/null +++ b/test/cases/foreign/wrote-past_ok.c @@ -0,0 +1,23 @@ +// RFC 0057 §6: the twin of wrote-past.c: the library writes what its +// contract states, and the checked build finds the bytes after it as it +// left them. +// CLEAN +// FLAGS: -O2 -fweavec-safe -fweavec-safe-checks=full +// UNITS: Inputs/lib.c +#include "Inputs/contracts.h" +#include +#include + +__attribute__((noinline)) static int fill(size_t extra) { + char *WEAVEC_COUNTED_BY(24) WEAVEC_OWNED text = calloc(24, 1); + if (text == NULL) + return -1; + int written = lib_fill_past(text, 24, extra); + free(text); + return written; +} + +int main(void) { + printf("%d\n", fill(0)); + return 0; +} diff --git a/unittests/Core/LibrarySpecTest.cpp b/unittests/Core/LibrarySpecTest.cpp index f061d6e..95a8c53 100644 --- a/unittests/Core/LibrarySpecTest.cpp +++ b/unittests/Core/LibrarySpecTest.cpp @@ -49,7 +49,7 @@ static std::string renderParam(const LibraryParam ¶m) { } switch (param.access) { case Access::None: - text = "none"; + text = param.handle ? "handle" : "none"; break; case Access::Read: text = "R"; @@ -69,7 +69,7 @@ static std::string renderParam(const LibraryParam ¶m) { text += " bytes=" + param.bytes->str(); if (param.count) text += " count=" + param.count->str(); - if (param.null == LibraryParam::Null::Allowed) + if (param.null == LibraryParam::Null::Allowed && !param.handle) text += " nullable"; if (param.null == LibraryParam::Null::AllowedIfZero) text += " nullable-if=" + (param.zeroTerm ? param.zeroTerm->str() : "?"); @@ -79,6 +79,8 @@ static std::string renderParam(const LibraryParam ¶m) { text += " reallocs"; if (param.owner) text += " owner"; + if (param.kept) + text += " kept"; return text; } @@ -98,6 +100,12 @@ static std::string renderResult(const LibraryEntry &entry) { case LibraryEntry::Result::Int: return entry.value ? "int value=" + entry.value->str() : "int"; case LibraryEntry::Result::Pointer: + if (entry.resultString) + return "ptr str"; + if (entry.resultBytes) + return "ptr bytes=" + entry.resultBytes->str(); + if (entry.resultOf) + return "ptr of=a" + std::to_string(*entry.resultOf); return entry.owned ? "ptr owned" : "ptr"; } return "?"; @@ -224,6 +232,9 @@ TEST(LibrarySpecTest, TermsParsePrintAndEvaluate) { EXPECT_EQ(roundTrip("a3-1"), "a3-1"); EXPECT_EQ(roundTrip("(a0+7)/8"), "(a0+7)/8"); EXPECT_EQ(roundTrip("a0*4/3"), "a0*4/3"); + EXPECT_EQ(roundTrip("a1 - a0"), "a1-a0"); + EXPECT_EQ(roundTrip("(a1-a0)/4"), "(a1-a0)/4"); + EXPECT_EQ(roundTrip("a1-a0-1"), "a1-a0-1"); std::string error; const auto sum = LibTerm::parse("a0+a1*a2", error); ASSERT_TRUE(sum.has_value()); @@ -231,7 +242,8 @@ TEST(LibrarySpecTest, TermsParsePrintAndEvaluate) { EXPECT_EQ(sum->operands[1].kind, LibTerm::Kind::Product); for (const char *bad : {"", "a", "a0+", "min(a0)", "a0 a1", "a256", "strlen(x)", "fmtlen(a1)", - "BUFSIZ", "a1-b", "x0", "a0/0", "a0/a1", "a0/-2"}) + "BUFSIZ", "a1-b", "x0", "a0/0", "a0/a1", "a0/-2", "4-a0", "a0*2-a1", + "a1-a256"}) EXPECT_FALSE(LibTerm::parse(bad, error).has_value()) << bad; const LibTerm::Values values{ @@ -251,6 +263,8 @@ TEST(LibrarySpecTest, TermsParsePrintAndEvaluate) { EXPECT_EQ(eval("(a0+7)/8"), 2); EXPECT_EQ(eval("(a0-17)/8"), -1); EXPECT_EQ(eval("a3"), std::nullopt); + // Two addresses: only the running program has them. + EXPECT_EQ(eval("a1-a0"), std::nullopt); EXPECT_EQ(eval("9223372036854775807+a0"), std::nullopt); EXPECT_EQ(eval("4611686018427387904*a1"), std::nullopt); } @@ -685,7 +699,7 @@ static constexpr auto HeapExpectations = std::to_array({ {"getline", "RW bytes=8 nullable owner, RW nullable, RW", "int", "wrapper=getline"}, {"getdelim", "RW bytes=8 nullable owner, RW nullable, int, RW", "int", - "wrapper=getdelim"}, + "wrapper=getdelim chk=__getdelim:0/1/2/3"}, {"tempnam", "R str nullable, R str nullable", "ptr owned", ""}, {"getcwd", "W bytes=a1 nullable, int", "ptr", "chk=__getcwd_chk:0/1/size"}, {"backtrace", "W bytes=a1*8, int", "int", ""}, @@ -735,13 +749,15 @@ static constexpr auto StringExpectations = std::to_array({ "chk=__strncpy_chk:0/1/2/size"}, {"stpcpy", "W bytes=strlen(a1)+1, R str", "ptr", "disjoint=0/1/strlen(a1)+1 wrapper=stpcpy " - "chk=__builtin___stpcpy_chk:0/1/size chk=__stpcpy_chk:0/1/size"}, + "chk=__builtin___stpcpy_chk:0/1/size chk=__stpcpy_chk:0/1/size " + "chk=__stpcpy:0/1"}, {"stpncpy", "W bytes=a2 nullable-if=a2, R bytes=min(a2,strlen(a1)+1) nullable-if=a2, " "int", "ptr", "disjoint=0/1/min(a2,strlen(a1)+1) chk=__builtin___stpncpy_chk:0/1/2/size " - "chk=__stpncpy_chk:0/1/2/size"}, + "chk=__stpncpy_chk:0/1/2/size " + "chk=__stpncpy:0/1/2"}, {"strcat", "RW str bytes=strlen(a0)+strlen(a1)+1, R str", "ptr", "disjoint=0/1/strlen(a0)+strlen(a1)+1 wrapper=strcat " "chk=__builtin___strcat_chk:0/1/size chk=__strcat_chk:0/1/size"}, @@ -779,7 +795,8 @@ static constexpr auto StringExpectations = std::to_array({ {"strspn", "R scan=1, R str", "int", ""}, {"strcspn", "R scan=1, R str", "int", ""}, {"strtok", "RW str nullable, R str", "ptr", "unshared"}, - {"strtok_r", "RW str nullable, R str, RW bytes=8", "ptr", ""}, + {"strtok_r", "RW str nullable, R str, RW bytes=8", "ptr", + "chk=__strtok_r:0/1/2"}, {"strsep", "RW, R str", "ptr", ""}, {"strerror", "int", "ptr", "unshared"}, {"strerror_r", "int, W bytes=a2 nullable-if=a2, int", "ptr", ""}, @@ -792,7 +809,7 @@ static constexpr auto StringExpectations = std::to_array({ {"bcopy", "R bytes=a2 nullable-if=a2, W bytes=a2 nullable-if=a2, int", "void", ""}, {"bcmp", "R bytes=a2 nullable-if=a2, R bytes=a2 nullable-if=a2, int", "int", - ""}, + "chk=__memcmpeq:0/1/2"}, {"index", "R str scan=1, int", "ptr", ""}, {"rindex", "R str, int", "ptr", ""}, {"strcasecmp", "R str, R str", "int", "wrapper=strcasecmp"}, @@ -818,9 +835,9 @@ static constexpr auto StdioExpectations = std::to_array({ {"popen", "R str, R str", "ptr", ""}, {"fflush", "RW nullable", "int", ""}, {"fpurge", "RW", "int", ""}, - {"setvbuf", "RW, W bytes=a3 nullable, int, int", "int", ""}, - {"setbuf", "RW, W nullable", "void", ""}, - {"setbuffer", "RW, W bytes=a2 nullable, int", "void", ""}, + {"setvbuf", "RW, W bytes=a3 nullable kept, int, int", "int", ""}, + {"setbuf", "RW, W bytes=1024 nullable kept", "void", ""}, + {"setbuffer", "RW, W bytes=a2 nullable kept, int", "void", ""}, {"setlinebuf", "RW", "void", ""}, {"fileno", "R", "int", ""}, {"fileno_unlocked", "R", "int", ""}, @@ -940,7 +957,7 @@ static constexpr auto StdlibExpectations = std::to_array({ {"secure_getenv", "R str", "ptr", ""}, {"setenv", "R str nullable, R str, int", "int", "unshared"}, {"unsetenv", "R str nullable", "int", "unshared"}, - {"putenv", "R str nullable", "int", "unshared"}, + {"putenv", "R str nullable kept", "int", "unshared"}, {"system", "R str nullable", "int", ""}, {"qsort", "RW bytes=a1*a2 nullable-if=a1*a2, int, int, fn", "void", "permutes"}, @@ -965,8 +982,8 @@ static constexpr auto StdlibExpectations = std::to_array({ {"mkdtemp", "RW str", "ptr", ""}, {"mktemp", "RW str", "ptr", ""}, {"rand_r", "RW", "int", ""}, - {"initstate", "int, W bytes=a2, int", "ptr", ""}, - {"setstate", "RW", "ptr", ""}, + {"initstate", "int, W bytes=a2 kept, int", "ptr", ""}, + {"setstate", "RW kept", "ptr", ""}, {"erand48", "RW bytes=6", "int", ""}, {"nrand48", "RW bytes=6", "int", ""}, {"jrand48", "RW bytes=6", "int", ""}, @@ -1154,7 +1171,7 @@ static constexpr auto UsersExpectations = std::to_array({ {"error", "int, int, R str, ...", "void", "printf=2/3"}, {"error_at_line", "int, int, R str nullable, int, R str, ...", "void", "printf=4/5"}, - {"openlog", "R str nullable, int, int", "void", ""}, + {"openlog", "R str nullable kept, int, int", "void", ""}, {"syslog", "int, R str, ...", "void", "printf=1/2 chk=__syslog_chk:0/_/1/2"}, {"vsyslog", "int, R str, other", "void", @@ -1287,7 +1304,7 @@ static constexpr auto SignalExpectations = std::to_array({ {"sem_init", "W, int, int", "int", ""}, {"sem_timedwait", "none, R", "int", ""}, {"sem_getvalue", "none, W", "int", ""}, - {"tsearch", "none nullable, RW nullable, fn", "ptr", ""}, + {"tsearch", "none nullable kept, RW nullable, fn", "ptr", ""}, {"tfind", "none nullable, R nullable, fn", "ptr", ""}, {"tdelete", "none nullable, RW nullable, fn", "ptr", ""}, {"lfind", "none nullable, R nullable, RW, int, fn", "ptr", ""}, @@ -1398,8 +1415,8 @@ static constexpr auto NetworkExpectations = std::to_array({ {"mq_unlink", "R str", "int", ""}, {"mq_send", "int, R bytes=a2 nullable-if=a2, int, int", "int", ""}, {"mq_receive", "int, W bytes=a2, int, W nullable", "int", ""}, - {"aio_read", "RW", "int", ""}, - {"aio_write", "RW", "int", ""}, + {"aio_read", "RW kept", "int", ""}, + {"aio_write", "RW kept", "int", ""}, {"aio_error", "R", "int", ""}, {"aio_return", "RW", "int", ""}, {"aio_suspend", "R bytes=a1*8, int, R nullable", "int", ""}, @@ -1481,7 +1498,7 @@ static constexpr auto WideExpectations = std::to_array({ {"wcstold", "R str, W bytes=8 nullable", "int", "wide"}, {"mbsinit", "R nullable", "int", "wide"}, {"mbrlen", "R bytes=min(a1,strlen(a0)+1) nullable, int, RW nullable", "int", - ""}, + "chk=__mbrlen:0/1/2"}, {"mbrtowc", "W nullable, R bytes=min(a2,strlen(a1)+1) nullable, int, RW nullable", "int", ""}, @@ -1547,18 +1564,18 @@ static constexpr auto WideExpectations = std::to_array({ // , , . static constexpr auto MathExpectations = std::to_array({ - {"frexp", "other, W", "int", ""}, - {"frexpf", "other, W", "int", ""}, - {"frexpl", "other, W", "int", ""}, - {"modf", "other, W", "int", ""}, - {"modff", "other, W", "int", ""}, - {"modfl", "other, W", "int", ""}, - {"remquo", "other, other, W", "int", ""}, - {"remquof", "other, other, W", "int", ""}, - {"remquol", "other, other, W", "int", ""}, - {"nan", "R str", "int", ""}, - {"nanf", "R str", "int", ""}, - {"nanl", "R str", "int", ""}, + {"frexp", "other, W", "int", "chk=__frexp:0/1"}, + {"frexpf", "other, W", "int", "chk=__frexpf:0/1"}, + {"frexpl", "other, W", "int", "chk=__frexpl:0/1"}, + {"modf", "other, W", "int", "chk=__modf:0/1"}, + {"modff", "other, W", "int", "chk=__modff:0/1"}, + {"modfl", "other, W", "int", "chk=__modfl:0/1"}, + {"remquo", "other, other, W", "int", "chk=__remquo:0/1/2"}, + {"remquof", "other, other, W", "int", "chk=__remquof:0/1/2"}, + {"remquol", "other, other, W", "int", "chk=__remquol:0/1/2"}, + {"nan", "R str", "int", "chk=__nan:0"}, + {"nanf", "R str", "int", "chk=__nanf:0"}, + {"nanl", "R str", "int", "chk=__nanl:0"}, {"sincos", "other, W, W", "void", ""}, {"sincosf", "other, W, W", "void", ""}, {"sincosl", "other, W, W", "void", ""}, @@ -1744,13 +1761,372 @@ static constexpr auto CxxExpectations = std::to_array({ }); // clang-format on +// RFC 0057 §4.3: the functions no guard needed a row for. +// clang-format off +static constexpr auto ContractExpectations = std::to_array({ + {"fclose", "handle", "int", ""}, + {"pclose", "handle", "int", ""}, + {"tmpfile", "", "ptr", ""}, + {"__srget", "handle", "int", ""}, + {"__swbuf", "int, handle", "int", ""}, + {"__svfscanf", "handle, R str, other", "int", "scanf=1/2"}, + {"__uflow", "handle", "int", ""}, + {"__overflow", "handle, int", "int", ""}, + {"atexit", "fn", "int", ""}, + {"at_quick_exit", "fn", "int", ""}, + {"ecvt", "other, int, W bytes=4, W bytes=4", "ptr str", "unshared"}, + {"fcvt", "other, int, W bytes=4, W bytes=4", "ptr str", "unshared"}, + {"l64a", "int", "ptr str", "unshared"}, + {"ptsname", "int", "ptr str", "unshared"}, + {"setkey", "R bytes=64", "void", "unshared"}, + {"encrypt", "RW bytes=64, int", "void", "unshared"}, + {"crypt", "R str, R str", "ptr str", "unshared"}, + {"getlogin", "", "ptr str", "unshared"}, + {"ttyname", "int", "ptr str", "unshared"}, + {"strsignal", "int", "ptr str", "unshared"}, + {"strerror_l", "int, handle", "ptr str", ""}, + {"strfromd", "W bytes=a1 nullable-if=a1, int, R str, other", "int", ""}, + {"strfromf", "W bytes=a1 nullable-if=a1, int, R str, other", "int", ""}, + {"strfroml", "W bytes=a1 nullable-if=a1, int, R str, other", "int", ""}, + {"memalign", "int, int", "ptr owned", ""}, + {"pvalloc", "int", "ptr owned", ""}, + {"malloc_usable_size", "handle", "int", ""}, + {"malloc_info", "int, handle", "int", ""}, + {"__error", "", "ptr", ""}, + {"__errno_location", "", "ptr", ""}, + {"__ctype_b_loc", "", "ptr", ""}, + {"__ctype_tolower_loc", "", "ptr", ""}, + {"__ctype_toupper_loc", "", "ptr", ""}, + {"setjmp", "W", "int", ""}, + {"_setjmp", "W", "int", ""}, + {"sigsetjmp", "W, int", "int", ""}, + {"__sigsetjmp", "W, int", "int", ""}, + {"longjmp", "R, int", "void", ""}, + {"_longjmp", "R, int", "void", ""}, + {"siglongjmp", "R, int", "void", ""}, + {"fegetenv", "W", "int", ""}, + {"feholdexcept", "W", "int", ""}, + {"fesetenv", "handle", "int", ""}, + {"feupdateenv", "handle", "int", ""}, + {"fegetexceptflag", "W, int", "int", ""}, + {"fesetexceptflag", "R, int", "int", ""}, + {"fetestexceptflag", "R, int", "int", ""}, + {"fegetmode", "W", "int", ""}, + {"fesetmode", "handle", "int", ""}, + {"canonicalize", "W, R", "int", ""}, + {"canonicalizef", "W, R", "int", ""}, + {"canonicalizel", "W, R", "int", ""}, + {"localeconv", "", "ptr", "unshared"}, + {"duplocale", "handle", "ptr", ""}, + {"freelocale", "handle", "int", ""}, + {"uselocale", "handle", "ptr", ""}, + {"nl_langinfo", "int", "ptr str", "unshared"}, + {"nl_langinfo_l", "int, handle", "ptr str", ""}, + {"catopen", "R str, int", "ptr", ""}, + {"catgets", "handle, int, int, R str", "ptr str", ""}, + {"catclose", "handle", "int", ""}, + {"isalnum_l", "int, handle", "int", ""}, + {"isalpha_l", "int, handle", "int", ""}, + {"isblank_l", "int, handle", "int", ""}, + {"iscntrl_l", "int, handle", "int", ""}, + {"isdigit_l", "int, handle", "int", ""}, + {"isgraph_l", "int, handle", "int", ""}, + {"islower_l", "int, handle", "int", ""}, + {"isprint_l", "int, handle", "int", ""}, + {"ispunct_l", "int, handle", "int", ""}, + {"isspace_l", "int, handle", "int", ""}, + {"isupper_l", "int, handle", "int", ""}, + {"isxdigit_l", "int, handle", "int", ""}, + {"tolower_l", "int, handle", "int", ""}, + {"toupper_l", "int, handle", "int", ""}, + {"__tolower_l", "int, handle", "int", ""}, + {"__toupper_l", "int, handle", "int", ""}, + {"iswalnum_l", "int, handle", "int", ""}, + {"iswalpha_l", "int, handle", "int", ""}, + {"iswblank_l", "int, handle", "int", ""}, + {"iswcntrl_l", "int, handle", "int", ""}, + {"iswdigit_l", "int, handle", "int", ""}, + {"iswgraph_l", "int, handle", "int", ""}, + {"iswlower_l", "int, handle", "int", ""}, + {"iswprint_l", "int, handle", "int", ""}, + {"iswpunct_l", "int, handle", "int", ""}, + {"iswspace_l", "int, handle", "int", ""}, + {"iswupper_l", "int, handle", "int", ""}, + {"iswxdigit_l", "int, handle", "int", ""}, + {"iswctype_l", "int, int, handle", "int", ""}, + {"towlower_l", "int, handle", "int", ""}, + {"towupper_l", "int, handle", "int", ""}, + {"towctrans", "int, handle", "int", ""}, + {"towctrans_l", "int, handle, handle", "int", ""}, + {"wctrans_l", "R str, handle", "ptr", ""}, + {"wctype_l", "R str, handle", "int", ""}, + {"wcscasecmp_l", "R str, R str, handle", "int", "wide"}, + {"wcsncasecmp_l", "R count=min(a2,strlen(a0)+1) nullable-if=a2, R count=min(a2,strlen(a1)+1) nullable-if=a2, int, handle", "int", "wide"}, + {"wcscoll_l", "R str, R str, handle", "int", "wide"}, + {"wcsxfrm_l", "W count=a2 nullable-if=a2, R str, int, handle", "int", "wide"}, + {"wcswcs", "R scan=strlen(a1), R str", "ptr", "wide"}, + {"wcstoimax", "R str, W bytes=8 nullable, int", "int", "wide chk=__isoc23_wcstoimax:0/1/2"}, + {"wcstoumax", "R str, W bytes=8 nullable, int", "int", "wide chk=__isoc23_wcstoumax:0/1/2"}, + {"closedir", "handle", "int", ""}, + {"fdopendir", "int", "ptr", ""}, + {"dlclose", "handle", "int", ""}, + {"dlerror", "", "ptr str", "unshared"}, + {"mlock", "handle, int", "int", ""}, + {"munlock", "handle, int", "int", ""}, + {"mprotect", "handle, int, int", "int", ""}, + {"msync", "handle, int, int", "int", ""}, + {"posix_madvise", "handle, int, int", "int", ""}, + {"iconv_close", "handle", "int", ""}, + {"getdate", "R str", "ptr", "unshared"}, + {"times", "W nullable", "int", ""}, + {"clock_getcpuclockid", "int, W bytes=4", "int", ""}, + {"timer_delete", "handle", "int", ""}, + {"timer_getoverrun", "handle", "int", ""}, + {"getpwent", "", "ptr", "unshared"}, + {"getpwuid", "int", "ptr", "unshared"}, + {"getgrent", "", "ptr", "unshared"}, + {"getgrgid", "int", "ptr", "unshared"}, + {"freeaddrinfo", "handle", "void", ""}, + {"gai_strerror", "int", "ptr str", ""}, + {"gethostent", "", "ptr", "unshared"}, + {"getnetbyaddr", "int, int", "ptr", "unshared"}, + {"getnetbyname", "R str", "ptr", "unshared"}, + {"getnetent", "", "ptr", "unshared"}, + {"getprotobynumber", "int", "ptr", "unshared"}, + {"getprotoent", "", "ptr", "unshared"}, + {"getservent", "", "ptr", "unshared"}, + {"inet_ntoa", "other", "ptr str", "unshared"}, + {"if_nameindex", "", "ptr", ""}, + {"if_freenameindex", "handle", "void", ""}, + {"freeifaddrs", "handle", "void", ""}, + {"getifmaddrs", "W bytes=8", "int", ""}, + {"freeifmaddrs", "handle", "void", ""}, + {"__cmsg_nxthdr", "R, R", "ptr", ""}, + {"hsearch", "other, int", "ptr", "unshared"}, + {"insque", "handle kept, handle", "void", ""}, + {"remque", "handle", "void", ""}, + {"twalk", "handle, fn", "void", ""}, + {"glob_b", "R str, int, fn, RW", "int", ""}, + {"scandir_b", "R str, W bytes=8, fn, fn", "int", ""}, + {"errc", "int, int, R str nullable, ...", "void", "printf=2/3 exits"}, + {"verrc", "int, int, R str nullable, other", "void", "printf=2/3 exits"}, + {"warnc", "int, R str nullable, ...", "void", "printf=1/2"}, + {"vwarnc", "int, R str nullable, other", "void", "printf=1/2"}, + {"err_set_exit", "fn", "void", ""}, + {"err_set_exit_b", "fn", "void", ""}, + {"err_set_file", "handle", "void", ""}, + {"backtrace_from_fp", "handle, W bytes=a2*8, int", "int", ""}, + {"backtrace_async", "W bytes=a1*8, int, W bytes=4 nullable", "int", ""}, + {"backtrace_image_offsets", "R bytes=a2*8, W bytes=a2*20, int", "void", ""}, + {"__darwin_check_fd_set_overflow", "int, handle, int", "int", ""}, + {"kevent64", "int, R bytes=a2*48 nullable-if=a2, int, W bytes=a4*48 nullable-if=a4, int, int, R nullable", "int", ""}, + {"epoll_pwait2", "int, W bytes=a2*12 nullable-if=a2, int, R nullable, R nullable", "int", ""}, + {"eventfd_read", "int, W bytes=8", "int", ""}, + {"posix_spawn_file_actions_init", "W", "int", ""}, + {"posix_spawn_file_actions_destroy", "RW", "int", ""}, + {"posix_spawn_file_actions_addclose", "RW, int", "int", ""}, + {"posix_spawn_file_actions_adddup2", "RW, int, int", "int", ""}, + {"posix_spawn_file_actions_addopen", "RW, int, R str, int, int", "int", ""}, + {"posix_spawn_file_actions_addchdir", "RW, R str", "int", ""}, + {"posix_spawn_file_actions_addfchdir", "RW, int", "int", ""}, + {"posix_spawnattr_init", "W", "int", ""}, + {"posix_spawnattr_destroy", "RW", "int", ""}, + {"posix_spawnattr_getflags", "R, W bytes=2", "int", ""}, + {"posix_spawnattr_getpgroup", "R, W bytes=4", "int", ""}, + {"posix_spawnattr_getsigdefault", "R, W", "int", ""}, + {"posix_spawnattr_getsigmask", "R, W", "int", ""}, + {"posix_spawnattr_getschedparam", "R, W", "int", ""}, + {"posix_spawnattr_getschedpolicy", "R, W bytes=4", "int", ""}, + {"posix_spawnattr_setflags", "RW, int", "int", ""}, + {"posix_spawnattr_setpgroup", "RW, int", "int", ""}, + {"posix_spawnattr_setsigdefault", "RW, R", "int", ""}, + {"posix_spawnattr_setsigmask", "RW, R", "int", ""}, + {"posix_spawnattr_setschedparam", "RW, R", "int", ""}, + {"posix_spawnattr_setschedpolicy", "RW, int", "int", ""}, + {"pthread_self", "", "int", ""}, + {"pthread_equal", "other, other", "int", ""}, + {"pthread_detach", "other", "int", ""}, + {"pthread_cancel", "other", "int", ""}, + {"pthread_kill", "other, int", "int", ""}, + {"pthread_exit", "handle kept", "void", ""}, + {"pthread_getspecific", "int", "ptr", ""}, + {"pthread_setspecific", "int, handle kept", "int", ""}, + {"tss_get", "int", "ptr", ""}, + {"tss_set", "int, handle kept", "int", ""}, + {"pthread_atfork", "fn, fn, fn", "int", ""}, + {"pthread_getschedparam", "other, W bytes=4 nullable, W nullable", "int", ""}, + {"pthread_setschedparam", "other, int, R", "int", ""}, + {"pthread_getcpuclockid", "other, W bytes=4", "int", ""}, + {"pthread_attr_getguardsize", "R, W bytes=8", "int", ""}, + {"pthread_attr_getinheritsched", "R, W bytes=4", "int", ""}, + {"pthread_attr_getschedparam", "R, W", "int", ""}, + {"pthread_attr_getschedpolicy", "R, W bytes=4", "int", ""}, + {"pthread_attr_getscope", "R, W bytes=4", "int", ""}, + {"pthread_attr_getstack", "R, W bytes=8, W bytes=8", "int", ""}, + {"pthread_attr_getstackaddr", "R, W bytes=8", "int", ""}, + {"pthread_attr_setguardsize", "RW, int", "int", ""}, + {"pthread_attr_setinheritsched", "RW, int", "int", ""}, + {"pthread_attr_setschedparam", "RW, R", "int", ""}, + {"pthread_attr_setschedpolicy", "RW, int", "int", ""}, + {"pthread_attr_setscope", "RW, int", "int", ""}, + {"pthread_attr_setstackaddr", "RW, handle", "int", ""}, + {"pthread_condattr_getpshared", "R, W bytes=4", "int", ""}, + {"pthread_condattr_setpshared", "RW, int", "int", ""}, + {"pthread_condattr_getclock", "R, W bytes=4", "int", ""}, + {"pthread_mutex_consistent", "RW", "int", ""}, + {"pthread_mutex_getprioceiling", "R, W bytes=4", "int", ""}, + {"pthread_mutex_setprioceiling", "RW, int, W bytes=4 nullable", "int", ""}, + {"pthread_mutexattr_getprioceiling", "R, W bytes=4", "int", ""}, + {"pthread_mutexattr_getprotocol", "R, W bytes=4", "int", ""}, + {"pthread_mutexattr_getpshared", "R, W bytes=4", "int", ""}, + {"pthread_mutexattr_getrobust", "R, W bytes=4", "int", ""}, + {"pthread_mutexattr_getpolicy_np", "R, W bytes=4", "int", ""}, + {"pthread_mutexattr_setprioceiling", "RW, int", "int", ""}, + {"pthread_mutexattr_setprotocol", "RW, int", "int", ""}, + {"pthread_mutexattr_setrobust", "RW, int", "int", ""}, + {"pthread_mutexattr_setpolicy_np", "RW, int", "int", ""}, + {"pthread_rwlock_timedrdlock", "RW, R", "int", ""}, + {"pthread_rwlock_timedwrlock", "RW, R", "int", ""}, + {"pthread_rwlockattr_init", "W", "int", ""}, + {"pthread_rwlockattr_destroy", "RW", "int", ""}, + {"pthread_rwlockattr_getpshared", "R, W bytes=4", "int", ""}, + {"pthread_rwlockattr_setpshared", "RW, int", "int", ""}, + {"pthread_rwlockattr_getkind_np", "R, W bytes=4", "int", ""}, + {"pthread_rwlockattr_setkind_np", "RW, int", "int", ""}, + {"pthread_barrierattr_init", "W", "int", ""}, + {"pthread_barrierattr_destroy", "RW", "int", ""}, + {"pthread_barrierattr_getpshared", "R, W bytes=4", "int", ""}, + {"pthread_barrierattr_setpshared", "RW, int", "int", ""}, + {"__pthread_register_cancel", "handle", "void", ""}, + {"__pthread_unregister_cancel", "handle", "void", ""}, + {"__pthread_unwind_next", "handle", "void", ""}, + {"sched_rr_get_interval", "int, W", "int", ""}, + {"__sched_cpualloc", "int", "ptr", ""}, + {"__sched_cpufree", "handle", "void", ""}, + {"__sched_cpucount", "int, R bytes=a0", "int", ""}, + {"sem_close", "none", "int", ""}, + {"sem_destroy", "none", "int", ""}, + {"sem_post", "none", "int", ""}, + {"sem_trywait", "none", "int", ""}, + {"sem_wait", "none", "int", ""}, + {"sigqueue", "int, int, other", "int", ""}, + {"__sysv_signal", "int, none nullable", "ptr", "handler"}, +}); +// clang-format on + +// RFC 0057 §3.4: the globals of the C library and their kinds. +// clang-format off +static constexpr auto GlobalExpectations = std::to_array>({ + {"stdin", "handle"}, + {"stdout", "handle"}, + {"stderr", "handle"}, + {"__stdinp", "handle"}, + {"__stdoutp", "handle"}, + {"__stderrp", "handle"}, + {"environ", "strings"}, + {"__environ", "strings"}, + {"tzname", "strings"}, + {"__tzname", "strings"}, + {"optarg", "str"}, + {"suboptarg", "str"}, + {"program_invocation_name", "str"}, + {"program_invocation_short_name", "str"}, + {"sys_errlist", "strings"}, + {"sys_siglist", "strings"}, + {"sys_signame", "strings"}, + {"_CurrentRuneLocale", "object"}, + {"_DefaultRuneLocale", "object"}, +}); +// clang-format on + +TEST(LibrarySpecTest, EveryGlobalRowMatchesItsExpectation) { + const LibrarySpec &table = LibrarySpec::shipped(); + for (const auto &[name, kind] : GlobalExpectations) { + const auto row = table.global(name); + ASSERT_TRUE(row.has_value()) << name; + EXPECT_EQ(*row, kind) << name; + } + EXPECT_EQ(table.globalCount(), GlobalExpectations.size()); + EXPECT_FALSE(table.global("errno").has_value()); +} + +// RFC 0057 §4.2: what the grammar gained for contracts. +TEST(LibrarySpecTest, ContractGrammar) { + const LibrarySpec spec = parseOk( + "open_it (r:str, handle, w:bytes(*a3), rw:bytes(8)) -> ptr:of(a1);\n" + "name_of (handle:kept) -> ptr:str;\n" + "bytes_of (handle, int) -> ptr:bytes(a1*4);\n" + "global the_log : handle;\n" + "global the_names : strings;\n"); + ASSERT_EQ(spec.entries().size(), 3U); + const LibraryEntry &open = spec.entries()[0]; + EXPECT_EQ(renderParams(open), "R str, handle, W bytes=*a3, RW bytes=8"); + EXPECT_EQ(renderResult(open), "ptr of=a1"); + EXPECT_TRUE(open.params[1].handle); + EXPECT_EQ(open.params[1].access, LibraryParam::Access::None); + EXPECT_EQ(open.params[1].null, LibraryParam::Null::Allowed); + EXPECT_EQ(renderParams(spec.entries()[1]), "handle kept"); + EXPECT_EQ(renderResult(spec.entries()[1]), "ptr str"); + EXPECT_EQ(renderResult(spec.entries()[2]), "ptr bytes=a1*4"); + EXPECT_EQ(spec.global("the_log"), "handle"); + EXPECT_EQ(spec.global("the_names"), "strings"); + EXPECT_FALSE(spec.global("open_it").has_value()); + + // `*aN` is the integer the argument points to when the call is made. + const LibTerm::Values values{ + .argument = [](unsigned) -> std::optional { + return std::nullopt; + }, + .stringLength = [](unsigned) -> std::optional { + return std::nullopt; + }, + .pointee = [](unsigned index) -> std::optional { + return index == 3 ? std::optional(40) : std::nullopt; + }}; + ASSERT_TRUE(open.params[2].bytes.has_value()); + EXPECT_EQ(open.params[2].bytes->evaluate(values), 40); + + // RFC 0057 amendment 4: the bytes from one pointer argument to another. + const LibrarySpec ended = + parseOk("fill_to (w:bytes(a1-a0):null-if-zero(a1-a0), handle) -> int;\n"); + ASSERT_EQ(ended.entries().size(), 1U); + ASSERT_TRUE(ended.entries()[0].params[0].bytes.has_value()); + const LibTerm &distance = *ended.entries()[0].params[0].bytes; + EXPECT_EQ(distance.kind, LibTerm::Kind::Distance); + EXPECT_EQ(distance.arg, 1U); + EXPECT_EQ(distance.value, 0); + EXPECT_EQ(renderParams(ended.entries()[0]), + "W bytes=a1-a0 nullable-if=a1-a0, handle"); + EXPECT_NE(parseError("f (w:bytes(a1-a0), int) -> int;\n") + .find("a1-a0 of parameter 0 names a non-pointer"), + std::string::npos); + EXPECT_NE( + parseError("f (w:bytes(a0-a2), handle) -> int;\n") + .find("argument a2 of parameter 0 is past the row's parameters"), + std::string::npos); + + EXPECT_NE(parseError("f (handle:null-ok) -> int;\n") + .find("'handle' takes no bytes, string or null flag"), + std::string::npos); + EXPECT_NE(parseError("f (handle:bytes(4)) -> int;\n") + .find("'handle' takes no bytes, string or null flag"), + std::string::npos); + EXPECT_NE(parseError("global g : pointer;\n") + .find("expected 'handle', 'str', 'strings' or 'object'"), + std::string::npos); + EXPECT_NE(parseError("global g : str;\nglobal g : str;\n") + .find("two rows for the global"), + std::string::npos); +} + TEST(LibrarySpecTest, EveryRowMatchesItsIndependentExpectation) { const std::vector> tables = { - HeapExpectations, StringExpectations, StdioExpectations, - StdlibExpectations, UnistdExpectations, SystemExpectations, - UsersExpectations, ThreadExpectations, SignalExpectations, - NetworkExpectations, WideExpectations, MathExpectations, - BuiltinExpectations, ExitExpectations, CxxExpectations, + HeapExpectations, StringExpectations, StdioExpectations, + StdlibExpectations, UnistdExpectations, SystemExpectations, + UsersExpectations, ThreadExpectations, SignalExpectations, + NetworkExpectations, WideExpectations, MathExpectations, + BuiltinExpectations, ExitExpectations, CxxExpectations, + ContractExpectations, }; std::map rows; std::map overloads;