Skip to content

Commit 34ddc48

Browse files
committed
New challenge: Verify the safety of CString
1 parent 6079edc commit 34ddc48

2 files changed

Lines changed: 231 additions & 0 deletions

File tree

‎doc/src/SUMMARY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,4 @@
4848
- [29: Safety of `boxed`](./challenges/0029-boxed.md)
4949
- [30: Safety and Correctness of Integer Logarithms](./challenges/0030-integer-logarithms.md)
5050
- [31: Verify the safety of `BinaryHeap` functions](./challenges/0031-binary-heap.md)
51+
- [34: Safety of `CString`, the owned C string](./challenges/0034-cstring.md)

‎doc/src/challenges/0034-cstring.md‎

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
# Challenge 34: Safety of `CString`, the owned C string
2+
3+
- **Status:** *Open*
4+
- **Solution:** *Option field to point to the PR that solved this challenge.*
5+
- **Tracking Issue:** [#NNN](https://github.com/model-checking/verify-rust-std/issues/NNN)
6+
- **Start date:** *YYYY/MM/DD*
7+
- **Reward:** *TBD*
8+
9+
-------------------
10+
11+
## Goal
12+
13+
Verify the safety of `CString` and its related types in
14+
[c_str.rs](https://github.com/model-checking/verify-rust-std/blob/main/library/alloc/src/ffi/c_str.rs)
15+
(`alloc::ffi::c_str`): every constructor, conversion and view must establish and preserve the
16+
representation invariant of an owned C string — the buffer is at least one byte long, its last byte
17+
is `0`, and it contains no other `0` byte — for byte vectors of arbitrary length.
18+
19+
## Motivation
20+
21+
`CString` is the owned counterpart of `CStr`: it is how safe Rust code manufactures a C string to
22+
hand to foreign code, and its whole contract is the invariant above. Safe code that later calls
23+
`as_ptr`, `CStr::from_ptr` or any C function trusts that the buffer really holds exactly one nul
24+
byte and that it sits at the end. The file enforces that invariant with unchecked code in several
25+
places:
26+
27+
- The safe constructors `CString::new` and `CString::from_vec_with_nul` scan with `core::slice::memchr`
28+
and then build the value through the private unchecked constructors; a wrong scan result, or a
29+
wrong branch on it, lets safe code create a `CString` with an interior nul or without a terminator.
30+
- `as_bytes` and the `Drop` implementation index the buffer with `get_unchecked`, justified only by
31+
the invariant (`len >= 1`).
32+
- Ownership crosses raw pointers: `into_raw` / `from_raw` hand the `Box<[u8]>` to C and take it back,
33+
recomputing the length with the C library's `strlen`; `into_boxed_c_str`, `From<Box<CStr>>` and the
34+
`Arc<CStr>` / `Rc<CStr>` conversions cast between `Box<[u8]>`, `Box<CStr>` and the reference-counted
35+
types with `Box::from_raw` / `Arc::from_raw` / `Rc::from_raw`.
36+
- `From<Vec<NonZero<u8>>>` reinterprets the vector's allocation through `Vec::into_raw_parts` and
37+
`Vec::from_raw_parts`, relying on `NonZero<u8>` and `u8` having the same layout.
38+
39+
[Challenge 13](0013-cstr.md) covers the borrowed half, `core::ffi::CStr`, and its in-tree proofs are
40+
bounded. No challenge lists a function of `alloc::ffi::c_str`, so none of the code above is covered.
41+
42+
## Description
43+
44+
`CString` is a single-field struct wrapping `Box<[u8]>`. The file also defines the error types
45+
`NulError`, `FromVecWithNulError` and `IntoStringError`, the `ToOwned` implementation for `CStr`,
46+
two inherent methods on `CStr` that need allocation (`to_string_lossy`, `into_c_string`), and the
47+
conversions between `CString`, `Box<CStr>`, `Cow<CStr>`, `Arc<CStr>`, `Rc<CStr>`, `Vec<u8>`,
48+
`Vec<NonZero<u8>>` and `String`. There are no loops in the file: the nul scan is delegated to
49+
`core::slice::memchr`, and copying is delegated to `Vec` and `Box`. The unsafe functions are
50+
`from_vec_unchecked`, `from_vec_with_nul_unchecked` and `from_raw` (plus the two private helpers
51+
they share with the safe constructors). `CString::new` is generic over `Into<Vec<u8>>` and is
52+
specialized for byte and string slices.
53+
54+
The following are out of scope:
55+
56+
- Methods of `core::ffi::CStr` itself (Challenge 13), including what a caller can do with the
57+
`&CStr` views this file returns. What this challenge must show is that the calls this file makes
58+
into `core` (for example `CStr::from_bytes_with_nul_unchecked` in `as_c_str`) satisfy their
59+
preconditions, and that the views have the stated bytes.
60+
- The internals of `Vec`, `Box`, `String`, `Arc` and `Rc` (their own challenges), beyond the calls
61+
this file makes with raw pointers.
62+
- Formatting: `Debug` for `CString` and the `Display` implementations of the error types only
63+
forward to `core::fmt` and to `CStr`'s formatting and contain no unsafe code of their own beyond
64+
the views covered below.
65+
- What foreign code does with a pointer from `into_raw` while it owns it. The contract of
66+
`from_raw` states what the caller must guarantee when the pointer comes back.
67+
68+
### Assumptions
69+
70+
- `core::slice::memchr` does the nul scan, and its first-occurrence semantics is what the
71+
constructors' `Ok`/`Err` decisions rest on. A solution may treat that semantics in either of two
72+
ways, and must say which: prove a first-index contract for the implementation its tool executes
73+
(with `cfg(kani)`, the byte-by-byte loop), or state it as an assumption, name the model or bound
74+
that replaces the scan in its unbounded proofs, and prove the scan decisions exactly against the
75+
real function on bounded inputs whose bound exceeds every behavior class the decision
76+
distinguishes. The first way needs a quantified postcondition, which at the time of writing Kani
77+
can state (`-Z quantifiers` is already a CI flag) but its default SAT backend ignores for
78+
symbolic bounds; that tooling gap is why the second way is offered, and it must still not leave
79+
any `Ok`/`Err` branch, error position, or invariant clause unproved. Re-verifying the
80+
word-at-a-time implementation is not required either way.
81+
- `CString::from_raw` recomputes the length with the C `strlen`. A solution may assume that, for a
82+
pointer satisfying the `from_raw` contract, `strlen` returns the index of the first nul byte, and
83+
must state how its tool models the extern function and why that model is sound for such pointers.
84+
- Two functions evaluate C string literals in their own bodies (`Default for Box<CStr>` and
85+
`Default for Rc<CStr>` return `Box::from(c"")` / `Rc::from(c"")`), and one through a callee
86+
(`Default for CString` calls `Default` for `&CStr`, which returns `c""` in `core`). At the time
87+
of writing Kani cannot evaluate C string literals
88+
([kani#2549](https://github.com/model-checking/kani/issues/2549)). A Kani solution may stub that
89+
one constant in `core` with the identical value built from a byte string, and may cover the two
90+
impls whose bodies hold the literal by proving the constructions they perform on the empty
91+
`CStr`, provided it says so. A tool that evaluates the literals needs neither allowance.
92+
- `Vec`, `Box`, `String`, `Arc`, `Rc` and the UTF-8 validation in `core::str` may be trusted
93+
through their documented behavior or existing verified contracts, listed in the solution.
94+
Allocation failure is out of scope, as in the general rules; a capacity-overflow panic on an
95+
input whose length is within the limits below is not acceptable, because no valid slice or
96+
vector has length above `isize::MAX`.
97+
- Proofs need only run on the 64-bit configuration that the repository's CI builds.
98+
- If the verification tool limits the size of one memory object, a solution may assume that the
99+
byte vector is no longer than that limit. It must state the limit and show that it comes from
100+
the tool. For example, with the `--object-bits 12` that CI passes to CBMC, Kani's pointer model
101+
keeps 52 bits for the offset inside an object, so a Kani solution may limit vectors to
102+
2^51 - 1 bytes. A length bound chosen in a harness for any other reason is not acceptable.
103+
104+
### Success Criteria
105+
106+
The verification must be unbounded where it states the absence of undefined behavior, byte
107+
preservation, lengths, and the invariant of values the harnesses generate: it must hold for byte
108+
vectors and slices of every length (up to the stated tool limit), including the empty input
109+
wherever the function accepts one, with no fixed-size input arrays and no unwinding bound on any
110+
input-length scan. The exceptions are the places whose exact behavior runs a whole-buffer scan or conversion whose
111+
symbolic-length cost at the current tool pins exceeds the CI verifier budgets, each of which a
112+
solution may instead prove on bounded inputs against the real code, with unwinding assertions
113+
checked and the bound exceeding every behavior class distinguished: the scan decisions (which
114+
branch `new` and `from_vec_with_nul` take, the exact error position, the fidelity of the
115+
invariant predicate, and the contract proofs whose `ensures` evaluates that predicate, under the
116+
second `memchr` route above); the UTF-8 functions `into_string`, `TryFrom<CString> for String`
117+
and `CStr::to_string_lossy` (empty, ASCII, multi-byte, invalid and truncated sequences are the
118+
classes); and byte-exactness plus drops for the copying shared-ownership conversions
119+
(`Arc`/`Rc`/`Box` from `CString`/`&CStr`/`&mut CStr`/`Cow`), whose in-file unsafe step is a raw
120+
pointer cast. For each exception the same functions must still be shown memory-safe at every
121+
length — for the conversions, the lengths they return and the terminator must also be pinned at
122+
every length — and the solution must list what it bounded and why. A solution whose tool proves
123+
any of these at every length within budget needs no bound there. There are no loops in this file
124+
itself.
125+
126+
1. State the representation invariant of `CString` (length at least 1, last byte `0`, no other
127+
`0` byte) as a checked predicate — for a Kani solution, by implementing the `Invariant` trait
128+
for `CString`, mirroring the existing implementation for `&CStr` — and show that the predicate
129+
accepts exactly the byte sequences that end with a single nul byte and contain no other.
130+
131+
2. Write and prove the safety contracts of the following unsafe functions. Each `requires` must be
132+
what the function's `# Safety` text requires, and each `ensures` must pin the result's bytes,
133+
not merely restate the invariant:
134+
135+
| Function | Location |
136+
|---------|---------|
137+
| `CString::from_vec_unchecked` | `alloc::ffi::c_str` |
138+
| `CString::from_vec_with_nul_unchecked` | `alloc::ffi::c_str` |
139+
| `CString::from_raw` | `alloc::ffi::c_str` |
140+
141+
Specifically: `from_vec_unchecked(v)` requires that `v` contains no `0` byte and ensures a
142+
valid `CString` whose bytes are `v` followed by one `0`; `from_vec_with_nul_unchecked(v)`
143+
requires `v.len() >= 1`, last byte `0` and no other `0`, and ensures a valid `CString` whose
144+
bytes are exactly `v`; `from_raw(ptr)` requires the documented conditions (the pointer came
145+
from `CString::into_raw`, the length was not modified, it is not dangling and is exclusively
146+
owned again) and ensures the reconstructed `CString` has the bytes the pointer denoted, so
147+
that `from_raw(into_raw(cs))` has the same bytes as `cs`. The contract annotations state the
148+
contract at every length; under the second `memchr` route their proofs may be among the
149+
bounded scan-decision proofs, and the `into_raw`/`from_raw` round trip must then additionally
150+
be shown memory-safe and byte-preserving at every length.
151+
152+
3. Prove the absence of undefined behavior, and the exact byte-level behavior stated below, for
153+
the following safe functions, for inputs of arbitrary length and content:
154+
155+
| Function | Location |
156+
|---------|---------|
157+
| `CString::new` (for `Vec<u8>`, `&[u8]`, `&mut [u8]` and `&str` inputs) | `alloc::ffi::c_str` |
158+
| `CString::from_vec_with_nul` | `alloc::ffi::c_str` |
159+
| `CString::into_raw` | `alloc::ffi::c_str` |
160+
| `CString::into_string` | `alloc::ffi::c_str` |
161+
| `CString::into_bytes`, `CString::into_bytes_with_nul` | `alloc::ffi::c_str` |
162+
| `CString::as_bytes`, `CString::as_bytes_with_nul`, `CString::as_c_str` | `alloc::ffi::c_str` |
163+
| `CString::into_boxed_c_str` | `alloc::ffi::c_str` |
164+
| `NulError::nul_position`, `NulError::into_vec` | `alloc::ffi::c_str` |
165+
| `FromVecWithNulError::as_bytes`, `FromVecWithNulError::into_bytes` | `alloc::ffi::c_str` |
166+
| `IntoStringError::into_cstring`, `IntoStringError::utf8_error` | `alloc::ffi::c_str` |
167+
| `CStr::to_string_lossy`, `CStr::into_c_string` | `alloc::ffi::c_str` |
168+
| `Drop for CString` | `alloc::ffi::c_str` |
169+
170+
4. Prove the same for the following trait implementations:
171+
172+
| Trait implementation | Location |
173+
|---------|---------|
174+
| `Deref for CString`, `Borrow<CStr> for CString`, `AsRef<CStr> for CString`, `Index<RangeFull> for CString` | `alloc::ffi::c_str` |
175+
| `Default for CString`, `Clone for CString`, `Default for Box<CStr>`, `Clone for Box<CStr>`, `Default for Rc<CStr>` | `alloc::ffi::c_str` |
176+
| `From<&CStr> for CString`, `ToOwned for CStr` (both `to_owned` and both branches of `clone_into`) | `alloc::ffi::c_str` |
177+
| `From<Box<CStr>> for CString`, `From<CString> for Box<CStr>` | `alloc::ffi::c_str` |
178+
| `From<Cow<CStr>> for CString`, `From<CString> for Cow<CStr>`, `From<&CString> for Cow<CStr>`, `From<&CStr> for Cow<CStr>` | `alloc::ffi::c_str` |
179+
| `From<Vec<NonZero<u8>>> for CString` | `alloc::ffi::c_str` |
180+
| `FromStr for CString`, `TryFrom<CString> for String` | `alloc::ffi::c_str` |
181+
| `From<CString> for Vec<u8>` | `alloc::ffi::c_str` |
182+
| `From<CString> for Arc<CStr>`, `From<&CStr> for Arc<CStr>`, `From<&mut CStr> for Arc<CStr>` | `alloc::ffi::c_str` |
183+
| `From<CString> for Rc<CStr>`, `From<&CStr> for Rc<CStr>`, `From<&mut CStr> for Rc<CStr>` | `alloc::ffi::c_str` |
184+
| `From<&CStr> for Box<CStr>`, `From<&mut CStr> for Box<CStr>`, `From<Cow<CStr>> for Box<CStr>` | `alloc::ffi::c_str` |
185+
| The `PartialEq` implementations between `CString`, `CStr` and `Cow<CStr>` | `alloc::ffi::c_str` |
186+
187+
In addition, prove the following properties, which are what make the unchecked operations inside
188+
the safe functions correct. The `Ok`/`Err` decisions and the returned bytes must be pinned exactly,
189+
against the input bytes and not merely against the invariant predicate:
190+
191+
* `CString::new(t)` returns `Ok` exactly when the input bytes contain no `0`; the result's bytes
192+
are then the input bytes followed by one `0`. On `Err(e)`, `e.nul_position()` is the index of
193+
the first `0` byte and `e.into_vec()` returns the input bytes.
194+
* `CString::from_vec_with_nul(v)` returns `Ok` exactly when `v` has exactly one `0` byte and it is
195+
the last byte; the result's bytes are then `v`. On `Err(e)`, `e.as_bytes()` and `e.into_bytes()`
196+
return `v`. The empty vector is an `Err`.
197+
* `as_bytes()` returns the buffer without its last byte and `as_bytes_with_nul()` the whole
198+
buffer; `into_bytes()` and `into_bytes_with_nul()` return the same two byte sequences as owned
199+
vectors. `as_c_str()`, and the `Deref`, `Borrow`, `AsRef` and `Index` views, have the
200+
nul-terminated bytes of the buffer.
201+
* `into_boxed_c_str()` preserves the bytes, and `CString::from(boxed)` and `boxed.into_c_string()`
202+
are its inverse: the round trip in either direction preserves the bytes exactly.
203+
* `into_string()` returns `Ok(s)` exactly when the bytes without the terminator are valid UTF-8,
204+
and then `s` holds those bytes; on `Err(e)`, `e.into_cstring()` returns a `CString` with the
205+
original bytes and `e.utf8_error()` is the UTF-8 error of those bytes.
206+
* `CString::from(v)` for `v: Vec<NonZero<u8>>` has the bytes of `v` followed by one `0`, including
207+
for the empty vector.
208+
* `to_owned()` and `clone_into` produce a `CString` with the source `CStr`'s nul-terminated
209+
bytes, in both branches of `clone_into` (equal length and different length), and `Default`
210+
produces the empty `CString`, a single `0` byte.
211+
* `CStr::to_string_lossy` on a `CStr` equals `String::from_utf8_lossy` of its bytes without the
212+
terminator (borrowed exactly when they are valid UTF-8).
213+
* The `Arc<CStr>`, `Rc<CStr>`, `Box<CStr>` and `Cow<CStr>` conversions preserve the nul-terminated
214+
bytes, and the `PartialEq` implementations agree with equality of those bytes.
215+
* Dropping any `CString`, including the empty one, is free of undefined behavior.
216+
217+
All proofs must automatically ensure the absence of the following undefined behaviors [ref](https://github.com/rust-lang/reference/blob/142b2ed77d33f37a9973772bd95e6144ed9dce43/src/behavior-considered-undefined.md):
218+
219+
* Accessing (loading from or storing to) a place that is dangling or based on a misaligned
220+
pointer: the `get_unchecked` in `as_bytes` and in `Drop`, the `ptr::read` in the private
221+
`into_inner`, and the `Box::from_raw`, `Arc::from_raw`, `Rc::from_raw` and
222+
`Vec::from_raw_parts` calls, including freeing an allocation with a layout different from the
223+
one it was created with.
224+
* Producing an invalid value: a `CString` or `&CStr` whose bytes do not end with exactly one
225+
nul byte, or a `Vec<u8>` reinterpreted from a `Vec<NonZero<u8>>` allocation with the wrong
226+
length or capacity.
227+
* Invoking undefined behavior via compiler intrinsics.
228+
229+
Note: All solutions to verification challenges need to satisfy the criteria established in the
230+
[challenge book](../general-rules.md) in addition to the ones listed above.

0 commit comments

Comments
 (0)