Skip to content

Commit 254f7df

Browse files
committed
New challenge: safety of core::slice::rotate (36)
Proposes Challenge 36 and adds its book entry. Documentation only: doc/src/challenges/0036-slice-rotate.md and one SUMMARY.md line.
1 parent 6079edc commit 254f7df

2 files changed

Lines changed: 136 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+
- [36: Verify the safety of `core::slice::rotate`](./challenges/0036-slice-rotate.md)
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Challenge 36: Verify the safety of `core::slice::rotate`
2+
3+
- **Status:** *Open*
4+
- **Solution:** *Option field to point to the PR that solved this challenge.*
5+
- **Tracking Issue:** *Link to issue*
6+
- **Start date:** *2026/11/17*
7+
- **Reward:** *TBD*
8+
9+
-------------------
10+
11+
## Goal
12+
13+
Verify the safety of the in-place slice rotation implementation in
14+
[rotate.rs](https://github.com/model-checking/verify-rust-std/blob/main/library/core/src/slice/rotate.rs),
15+
which backs `<[T]>::rotate_left` and `<[T]>::rotate_right`, for arbitrary rotation sizes and for generic
16+
`T`, and verify that it actually rotates.
17+
18+
## Motivation
19+
20+
`rotate_left` and `rotate_right` are safe, stable (and now `const`) slice methods used throughout the
21+
standard library and by user code. All of their work is done by one private unsafe function,
22+
`ptr_rotate`, which picks one of three raw-pointer algorithms at run time according to the size of `T`
23+
and the split point:
24+
25+
- `ptr_rotate_memmove`, which parks the smaller half in a 256-byte `MaybeUninit` stack buffer and uses
26+
`ptr::copy` / `ptr::copy_nonoverlapping`;
27+
- `ptr_rotate_gcd`, the juggling algorithm, which walks the cycles of the permutation
28+
`i -> i + right (mod left + right)` with `read` / `replace` / `write`, computing the number of cycles
29+
(the gcd) as a side effect of the first cycle;
30+
- `ptr_rotate_swap`, the Gries--Mills block-swap algorithm, which repeatedly applies
31+
`ptr::swap_nonoverlapping` to adjacent blocks whose sizes are the residues of a Euclidean algorithm.
32+
33+
The safety argument at each pointer operation rests on arithmetic facts that are written only in prose:
34+
that the gcd walk never leaves `[0, left + right)` (the `[long-safety-expl]` comments), that the value
35+
computed as a side effect really is the cycle count and so bounds the starting offsets of the remaining
36+
cycles, and that the block swaps stay inside the range while `mid` walks back and forth. A mistake of one
37+
in any of these reads or writes an element outside the slice that safe code handed to `rotate_left`, or
38+
duplicates or loses an element of a type with a destructor. We know of no soundness bug reported against
39+
this file; the case for the challenge is that the argument is subtle, serves a safe API, and has no
40+
machine-checked statement.
41+
42+
## Description
43+
44+
`ptr_rotate(left, mid, right)` rotates the range `[mid - left, mid + right)` so that the element at
45+
`mid` becomes the first. It returns at once for zero-sized `T` and for a zero split. Otherwise, unless
46+
the crate is built with `optimize_for_size`, it uses the memmove strategy when the smaller side fits in
47+
the stack buffer (`min(left, right) <= size_of::<[usize; 32]>() / size_of::<T>()`), else the gcd strategy
48+
when `left + right < 24` or `size_of::<T>() > size_of::<[usize; 4]>()`, else the block-swap strategy.
49+
Its only callers are `rotate_left` and `rotate_right` in `core::slice`, which pass the length checks of
50+
the safe API. The file also contains a `const`-compatible `const_min`.
51+
52+
The following are out of scope:
53+
54+
- The rotation-like block moves inside `core::slice::sort` (they do not call this file).
55+
- `rotate_left` / `rotate_right` panic behavior for a split larger than the length (it is a plain
56+
`assert!` before any unsafe code; a proof of `ptr_rotate` under its precondition covers the unsafe
57+
part of both methods).
58+
- Performance of the strategy choice.
59+
60+
No existing challenge lists a function of `core::slice::rotate`. The primitives it uses
61+
(`ptr::copy_nonoverlapping`, `ptr::swap_nonoverlapping`, `<*mut T>::replace`) are targets of
62+
[Challenge 2](0002-intrinsics-memory.md) and [Challenge 3](0003-pointer-arithmentic.md); their
63+
verification is not repeated here.
64+
65+
### Assumptions
66+
67+
- `core::ptr` intrinsics and `core::mem::MaybeUninit` may be assumed correct, and their existing
68+
verified contracts may be reused. Deductive tools may rely on their own specifications of these.
69+
- The safety precondition of each function is the one in its `# Safety` documentation: the range
70+
`[mid - left, mid + right)` is valid for reading and writing elements of `T`. For non-zero-sized `T`
71+
this includes the usual requirement that the byte size of the range does not exceed `isize::MAX`.
72+
A contract may add a side condition only where the function is in fact never called without it and
73+
the condition is recorded next to the contract; in particular the gcd and block-swap strategies are
74+
only ever called with `left > 0`, `right > 0` and non-zero-sized `T`, and the memmove strategy only
75+
when the smaller side fits in its buffer.
76+
- Proofs must cover every strategy, including the branches taken when the crate is built with
77+
`optimize_for_size` (in that configuration only the block-swap strategy runs, so proving each
78+
strategy under its own precondition covers both configurations).
79+
- No user code runs during a rotation (`T` is moved, never dropped or cloned by the rotation itself),
80+
so unwinding need not be modeled. Dropping the rotated elements afterwards must still be safe: no
81+
element may be duplicated or lost.
82+
83+
### Success Criteria
84+
85+
Write and prove a safety contract for each of the following unsafe functions, with the precondition
86+
above (restricted as recorded for the three strategies), stating that the range is still valid for
87+
reading and writing afterwards:
88+
89+
| Function | Location |
90+
|---------|---------|
91+
| `ptr_rotate` | `core::slice::rotate` |
92+
| `ptr_rotate_memmove` | `core::slice::rotate` |
93+
| `ptr_rotate_gcd` | `core::slice::rotate` |
94+
| `ptr_rotate_swap` | `core::slice::rotate` |
95+
96+
Prove the absence of undefined behavior in these functions, including the early returns for
97+
zero-sized `T` and for `left == 0` or `right == 0`, and all three dispatch branches of
98+
`ptr_rotate`. For `ptr_rotate` on inputs that take the memmove branch, and for
99+
`ptr_rotate_memmove` itself, this must hold for arbitrary `left` and `right` (unbounded: no fixed
100+
bound on `left + right` other than the one in the precondition). For the gcd and block-swap
101+
strategies it must hold for every split with `left + right <= B`, with `B >= 24` stated in the
102+
solution (the dispatcher's whole small-total region for the gcd strategy), for the reason given
103+
under functional correctness below; a proof for arbitrary `left` and `right` exceeds this
104+
criterion and is welcome. `const_min` is safe code with no unsafe operations; its result is the
105+
smaller of its arguments, which the dispatch proof may rely on.
106+
107+
The verification must hold for generic `T` (what satisfies this clause is to be decided in
108+
[issue #734](https://github.com/model-checking/verify-rust-std/issues/734)). In particular it must
109+
cover zero-sized `T`, sizes that do and do not divide the memmove buffer, alignments above `usize`,
110+
elements larger than the buffer, types with a validity invariant (such as `NonZero`), and types with a
111+
destructor, for each of which the safety argument takes a different branch somewhere in the file.
112+
113+
Prove functional correctness of the rotation: after `ptr_rotate(left, mid, right)`, the element at
114+
each position `j` of `[mid - left, mid + right)` is the element previously at position
115+
`(j + left) mod (left + right)` of that range. This must be proved for each of the three strategies.
116+
For the memmove strategy it must be proved for arbitrary `left` and `right`. For the gcd and
117+
block-swap strategies, whose loop invariants in a bounded model checker cannot name the input
118+
arrangement of a generic `T`, it is enough to prove it for every `left` and `right` with
119+
`left + right <= B`, where `B` is stated in the solution and `B >= 24` (so the whole input range in
120+
which the dispatcher prefers the gcd strategy for small totals is included), for element types whose
121+
values can be told apart. Solutions that prove the rotation postcondition for arbitrary `left` and
122+
`right` for all three strategies (for example with ghost state in a deductive tool) are welcome and
123+
exceed this criterion. The same bound `B` may be used for the safety proof of those two strategies, as stated above.
124+
125+
### List of UBs
126+
127+
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):
128+
129+
* Accessing (loading from or storing to) a place that is dangling or based on a misaligned pointer.
130+
* Invoking undefined behavior via compiler intrinsics.
131+
* Reading from uninitialized memory except for padding or unions.
132+
* Producing an invalid value
133+
134+
Note: All solutions to verification challenges need to satisfy the criteria established in the [challenge book](../general-rules.md)
135+
in addition to the ones listed above.

0 commit comments

Comments
 (0)